4

I have tried many alternatives for this simple thing but could not get it work. I want user to define a table from Lua in the 1st step:

a={["something"]=10} -- key=something, value=10

Then, in the second step the user will call from Lua a function designed in C++:

b=afunction(a) -- afunction will be designed in C++

The C++ code:

int lua_afunction(lua_State* L)
{

   int nargs = lua_gettop(L);
   if(nargs>1) throw "ERROR: Only 1 argument in the form of table must be supplied.";
   int type = lua_type(L, 1);
   if(type!=LUA_TTABLE) throw "ERROR: Argument must be a table";
   //Until here it works as expected
   lua_pushnil(L); //does not work with or without this line
   const char* key=lua_tostring(L,-2);
   double val=lua_tonumber(L,-1);

   return 0;
}

As evidenced from the code lua_type(L,1) the bottom of the stack is the table itself. I was assuming on top of the table, the key will reside and on its top the value. So the height of the stack is 3 with idx=-1 the value, idx=-2 the key. However, it seems that I can neither read the key ("something") nor the value (10). Any ideas appreciated.

macroland
  • 973
  • 9
  • 27

1 Answers1

2

You need to call lua_next(L,-2) after lua_pushnil(L).

You need lua_next because apparently you don't know the key in the table. So you have to use the table traversal protocol, which is to push the table, push nil, call lua_next(L,-2), and get the key and value on the stack. This works because the table contains only one pair.

If you knew the key in the table, you could just have called lua_gettable or lua_getfield, without calling lua_next and lua_pushnil.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • It works! However, I am not sure I understand the logic behind `lua_pushnil(L)` and then calling `lua_next(L,-2)`. Apparently the table when `lua_pushnil(L)` is called stays where it is (bottom of stack) and now we have a null element, so stack height is 2. What does `lua_next` do? – macroland Jun 17 '15 at 10:57