• Subject: SV: Tables, Functions & varargs
• From: "Andreas Stenius" <andreas.stenius@...>
• Date: Fri, 10 Oct 2003 09:38:21 +0200

Maybe this isn't what you're looking for and it doesn't do varargs, but I've
found it quite usefull, and might give some ideas..

====8<----
-- an extended ?table.foreach' kind of function..
function tfe( t )
local level = 0
local tables = {}
tables[ t ] = true

local function f( key, val )
print( string.rep( "\t\t", level ) .. key, val )
if( type(val) == "table" ) then
if( tables[ val ] ~= true ) then
tables[ val ] = true
level = level + 1
table.foreach( val, f )
level = level - 1
else
print( "\t*recursion*" )
end
end
end

table.foreach( t, f )
end
------>8========

Example use:
>tfe( _G )
or
>tfe{ my_table, some_other_table, foo_table } -- notice that I've
still only passed one argument to tfe..

//Andreas

> > when I try to use any of my indent_level assignments above
> > I get an error in the for loop (to print the tabs) about
> > indent_level not being a number!!!
>
> I don't see the problem in the code you posted. This will work
> fine:
>
> function printAll (node, ...)
>   print(arg[1])
>   print(type(arg[1]))
> end
>
> level = 1
> printAll("foo", level)
>
>
> Here's a simple example of what (I think) you're trying to do
> (though varargs aren't necessary in this example). Maybe it will
> help:
>
> function indent(n)
>   for i=1,n do io.write(' ') end
> end
>
> function printTable (t, ...)
>   for k,v in t do
>     indent(arg[1])
>     if type(v) == "table" then
>       print(k)
>       printTable(v, arg[1] + 2)
>     else
>       print(k.." = "..v)
>     end
>   end
> end
>
> a = {
>   ba = {},
>   bb = {
>     ca = { "da", "db", "dc", },
>     cb = {
>       da = { "ea" },
>     },
>   },
> }
>
> printTable (a, 1)
>