hhile L GDScript Loops - Godot Game Engine
Home Blog Gaming

GDScript Loops

Godot Tutorials > GDScript Loops

Loops execute code for a specified number of iterations. There are two types of GDScript loops: for loops and while loops


For Loops

For loops execute code for a given number of iteration, within a specified range. Each time the same code executes it is called an iteration.

For loops are commonly used to loop through arrays and dictionaries. Let's look at some code examples.

Looping Through an Array

Mouse Hover over the yellow text in the description to highlight the code.

Linux (Ubuntu)+ NodeJS + Postgres
extends Node
# Declare Array
var paladinSkills = [20,5,15,18,5,10]
# Declare totalskill
var totalskill = 0

func _ready():
  # Loop through paladinSkills
  for skill in paladinSkills:
    # add up the sum of all skill scores
    totalskill += skill

  # print the skill score sum
  print (totalskill)

➼ Declare paladinSkills - Declare an array called paladinSkills which holds a set of skill scores.
➼ Declare totalskills - We are declaring a variable named totalskills and intializing it at zero.
➼ for - keyword indicating a for loop begins!
➼ skill - The variable name we are giving to the current array item.
➼ paladinSkills - The array we are looping through
➼ totalskills += skill - We are adding the current array item's value to totalskills. When the loop ends, totalskills will equal the sum of all the array's skill scores.

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
73
** Debug Process Stopped **

Sexy Linux T-shirt

Looping through a Dictionary

extends Node
# Declare Dictionary
var player = {"name": "sud0gh0st", "highscore": 666, "email": "demon@gmail.com"}

func _ready():
  # loop through player dictionary
  for prop in player:
    # print current dictionary item
    print (prop)

➼ Declare player - We declare our player dictionary
➼ for - keyword indicating that our for loop begins!
➼ prop - Variable name for the current dictionary item
➼ player - The name of the dictionary we are looping through.
➼ print (prop) - print the current dictionary item

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
name
highscore
email
** Debug Process Stopped **

Looping through a String

# Declare Variable
var animal = "zebra"

func _ready():
  # Loop through string variable named animal
  for l in animal:
    print (l)

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
z
e
b
r
a
** Debug Process Stopped **

Loop Through a Numerical Range

When you loop through a numerical range, by default the range starts at 0 and contimues until the specified number minus one.

  for n in range(7):
    print (n)

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
0
1
2
3
4
5
6
** Debug Process Stopped **

If you don't want the loop to start at 0, you can add an aditional parameter indicating where the loop should start.

  for n in range(3,7):
    print (n)

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
3
4
5
6
** Debug Process Stopped **

You can add a third parameter to change how the itierations step over numbers in your range.

  for n in range(10,2,-2):
    print (n)

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
10
8
6
4
** Debug Process Stopped **

While Loops

While loops repeat code as long as a condition is satisfied. Let's look at an example!

The player fights a zombie. The zombie starts with 30 hit points. The player continuously attacks the zombie until the zombie dies (when he runs out of hit points). Every time the player attacks, the zombie looses 10 hit points.

extends Node

# Initalize Zombie's Hit Points at 30
var zombie_hitpoints = 30

# Function to simulate an attack
func attack_zombie(attack_points):
  zombie_hitpoints -= attack_points

func _ready():
  # While the Zombie has hit points
  while zombie_hitpoints > 0:
    # Attack with 10 point attack
    attack_zombie(10)
    # Print the zombie's remaining hit points
    print (zombie_hitpoints)

➼ zombie_hitpoints - Declare zombie_hitpoints and intialize it at 30 points
➼ attack_zombie - Declare a function named attack_zombie that takes in the number of attack points. I am calling the zombie's loss of hitpoints "attack_points"
➼ Function Code - When this function is called the number of attack_points will be subtracted from the zombie's hit points.
➼ while - Keyword indicating the start of a while loop
➼ loop condtion - While the zombie has hitpoints, keep repeating the loop's code
➼ loop code - Call the attack_zombie function, then print the zombie's remaining hit points.

Ouput

** Debug Process Started **
OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
20
10
0
** Debug Process Stopped **

Homework

Use GDScript loops to perform the following tasks.
  1. Delare a druid skill array, containing 6 skill scores. Loop through the array and add up the sum of all skill scores.

  2. A knight is fighting a troll. The knight starts with 80 hit points and the troll starts with 45 hit points. Each round the knight looses 8 hit points and the troll looses 12 hit points. Once a character is down to 0 hit points the character dies and the fight is over. Write code to simulate the fight.

  3. Declare a dictionary containing data about your favorite video game. Loop through the dictionary printing the key: value pairs.

Support Coding Commanders

Because it is crucial to achieving upward economic mobility, Coding Commanders believes everyone should have access to free quality STEM education. My tutorials explain complex concepts in plain English using relatable examples. No previous mathematics or technical knowledge required!



Donate
Women in Tech - Milly Berst
Women in Tech - she_who_codes
Virtual Private Network with Commander Candy
Previous Lesson | Next Lesson