In my Spacewar game, I have a table of flying objects. In one of the implementations, I add objects when they are born (like bullets or debris) and remove them when they die. (The other implementation has a fixed number of objects but I don’t like that.)
To add, I do
FlyingObjects[newObj] = newObj and to remove,
FlyingObjects[deadObj] = nil.
This lets me do things like:
for _,ship in FlyingObjects do draw(ship) end, which seems pretty clean to me.
Is there some better idiom for tables subject to adding and removing?
That looks pretty good to me, and I think that’s how most of us implement dynamic numbers of objects.
If any of them are physics objects, be sure to destroy them first (use the destroy command on the physics object) before removing them from the table, otherwise they will remain alive as invisible “zombie” objects that interact with your live objects, until the next garbage collection, as much as a minute later.
Yep, very much the pattern i do. much easier to just nil them and they dissappear from a for k,v in pairs(table). You don’t want to get into ipairs(table) and numbering the items becuase then you have to manage the cleanup more.
yep, if the items are numbered, you have to loop backwards to avoid reindexing problems
Yay, thanks, doing something right!