c++ - 使用 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++ 实现的真正的迭代器类(在 Lua 文档中称为它)。这些不能与 for 循环一起使用,但这就是您在 c++ 中获得回调函数的方式。
为了完成我最初的要求,我们假设我们已经使用luamyArray
中的表格或您喜欢的任何界面提供。(这可能需要一个包装类。)您在 Lua 中完全实现了我所要求的内容,如下所示。(这几乎是Lua 文档中的一个示例,但不知何故我之前错过了它。)my_array
LuaBridge
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"
);
推荐阅读
- reactjs - 使用 React JS 中的钩子未按时在状态上设置数据
- python - 如何管理过时的 websocket 连接
- python - Pyinstaller pygame.mixer 不播放 mp3 文件?
- javascript - 我需要在 angular 的 http get 请求中传递一个 x 授权令牌
- python - 课堂 API / Python:invitation().delete 方法不起作用
- extjs - 有没有办法为特定的 xtypes/容器创建控制器?
- javascript - 无效的挂钩调用错误:适用于 localhost 但不适用于 Jest
- javascript - 为什么 alert() 函数的行为如此奇怪?
- laravel - Laravel 在 url 中传递多个参数并取特定参数
- java - Glacier Class Immutable Checker 不适用于 Checker Framework 3.6.0