6

我想使用我在 lua-wiki 站点上找到的 Ordered Table Simple 示例。这是链接

在 Lua 中,它可以很好地迭代:

for i,v in t:opairs() do
   print( i,v )
end

而不是在lua中迭代,我想传递t给一个C方法并在那里迭代表。在 C API 中,我只找到lua_next了原始pairs迭代器。如何在 C 中迭代此 lua 代码?

4

1 回答 1

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

然后,您可以在 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;
}

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

于 2013-08-21T20:23:05.413 回答