PackerMan wrote: ↑Thu Dec 10, 2020 4:18 am
But looping backwards will result in a nil loop whenever a bullet dies, right?? Since the end of the table is moving faster than the counter.
It isn't moving faster. At most it's moving at exactly the same speed.
Imagine you have bullets b1, b2, b3, b4 and b5, in positions 1, 2, 3, 4 and 5 respectively. Say you had to remove all except 5. Then you would have this:
- i = 5. Bullet b5 is checked, it does not need to be deleted.
- i = 4. Bullet b4 is checked, it needs to be deleted. You delete position 4, so the array becomes: 1:b1, 2:b2, 3:b3, 4:b5.
- i = 3. Bullet b3 is checked, it needs to be deleted. You delete position 3, so the array becomes: 1:b1, 2:b2, 3:b5.
- i = 2. Bullet b2 is checked, it needs to be deleted. You delete position 2, so the array becomes: 1:b1, 2:b5.
- i = 1. Bullet b1 is checked, it needs to be deleted. You delete position 1, so the array becomes: 1:b5.
And everyone is happy.
Notice that every time you delete a bullet, all bullets
after it are scrolled/shifted, but the ones you will check next are the bullets
before that one, so you're safe.
PackerMan wrote: ↑Thu Dec 10, 2020 4:18 am
Edit: First I tried the "in place" solution of decrementing i by one everytime a bullet is removed, didn't work. I tried the reverse for loop and it threw me an error about trying to call something with number on the for loop line. So I went with the while loop and it made the gameplay looks clean.
It's weird that looping backwards didn't work. Looping backwards has one more advantage: the length of the table is only calculated once. With the while method, it's calculated as many times as there are elements in the table. I mentioned it because sometimes, order is important, and looping backwards is not viable. In these cases, the while method can be used.
Edit: Ok, I made a typo, I wrote "for i in #bullets, 1, -1" and I should have written "for i = #bullets, 1, -1" (i.e. with "=" instead of "in"). That would explain the error. I've fixed it above.