lua-users home
lua-l archive

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


Hi

In fact, the directory factory returns the iterator function and a
userdata, which should be closed if you interrupt the loop.  A correct
implementation of that code should be:

local lfs = require("lfs")
for t = 1, 10000 do
   local i = 0
   local iter, dir_handle = lfs.dir("/usr/lib")
   for e in iter, dir_handle do
      i = i + 1
      if i == 100 then
         break
      end
   end
   dir_handle:close()
end

The original implementation would close the userdata at the end of the
loop (after its last iteration) and let the garbage collector do the
job otherwise (when the loop is interrupted).

Regards,
Tomás

Em sex., 24 de abr. de 2020 às 05:43, Dibyendu Majumdar
<mobile@majumdar.org.uk> escreveu:
>
> On Fri, 24 Apr 2020 at 07:42, Hugo Musso Gualandi
> <hgualandi@inf.puc-rio.br> wrote:
> >
> > Em qui, 2020-04-23 às 22:14 +0100, Dibyendu Majumdar escreveu:
> > > On Thu, 23 Apr 2020 at 02:30, Hisham <h@hisham.hm> wrote:
> > > > For example, with `uname -n` set below 10000, this script crashes
> > > > on
> > > > Lua < 5.4, and works in Lua 5.4:
> > > >
> > > > local lfs = require("lfs")
> > > > for t = 1, 10000 do
> > > >    local i = 0
> > > >    for e in lfs.dir("/usr/lib") do
> > > >       i = i + 1
> > > >       if i == 100 then
> > > >          break
> > > >       end
> > > >    end
> > > > end
> > > >
> > >
> > > Out of interest, how would you have written this in older versions of
> > > Lua?
> >
> > IIRC, the most most direct workaround was to manually call
> > collectgarbage in order to run the iterator's __gc metamethod. The
> > performance is not ideal though.
> >
>
> Looks like the api is badly designed since looking at the code above
> you can't tell that a close is required.
> I have argued against an implicit close in a for loop for exactly this reason.
> How can you tell what this code is doing?
> It will behave differently in 5.4 silently.
> Other languages all have explicit constructs for this kind of thing.
>
> Regards
> _______________________________________________
> lua-l mailing list -- lua-l@lists.lua.org
> To unsubscribe send an email to lua-l-leave@lists.lua.org
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org