【问题标题】:Printing recursive tables打印递归表
【发布时间】:2017-06-22 02:33:39
【问题描述】:

我正在尝试打印一个可能包含表格的表格。但是,我无法让它递归打印。

function debugTable (t, indent)
    local ind = indent or "";
    local printFunc = print
    if (fibaro or {}).debug then
       function printFunc(...)
          return fibaro:debug(...)
       end
    end
    for k, v in pairs(t) do
        if(type(v) == "table") then
            -- recursive call if table
            debugTable(v, " - ");
        else
            printFunc(ind .. k .." ".. tostring(v));
        end;
    end;
end;

这是一个测试表:

a = {};
c ={["33"] = 44,["55"]=43}
b = {["12"] = 30, ["11"]= 40,["66"]=c};

a["12"] = 10;
a["10"] = 11;
a["22"] = {10,["13"]=b};
a["11"] = 11;

现在,当我打印表格时,我得到了:

> debugTable(a)
 - 1 10
 - 12 30
 - 33 44
 - 55 43
 - 11 40
12 10
10 11
11 11

这让我感到困惑,因为我期待的树比我得到的更深。 我错过了什么?

【问题讨论】:

    标签: recursion printing lua recursive-datastructures


    【解决方案1】:

    我认为您有一个小“错误”,只是将它弄平了。改变

    debugTable(v, " - ");
    

    到(类似)

    debugTable(v, ind..'-- ')
    

    你会看到真正的深度。

    10 11
    11 11
    12 10
    -- 1 10
    -- -- -- 33 44
    -- -- -- 55 43
    -- -- 12 30
    -- -- 11 40
    

    【讨论】:

      【解决方案2】:

      对于大量深度嵌套的表,您最终会使用该方法溢出堆栈。如果输出字符串变得太大,巨大的表也会在字符串连接期间导致“内存不足”错误。如果你遇到这个问题,你可以在这里试试我的答案:How to dump a table to console?

      【讨论】:

      • 谢谢。我会看看这个。在我计划使用此功能的情况下,表格不会非常嵌套。但是,更好就是更好,所以我会改用你的方法,如果可以的话。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2016-05-07
      • 2016-06-23
      • 1970-01-01
      • 2018-03-29
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多