lua-users home
lua-l archive

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


Try this:

function visit (x,v)
-- Visit potentially recursive and circular structures.
   local cv = v or 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,cv)
       end
     end
   end
end

Regards,

Dave Nichols
Match-IT Limited
Tel: 0845 1300 510
Fax: 0845 1300 610
mailto:dave.nichols@make247.com
http://www.make247.com

Email Disclaimer: The contents of this electronic mail message and any
attachments (collectively "this message") are confidential, possibly
privileged and intended only for its addressee ("the addressee"). If
received in error, please delete immediately without disclosing its contents
to anyone. Neither the sender nor its management or employees will in any
way be responsible for any advice, opinion, conclusion or other information
contained in this message or arising from it's disclosure.


-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br]On Behalf Of Stefan
Brantschen
Sent: 28 July 2006 13:24
To: Lua list
Subject: Closures & Recursion


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