lua-users home
lua-l archive

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


When trying to use the first version of the "Dir Tree Iterator" sample
code on the lua-user.org Wiki page[1], I get the error:

attempt to call field '?' (a userdata value)

for this line:
      local entry = diriters[#diriters]()

The second example, using coroutines, works fine.

What's the issue with the first example?

Thanks,

Mark

[1] http://lua-users.org/wiki/DirTreeIterator

Code from example #1 pasted below, for convenience:

-- code by AlexanderMarinov
-- Compatible with Lua 5.1 (not 5.0).
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 diriters = {lfs.dir(dir)}
  local dirs = {dir}

  return function()
    repeat 
      local entry = diriters[#diriters]()
      if entry then 
        if entry ~= "." and entry ~= ".." then 
          local filename = table.concat(dirs, "/").."/"..entry
          local attr = lfs.attributes(filename)
          if attr.mode == "directory" then 
            table.insert(dirs, entry)
            table.insert(diriters, lfs.dir(filename))
          end
          return filename, attr
        end
      else
        table.remove(dirs)
        table.remove(diriters)
      end
    until #diriters==0
  end
end

Example usage:
for filename, attr in dirtree(".") do
   print(attr.mode, filename)
end