3.19 – Error Handling in C

Internally, Lua uses the C longjmp facility to handle errors. When Lua faces any error (such as memory allocation errors, type errors, syntax errors) it raises an error, that is, it does a long jump. A protected environment uses setjmp to set a recover point; any error jumps to the most recent active recover point.

If an error happens outside any protected environment, Lua calls a panic function and then calls exit(EXIT_FAILURE). You can change the panic function with

  1. lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);

Your new panic function may avoid the application exit by never returning (e.g., by doing a long jump). Nevertheless, the corresponding Lua state will not be consistent; the only safe operation with it is to close it.

Almost any function in the API may raise an error, for instance due to a memory allocation error. The following functions run in protected mode (that is, they create a protected environment to run), so they never raise an error: lua_open, lua_close, lua_load, and lua_pcall.

There is yet another function that runs a given C function in protected mode:

  1. int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);

lua_cpcall calls func in protected mode. func starts with only one element in its stack, a light userdata containing ud. In case of errors, lua_cpcall returns the same error codes as lua_pcall (see 3.15), plus the error object on the top of the stack; otherwise, it returns zero, and does not change the stack. Any value returned by func is discarded.

C code can generate a Lua error calling the function

  1. void lua_error (lua_State *L);

The error message (which actually can be any type of object) must be on the stack top. This function does a long jump, and therefore never returns.