Wednesday, January 20, 2010

Storing State in C Functions













Programming in Lua
Part IV. The C API
            
Chapter 27. Techniques for Writing C Functions



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.










Programming in Lua



No comments: