[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Why do we need “toclose” (or those angle brackets) at all?
- From: David Heiko Kolf <david@...>
- Date: Fri, 14 Jun 2019 13:55:23 +0200
Paul Ducklin wrote:
> A <toclose> variable *must have* a __close metamethod or else an error is raised when it goes out of scope. So why can’t the presence of a __close metamethod be the signal to Lua that it is handling a to-be-closed variable?
>
> The <toclose> flag for a variable should simply be set automatically at runtime when the setmetatable() function is called for the variable.
Lua cannot easily tell the intended scope of a variable without some
extra informations. Consider this case:
function foo (fname)
local f, err = io.open(fname, "w")
if not f then
print(("Failed to open %s: %s"):format(fname, err))
else
bar(f)
end
end
Now what does "bar(f)" do to the file? It could just write some stuff in
the file and it should be closed once f in "foo" goes out of scope:
function bar (f)
f:write("some stuff")
end
However, it could also save the file handle somewhere else where it is
expected to be still open at a later point:
function bar (f)
activefile = f
end
How would Lua know there is still a reference to the file? At least
without running the GC every time a variable with a __close metamethod
goes out of scope.
Best regards
David