lua-users home
lua-l archive

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

On 11/5/13, Paul K <> wrote:
> Hi All,
> I've written on several occasions something that looks like this:
> local exists ="/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.

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 =
    if file then
	    return true
	    return false