While Loop
Hello and welcome to the GDScript fundamental tutorial series.
In this episode, I go over while loops in Godot GDScript.
While keyword
With the while
keyword, you can run the block of code for as long as the while loop’s condition continues to be true.
var x: int = 0
while x < 10:
print(x)
x = x + 1
Break keyword
With the break
keyword, you can get out of a loop.
var x: int = 0
while x < 10:
break
# you don't get a chance to run the rest of the code block
print(x)
x = x + 1
Infinite Loop
An infinite loop, also referred to as an endless loop, lacks a functional exit and repeats indefinitely.
Types of Infinite Loops
There are 3 different types of loops you may find yourself using:
- Fake Infinite Loop
- Intended Infinite Loop
- Unintended Infinite Loop
Fake Infinite Loop
Fake infinite loops give the impression of an endless loop, but when you look closely, they have an exit:
var x: int = 0
while true:
print("Hello World")
break # an exit, without this the loop would run forever
In the example above, it looks like it would run indefinitely; however, on closer inspection, you will see that there is a break keyword; therefore, the block of code will run only once.
Intended Infinite Loop
An intended infinite loop is an endless loop where the programmer intentionally writes a loop where they don’t want it to end.
An example of an intended infinite loop would be the game loop.
In game programming, your code is always running an intended infinite loop.
You only ever stop the loop when a game user exits the game.
Unintended Infinite Loop
As the name suggests, this type of loop is one where the programmer makes a mistake.
Try your best not to make this type of infinite loop.