lua-users home
lua-l archive

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


The answer below is a good explanatory example - but it depends on a (new) user knowing or being able to find out that Lua’s “file” object has a __close metamethod set by default when io.open() returns.

I couldn’t find reference to that in the Reference Manual - in other words there is no easy way for someone to find out that your example of autoclosing files is a valid use case for <toclose>. (IIRC the only way to snoop on the metatable of a userdata object is via the debug module.)

A reasonable user might infer, from your example, that “toclose” can reliably be assumed to work with any file-like object that is traditionally closed with an obj:close() call, but that’s not necessarily true, because the semantics and the API of the  __close metamethod are not the same as most library’s :close methods, and <toclose> doesn’t call :close.

Suggestions: [1] the manual should list __close more prominently as a first-class metamethod along with already well-known examples such as _call and _add; [2] the manual should include a simple example of its use; [3] any library objects that support “toclose” - such as Lua files - should be officially labelled as “toclosable” in their own documentation.

Oh, [4] I suspect “autoclose” is a clearer name that “toclose”. 

IMO it denotes that the object gets a “close” metamethod called automatically more clearly that “toclose”, and it avoids the need for the clumsy hyphenated adjectival term “to-be-closed” (which doesn’t convey that the close is automatic anyway).  Like this:

“A local variable tagged with the attribute <autoclose> will automatically have its __close metamethod called as soon as it goes out of scope.    

This is a convenient and reliable way for Lua objects to clean up after themselves automatically without waiting for garbage collection, which could happen some time after the variable goes out of scope. 

One example of an object that can usefully be used with <autoclose> is a Lua file, as returned by io.open() [q.v.]”



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.


 You generally want to use <toclose> for resources other than memory where
waiting for garbage collection may be too long.  And remember, this is a
contrived example.  Imaging two files being processed, or the function being
longer, or more possible error paths (or all the above).

 -spc