If I'm understanding correctly, it seems it goes like this:
Let's assume ring
variable at that point looks like this:
[ foo, bar, buzz ]
foo
has index 0, bar
index 1, buzz
index 2.
Now, let's say we want to remove foo
and buzz
, so we get their indexes, 0 and 2 respectively. (That's what you store in toRemoveFromRing
)
We do ring.remove(0)
to remove foo
.
Now ring
looks like this:
[ bar, buzz ]
And now we want to remove buzz
, which had index 2, so we would do ring.remove(2)
. But now buzz
is actually at index 1, and index 2 is out of bounds. All that because when we removed an element in "moved" other elements that were after that one index lower.
There are two solutions that come to my mind:
1. Store objects to be removed instead of indexes and use .erase()
. It most of the time works the way you want, but you need to remember that it removes the first occurrence of the item from the array. So if you have var arr = [ foo, bar, buzz, foo ]
and do arr.erase(foo)
it would result in [ bar, buzz, foo]
. Which might not always be what you wanted.
2. Instead of removing from the old array, make a new one with only the things you need. Code would look like this:
var new_ring = []
for i in range(ring.size()):
ringDist = GLOBALS.hex_dist(ring[i], initial)
if ringDist > radius:
new_ring.append(ring[i])
ring = new_ring
Not sure which one is more optimal, I'd guess they are similar.
There's probably a better way to do this, but that's what I've come up with and it should work (I haven't tested this particular code though).
Hope this helps!