2011-02-08 28 views
2

嵌套表結果我有一個包含以下獲得LUA

for i,v in pairs(Table A) do print (i,v) end 

1 a 
2 table : 50382A03  -- table B 
3 hi 

表格中的。在打印父表A時,是否有辦法讓表B的值被打印出來,或者我可以使用相同的函數將其存儲並再次打印出來?

感謝 太平紳士

回答

3

當問題包含 「嵌套」,答案可能會包含遞歸:

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 

只需提防循環引用。到LUA用戶維基上table serialization頁面,選擇你的英雄

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'}) 
+2

又見`在Lua的現場演示globals`程序:http://www.lua.org/demo.html – lhf 2011-02-08 14:50:56

0

有點更好的輸出和抽象更改的功能。例如,下面的代碼處理一切,包括在週期表(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 
0

只是頭: