lua-users home
lua-l archive

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


On Wed, 28 Sept 2022 at 05:54, Jorge Visca <xxopxe@gmail.com> wrote:
> I'm trying to understand to-be-closed variables and got a bit stumped.

They are just a variation of try/finally, similar to
try-with-resources, not that difficult to understand.

> 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.

That's a problem. "can not be used anymore" is a difficult thing to
determine accurately and timely in a garbage collection environment
like lua.

> 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!

Thay are not useless, they are unused, they are very useful for the
users who read the docs ( I'm assuming the docs clearly state how to
release the resource and the consequences of not doing so ). The "get
a variable and use it" is a bit misleading, things are not that
simple. Even in a simple local real object, like a C++ object with a
destructor, the user has a to remember to not store it in a pointer
and then leak it ( which is more complex than just declaring the
object ).

Your problem is garbage collection is fine for memory management, but
problematic for many other kinds of resources, like open files,
database connections and cursors, file openings and locks, .... For
these things like reference counting are easier, but they have their
own problems. In general once you enter the domain of complex things,
with long lived libraries locking scarce things and similar, programs
cease to be simple.

> Is there a way for releasing library resources transparently for the
> user (that works better than __gc)?

_gc does it, transparently, but is not speed. _close speeds it up.


>

> (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).

The unreferenced stuff exists, and is called __gc. The problem is
unreferenced is defined as "going to be collected now".

Francisco Olarte.