使用自定义对函数迭代c中的lua表

use*_*195 6 c lua iterator

我想在lua-wiki网站上找到Ordered Table Simple示例.这是链接.

在Lua它用这个迭代很好:

for i,v in t:opairs() do
   print( i,v )
end
Run Code Online (Sandbox Code Playgroud)

而是在lua中迭代,我希望传递t给C方法并在那里迭代表.在C API中,我发现只有lua_next原始pairs迭代器.如何在C中迭代这个lua代码?

gre*_*olf 2

您可以做的是编写一个自定义nextC 函数,该函数模仿lua_next但在该有序表上运行,而不是使用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;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以在 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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我没有对此进行测试,但它应该可以工作。