我已经为这个简单的事情尝试了很多替代方案,但是无法让它发挥作用。我希望用户在第一步中从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)。任何想法都赞赏。
答案 0 :(得分:2)
您需要在lua_next(L,-2)
之后致电lua_pushnil(L)
。
您需要lua_next
,因为显然您不知道表格中的密钥。因此,您必须使用表遍历协议,即推送表,推送nil,调用lua_next(L,-2)
,并获取堆栈上的键和值。这是有效的,因为该表只包含一对。
如果您知道表格中的密钥,则可以调用lua_gettable
或lua_getfield
,而无需拨打lua_next
和lua_pushnil
。