This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


24.3.1 – Error Handling in Application Code

Typically, your application code runs unprotected. Because its code is not called by Lua, Lua cannot set an appropriate context to catch errors (that is, it cannot call setjmp). In such environments, when Lua faces an error like "not enough memory", there is not much that it can do. It calls a panic function and, if the function returns, exits the application. (You can set your own panic function with the lua_atpanic function.)

Not all API functions throw exceptions. The functions lua_open, lua_close, lua_pcall, and lua_load are all safe. Moreover, most other functions can only throw an exception in case of memory-allocation failure: For instance, luaL_loadfile fails if there is not enough memory for a copy of the file name. Several programs have nothing to do when they run out of memory, so they may ignore these exceptions. For those programs, if Lua runs out of memory, it is OK to panic.

If you do not want your application to exit, even in case of a memory-allocation failure, then you must run your code in protected mode. Most (or all) of your Lua code typically runs through a call to lua_pcall; therefore, it runs in protected mode. Even in case of memory-allocation failure, lua_pcall returns an error code, leaving the interpreter in a consistent state. If you also want to protect all your C code that interacts with Lua, then you can use lua_cpcall. (See the reference manual for further details of this function; see file lua.c in the Lua distribution for an example of its use.)