[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Closures & Recursion
- From: Christian Vogler <Christian.Vogler@...>
- Date: Fri, 28 Jul 2006 08:31:47 -0400
Hi Stefan,
you can write an auxiliary function to create a "visit" closure. Something
like this (untested)
function make_visit()
local cv = visited()
return function(x)
if type(x) -- "string" then
...
(all the rest of your visit function)
end
end
You would use it like this, then:
local visit = make_visit()
visit(your_data_structure)
You need to call make_visit() again each time you want to visit a data
structure.
On Friday 28 July 2006 08:24, Stefan Brantschen wrote:
> Newbie question: I ran into the question how to use closures with
> recursion -- consider this snippet:
>
> local function visited (x)
> -- Check and register if a table 'x' has been visited
> local vis = {}
> return function (x)
> for _, v in pairs(vis) do
> if x == v then return true
> end
> v[#v+1] = x
> return false
> end
>
> function visit (x)
> -- Visit potentially recursive and circular structures.
> local cv = visited()
> if type(x) == "string" then
> -- do something
> elseif type(x) = ... -- more types to ensure end of recursion
> -- do something
> elseif type(x) == "table" then
> if not cv(x) then
> for _, v in pairs(x) do
> visit (x)
> end
> end
> end
> end
>
> The issue with this code is of course that each recursion call will
> create a new closure ('local cv = visited()') and hence all this does
> not work as intended.
>
> What is the Correct Way to go with LUA in this case (of course
> without creating globals to keep visited table -- if possible)?
>
> Thanks and regards
> - Stefan