Lua: How to check if one of the values ​​associated with a specified table key from api

In lua, it is legal to do this:

table={}
bar
if(table[key]==nil) then
foo

      

However, using the C API, I could not find a way to check if the nil value is not at the specified position.

lua_getglobal(L,"table");
lua_gettable(L,key);

      

If the nil value is stored in the [key] table, lua_gettable will give me an "unprotected error when calling the Lua API (attempting to index the nil value)".

Is there a way to check if something is really related to this key before actually pressing a key for it?

+2


a source to share


1 answer


You are calling lua_gettable

wrong. It should be:

lua_getglobal(L, "tableVar");
lua_pushstring(L, key);   //assuming key is a string
lua_gettable(L, -2);

      

The second parameter lua_gettable

is the stack index into the table, not the key.



If the key is a string, you can call instead lua_getfield

:

lua_getglobal(L, "tableVar");
lua_getfield(L, -1, key);

      

+3


a source







All Articles