lua-users home
lua-l archive

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


It was thus said that the Great Patrick Donnelly once stated:
> On Tue, Nov 5, 2013 at 5:21 PM, Leo Razoumov <slonik.az@gmail.com> wrote:
> > On 11/5/13, Paul K <paulclinger@yahoo.com> wrote:
> >> Hi All,
> >>
> >> I've written on several occasions something that looks like this:
> >>
> >> local exists = io.open("/somefile") ~= nil
> >>
> >> What happens to the returned file handle in those cases when
> >> "/somefile" exists? The documentation states that the file is closed
> >> when the handle is garbage collected after going out of scope, but
> >> does it go out of scope immediately (as it's not assigned to anything)
> >> or only after reaching the "end" statement for the current scope?
> >> Thank you.
> >>
> >> Paul.
> >>
> >
> > Paul,
> > GC is non-deterministic. The only guarantee it provides is that the
> > variable will not be collected while it is
> > still referenced. A more deterministic approach would be to close it
> > immediately yourself.
> > The following helper function does just that:
> >
> > function file_exists(filename)
> >     local file = io.open(filename)
> >     if file then
> >             io.close(file)
> >             return true
> >     else
> >             return false
> >     end
> > end
> 
> It's not quite so simple. You need to check that the error is indeed
> ENOENT (the third return value of io.open). Of course, the value of
> ENOENT is implementation-defined. :(
> 
> [It would be nice if the io/os library provided fields in the io/os
> table for each of these (ANSI only) errors. Of course, if you're doing
> something complicated you might as well use a POSIX-y library.]

  C89 (which is what Lua is written to) only defines the following errors:

	EDOM
	ERANGE

  C99 adds the following:

	EILSEQ

  ENOENT is POSIX.  

  -spc (Obligatory plug: https://github.com/spc476/lua-conmanorg/blob/master/src/errno.c)