Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GDScript: Document match pattern guards #8094

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions _extensions/gdscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ def innerstring_rules(ttype):
"match",
"pass",
"return",
"when",
"while",
),
suffix=r"\b",
Expand Down
39 changes: 32 additions & 7 deletions tutorials/scripting/gdscript/gdscript_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1439,13 +1439,12 @@ It's the equivalent of the ``switch`` statement found in many other languages, b

Basic syntax::

match (expression):
[pattern](s):
[block]
[pattern](s):
[block]
[pattern](s):
[block]
match <expression>:
<pattern(s)>:
<block>
<pattern(s)> when <guard expression>:
<block>
<...>

.. warning::

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

**Pattern guards**:

Only one branch can be executed per ``match``. Once a branch is chosen, the rest are not checked.
If you want to use the same pattern for multiple branches or to prevent choosing a branch with too general pattern,
you can specify a guard expression after the list of patterns with the ``when`` keyword::

match point:
[0, 0]:
print("Origin")
[_, 0]:
print("Point on X-axis")
[0, _]:
print("Point on Y-axis")
[var x, var y] when y == x:
print("Point on line y = x")
[var x, var y] when y == -x:
print("Point on line y = -x")
[var x, var y]:
print("Point (%s, %s)" % [x, y])

- If there is no matching pattern for the current branch, the guard expression
is **not** evaluated and the patterns of the next branch are checked.
- If a matching pattern is found, the guard expression is evaluated.
- If it's true, then the body of the branch is executed and ``match`` ends.
- If it's false, then the patterns of the next branch are checked.

Classes
~~~~~~~

Expand Down