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