lua-users home
lua-l archive

Closures & Recursion

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


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

AltStyle によって変換されたページ (->オリジナル) /