Simple For Loop Not Working As Expected??

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By scrubswithnosleeves

Hey All,

I am turning this over to you because my brain is about to melt.

For some reason, the following for loop only runs twice despite there being 3 items in the array it is iterating over. No change if I increase the size of the array (enemies_stack). I know the break statement is not being run because a print() put before it does not output anything.

var ENEMY = preload(....tscn)
var num_active_enemies = 0
enemies_stack = [3,3,3]

func spawn_enemies():
	for enemy in enemies_stack:
		if num_active_enemies >= 10:
		var enemy_instance = ENEMY.instance()
		enemy_instance.global_position = random_spawn_loc(enemy)
		num_active_enemies += 1

HERE is the GitHub link with the full script and project files. Please help me lol.

:bust_in_silhouette: Reply From: MrEliptik

You’re starting your loop on a stack with 3 elements but you remove elements as you go, so your loop can’t complete. The solution is to not modify your list as you’re iterating on it. You can make a copy before starting your loop for example and remove elements from that copy.

If you’re sure you want to remove elements as you go, you could use pop_front

for i in range(stack.size()):
    var enemy = stack.pop_front() # this element is removed from the stack