从C ++中读取Lua表格

我已经尝试过许多替代方法来完成这件简单的事情,但无法工作。我希望用户在第一步中从Lua中定义表格:

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

然后,在第二步中,用户将从Lua中调用一个在C++中设计的函数:

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

C++代码:

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;
}

从代码中可以看出,lua_type(L,1) 底部是表本身。我假设在表的顶部,键将驻留在其上,值将位于其上。因此,堆栈的高度为3,其中 idx=-1 为值,idx=-2 为键。然而,似乎我既不能读取键(“something”)也不能读取值(10)。任何想法都很受欢迎。

点赞
用户107090
用户107090

你需要在lua_pushnil(L)之后调用lua_next(L,-2)

你需要使用lua_next是因为显然你不知道表中的键。因此,你必须使用表遍历协议,先是推入表,再是推入nil,接着是调用lua_next(L,-2),最后获取栈中的键和值。这会成功,因为表中只有一对键和值。

如果你知道表中的键,你可以直接调用lua_gettablelua_getfield,而不需要调用lua_nextlua_pushnil

2015-06-17 10:20:42