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.2 – Error Handling in Library Code

Lua is a safe language. That means that, no matter what you write, no matter how wrong it is, you can always understand the behavior of a program in terms of Lua itself. Moreover, errors are detected and explained in terms of Lua, too. You can contrast that with C, where the behavior of many wrong programs can only be explained in terms of the underling hardware and error positions are given as a program counter.

Whenever you add new C functions to Lua, you can break that safety. For instance, a function like poke, which stores an arbitrary byte at an arbitrary memory address, can cause all sorts of memory corruption. You must strive to ensure that your add-ons are safe to Lua and provide good error handling.

As we discussed earlier, each C program has its own way to handle errors. When you write library functions for Lua, however, there is a standard way to handle errors. Whenever a C function detects an error, it simply calls lua_error, (or better yet luaL_error, which formats the error message and then calls lua_error). The lua_error function clears whatever needs to be cleared in Lua and jumps back to the lua_pcall that originated that execution, passing along the error message.