lua-users home
lua-l archive

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



On 9-Feb-07, at 11:12 PM, Glenn Maynard wrote:

On Fri, Feb 09, 2007 at 10:49:48PM -0500, Rici Lake wrote:
That's exactly what it does (or would do).

This is how Lua works (currently) when an error is thrown:

1) the error function is called immediately when an
error is encountered, so it sees the current stack.

2) Then upvalues are closed back to the last pcall() (or to the
beginning of the stack.) That's necessary because the stack
is about to be popped back to that pcall().

3) Finally, the stack is popped back to the pcall, and control
is returned to the pcall.

That's precisely why I think that the upvalue closure
mechanism can be used as well to implement finalizers.
The proposed finalizer mechanism runs the finalizer during
the upvalue closure sequence, which means it will run
at step 2, above, ensuring that the finalizer executes
before the pcall is returned to.

In this case, could it be possible to have a C API to add a cleanup
function to the running CFunction (rather than messing with the error
handler) through the same mechanism (perhaps requiring reserving
a closure slot in advance, though ideally not)?

I think so. As with regular Lua functions, you should be able to use
the call-frame's "Slot 0"; the upvalue finalizer is not actually stored
on the stack; it just refers to the (absolute) stack level.

The cleanup function would have to be a regular lua_CFunction and it
wouldn't have access to the Lua stack when it ran. Also, it would always
run (not just on errors). But that might solve some problems, anyway.

Bear in mind that I haven't actually tried to write this patch,
although the original message from 2005 does have quite a lot
of code in it; if the idea works, it should be pretty simple
to implement.