Array Patterns
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 8 of 78.
An array pattern is written like an array literal. It matches an array of the same size whose elements match one by one. Each element of the pattern can be a literal, _ or a binding:
var point := [0, 7]
match point:
[0, 0]:
print("Origin")
[0, var y]:
print("On the y-axis at ", y)
[var x, var y]:
print("Point ", x, ", ", y)On the y-axis at 7The size must be the same: [var x, var y] does not match [1, 2, 3]. Put .. as the last element to allow any number of extra elements (zero included), and write [] for an empty array:
var cmd := ["give", "sword", "Ana"]
match cmd:
[]:
print("Nothing typed")
["give", var item, ..]:
print("Giving ", item)Giving swordGuards work with array patterns too: [var a, var b] when a == b: matches two equal elements.
Array patterns match only the Array type. The PackedStringArray returned by split() never matches them. Store the result in a variable declared as Array, which converts it:
var words: Array = "go north".split(" ")
match words:
["go", var dir]:
print("Heading ", dir)Heading northChallenge
EasyThe program reads a point written as x,y and stores it in the array point as two integers (already written). Use a match statement with array patterns to print where the point is, using the first rule that fits:
- Both are
0:Origin xis0:On the y-axis at y=followed byyyis0:On the x-axis at x=followed byxxandyare equal:On the diagonal atfollowed by the value- Anything else:
Point at (x, y)with the two values
For the input 0,5, the output is:
On the y-axis at y=5For the input 2,7, it is:
Point at (2, 7)Try it yourself
extends Node
func _ready():
var parts := OS.read_string_from_stdin().split(",")
var point := [int(parts[0]), int(parts[1])]
# Match point against array patterns
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler