Reading Lua table from C ++

I tried many alternatives for this simple thing, but couldn't make it work. I want the user to define a table from Lua in the first step:

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

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

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

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 you can see from the code lua_type(L,1), the bottom of the stack is the table itself. I took over the table, the key will be located at the top of the value. Thus, the stack height is 3 with idx = -1 value, idx = -2 key. However, it seems that I can neither read the key ("something") nor the value (10). Any ideas appreciated.

+4
source share
1 answer

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

lua_next, , , . , , , nil, lua_next(L,-2) . , .

, lua_gettable lua_getfield, lua_next lua_pushnil.

+2

All Articles