tags:

views:

123

answers:

1

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 ?

+2  A: 

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);
interjay
Gah.I guess it's time to sleep. Thanks for reminding how to use it.
felace