From da3f1a1275d593a530d27bae98ad75dd277fe8c2 Mon Sep 17 00:00:00 2001 From: Danil Alexeev Date: Fri, 29 Sep 2023 14:08:57 +0300 Subject: [PATCH] GDScript: Document `match` pattern guards --- _extensions/gdscript.py | 1 + .../scripting/gdscript/gdscript_basics.rst | 39 +++++++++++++++---- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/_extensions/gdscript.py b/_extensions/gdscript.py index 30091413eed..2ebadb1e028 100644 --- a/_extensions/gdscript.py +++ b/_extensions/gdscript.py @@ -176,6 +176,7 @@ def innerstring_rules(ttype): "match", "pass", "return", + "when", "while", ), suffix=r"\b", diff --git a/tutorials/scripting/gdscript/gdscript_basics.rst b/tutorials/scripting/gdscript/gdscript_basics.rst index 022800f3885..563278a2069 100644 --- a/tutorials/scripting/gdscript/gdscript_basics.rst +++ b/tutorials/scripting/gdscript/gdscript_basics.rst @@ -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 : + : + + when : + + <...> .. warning:: @@ -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 ~~~~~~~