2

I'm currently working on a MOAI project using Lua. I"m trying to set up some stress tests for some of the game objects, and in turn tracking when the Lua objects I have are created and destroyed during a game session. I can easily track when an "class" object/table has been initialized by incrementing the count in the constructor or initializer. However, because Lua does not have destructors, I'm not sure how I can track when an object has been removed from memory.

Would appreciate any help or suggestions on this matter. Thanks!

finnw
  • 47,861
  • 24
  • 143
  • 221
user695624
  • 123
  • 1
  • 8

2 Answers2

2

To be notified when a Lua object (I assume full userdata or table) is gone, you set a _gc metamethod for it.

hugomg
  • 68,213
  • 24
  • 160
  • 246
lhf
  • 70,581
  • 9
  • 108
  • 149
  • 1
    I don't think this will work in MOAI as it uses Lua 5.1. Also `debug` and `newproxy` are not available. – finnw Mar 14 '13 at 23:24
  • @finnw, you're right, if the objects are pure Lua tables, then there is no way to get gc notifications. I thought they were userdata created in C. – lhf Mar 15 '13 at 00:30
1

Perhaps weak tables is your answer, with nesting. Here's a snippet:

objectArray={}

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

Now, in a function/block that runs every frame:

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

Unfortunately, you can't get the table back. I'm not sure if there's an easy solution to this, because __index halts GC.

LuaWeaver
  • 316
  • 2
  • 8