0

I am trying to print a table may contain tables. However, I fail to get it to print recursively.

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;

This is a test table:

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;

now, when I print the table, I get this:

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

which is puzzling for me, as I was expecting a deeper tree than what I got. What I am missing?

Fredrik Karlsson
  • 485
  • 8
  • 21

2 Answers2

1

I think you have a minor 'bug' that simply flattened it. Change

debugTable(v, " - ");

to (something like)

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

and you see the true depth.

10 11
11 11
12 10
-- 1 10
-- -- -- 33 44
-- -- -- 55 43
-- -- 12 30
-- -- 11 40
tonypdmtr
  • 3,037
  • 2
  • 17
  • 29
0

With a large amount of deeply nested tables you will eventually overflow the stack using that method. Huge tables will also cause 'out of memory' error during string concatenation if the output string becomes too large. If you run into this problem you can try my answer here: How to dump a table to console?

Community
  • 1
  • 1
Alundaio
  • 551
  • 4
  • 8
  • Thanks. I will have a look at this. Tables will not be terribly nested in the cases where I was planning to use this function. But, better is better, so I will use your method instead, if that is ok. – Fredrik Karlsson Feb 06 '17 at 08:49