Reputation: 1030
In lua, it's legal to do this :
table={}
bar
if(table[key]==nil) then
foo
However, using C API, I couldn't find way to check if there's a nil value on the specified position.
lua_getglobal(L,"table");
lua_gettable(L,key);
If there's a nil value stored in table[key], lua_gettable would give me the "unprotected error in call to Lua API (attempt to index a nil value)" message.
Is there any way to check if there's actually something associated with that key, before actually pushing the key to do so ?
Upvotes: 3
Views: 2045
Reputation: 110069
You're 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 to lua_gettable
is the stack index to the table, not the key.
If the key is a string, you can call lua_getfield
instead:
lua_getglobal(L, "tableVar");
lua_getfield(L, -1, key);
Upvotes: 4