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
orangeOn 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
howdyChallenge
EasyThe 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Arrays
Iterating Over ElementsIterating With IndexesIterating Over Strings Part 1Iterating Over Strings Part 25Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler