Storing information for later use

The problem

Let’s say you’d like to store some information in Lua for later use. As we’ve discussed in this post everything in lua has to go on the Lua state and thus on the stack somehow: If it’s not on the stack it doesn’t exit. So how can you push information on that stack so that it can be retrieved easily for use at any later point in time? (If you already know when you’re going to use it then the answer is trivial: Push the value on the stack and adjust it properly so you know where the information is at the time you need it.)

A solution

As it turns out there’s two general approaches to this problem:

  1. Push the information into the globals table where it is visible for all and anyone. Doing that is fairly easy: Define a global variable and assign a non-nil value to it.

    like (in Lua):

    foo = "bar"
    

    or (in C):

    lua_pushstring (L, "bar");
    lua_setglobal (L, "foo");
    

    Of course there’s one huge catch doing so: It must have a regular string as key and is fully visible and open to manipulation for any part of the programm which has access to this stack.

  2. Push the information on the registry. Like the globals table, the registry is a special (and in this case hidden) table allowing to store information for later use. For the registry there’s no limitation on what the key might be and in fact in order to avoid conflicts the Lua people suggest to use some unique information only the relevant part of program knows as a key, like the address of a static variable in C.

    To set a new entry in the registry you might use something along the lines of:

    lua_pushstring (L, "foo");
    lua_pushstring  (L, "bar");
    lua_settable (L, LUA_REGISTRYINDEX);
    

    And to retrieve it:

    lua_pushstring (L, "foo");
    lua_gettable (L, LUA_REGISTRYINDEX);
    /* index -1 now contains the string "bar" */
    

In closing

In a future post I’m going to extend on the potential uses of this storage. Especially in cooperation the the thread cloning mentioned in this post this allows for some nice possibilites…

Until then, take care.