Sequence Operators
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 74 of 92.
The + operator joins two arrays into a new array, the elements of the first followed by those of the second:
var team_a := [1, 2, 3]
var team_b := [4, 5, 6]
var everyone := team_a + team_b
print(everyone)[1, 2, 3, 4, 5, 6]The two original arrays do not change. To add the elements of an array to an existing one, use +=:
var loot := ["coin"]
loot += ["gem", "key"]
print(loot)["coin", "gem", "key"]+ joins strings the same way: "Good" + " " + "Morning" is "Good Morning".
== compares two arrays element by element, in order. [1, 2] == [1, 2] is true, and [1, 2] == [2, 1] is false.
GDScript has no repetition operator: [1, 2] * 3 and "#" * 3 are errors. Repeat an array with += in a loop, and a string with the repeat() method:
var pattern := []
for i in range(3):
pattern += [1, 2]
print(pattern)
print("*".repeat(5))[1, 2, 1, 2, 1, 2]
*****Challenge
EasyThe program reads a line of whole numbers separated by commas into numbers, and a second line into repeats (already written).
- Join
numberswith itself using+ - Build
pattern: that doubled array,repeatstimes in a row - Print
pattern
For the inputs 1,2,3 and 2, the output is:
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]Try it yourself
extends Node
func _ready():
var parts := OS.read_string_from_stdin().split(",")
var numbers: Array[int] = []
for part in parts:
numbers.append(int(part))
var repeats := int(OS.read_string_from_stdin())
# Write your code below
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 Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler