Explorar o código

Document nested ternary-if usage example in GDScript basics

Hugo Locurcio %!s(int64=4) %!d(string=hai) anos
pai
achega
5deed61c59
Modificáronse 1 ficheiros con 23 adicións e 0 borrados
  1. 23 0
      getting_started/scripting/gdscript/gdscript_basics.rst

+ 23 - 0
getting_started/scripting/gdscript/gdscript_basics.rst

@@ -835,6 +835,29 @@ boolean expression. In this case, ternary-if expressions come in handy::
     var x = [value] if [expression] else [value]
     var x = [value] if [expression] else [value]
     y += 3 if y < 10 else -1
     y += 3 if y < 10 else -1
 
 
+Ternary-if expressions can be nested to handle more than 2 cases. When nesting
+ternary-if expressions, it is recommended to wrap the complete expression over
+multiple lines to preserve readability::
+
+    var count = 0
+
+    var fruit = (
+            "apple" if count == 2
+            else "pear" if count == 1
+            else "banana" if count == 0
+            else "orange"
+    )
+    print(fruit)  # banana
+
+    # Alternative syntax with backslashes instead of parentheses (for multi-line expressions).
+    # Less lines required, but harder to refactor.
+    var fruit_alt = \
+            "apple" if count == 2 \
+            else "pear" if count == 1 \
+            else "banana" if count == 0 \
+            else "orange"
+    print(fruit_alt)  # banana
+
 while
 while
 ^^^^^
 ^^^^^