lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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