[英]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.