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.1 – The Registry

The registry is always located at a pseudo-index, whose value is defined by LUA_REGISTRYINDEX. A pseudo-index is like an index into the stack, except that its associated value is not in the stack. Most functions in the Lua API that accept indices as arguments also accept pseudo-indices---the exceptions being those functions that manipulate the stack itself, such as lua_remove and lua_insert. For instance, to get a value stored with key "Key" in the registry, you can use the following code:

    lua_pushstring(L, "Key");
    lua_gettable(L, LUA_REGISTRYINDEX);

The registry is a regular Lua table. As such, you can index it with any Lua value but nil. However, because all C libraries share the same registry, you must choose with care what values you use as keys, to avoid collisions. A bulletproof method is to use as key the address of a static variable in your code: The C link editor ensures that this key is unique among all libraries. To use this option, you need the function lua_pushlightuserdata, which pushes on the Lua stack a value representing a C pointer. The following code shows how to store and retrieve a number from the registry using this method:

    /* variable with an unique address */
    static const char Key = 'k';
    
    /* store a number */
    lua_pushlightuserdata(L, (void *)&Key);  /* push address */
    lua_pushnumber(L, myNumber);  /* push value */
    /* registry[&Key] = myNumber */
    lua_settable(L, LUA_REGISTRYINDEX);
    
    /* retrieve a number */
    lua_pushlightuserdata(L, (void *)&Key);  /* push address */
    lua_gettable(L, LUA_REGISTRYINDEX);  /* retrieve value */
    myNumber = lua_tonumber(L, -1);  /* convert to number */
We will discuss light userdata in more detail in Section 28.5.

Of course, you can also use strings as keys into the registry, as long as you choose unique names. String keys are particularly useful when you want to allow other independent libraries to access your data, because all they need to know is the key name. For such keys, there is no bulletproof method of choosing names, but there are some good practices, such as avoiding common names and prefixing your names with the library name or something like it. Prefixes like lua or lualib are not good choices. Another option is to use a universal unique identifier (uuid), as most systems now have programs to generate such identifiers (e.g., uuidgen in Linux). An uuid is a 128-bit number (written in hexadecimal to form a string) that is generated by a combination of the host IP address, a time stamp, and a random component, so that it is assuredly different from any other uuid.