lua-users home
lua-l archive

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


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[1] 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)
    longjmp(buf, 1);

... some init function here that calls lua_atpanic(s, panic_handler) ...

void safe_gettable(lua_State* s, const int index)
    if (setjmp(buf) == 0)
        lua_gettable(s, index);
        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
errors. ]

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
the top)?

Thanks in advance!

1: - 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.

Julio Merino