首页 > 解决方案 > 使用 LuaBridge 从 Lua 迭代 C 数组类型的容器类

问题描述

这可能是一个新手问题,但我无法通过网络搜索找到答案,甚至可以帮助我入门。我有一个容器类,它本质上是一个 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++lualuabridge

解决方案


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

为了完成我最初的要求,我们假设我们已经使用luamyArray中的表格或您喜欢的任何界面提供。(这可能需要一个包装类。)您在 Lua 中完全实现了我所要求的内容,如下所示。(这几乎是Lua 文档中的一个示例,但不知何故我之前错过了它。)my_arrayLuaBridge

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"
);

推荐阅读