[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: avoiding recursion in a dump_table function
- From: Peter Cawley <lua@...>
- Date: Tue, 10 May 2011 16:36:59 +0100
On Tue, May 10, 2011 at 4:31 PM, Dave Collins
<Dave.Collins@mercatustechnologies.com> wrote:
> I’ve got a large object which, for convenience of pulling data from it, is
> self-referencing. (sometimes I need items from a dept, sometimes I need all
> items).
>
>
>
> Essentially, I’ve got this:
>
>
>
> Flyer
>
> Departments
>
> Dept1
>
> Item1
>
> Item2
>
> Dept2
>
> Item3
>
> Item4
>
> Items
>
> Item1
>
> Item2
>
> Item3
>
> Item4
>
>
>
>
>
> When I need to look inside this table using the following dump_table method,
> I get infinite recursion.
>
>
>
> Any ideas on how I can add some smarts to my dump_table to defeat the
> infinite recursion?
>
>
>
> function dump_table(t, prefix)
>
> if(prefix == nil) then
>
> prefix = ""
>
> end
>
>
>
> local k,v
>
> for k,v in pairs(t) do
>
> if(type(v) == "table") then
>
> dump_table(v, prefix .. k .. ":")
>
> else
>
> print(prefix .. k .. "=" .. tostring(v))
>
> end
>
> end
>
> end
>
>
>
>
>
>
>
> Dave Collins
>
> Front-End Engineer
>
> Mercatus Technologies Inc.
> 60 Adelaide Street East, Suite 700
> Toronto ON M5C 3E4
> T 416 603 3406 x 298
> F 416 603 1790
>
>
>
> dave.collins@mercatustechnologies.com
>
> www.mercatustechnologies.com
>
>
function dump_table(t, prefix, seen)
prefix = prefix or ""
seen = seen or {}
if seen[t] then
print(prefix .. " is recursive")
else
seen[t] = t
local k,v
for k,v in pairs(t) do
if(type(v) == "table") then
dump_table(v, prefix .. k .. ":",seen)
else
print(prefix .. k .. "=" .. tostring(v))
end
end
end
end