alecmce / xember

A riff on the Ember entity system
MIT License
48 stars 7 forks source link

Removing an entity when iterating over a family stops the iteration #11

Closed richardlord closed 13 years ago

richardlord commented 13 years ago

If you remove the current item from the list your iterating over, the iteration will stop because node.next will be null on the node just removed. This will happen, for example, in the asteroids example collision system when checking collisions on the bullets...

for (bullet = userBullets.head as BulletCollisionNode; bullet; bullet = bullet.next) { ... entityCreator.destroyEntity(bullet.entity); ... }

This can be solved in the game code by fetching the next node before processing the current one

for (bullet = userBullets.head as BulletCollisionNode; bullet; bullet = next) { next = bullet.next; ... entityCreator.destroyEntity(bullet.entity); ... }

but it would be better if the list could handle this itself. Although I don't yet have a clear idea how best to do this, the simplest option is not nulling the next and previous on the removed node, which feels messy but would do the job (importantly, the removed node is still free to be garbage collected when the currently executing code has finished with it).

alecmce commented 13 years ago

Good catch, thanks!

I'm inclined towards the simple solution that you suggest - that the node being removed doesn't have it's prev and next values cleared. I want to keep the logic as simple as possible within the loops as a more managed solution will impact loop performance.

richardlord commented 13 years ago

Sounds good to me.