Quellcode durchsuchen

Document nested ternary-if usage example in GDScript basics

Hugo Locurcio vor 3 Jahren
Ursprung
Commit
5deed61c59
1 geänderte Dateien mit 23 neuen und 0 gelöschten Zeilen
  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]
     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
 ^^^^^