【问题标题】:Iterate a lua table in c with a custom pair function使用自定义对函数迭代 c 中的 lua 表
【发布时间】:2013-08-21 08:59:13
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c lua iterator


    【解决方案1】:

    您可以做的是编写一个自定义的 next C 函数,该函数模仿 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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2019-02-20
      相关资源
      最近更新 更多