3.6 – Pushing Values onto the Stack
The API has the following functions to push C values onto the stack:
- void lua_pushboolean (lua_State *L, int b);
- void lua_pushnumber (lua_State *L, lua_Number n);
- void lua_pushlstring (lua_State *L, const char *s, size_t len);
- void lua_pushstring (lua_State *L, const char *s);
- void lua_pushnil (lua_State *L);
- void lua_pushcfunction (lua_State *L, lua_CFunction f);
- void lua_pushlightuserdata (lua_State *L, void *p);
These functions receive a C value, convert it to a corresponding Lua value, and push the result onto the stack. In particular, lua_pushlstring
and lua_pushstring
make an internal copy of the given string. lua_pushstring
can only be used to push proper C strings (that is, strings that end with a zero and do not contain embedded zeros); otherwise, you should use the more general lua_pushlstring
, which accepts an explicit size.
You can also push “formatted” strings:
- const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
- const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);
These functions push onto the stack a formatted string and return a pointer to that string. They are similar to sprintf
and vsprintf
, but with some important differences:
- You do not have to allocate the space for the result: The result is a Lua string and Lua takes care of memory allocation (and deallocation, through garbage collection).
- The conversion specifiers are quite restricted. There are no flags, widths, or precisions. The conversion specifiers can be simply `
%%
´ (inserts a `%
´ in the string), `%s
´ (inserts a zero-terminated string, with no size restrictions), `%f
´ (inserts alua_Number
), `%d
´ (inserts anint
), and `%c
´ (inserts anint
as a character).
The function
- void lua_concat (lua_State *L, int n);
concatenates the n
values at the top of the stack, pops them, and leaves the result at the top. If n
is 1, the result is that single string (that is, the function does nothing); if n
is 0, the result is the empty string. Concatenation is done following the usual semantics of Lua (see 2.5.4).