I am still curious whether that could work as I suggested, calling
__gc as a kind of emergency collection, only when some resource
allocation fails. For instance, in the case of file handles in Linux,
that would mean ~1 full GC for every 1000 streams created, not
one GC per stream.
If Lua is embedded in a larger program that uses files or other types of resources elsewhere you end up having to call the emergency Lua GC from who knows where in the code. This may be a 3rd party library, or even a system shared library/DLL that you have no control over. A failure to allocate a file handle somewhere deep in library code may be unrecoverable.
It's not something I would want to rely on. I have ended up coding a version of the Lisp unwind-protect construct to handle this issue. It's not perfect because you lose error information when you 'rethrow' an error after releasing the resource, and you have to define two local functions in the Lua version.