[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: to-be-closed variables as resources from a library.
- From: Jorge Visca <xxopxe@...>
- Date: Wed, 28 Sep 2022 00:54:07 -0300
I'm trying to understand to-be-closed variables and got a bit stumped.
Let's suppose I am writing a library that produces an object that locks
some resource I want released when the object can not be used anymore.
---------------------------------------------------------------------------------
-- library
local M = {
get_object = function ()
local obj = setmetatable( {resource=acquire_resource() },
{__close=function (self)
release_resource(self.resource) end } )
return obj
end
}
-- user
do
local obj <close> = M.get_object()
-- do stuff with obj
end
-- obj does not exist anymore and was closed
---------------------------------------------------------------------------------
My intention was to spare the library's user from having to release
resources, just get a variable and use it. But now if the user forgets
to tag the variable as <close> when using my library then my __closes
are useless!
Is there a way for releasing library resources transparently for the
user (that works better than __gc)?
(I SO wanted using the <close> inside the library's method to work, it
just made sense to me. OR just skip the <close> altogether, and if
there's a __toclose use it when getting unreferenced).
Jorge