Object removal and destruction
Posted: Wed Jan 02, 2013 3:41 am
Hello guys, and happy new year!
I'm wondering if my method for removing inactive entities (e.g. enemies) is enough for destroying the actual object and deallocating it from memory, I would like any advice on this, if possible.
This is my current approach:
Every object is described as a SECS class, with the usual init(), update() and draw() functions/methods. Every object has an “active” property, defined as a “self.active” boolean variable inside the init block:
Filename: grumpyEnemy.lua
So far so good, once the appropriate conditions are met, the object may be “inactive”, setting self.active = false, and it now must be destroyed. This step is basically the marking of an entity to be soon destroyed.
In the case of my enemies, all my “enemies” instances are stored inside an “enemies” table, managed directly in my level class. I loop through all my level objects in the update cycle. When I dispose of an object, I first check its active status and, if set to false, I proceed to remove it from the corresponding table :
Filename: level.lua
And that's all, so far it seems to be working, but I'm not entirely sure if that's a good approach to be removing objects. Do you think I'm doing nonsense?
Thanks for your time!
I'm wondering if my method for removing inactive entities (e.g. enemies) is enough for destroying the actual object and deallocating it from memory, I would like any advice on this, if possible.
This is my current approach:
Every object is described as a SECS class, with the usual init(), update() and draw() functions/methods. Every object has an “active” property, defined as a “self.active” boolean variable inside the init block:
Filename: grumpyEnemy.lua
Code: Select all
…
function grumpyEnemy:init(x, y)
self.x = x
self.y = y
self.active = true
…
end
…
In the case of my enemies, all my “enemies” instances are stored inside an “enemies” table, managed directly in my level class. I loop through all my level objects in the update cycle. When I dispose of an object, I first check its active status and, if set to false, I proceed to remove it from the corresponding table :
Filename: level.lua
Code: Select all
…
function level:init()
self.enemies = {}
--this level currently has only one grumpy enemy:
self.enemies[1] = grumpyEnemy:new(100,100)
end
function level:update(dt)
-- I will loop through all the level tables and update each object as necessary:
for k,v in pairs(self) do
for i = 1, #v do
-- update each object:
if v[i].update then
v[i]:update(dt)
-- now, if the object is inactive, remove it from the object table:
if (v[i].active == false) then
table.remove(v, i)
end
end
end
end
end
…
Thanks for your time!