While loop crashing the game

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

Whenever I use a while loop, doesn’t matter what is in it or what is the condition, it crashes the game. I even tried creating a new project and only adding the code below to _proccess(delta) but it crashed too. Is this only with me? I’m using the Steam Version v3.0.6.stable.official.8314054 (latest version avaliable for Steam today)

while true:
    print("test")
:bust_in_silhouette: Reply From: TecoSV

You should add the following line at the end of the while loop:

yield(get_tree(), "idle_frame")

Perhaps, but this doesn’t answer “why”, and isn’t a good solution to what’s probably a fundamental misunderstanding of how the engine operates. Better to understand the main loop execution before diving into coroutines.

kidscancode | 2019-01-17 04:49

Add the following line like this?

	while y == true and yield(get_tree(),"idle_frame"):
	movement.y += 1

Like that right?

(pseudocode)
When y is true and yield get tree idle frame:
movement y += 1

Maxlaughter | 2021-11-21 01:48

:bust_in_silhouette: Reply From: kidscancode

A while loop like that is infinite - it never exits. If it never exits, then the _process() function can never end. Since _process() is called every frame, you have now locked up the application and no more frames will ever be executed.

This is the case in most graphical applications, where you already have a central loop running the core processes of the application. Instead of using a while loop you should ask yourself what you’re trying to accomplish. For example, if you just wanted to print “test” over and over again, you could just do this:

func _process(delta):
    print("test")

Now when you run the game, your output panel will be flooded with “test” prints every 1/60 of a second.