4.6 – Error Handling in C
Internally, Lua uses the C longjmp
facility to handle errors. (You can also choose to use exceptions if you compile Lua as C++; search for LUAI_THROW
in the source code.) When Lua faces any error (such as a memory allocation error, type errors, syntax errors, and runtime errors) 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.
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 runs as if it were a message handler (see §2.3); in particular, the error message is at the top of the stack. However, there is no guarantees about stack space. To push anything on the stack, the panic function should first check the available space (see §4.2).
Most functions in the API can throw an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can throw errors.
Inside a C function you can throw an error by calling lua_error
.