Skip to content

Commit 49ac573

Browse files
authored
Merge pull request godotengine#8094 from dalexeev/gds-add-match-pattern-guard-info
GDScript: Document `match` pattern guards
2 parents 793baa1 + da3f1a1 commit 49ac573

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

_extensions/gdscript.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ def innerstring_rules(ttype):
176176
"match",
177177
"pass",
178178
"return",
179+
"when",
179180
"while",
180181
),
181182
suffix=r"\b",

tutorials/scripting/gdscript/gdscript_basics.rst

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1439,13 +1439,12 @@ It's the equivalent of the ``switch`` statement found in many other languages, b
14391439

14401440
Basic syntax::
14411441

1442-
match (expression):
1443-
[pattern](s):
1444-
[block]
1445-
[pattern](s):
1446-
[block]
1447-
[pattern](s):
1448-
[block]
1442+
match <expression>:
1443+
<pattern(s)>:
1444+
<block>
1445+
<pattern(s)> when <guard expression>:
1446+
<block>
1447+
<...>
14491448

14501449
.. warning::
14511450

@@ -1580,6 +1579,32 @@ There are 6 pattern types:
15801579
"Sword", "Splash potion", "Fist":
15811580
print("Yep, you've taken damage")
15821581

1582+
**Pattern guards**:
1583+
1584+
Only one branch can be executed per ``match``. Once a branch is chosen, the rest are not checked.
1585+
If you want to use the same pattern for multiple branches or to prevent choosing a branch with too general pattern,
1586+
you can specify a guard expression after the list of patterns with the ``when`` keyword::
1587+
1588+
match point:
1589+
[0, 0]:
1590+
print("Origin")
1591+
[_, 0]:
1592+
print("Point on X-axis")
1593+
[0, _]:
1594+
print("Point on Y-axis")
1595+
[var x, var y] when y == x:
1596+
print("Point on line y = x")
1597+
[var x, var y] when y == -x:
1598+
print("Point on line y = -x")
1599+
[var x, var y]:
1600+
print("Point (%s, %s)" % [x, y])
1601+
1602+
- If there is no matching pattern for the current branch, the guard expression
1603+
is **not** evaluated and the patterns of the next branch are checked.
1604+
- If a matching pattern is found, the guard expression is evaluated.
1605+
- If it's true, then the body of the branch is executed and ``match`` ends.
1606+
- If it's false, then the patterns of the next branch are checked.
1607+
15831608
Classes
15841609
~~~~~~~
15851610

0 commit comments

Comments
 (0)