[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Example iterator for recursive traversals with coroutines
- From: David Kastrup <dak@...>
- Date: Wed, 29 Aug 2007 19:53:16 +0200
Hi,
I just added the following code example to
<URL:http://lua-users.org/wiki/DirTreeIterator>.
I think that it makes for quite a nice example how to create iterators
for recursive structures by using coroutines. Very basic (and
illustrates that coroutines inhabit a different application space from
that of threads).
The code is
require "lfs"
function dirtree(dir)
assert(dir and dir ~= "", "directory parameter is missing or empty")
if string.sub(dir, -1) == "/" then
dir=string.sub(dir, 1, -2)
end
local function yieldtree(dir)
for entry in lfs.dir(dir) do
if entry ~= "." and entry ~= ".." then
entry=dir.."/"..entry
local attr=lfs.attributes(entry)
coroutine.yield(entry,attr)
if attr.mode == "directory" then
yieldtree(entry)
end
end
end
end
return coroutine.wrap(function() yieldtree(dir) end)
end
and can, like the previous version, be used as
for filename, attr in dirtree(".") do
print(attr.mode, filename)
end
--
David Kastrup