[英]Iterating C array-type container class from Lua using LuaBridge
这可能是一个新手问题,但我无法通过 web 搜索找到甚至可以帮助我入门的答案。 我有一个容器 class,它本质上是一个 C 风格的数组。 为简单起见,我们将其描述为:
int *myArray = new int[mySize];
使用LuaBridge
,我们可以假设我已经在全局命名空间中成功地将它注册为my_array
。 我想从 Lua 像这样迭代它:
for n in each(my_array) do
... -- do something with n
end
我猜我可能需要在全局命名空间中each
注册一个 function。 问题是,我不知道 function 在 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++ 中实现的真正的迭代器 class (在 Lua 文档中称为它)。这些不能与 for 循环一起使用,但这就是您在 c++ 中获得回调 function 的方式。
为了完成我最初的要求,我们假设我们已经使用LuaBridge
或您喜欢的任何接口使myArray
在 lua 中作为表my_array
可用。 (这可能需要包装器 class。)您按如下方式完全实现我在 Lua 中提出的要求。 (这几乎完全是 Lua 文档中的示例,但不知何故我之前错过了它。)
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
function,你可以在执行脚本之前直接从 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"
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.