我已经为这个简单的东西尝试了许多替代方法,但是无法使其正常工作。我希望用户在第一步中从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为键。但是,似乎我既无法读取键(“某物”),也无法读取值(10)。任何想法表示赞赏。
您需要在lua_next(L,-2)
之后致电lua_pushnil(L)
。
您需lua_next
要这样做,因为显然您不知道表中的键。因此,您必须使用表遍历协议,该协议用于推表,推nil,calllua_next(L,-2)
并获取堆栈上的键和值。这是可行的,因为该表仅包含一对。
如果您知道表中的键,则可以只调用lua_gettable
or lua_getfield
,而无需调用lua_next
and lua_pushnil
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句