lua-users home
lua-l archive

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


On 6/15/19, 3:37 PM, "lua-l-bounces@lists.lua.org on behalf of Paul Ducklin" <lua-l-bounces@lists.lua.org on behalf of pducklin@outlook.com> wrote:

    I think that the 5.4.0 reference manual ought to:
    
    * Add __close and __gc into the list of metamethod events so that all valid metamethods are clearly documented in one place.
    
    * Explain the difference between __close and __gc, and clarify that closing a variable doesn’t finalize it.
    
    (That was not at all clear to me until someone mentioned it here. When you think of “closing” something, the obvious examples are files and sockets, and when you close them you have finished with them and their resources can be reclaimed at once.)
    
    * Give a simple example of how each might be used. (I know it’s a reference manual not a training book but there are useful examples elsewhere in it and they help a lot.)
    
    The biggest problem I have with “toclose” is that having come across it in the manual I still have no real idea why it’s there or what I can do with it that I can’t already do with a finalizer. 
    
    It’s also not that clear how to use it, given that the manual says that to-be-closed variables are constants. My thought is that seems like a great feature for things like files and sockets as a way of recovering cleanly from errors - but I’ve never thought of files and sockets as “constant variables” because they are all about side effects and continuously changing state.
    
    In short: why do I need <toclose>, what do I do with it, and how do I use it properly?

------

For myself, every time I wanted to use __gc, I found that I couldn't, because what I wanted to do was dispose of some big resource that was outside of Lua's memory allocation / management. For example, I may have a UD object pointing at a big buffer created in C, and I need to control when that buffer is disposed of, even if I don't care about when the table containing the UD is GC'd.

I've been following the naming discussion and it strikes me that "__tocolose" is probably just as good as anything else. I thought that "__scoped" seemed good at first, but then thought that it has potential to infer that other variables aren't scoped. We could do "__tocloseatendofscoperegardlessoferror" but that's a lot of typing.

 The distinction between GC and closing is good to keep in mind:

1: The value that the variable points to is not necessarily collected. Other variables can still point to it and prevent collection.
2: You can close off external (expensive) resources at the end of the scope in a simple, deterministic fashion. 

This appears to solve a huge problem for a relatively common and important use case. Here I thought Lua had nothing more to add. :)

-Andrew


-- Andrew Starks