[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Why is the stack cleared on panic?
- From: Julio Merino <jmmv84@...>
- Date: Mon, 10 Jan 2011 15:50:45 +0000
For a variety of reasons, I want to write thin C++ wrapper functions
around the Lua C API to provide better error handling. One of the
mechanisms I attempted is to install an error handler with
lua_atpanic and to use longjmp from within such handler to recover the
error. According to the documentation, using longjmp in this context
is safe (aka no resource leaks as I understand it).
The code for such a simple wrapper would look like:
static jmp_buf buf;
int panic_handler(lua_State* s)
... some init function here that calls lua_atpanic(s, panic_handler) ...
void safe_gettable(lua_State* s, const int index)
if (setjmp(buf) == 0)
throw error('Uh oh, lua_gettable failed');
[ Pardon any mistakes in the code above; it's just an ad-hoc example
for this email and it may contain any kind of syntax / inconsistency
The code above works just fine. BUT one of the invariants I would
like to maintain in my wrappers is: on error, the Lua stack remains
unmodified (it is just a good programming rule to leave state
unmodified on errors, isn't it? :-P). And here comes the problem: Lua
will clear the stack right before calling the panic handler, which
completely prevents me from implementing this invariant.
What is the reason for the stack being cleared when executing the
panic handler? (This is a genuine question. The documentation does
not really provide many details on how to handle errors and this
little fact is not documented.)
Could this "clear stack" operation be removed from the error path so
that, when the panic handler runs, it has access to the original,
unmodified stack (with the exception of an additional error message at
Thanks in advance!
1: http://blog.julipedia.org/2011/01/error-handling-in-lua.html - A
post detailing all the things I tried while attempting to deal with
errors to calls to Lua C API functions from an unprotected environment
using prebuilt Lua binary libraries.