3.5 – Getting Values from the Stack
To translate a value in the stack to a specific C type, you can use the following conversion functions:
- int lua_toboolean (lua_State *L, int index);
- lua_Number lua_tonumber (lua_State *L, int index);
- const char *lua_tostring (lua_State *L, int index);
- size_t lua_strlen (lua_State *L, int index);
- lua_CFunction lua_tocfunction (lua_State *L, int index);
- void *lua_touserdata (lua_State *L, int index);
- lua_State *lua_tothread (lua_State *L, int index);
- void *lua_topointer (lua_State *L, int index);
These functions can be called with any acceptable index. When called with a non-valid index, they act as if the given value had an incorrect type.
lua_toboolean
converts the Lua value at the given index to a C “boolean” value (0 or 1). Like all tests in Lua, lua_toboolean
returns 1 for any Lua value different from false and nil; otherwise it returns 0. It also returns 0 when called with a non-valid index. (If you want to accept only real boolean values, use lua_isboolean
to test the type of the value.)
lua_tonumber
converts the Lua value at the given index to a number (by default, lua_Number
is double
). The Lua value must be a number or a string convertible to number (see 2.2.1); otherwise, lua_tonumber
returns 0.
lua_tostring
converts the Lua value at the given index to a string (const char*
). The Lua value must be a string or a number; otherwise, the function returns NULL
. If the value is a number, then lua_tostring
also changes the actual value in the stack to a string. (This change confuses lua_next
when lua_tostring
is applied to keys.) lua_tostring
returns a fully aligned pointer to a string inside the Lua state. This string always has a zero ('\0'
) after its last character (as in C), but may contain other zeros in its body. If you do not know whether a string may contain zeros, you can use lua_strlen
to get its actual length. Because Lua has garbage collection, there is no guarantee that the pointer returned by lua_tostring
will be valid after the corresponding value is removed from the stack. If you need the string after the current function returns, then you should duplicate it or put it into the registry (see 3.18).
lua_tocfunction
converts a value in the stack to a C function. This value must be a C function; otherwise, lua_tocfunction
returns NULL
. The type lua_CFunction
is explained in 3.16.
lua_tothread
converts a value in the stack to a Lua thread (represented as lua_State *
). This value must be a thread; otherwise, lua_tothread
returns NULL
.
lua_topointer
converts a value in the stack to a generic C pointer (void *
). The value may be a userdata, a table, a thread, or a function; otherwise, lua_topointer
returns NULL
. Lua ensures that different objects of the same type return different pointers. There is no direct way to convert the pointer back to its original value. Typically this function is used for debug information.
lua_touserdata
is explained in 3.8.