lua-users home
lua-l archive

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


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