Lua - 当从内存中删除对象时递减“类”对象计数

时间:2013-03-14 17:51:19

标签: lua destructor counter moai

我目前正在使用Lua开展MOAI项目。我试图为一些游戏对象设置一些压力测试,然后跟踪我在游戏会话期间创建和销毁我拥有的Lua对象。我可以轻松地跟踪“类”对象/表的何时通过在构造函数或初始化程序中递增计数来初始化。但是,因为Lua没有析构函数,所以我不确定如何从内存中删除对象时如何跟踪。

非常感谢有关此事的任何帮助或建议。谢谢!

2 个答案:

答案 0 :(得分:2)

要在Lua对象(我假设完整的用户数据或表格)消失时收到通知,请为其设置_gc metamethod

答案 1 :(得分:1)

也许弱表是你的答案,有嵌套。这是一个片段:

objectArray={}

function newObj(...)
   --your OOP code here
   --obj is the new table you made
   objectArray[#objectArray+1]=setmetatable({obj},{__mode='v'})
end

现在,在每个帧运行的函数/块中:

for i=1,#objectArray do --no pairs for efficiency, being run every frame this matters
   local stillThere=#objectArray[i]
   stillThere=stillThere==1
   if not stillThere then deconstruct() end
end

不幸的是,你无法取回桌面。我不确定是否有一个简单的解决方案,因为__index会停止GC。