lua-users home
lua-l archive

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


If I use a function to recursively traverse a graph (or tree), it appears
that I must make that function global.  Is that true?

Here's how I would like to do it:

local traverse = function( index, subTree )
  DoSomething( subTree )
  foreach( subTree, %traverse )
end
foreach( tree, traverse )

However, it's not that easy, because the local traverse doesn't get
assigned anything until after the upvalue %traverse has been
defined.  Here's the best I could come up with:

local traverse = {}
traverse[1] = function( index, subTree )
  DoSomething( subTree )
  foreach( subTree, %traverse[1] )
end
foreach( tree, traverse[1] )

(Note that it's important that you assign the local traverse an empty
table before you create the function.)

I hope everyone agrees that this is ugly and not intuitive.  Is it
possible to create a library function "this()" that returns the function
that is currently running?  Then it would look like this:

local traverse = function( index, subTree )
  DoSomething( subTree )
  foreach( subTree, this() )
end
foreach( tree, traverse )

I'm not that familiar with the source code, so I didn't look to see how
easy that would be.

-Fred