I'm trying to figure out why this function is ignoring the middle most table? I'm overlooking something simple I assume.
Here's the code
tbl = {
name = "first table";
tbl = {
name = "middle table";
tbl = {
name = "last table";
};
};
}
sayName = function(tbl)
print(tbl.name)
if tbl.tbl ~= nil then
for _,v in pairs(tbl.tbl) do
sayName(v)
end;
end;
end;
sayName(tbl)
Output>
first table
last table
nil
CodePudding user response:
In your example, you have a recursive structure, each table have 1 name
and possibly a sub-table named tbl
. So, I am not clear why would one use the for
loop in these conditions.
tbl = {
name = "first table",
tbl = {
name = "middle table",
tbl = {
name = "last table"
}
}
}
function PrintTable (Table)
print("# Name", Table.name)
local SubTable = Table.tbl
if SubTable then
PrintTable(SubTable)
end
end
PrintTable(tbl)
Will return:
# Name first table
# Name middle table
# Name last table