I have a table A that contain the following
for i,v in pairs(Tab开发者_StackOverflowle A) do print (i,v) end
1 a
2 table : 50382A03 -- table B
3 hi
. Is there a way that I can get the table B value to be print out while I m printing the parent table A, or i can store it and print it again using the same function?.
thanks Jp
When the question contains "nested", the answer will probably contain recursion:
function printTable(t)
function printTableHelper(t, spacing)
for k,v in pairs(t) do
print(spacing..tostring(k), v)
if (type(v) == "table") then
printTableHelper(v, spacing.."\t")
end
end
end
printTableHelper(t, "");
end
Just beware of circular references.
A bit changed function for better output and abstraction:
function printTableHelper(t,spacing)
local spacing = spacing or ''
if type(t)~='table' then
print(spacing..tostring(t))
else
for k,v in pairs(t) do
print(spacing..tostring(k),v)
if type(v)=='table' then
printTableHelper(v,spacing..'\t')
end
end
end
end
printTableHelper({'a',{'b'},'c'})
Just head on to the lua-users wiki page on table serialization and choose your champion. For example the following code handles everything including cycles in tables (local a={}; a.t = a
):
-- alt version2, handles cycles, functions, booleans, etc
-- - abuse to http://richard.warburton.it
-- output almost identical to print(table.show(t)) below.
function print_r (t, name, indent)
local tableList = {}
function table_r (t, name, indent, full)
local serial=string.len(full) == 0 and name
or type(name)~="number" and '["'..tostring(name)..'"]' or '['..name..']'
io.write(indent,serial,' = ')
if type(t) == "table" then
if tableList[t] ~= nil then io.write('{}; -- ',tableList[t],' (self reference)\n')
else
tableList[t]=full..serial
if next(t) then -- Table not empty
io.write('{\n')
for key,value in pairs(t) do table_r(value,key,indent..'\t',full..serial) end
io.write(indent,'};\n')
else io.write('{};\n') end
end
else io.write(type(t)~="number" and type(t)~="boolean" and '"'..tostring(t)..'"'
or tostring(t),';\n') end
end
table_r(t,name or '__unnamed__',indent or '','')
end
精彩评论