lua-users home
lua-l archive

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


Thanks, Alexey, that helped.  Here is a complete example with a pcall to capture the case when "path" can't be opened.  The annoying thing is that I have to resort to the "wrapper_lfs_dir()" routine so that I can get the return values via the lsfT table.  So this pretty ugly code but it does work.  

Thanks to all.
Robert McLay

--------------------------------------------------------------------------

local lfs    = require("lfs")
function wrapper_lfs_dir(path, lfsT)
   local dir_next, dir = lfs.dir(path)
   lfsT.dir_next = dir_next
   lfsT.dir      = dir
end

function main()
   local path = "/path/that/cannot/be/opened"

   local lfsT = {}
   
   local status, msg = pcall (wrapper_lfs_dir, path, lfsT)
   if (not status) then
      print(msg)
      return
   end
   local dir_next, dir = lfsT.dir_next, lfsT.dir
   while (true) do
      local f = dir_next(dir, path)
      if (not f) then
         if (dir) then
            dir:close()
         end
         break
      end
      local file = path .. "/" .. f
      print(file)
   end
   
end

main()


On Sat, Sep 8, 2018 at 3:49 AM Alexey Melnichuck <alexeymelnichuck@gmail.com> wrote:
lfs.dir returns context object startign i think from 1.6 version.
So more accurate example will be

local dir_next, dir, path = lfs.dir(path) while true do path = dir_next(dir, path) if not path then if dir then dir:close() end break end ... end


чт, 6 сент. 2018 г. в 23:50, Dirk Laurie <dirk.laurie@gmail.com>:
Op Do., 6 Sep. 2018 om 22:40 het Robert McLay <mclay@tacc.utexas.edu> geskryf:
>
> I have some code which does this under unix:
>
>      local path = "/path/to/somewhere"
>      local lfs = require("luafilesystem")
>      local posix = require("posix")
>      if (posix.access(path,"x")) then
>         for f in lfs.dir(path) do
>            ...
>         end
>      end
>
> The problem is that between the posix.access() test and the lfs.dir() call the permissions on path could change.
>
> What I would like instead is some way to ignore the error that lfs.dir() is causing.  Normally one can ignore errors with pcall() but I don't see how to use pcall with an iterator like lfs.dir().

iterator = lfs.dir()
while true do
  local f = pcall(iterator)
  if not p then break end
  ...
end