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.


27.3 – Storing State in C Functions

Frequently, C functions need to keep some non-local data, that is, data that outlive their invocation. In C, we typically use global or static variables for that need. When you are programming library functions for Lua, however, global and static variables are not a good approach. First, you cannot store a generic Lua value in a C variable. Second, a library that uses such variables cannot be used in multiple Lua states.

An alternative approach is to store such values into Lua global variables. This approach solves the two previous problems. Lua global variables store any Lua value and each independent state has its own independent set of global variables. However, this is not always a satisfactory solution, because Lua code can tamper with those global variables and therefore compromise the integrity of C data. To avoid this problem, Lua offers a separate table, called the registry, that C code can freely use, but Lua code cannot access.