How to print a table's contents within a table? [Lua]

大城市里の小女人 提交于 2021-02-08 07:18:24

问题


What I want to do is ONLY print a table's contents within a table. For example:

local stats = {
  table1 = {
    tTable1 = 
    {
      data = 1
    },
    tTable2 = 
    {
      data2 = 2
    },
    tTable3 =
    {
      data3 = 3
    },
  }
}

I don't really care about table1 or all the tTables but rather the information in the data variables. How can I print them?

This is a snippet of my real code:

local stats = {
  [1] = { 
    [1] = { 
      [1] = 1,
      [2] = -1,
      [3] = -1,
      ["n"] = 3,
    },
    [2] = { 
      [1] = nuclearcraft:cooler,
      [2] = 10,
      ["n"] = 2,
    },
    ["n"] = 2,
  },
  [2] = { 
    [1] = {
      [1] = 2,
      [2] = -1,
      [3] = -1,
      ["n"] = 3,
    },
    [2] = { 
      [1] = nuclearcraft:cell_block,
      [2] = 0,
      ["n"] = 2,
    },
    ["n"] = 2,
  },
  [3] = {
    [1] = {
      [1] = 3,
      [2] = -1,
      [3] = -1,
      ["n"] = 3,
    },
    [2] = { 
      [1] = nuclearcraft:cooler,
      [2] = 10,
      ["n"] = 2,
    },
    ["n"] = 2,
  },
}

This code actually goes on for a bit longer than this. In the real code, I don't care for any of the data except for the areas where it says "nuclearcraft" and the number beneath it.


回答1:


recursive table traversal is suitable for this case:

local function TablePrint(t)
     for k,v in pairs(t)  do
         if type(v)=="table" then
            print(k)
            TablePrint(v)
         else 
            print('\t',k,v)
         end
     end      
end
TablePrint(stats)

result:

table1
tTable3
        data3   3
tTable2
        data2   2
tTable1
        data    1

keep in mind that the order of non-index values in the table is not defined



来源:https://stackoverflow.com/questions/59515669/how-to-print-a-tables-contents-within-a-table-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!