lua-users home
lua-l archive

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


Usually you'd use both __close and __gc (and document prominently that
your library needs to be closed to have the resource released). Even if
the user forgets to mark their variable as to-be-closed, garbage
collection will take care of it eventually. This is also how Lua's file
handles work.

On 28.09.22 05:54, Jorge Visca wrote:
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