3.4 – Querying the Stack
To check the type of a stack element, the following functions are available:
- int lua_type (lua_State *L, int index);
- int lua_isnil (lua_State *L, int index);
- int lua_isboolean (lua_State *L, int index);
- int lua_isnumber (lua_State *L, int index);
- int lua_isstring (lua_State *L, int index);
- int lua_istable (lua_State *L, int index);
- int lua_isfunction (lua_State *L, int index);
- int lua_iscfunction (lua_State *L, int index);
- int lua_isuserdata (lua_State *L, int index);
- int lua_islightuserdata (lua_State *L, int index);
These functions can be called with any acceptable index.
lua_type
returns the type of a value in the stack, or LUA_TNONE
for a non-valid index (that is, if that stack position is “empty”). The types returned by lua_type
are coded by the following constants defined in lua.h
: LUA_TNIL
, LUA_TNUMBER
, LUA_TBOOLEAN
, LUA_TSTRING
, LUA_TTABLE
, LUA_TFUNCTION
, LUA_TUSERDATA
, LUA_TTHREAD
, LUA_TLIGHTUSERDATA
. The following function translates these constants to strings:
- const char *lua_typename (lua_State *L, int type);
The lua_is*
functions return 1 if the object is compatible with the given type, and 0 otherwise. lua_isboolean
is an exception to this rule: It succeeds only for boolean values (otherwise it would be useless, as any value has a boolean value). They always return 0 for a non-valid index. lua_isnumber
accepts numbers and numerical strings; lua_isstring
accepts strings and numbers (see 2.2.1); lua_isfunction
accepts both Lua functions and C functions; and lua_isuserdata
accepts both full and light userdata. To distinguish between Lua functions and C functions, you can use lua_iscfunction
. To distinguish between full and light userdata, you can use lua_islightuserdata
. To distinguish between numbers and numerical strings, you can use lua_type
.
The API also contains functions to compare two values in the stack:
- int lua_equal (lua_State *L, int index1, int index2);
- int lua_rawequal (lua_State *L, int index1, int index2);
- int lua_lessthan (lua_State *L, int index1, int index2);
lua_equal
and lua_lessthan
are equivalent to their counterparts in Lua (see 2.5.2). lua_rawequal
compares the values for primitive equality, without metamethods. These functions return 0 (false) if any of the indices are non-valid.