Menu
CoddyTech

Iterating Over Elements

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 69 of 92.

Iterating means going through the elements of an array one by one. A for loop can take the elements directly:

var fruits := ["apple", "banana", "orange"]
for fruit in fruits:
	print(fruit)
apple
banana
orange

On each pass, the loop variable fruit holds the next element, from the first to the last. The loop runs once per element, so it needs no index and no size().

Inside the loop you can test each element. The length() method returns how many characters a string has ("apple".length() is 5), so this loop prints only the words longer than 3 characters:

var words := ["hi", "hello", "hey", "howdy"]
for word in words:
	if word.length() > 3:
		print(word)
hello
howdy
challenge icon

Challenge

Easy

The program reads one line of words separated by commas and splits it into the array words (already written).

Add every word longer than 5 characters to the array long_words, keeping their order. The print(long_words) line is already written. For the input penguin,koala,dolphin, the output is:

["penguin", "dolphin"]

Try it yourself

extends Node

func _ready():
	# Reads a line such as cat,penguin,dog and cuts it at the commas into an array of words
	var words := OS.read_string_from_stdin().split(",")
	var long_words: Array[String] = []
	# Add every word longer than 5 characters to long_words
	print(long_words)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler