lua-users home
lua-l archive

Re: to-be-closed variables as resources from a library.

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


On 28/09/2022 16:24, Jorge Visca wrote:
On 28/9/22 04:25, Francisco Olarte wrote:
They are just a variation of try/finally, similar to
try-with-resources, not that difficult to understand.
My problem was that in my mind "going out of scope" was "going out of scope everywhere in the program". Yes I see that that's not how Lua's gc works.
"going out of scope everywhere in the program": are you sure you are not conflating/confusing scope with lifetime? Scope is a textual concept (at least in lexically-scoped languages, like Lua), lifetime is a temporal concept. You seem to imply that you want to clean-up library resources (automatically) just when the program terminates (otherwise I cannot understand what you mean by "going out of scope everywhere in the program"). The garbage collector guarantees that when a program terminates any object marked for finalization will have their __gc metamethods called. So any object created in a library, if you give it a __gc MM, will get a chance to free their acquired resources, too.
So, my takeaways (basically derived from what you describe):
* i'll not use <close> variables anywhere i do not have full control of them or they can leak, nor depend on __close for the system to be correct. * Conceptually, the main place to release stuff is __gc. Define __close to call __gc to speed up memory release when the user mind it enough.
* All releasing should be idempotent, always.
* Treat <close> as a memory use optimization, to be used when matters where it matters.
Thanks for the comments!
Jorge

AltStyle によって変換されたページ (->オリジナル) /