【问题标题】:Lua - decrementing "class" object count when object is removed from memoryLua - 从内存中删除对象时减少“类”对象计数
【发布时间】:2013-03-14 17:51:19
【问题描述】:

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

对于此事的任何帮助或建议将不胜感激。谢谢!

【问题讨论】:

    标签: lua destructor counter moai


    【解决方案1】:

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

    【讨论】:

    • 我不认为这将在 MOAI 中工作,因为它使用 Lua 5.1。 debugnewproxy 也不可用。
    • @finnw,你是对的,如果对象是纯 Lua 表,那么就没有办法获得 gc 通知。我以为它们是用 C 语言创建的用户数据。
    【解决方案2】:

    也许弱表是您的答案,嵌套。这是一个sn-p:

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多