lua-users home
lua-l archive

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


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