【问题标题】:Iterating C array-type container class from Lua using LuaBridge使用 LuaBridge 从 Lua 迭代 C 数组类型的容器类
【发布时间】:2021-11-25 17:52:23
【问题描述】:

这可能是一个新手问题,但我无法通过网络搜索找到答案,甚至可以帮助我入门。我有一个容器类,它本质上是一个 C 风格的数组。为简单起见,我们将其描述为:

int *myArray = new int[mySize];

有了LuaBridge,我们可以假设我已经在全局命名空间中成功地将它注册为my_array。我想像这样从 Lua 迭代它:

for n in each(my_array) do
   ... -- do something with n
end

我猜我可能需要在全局命名空间中注册一个函数each。问题是,我不知道那个函数在 C++ 中应该是什么样子。

<return-type> DoForEach (<function-signature that includes luabridge::LuaRef>)
{
   // execute callback using luabridge::LuaRef, which I think I know how to do

   return <return-type>; //what do I return here?
}

如果代码使用了std::vector,这可能会更容易,但我正在尝试为现有的代码库创建一个 Lua 接口,该接口很难更改。

【问题讨论】:

    标签: c++ lua luabridge


    【解决方案1】:

    我正在回答我自己的问题,因为我发现这个问题做出了一些不正确的假设。我正在使用的现有代码是用 c++ 实现的 true iterator class(在 Lua 文档中就是这样称呼的)。这些不能与 for 循环一起使用,但这就是您在 c++ 中获得回调函数的方式。

    按照我最初的要求,我们假设我们已经使用LuaBridge 或您喜欢的任何接口在lua 中将myArray 用作表my_array。 (这可能需要一个包装类。)您在 Lua 中完全实现了我所要求的内容,如下所示。 (这几乎完全是an example in the Lua documentation,但不知何故我之前错过了它。)

    function each (t)
       local i = 0
       local n = table.getn(t)
       return function ()
                i = i + 1
                if i <= n then return t[i] end
              end
    end
    
    --my_array is a table linked to C++ myArray
    --this can be done with a wrapper class if necessary
    for n in each(my_array) do
       ... -- do something with n
    end
    

    如果您想为您运行的每个脚本提供each 函数,请在执行脚本之前直接从 C++ 中添加它,如下所示。

    luaL_dostring(l,
       "function each (t)" "\n"
          "local i = 0" "\n"
          "local n = table.getn(t)" "\n"
          "return function ()" "\n"
          "   i = i + 1" "\n"
          "   if i <= n then return t[i] end" "\n"
          "end" "\n"
       "end"
    );
    

    【讨论】:

      猜你喜欢
      • 2015-02-12
      • 1970-01-01
      • 2021-12-02
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2016-05-09
      • 2023-03-04
      相关资源
      最近更新 更多