这可能是一个新手问题,但我还没有找到一个网络搜索的答案,甚至可以帮助我开始。我有一个容器类,它的核心是一个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接口,该接口很难更改。
发布于 2021-10-06 16:08:46
我在回答我自己的问题,因为我发现这个问题做了一些不正确的假设。我使用的现有代码是一个在c++中实现的true iterator class (在Lua文档中是这样叫的)。这些函数不能与for循环一起使用,但这是在c++中获取回调函数的方式。
为了满足我最初的要求,我们假设已经在lua中使用LuaBridge或任何您喜欢的接口将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"
);https://stackoverflow.com/questions/69450654
复制相似问题