The Microsoft C# compiler does precisely this when running in release mode, and I suspect most other compiled languages that use finalizers and a garbage collector do the same thing.
An object (a window object) that was accessed via a weak reference literally disappeared because the reference from the main program was optimized away, but when running in debug mode this never happened.
This was easily fixed, but is surprised quite a few people. Compilers need to perform this optimization to limit the number of registers and stack locations used and speed up the code. I would expect a Lua implementation that has a JIT compiler to perform this too (the new ‘toclose’ local variables would be live until the end of the scope because of the call to the __close metamethod)
I have not seen anything in the Lua spec that guarantees the lifetime of an object referenced by a local variable to extend to the point where the execution exits a scope, even if the program no longer accesses the object via that variable. It may be that the current Lua implementation actually does that (except for tail calls) but is it required?
Gé
--