Menu
CoddyTech

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 7

The 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 sword

Guards 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 north
challenge icon

Challenge

Easy

The 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
  • x is 0: On the y-axis at y= followed by y
  • y is 0: On the x-axis at x= followed by x
  • x and y are equal: On the diagonal at followed 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=5

For 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
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler