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.2.1 – Pushing Elements

The API has one push function for each Lua type that can be represented in C: lua_pushnil for the constant nil, lua_pushnumber for numbers (double), lua_pushboolean for booleans (integers, in C), lua_pushlstring for arbitrary strings (char *), and lua_pushstring for zero-terminated strings:

    void lua_pushnil (lua_State *L);
    void lua_pushboolean (lua_State *L, int bool);
    void lua_pushnumber (lua_State *L, double n);
    void lua_pushlstring (lua_State *L, const char *s,
                                        size_t length);
    void lua_pushstring (lua_State *L, const char *s);
There are also functions to push C functions and userdata values on the stack; we will discuss them later.

Strings in Lua are not zero-terminated; in consequence, they can contain arbitrary binary data and rely on an explicit length. The official function to push a string onto the stack is lua_pushlstring, which requires an explicit length as an argument. For zero-terminated strings, you can use also lua_pushstring, which uses strlen to supply the string length. Lua never keeps pointers to external strings (or to any other object, except to C functions, which are always static). For any string that it has to keep, Lua either makes an internal copy or reuses one. Therefore, you can free or modify your buffer as soon as these functions return.

Whenever you push an element onto the stack, it is your responsibility to ensure that the stack has space for it. Remember, you are a C programmer now; Lua will not spoil you. When Lua starts and any time that Lua calls C, the stack has at least 20 free slots (this constant is defined as LUA_MINSTACK in lua.h). This is more than enough for most common uses, so usually we do not even think about that. However, some tasks may need more stack space (e.g., for calling a function with a variable number of arguments). In such cases, you may want to call

    int lua_checkstack (lua_State *L, int sz);
which checks whether the stack has enough space for your needs. (More about that later.)