I like to use extra properties for my display objects for keeping track of stats, and also for references to event listeners, timers, and maybe even other display objects.
For example:
[lua] enemy = display.newImageRect(“enemy.png”, 30, 60)
– touch handler
enemy.touch = enemyTouchHandler
enemy.touchListener = enemy:addEventListener( “touch”, enemy)
– timer for animation
enemy.animationTimer = timer.performWithDelay ( 500, function() return animateEnemy( enemy ) end, 0)
enemy.name = “enemy”
enemy.poweredUp = false
enemy.status = “alive”
enemy.type = “default”
enemy.speed = 25
enemy.health = 100[/lua]
When I want to destroy the enemy, I do the following:
- Cancel the timer and touch listener (although I don’t think I need to cancel the touch listener as it’s taken care of by removeSelf())
- use enemy:removeSelf(), then enemy = nil
So is the REFRERNCE to the timer removed? And are all my properties removed? I guess what I’m asking is if enemy.animationTimer is set to nil? What if my reference to the timer was one level deeper, like enemy.timers.animation?
Similarly, if I just have a table (that’s not a display object), I can’t use removeSelf(), so I just nil the table. When I nil a table, does it ALSO nil all its indexes (all the way down)? This is especially important if I use an index as a reference to a timer or display object…
[lua] table1 = {}
table1.timers = {}
table1.timers.name = “a table to hold the timers”
table1.timers.timer1 = timer.performWithDelay ( 500, doSomething, 0 )
timer.cancel (table1.timers.timer1) – timer is cancelled but memory isn’t freed since there’s still a reference to it
table1 = nil – does this also nil out table1.timers.name, and table1.timers.timer1?[/lua]
Does that last line above get rid of the name string and the timer reference, allowing those objects to be GC’ed? Or is the timer and the string still around, but now inaccessible, since I’ve eliminated the table1? I think the way GC in Lua works is that if there’s no way to reference it, then it’s GC’ed, but I always see examples of nilling the reference itself - never its “parent table” (or whatever you call that).
I suppose this question is even applicable to the following:
[lua]_G = nil – does this clear all global variables?[/lua]
[import]uid: 49372 topic_id: 9435 reply_id: 309435[/import]
But I would like to figure it out at some point.
[import]uid: 6175 topic_id: 9435 reply_id: 34712[/import]