4.6 – Error Handling in C
Internally, Lua uses the C longjmp
facility to handle errors. (Lua will use exceptions if you compile it as C++; search for LUAI_THROW
in the source code for details.) When Lua faces any error (such as a memory allocation error or a type error) it raises an error; that is, it does a long jump. A protected environment uses setjmp
to set a recovery point; any error jumps to the most recent active recovery point.
Inside a C function you can raise an error by calling lua_error
.
Most functions in the API can raise an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can raise errors.
If an error happens outside any protected environment, Lua calls a panic function (see lua_atpanic
) and then calls abort
, thus exiting the host application. Your panic function can avoid this exit by never returning (e.g., doing a long jump to your own recovery point outside Lua).
The panic function, as its name implies, is a mechanism of last resort. Programs should avoid it. As a general rule, when a C function is called by Lua with a Lua state, it can do whatever it wants on that Lua state, as it should be already protected. However, when C code operates on other Lua states (e.g., a Lua parameter to the function, a Lua state stored in the registry, or the result of lua_newthread
), it should use them only in API calls that cannot raise errors.
The panic function runs as if it were a message handler (see §2.3); in particular, the error object is at the top of the stack. However, there is no guarantee about stack space. To push anything on the stack, the panic function must first check the available space (see §4.2).