[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:59:15 +0100
On Tue, May 10, 2011 at 4:56 PM, Sean Conner <sean@conman.org> wrote:
> It was thus said that the Great Peter Cawley once stated:
>> On Tue, May 10, 2011 at 4:45 PM, Sean Conner <sean@conman.org> wrote:
>> > It was thus said that the Great Dave Collins once stated:
>> >> 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
>> >
>> > Try the following:
>> >
>> > do
>> > local did_it_already
>> >
>> > function dump_table(t,prefix,initialized)
>> >
>> > if not initialized then
>> > did_it_already = {}
>> > end
>> >
>> > local prefix = prefix or ""
>> >
>> > for k,v in pairs(t) do
>> > if type(v) == 'table' and not did_it_already[v] then
>> > did_it_already[v] = true
>> > dump_table(v,prefix .. k .. ":",true)
>> > else
>> > print(prefix .. k .. "=" .. tostring(v))
>> > end
>> > end
>> > end
>> > end
>> >
>> > The reason you were seeing infinite recursion was because of nested
>> > tables. This routine keeps track of any tables already processed and skips
>> > them.
>> >
>> > -spc
>> >
>>
>> Isn't that going to have problems if you ever want to dump the same
>> table more than once?
Ah yes, sorry for the noise; I read it too fast and thought that
initialized had a similar lifetime to did_it_already.