how do I make a table go showing tables

Asked

Viewed 124 times

1

wanted to do a function that makes kind of something like the thing below

for i in pairs(v) do
    if type(v[i])=="table" then
        for j in pairs(v[i]) do
             if type(v[i][j])=="table" then
                 print("...")
             else
                 print(i,j,v[i][j])
             end
        end
    else
        print(i,v[i])
    end
end

but that worked for indefinite numbers of tables inside other, like {{{{{1},{2},3},{4},5},{6},7},{8},9}

it is possible to make a function for this?

http://ideone.com/22Ddmf --example quoted above Xp

  • 1

    Answered in http://stackoverflow.com/questions/40580849/how-to-make-a-function-version-of-this.

2 answers

2


You need a recursive function. See the example below in online demonstration Lua. Turn on dump your table instead of _G.

-- globals.lua
-- show all global variables

local seen={}

function dump(t,i)
    seen[t]=true
    local s={}
    local n=0
    for k in pairs(t) do
        n=n+1 s[n]=k
    end
    table.sort(s)
    for k,v in ipairs(s) do
        print(i,v)
        v=t[v]
        if type(v)=="table" and not seen[v] then
            dump(v,i.."\t")
        end
    end
end

dump(_G,"")

1

Or even easier, use the

json.cod(tabela)

--saída: { "matriz": [ "filhos" : [ "netos" : [ 1,2,3] ] ]}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.