lua-users home
lua-l archive

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


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

--Leo--