我想使用Ordered Table简单示例,我在lua-wiki网站上找到了。这是the link。
在Lua中,迭代很好:
for i,v in t:opairs() do
print( i,v )
end
而是在lua中迭代,我希望将t
传递给C方法并在那里迭代表。在C API中,我发现原始lua_next
迭代器只有pairs
。如何在C中迭代这个lua代码?
答案 0 :(得分:2)
您可以做的是编写一个模仿next
的自定义lua_next
C函数,但在该有序表上工作,而不是使用opairs
方法。
int luaL_orderednext(luaState *L)
{
luaL_checkany(L, -1); // previous key
luaL_checktype(L, -2, LUA_TTABLE); // self
luaL_checktype(L, -3, LUA_TFUNCTION); // iterator
lua_pop(L, 1); // pop the key since
// opair doesn't use it
// iter(self)
lua_pushvalue(L, -2);
lua_pushvalue(L, -2);
lua_call(L, 1, 2);
if(lua_isnil(L, -2))
{
lua_pop(L, 2);
return 0;
}
return 2;
}
然后,您可以在C中使用它,类似于lua_next
:
int orderedtraverse(luaState *L)
{
lua_settop(L, 1);
luaL_checktype(L, 1, LUA_TTABLE);
// t:opairs()
lua_getfield(L, 1, "opairs");
lua_pushvalue(L, -2);
lua_call(L, 1, 2);
// iter, self (t), nil
for(lua_pushnil(L); luaL_orderednext(L); lua_pop(L, 1))
{
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
}
return 0;
}
注意,我没有对此进行测试,但它应该可以正常工作。