lua-users home
lua-l archive

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


I also think this requirement of writing <close> is somehow too much
for the typical Lua user I think off.

Lua is intended usually to be "simple programmable".

And then it really would be much better, if the __close metafunction
is used automatically (if it exists).

Am Mi., 28. Sept. 2022 um 05:54 Uhr schrieb Jorge Visca <xxopxe@gmail.com>:
>
> 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
>
>
>