← Pixel Dreamer Studio

Remove items from an Array while checking them, without skipping any

Loop over the indexes from the end, or build a new array with filter().

Removing an item moves every item after it one place forward, but the loop still steps on to the next position, so the item that moved into the gap is never checked. In our Godot 4.7 test, erase() inside for d in disciples left 2 of 6 exhausted disciples in the list. Loop backwards with remove_at(i), or use filter(): both removed all 6.

The code

remove_where() removes everything the Callable says yes to and gives back what it removed, in the original order, so you can send those disciples home, play an effect for those enemies or show which buffs ran out. It changes the array you pass in.

extends Node
## Remove items from an Array safely: send home disciples with no stamina left,
## clear dead enemies, drop used-up buffs. Never erase from the array you are looping over.


static func remove_where(items: Array, should_remove: Callable) -> Array:
	var removed: Array = []
	for i in range(items.size() - 1, -1, -1):  # backwards: removing does not move what is still to check
		if should_remove.call(items[i]):
			removed.append(items[i])
			items.remove_at(i)
	removed.reverse()  # back to the original order
	return removed

What we measured

10 disciples with stamina 0, 0, 5, 0, 3, 0, 0, 8, 0 and 2: 6 with none left, including two pairs next to each other. Two runs with the same results.

Why it happens

A for loop over an Array walks it by position. When D1 is erased from position 0, D2 moves into position 0, and the loop goes on to position 1, which is now D3. D2 is never looked at. Going backwards, removing an item only moves items you have already checked. filter() does not change the array it reads, it builds a new one.

What to change

Progress while the game is closed: idle game offline progress.

A ready-made system: Xianxia Sect Management System for Godot 4 is an idle sect game system: disciples with jobs, 9 buildings, 8 missions, random events, reputation, save/load and offline progress.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Xianxia Sect Management System for Godot 4 is an idle sect game system: disciples with jobs, 9 buildings, 8 missions, random events, reputation, save/load and offline progress.

More how-tos for Xianxia Sect Management System for Godot 4: Big numbers with thousands separators, minus signs and all

More how-tos: Game systems