3.15 – Protected Calls
When you call a function with lua_call
, any error inside the called function is propagated upwards (with a longjmp
). If you need to handle errors, then you should use lua_pcall
:
- int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
Both nargs
and nresults
have the same meaning as in lua_call
. If there are no errors during the call, lua_pcall
behaves exactly like lua_call
. However, if there is any error, lua_pcall
catches it, pushes a single value at the stack (the error message), and returns an error code. Like lua_call
, lua_pcall
always removes the function and its arguments from the stack.
If errfunc
is 0, then the error message returned is exactly the original error message. Otherwise, errfunc
gives the stack index for an error handler function. (In the current implementation, that index cannot be a pseudo-index.) In case of runtime errors, that function will be called with the error message and its return value will be the message returned by lua_pcall
.
Typically, the error handler function is used to add more debug information to the error message, such as a stack traceback. Such information cannot be gathered after the return of lua_pcall
, since by then the stack has unwound.
The lua_pcall
function returns 0 in case of success or one of the following error codes (defined in lua.h
):
LUA_ERRRUN
—- a runtime error.LUA_ERRMEM
—- memory allocation error. For such errors, Lua does not call the error handler function.LUA_ERRERR
—- error while running the error handler function.