Loops
We’ve been putting lines of code one after the other and Godot Engine executed them nicely from top to bottom. But there comes a time when we want to repeat one or multiple lines of code. For example, what if we want to print out every item in the player’s inventory in a nice way?
We could do something like that with the following code:
var inventory = ["Boots", "Bananas", "Bandages"] for item in inventory: print("You possess ", item)
This is called a loop; this specific one is a for loop. We’ll have a look at the two kinds of loops that are present in GDScript in the next few sections.
For loops
A for loop will repeat its code block for every element of an array. In the case of the example provided in the introduction, this element will be available in the variable that is only valid within the for
loop called item. Of course, we can use the same structure for other arrays and call...