使用lubridge从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++中获得回调函数的方式。

做我最初问,我们假设myArray提供如表my_array在lua中使用LuaBridge或你喜欢哪个接口。(这可能需要一个包装器类。)你完全在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函数,您可以在执行脚本之前直接从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"
);

最新更新