diff options
| -rw-r--r-- | doc/yue-de.md | 2497 | ||||
| -rw-r--r-- | doc/yue-en.md | 2497 | ||||
| -rw-r--r-- | doc/yue-id-id.md | 2497 | ||||
| -rw-r--r-- | doc/yue-pt-br.md | 2496 | ||||
| -rw-r--r-- | doc/yue-zh.md | 2495 | ||||
| -rw-r--r-- | spec/inputs/compile_doc.yue | 6 | ||||
| -rw-r--r-- | spec/outputs/compile_doc.lua | 2 |
7 files changed, 15 insertions, 12475 deletions
diff --git a/doc/yue-de.md b/doc/yue-de.md index 1a13a47..94bfd4b 100644 --- a/doc/yue-de.md +++ b/doc/yue-de.md | |||
| @@ -1,11 +1,5 @@ | |||
| 1 | --- | ||
| 2 | title: Referenz | ||
| 3 | --- | ||
| 4 | |||
| 5 | # YueScript-Dokumentation | 1 | # YueScript-Dokumentation |
| 6 | 2 | ||
| 7 | <img src="/image/yuescript.svg" width="250px" height="250px" alt="logo" style="padding-top: 3em; padding-bottom: 2em;"/> | ||
| 8 | |||
| 9 | Willkommen in der offiziellen <b>YueScript</b>-Dokumentation!<br/> | 3 | Willkommen in der offiziellen <b>YueScript</b>-Dokumentation!<br/> |
| 10 | Hier findest du Sprachfeatures, Nutzung, Referenzbeispiele und Ressourcen.<br/> | 4 | Hier findest du Sprachfeatures, Nutzung, Referenzbeispiele und Ressourcen.<br/> |
| 11 | Bitte wähle ein Kapitel in der Seitenleiste, um mit YueScript zu beginnen. | 5 | Bitte wähle ein Kapitel in der Seitenleiste, um mit YueScript zu beginnen. |
| @@ -21,17 +15,6 @@ do | |||
| 21 | print var -- nil hier | 15 | print var -- nil hier |
| 22 | ``` | 16 | ``` |
| 23 | 17 | ||
| 24 | <YueDisplay> | ||
| 25 | |||
| 26 | ```yue | ||
| 27 | do | ||
| 28 | var = "hallo" | ||
| 29 | print var | ||
| 30 | print var -- nil hier | ||
| 31 | ``` | ||
| 32 | |||
| 33 | </YueDisplay> | ||
| 34 | |||
| 35 | YueScripts **do** kann auch als Ausdruck verwendet werden. So kannst du mehrere Zeilen in einem Ausdruck kombinieren. Das Ergebnis des `do`-Ausdrucks ist die letzte Anweisung im Block. `do`-Ausdrücke unterstützen die Verwendung von `break`, um den Kontrollfluss zu unterbrechen und mehrere Rückgabewerte vorzeitig zurückzugeben. | 18 | YueScripts **do** kann auch als Ausdruck verwendet werden. So kannst du mehrere Zeilen in einem Ausdruck kombinieren. Das Ergebnis des `do`-Ausdrucks ist die letzte Anweisung im Block. `do`-Ausdrücke unterstützen die Verwendung von `break`, um den Kontrollfluss zu unterbrechen und mehrere Rückgabewerte vorzeitig zurückzugeben. |
| 36 | 19 | ||
| 37 | ```yuescript | 20 | ```yuescript |
| @@ -42,18 +25,6 @@ status, value = do | |||
| 42 | break "small", n | 25 | break "small", n |
| 43 | ``` | 26 | ``` |
| 44 | 27 | ||
| 45 | <YueDisplay> | ||
| 46 | |||
| 47 | ```yue | ||
| 48 | status, value = do | ||
| 49 | n = 12 | ||
| 50 | if n > 10 | ||
| 51 | break "large", n | ||
| 52 | break "small", n | ||
| 53 | ``` | ||
| 54 | |||
| 55 | </YueDisplay> | ||
| 56 | |||
| 57 | ```yuescript | 28 | ```yuescript |
| 58 | counter = do | 29 | counter = do |
| 59 | i = 0 | 30 | i = 0 |
| @@ -65,21 +36,6 @@ print counter! | |||
| 65 | print counter! | 36 | print counter! |
| 66 | ``` | 37 | ``` |
| 67 | 38 | ||
| 68 | <YueDisplay> | ||
| 69 | |||
| 70 | ```yue | ||
| 71 | counter = do | ||
| 72 | i = 0 | ||
| 73 | -> | ||
| 74 | i += 1 | ||
| 75 | i | ||
| 76 | |||
| 77 | print counter! | ||
| 78 | print counter! | ||
| 79 | ``` | ||
| 80 | |||
| 81 | </YueDisplay> | ||
| 82 | |||
| 83 | ```yuescript | 39 | ```yuescript |
| 84 | tbl = { | 40 | tbl = { |
| 85 | key: do | 41 | key: do |
| @@ -88,18 +44,6 @@ tbl = { | |||
| 88 | } | 44 | } |
| 89 | ``` | 45 | ``` |
| 90 | 46 | ||
| 91 | <YueDisplay> | ||
| 92 | |||
| 93 | ```yue | ||
| 94 | tbl = { | ||
| 95 | key: do | ||
| 96 | print "Schlüssel wird zugewiesen!" | ||
| 97 | 1234 | ||
| 98 | } | ||
| 99 | ``` | ||
| 100 | |||
| 101 | </YueDisplay> | ||
| 102 | |||
| 103 | # Line-Decorators | 47 | # Line-Decorators |
| 104 | 48 | ||
| 105 | Zur Vereinfachung können `for`-Schleifen und `if`-Anweisungen auf einzelne Anweisungen am Zeilenende angewendet werden: | 49 | Zur Vereinfachung können `for`-Schleifen und `if`-Anweisungen auf einzelne Anweisungen am Zeilenende angewendet werden: |
| @@ -108,28 +52,12 @@ Zur Vereinfachung können `for`-Schleifen und `if`-Anweisungen auf einzelne Anwe | |||
| 108 | print "Hallo Welt" if name == "Rob" | 52 | print "Hallo Welt" if name == "Rob" |
| 109 | ``` | 53 | ``` |
| 110 | 54 | ||
| 111 | <YueDisplay> | ||
| 112 | |||
| 113 | ```yue | ||
| 114 | print "Hallo Welt" if name == "Rob" | ||
| 115 | ``` | ||
| 116 | |||
| 117 | </YueDisplay> | ||
| 118 | |||
| 119 | Und mit einfachen Schleifen: | 55 | Und mit einfachen Schleifen: |
| 120 | 56 | ||
| 121 | ```yuescript | 57 | ```yuescript |
| 122 | print "Element: ", item for item in *items | 58 | print "Element: ", item for item in *items |
| 123 | ``` | 59 | ``` |
| 124 | 60 | ||
| 125 | <YueDisplay> | ||
| 126 | |||
| 127 | ```yue | ||
| 128 | print "Element: ", item for item in *items | ||
| 129 | ``` | ||
| 130 | |||
| 131 | </YueDisplay> | ||
| 132 | |||
| 133 | Und mit `while`-Schleifen: | 61 | Und mit `while`-Schleifen: |
| 134 | 62 | ||
| 135 | ```yuescript | 63 | ```yuescript |
| @@ -138,16 +66,6 @@ game\update! while game\isRunning! | |||
| 138 | reader\parse_line! until reader\eof! | 66 | reader\parse_line! until reader\eof! |
| 139 | ``` | 67 | ``` |
| 140 | 68 | ||
| 141 | <YueDisplay> | ||
| 142 | |||
| 143 | ```yue | ||
| 144 | game\update! while game\isRunning! | ||
| 145 | |||
| 146 | reader\parse_line! until reader\eof! | ||
| 147 | ``` | ||
| 148 | |||
| 149 | </YueDisplay> | ||
| 150 | |||
| 151 | # Makros | 69 | # Makros |
| 152 | 70 | ||
| 153 | ## Häufige Verwendung | 71 | ## Häufige Verwendung |
| @@ -183,39 +101,6 @@ if $and f1!, f2!, f3! | |||
| 183 | print "OK" | 101 | print "OK" |
| 184 | ``` | 102 | ``` |
| 185 | 103 | ||
| 186 | <YueDisplay> | ||
| 187 | |||
| 188 | ```yue | ||
| 189 | macro PI2 = -> math.pi * 2 | ||
| 190 | area = $PI2 * 5 | ||
| 191 | |||
| 192 | macro HELLO = -> "'Hallo Welt'" | ||
| 193 | print $HELLO | ||
| 194 | |||
| 195 | macro config = (debugging) -> | ||
| 196 | global debugMode = debugging == "true" | ||
| 197 | "" | ||
| 198 | |||
| 199 | macro asserts = (cond) -> | ||
| 200 | debugMode and "assert #{cond}" or "" | ||
| 201 | |||
| 202 | macro assert = (cond) -> | ||
| 203 | debugMode and "assert #{cond}" or "#{cond}" | ||
| 204 | |||
| 205 | $config true | ||
| 206 | $asserts item ~= nil | ||
| 207 | |||
| 208 | $config false | ||
| 209 | value = $assert item | ||
| 210 | |||
| 211 | -- übergebene Ausdrücke werden als Strings behandelt | ||
| 212 | macro and = (...) -> "#{ table.concat {...}, ' and ' }" | ||
| 213 | if $and f1!, f2!, f3! | ||
| 214 | print "OK" | ||
| 215 | ``` | ||
| 216 | |||
| 217 | </YueDisplay> | ||
| 218 | |||
| 219 | ## Rohcode einfügen | 104 | ## Rohcode einfügen |
| 220 | 105 | ||
| 221 | Eine Makrofunktion kann entweder einen YueScript-String oder eine Konfigurationstabelle mit Lua-Code zurückgeben. | 106 | Eine Makrofunktion kann entweder einen YueScript-String oder eine Konfigurationstabelle mit Lua-Code zurückgeben. |
| @@ -246,36 +131,6 @@ end | |||
| 246 | ]==] | 131 | ]==] |
| 247 | ``` | 132 | ``` |
| 248 | 133 | ||
| 249 | <YueDisplay> | ||
| 250 | |||
| 251 | ```yue | ||
| 252 | macro yueFunc = (var) -> "local #{var} = ->" | ||
| 253 | $yueFunc funcA | ||
| 254 | funcA = -> "Zuweisung an die vom Yue-Makro definierte Variable schlägt fehl" | ||
| 255 | |||
| 256 | macro luaFunc = (var) -> { | ||
| 257 | code: "local function #{var}() end" | ||
| 258 | type: "lua" | ||
| 259 | } | ||
| 260 | $luaFunc funcB | ||
| 261 | funcB = -> "Zuweisung an die vom Lua-Makro definierte Variable schlägt fehl" | ||
| 262 | |||
| 263 | macro lua = (code) -> { | ||
| 264 | :code | ||
| 265 | type: "lua" | ||
| 266 | } | ||
| 267 | |||
| 268 | -- führende und abschließende Symbole des Raw-Strings werden automatisch getrimmt | ||
| 269 | $lua[==[ | ||
| 270 | -- Einfügen von rohem Lua-Code | ||
| 271 | if cond then | ||
| 272 | print("Ausgabe") | ||
| 273 | end | ||
| 274 | ]==] | ||
| 275 | ``` | ||
| 276 | |||
| 277 | </YueDisplay> | ||
| 278 | |||
| 279 | ## Makros exportieren | 134 | ## Makros exportieren |
| 280 | 135 | ||
| 281 | Makrofunktionen können aus einem Modul exportiert und in ein anderes Modul importiert werden. Exportierte Makros müssen in einer einzelnen Datei liegen, und im Export-Modul dürfen nur Makrodefinitionen, Makro-Imports und Makro-Expansionen stehen. | 136 | Makrofunktionen können aus einem Modul exportiert und in ein anderes Modul importiert werden. Exportierte Makros müssen in einer einzelnen Datei liegen, und im Export-Modul dürfen nur Makrodefinitionen, Makro-Imports und Makro-Expansionen stehen. |
| @@ -295,28 +150,6 @@ import "utils" as { | |||
| 295 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | 150 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ |
| 296 | ``` | 151 | ``` |
| 297 | 152 | ||
| 298 | <YueDisplay> | ||
| 299 | |||
| 300 | ```yue | ||
| 301 | -- Datei: utils.yue | ||
| 302 | export macro map = (items, action) -> "[#{action} for _ in *#{items}]" | ||
| 303 | export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" | ||
| 304 | export macro foreach = (items, action) -> "for _ in *#{items} | ||
| 305 | #{action}" | ||
| 306 | |||
| 307 | -- Datei main.yue | ||
| 308 | -- Import-Funktion im Browser nicht verfügbar, in echter Umgebung testen | ||
| 309 | --[[ | ||
| 310 | import "utils" as { | ||
| 311 | $, -- Symbol zum Importieren aller Makros | ||
| 312 | $foreach: $each -- Makro $foreach in $each umbenennen | ||
| 313 | } | ||
| 314 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | ||
| 315 | ]] | ||
| 316 | ``` | ||
| 317 | |||
| 318 | </YueDisplay> | ||
| 319 | |||
| 320 | ## Eingebaute Makros | 153 | ## Eingebaute Makros |
| 321 | 154 | ||
| 322 | Es gibt einige eingebaute Makros, aber du kannst sie überschreiben, indem du Makros mit denselben Namen deklarierst. | 155 | Es gibt einige eingebaute Makros, aber du kannst sie überschreiben, indem du Makros mit denselben Namen deklarierst. |
| @@ -326,15 +159,6 @@ print $FILE -- String des aktuellen Modulnamens | |||
| 326 | print $LINE -- gibt 2 aus | 159 | print $LINE -- gibt 2 aus |
| 327 | ``` | 160 | ``` |
| 328 | 161 | ||
| 329 | <YueDisplay> | ||
| 330 | |||
| 331 | ```yue | ||
| 332 | print $FILE -- String des aktuellen Modulnamens | ||
| 333 | print $LINE -- gibt 2 aus | ||
| 334 | ``` | ||
| 335 | |||
| 336 | </YueDisplay> | ||
| 337 | |||
| 338 | ## Makros mit Makros erzeugen | 162 | ## Makros mit Makros erzeugen |
| 339 | 163 | ||
| 340 | In YueScript erlauben Makrofunktionen Codegenerierung zur Compile-Zeit. Durch das Verschachteln von Makrofunktionen kannst du komplexere Generierungsmuster erzeugen. Damit kannst du eine Makrofunktion definieren, die eine andere Makrofunktion erzeugt. | 164 | In YueScript erlauben Makrofunktionen Codegenerierung zur Compile-Zeit. Durch das Verschachteln von Makrofunktionen kannst du komplexere Generierungsmuster erzeugen. Damit kannst du eine Makrofunktion definieren, die eine andere Makrofunktion erzeugt. |
| @@ -357,28 +181,6 @@ print "Gültiger Enum-Typ:", $BodyType Static | |||
| 357 | -- print "Kompilierungsfehler bei Enum-Typ:", $BodyType Unknown | 181 | -- print "Kompilierungsfehler bei Enum-Typ:", $BodyType Unknown |
| 358 | ``` | 182 | ``` |
| 359 | 183 | ||
| 360 | <YueDisplay> | ||
| 361 | |||
| 362 | ```yue | ||
| 363 | macro Enum = (...) -> | ||
| 364 | items = {...} | ||
| 365 | itemSet = {item, true for item in *items} | ||
| 366 | (item) -> | ||
| 367 | error "erhalten: \"#{item}\", erwartet eines von #{table.concat items, ', '}" unless itemSet[item] | ||
| 368 | "\"#{item}\"" | ||
| 369 | |||
| 370 | macro BodyType = $Enum( | ||
| 371 | Static | ||
| 372 | Dynamic | ||
| 373 | Kinematic | ||
| 374 | ) | ||
| 375 | |||
| 376 | print "Gültiger Enum-Typ:", $BodyType Static | ||
| 377 | -- print "Kompilierungsfehler bei Enum-Typ:", $BodyType Unknown | ||
| 378 | ``` | ||
| 379 | |||
| 380 | </YueDisplay> | ||
| 381 | |||
| 382 | ## Argument-Validierung | 184 | ## Argument-Validierung |
| 383 | 185 | ||
| 384 | Du kannst erwartete AST-Knotentypen in der Argumentliste deklarieren und zur Compile-Zeit prüfen, ob die übergebenen Makroargumente den Erwartungen entsprechen. | 186 | Du kannst erwartete AST-Knotentypen in der Argumentliste deklarieren und zur Compile-Zeit prüfen, ob die übergebenen Makroargumente den Erwartungen entsprechen. |
| @@ -393,20 +195,6 @@ macro printNumAndStr = (num `Num, str `String) -> | | |||
| 393 | $printNumAndStr 123, "hallo" | 195 | $printNumAndStr 123, "hallo" |
| 394 | ``` | 196 | ``` |
| 395 | 197 | ||
| 396 | <YueDisplay> | ||
| 397 | |||
| 398 | ```yue | ||
| 399 | macro printNumAndStr = (num `Num, str `String) -> | | ||
| 400 | print( | ||
| 401 | #{num} | ||
| 402 | #{str} | ||
| 403 | ) | ||
| 404 | |||
| 405 | $printNumAndStr 123, "hallo" | ||
| 406 | ``` | ||
| 407 | |||
| 408 | </YueDisplay> | ||
| 409 | |||
| 410 | Wenn du flexiblere Argumentprüfungen brauchst, kannst du das eingebaute Makro `$is_ast` verwenden, um manuell an der passenden Stelle zu prüfen. | 198 | Wenn du flexiblere Argumentprüfungen brauchst, kannst du das eingebaute Makro `$is_ast` verwenden, um manuell an der passenden Stelle zu prüfen. |
| 411 | 199 | ||
| 412 | ```yuescript | 200 | ```yuescript |
| @@ -418,19 +206,6 @@ macro printNumAndStr = (num, str) -> | |||
| 418 | $printNumAndStr 123, "hallo" | 206 | $printNumAndStr 123, "hallo" |
| 419 | ``` | 207 | ``` |
| 420 | 208 | ||
| 421 | <YueDisplay> | ||
| 422 | |||
| 423 | ```yue | ||
| 424 | macro printNumAndStr = (num, str) -> | ||
| 425 | error "als erstes Argument Num erwartet" unless $is_ast Num, num | ||
| 426 | error "als zweites Argument String erwartet" unless $is_ast String, str | ||
| 427 | "print(#{num}, #{str})" | ||
| 428 | |||
| 429 | $printNumAndStr 123, "hallo" | ||
| 430 | ``` | ||
| 431 | |||
| 432 | </YueDisplay> | ||
| 433 | |||
| 434 | Weitere Details zu verfügbaren AST-Knoten findest du in den großgeschriebenen Definitionen in `yue_parser.cpp`. | 209 | Weitere Details zu verfügbaren AST-Knoten findest du in den großgeschriebenen Definitionen in `yue_parser.cpp`. |
| 435 | 210 | ||
| 436 | # Try | 211 | # Try |
| @@ -465,38 +240,6 @@ catch err | |||
| 465 | print result | 240 | print result |
| 466 | ``` | 241 | ``` |
| 467 | 242 | ||
| 468 | <YueDisplay> | ||
| 469 | |||
| 470 | ```yue | ||
| 471 | try | ||
| 472 | func 1, 2, 3 | ||
| 473 | catch err | ||
| 474 | print yue.traceback err | ||
| 475 | |||
| 476 | success, result = try | ||
| 477 | func 1, 2, 3 | ||
| 478 | catch err | ||
| 479 | yue.traceback err | ||
| 480 | |||
| 481 | try func 1, 2, 3 | ||
| 482 | catch err | ||
| 483 | print yue.traceback err | ||
| 484 | |||
| 485 | success, result = try func 1, 2, 3 | ||
| 486 | |||
| 487 | try | ||
| 488 | print "Versuche" | ||
| 489 | func 1, 2, 3 | ||
| 490 | |||
| 491 | -- Verwendung mit if-Zuweisungsmuster | ||
| 492 | if success, result := try func 1, 2, 3 | ||
| 493 | catch err | ||
| 494 | print yue.traceback err | ||
| 495 | print result | ||
| 496 | ``` | ||
| 497 | |||
| 498 | </YueDisplay> | ||
| 499 | |||
| 500 | ## Try? | 243 | ## Try? |
| 501 | 244 | ||
| 502 | `try?` ist eine vereinfachte Fehlerbehandlungs-Syntax, die den booleschen Status aus dem `try`-Statement weglässt. Bei Erfolg gibt sie das Ergebnis des `try`-Blocks zurück, ansonsten `nil` statt eines Fehlerobjekts. | 245 | `try?` ist eine vereinfachte Fehlerbehandlungs-Syntax, die den booleschen Status aus dem `try`-Statement weglässt. Bei Erfolg gibt sie das Ergebnis des `try`-Blocks zurück, ansonsten `nil` statt eines Fehlerobjekts. |
| @@ -519,44 +262,14 @@ catch e | |||
| 519 | e | 262 | e |
| 520 | ``` | 263 | ``` |
| 521 | 264 | ||
| 522 | <YueDisplay> | ||
| 523 | |||
| 524 | ```yue | ||
| 525 | a, b, c = try? func! | ||
| 526 | |||
| 527 | -- mit Nil-Verschmelzungs-Operator | ||
| 528 | a = (try? func!) ?? "Standardwert" | ||
| 529 | |||
| 530 | -- als Funktionsargument | ||
| 531 | f try? func! | ||
| 532 | |||
| 533 | -- mit catch-Block | ||
| 534 | f try? | ||
| 535 | print 123 | ||
| 536 | func! | ||
| 537 | catch e | ||
| 538 | print e | ||
| 539 | e | ||
| 540 | ``` | ||
| 541 | |||
| 542 | </YueDisplay> | ||
| 543 | |||
| 544 | # Tabellenliterale | 265 | # Tabellenliterale |
| 545 | 266 | ||
| 546 | Wie in Lua werden Tabellen mit geschweiften Klammern definiert. | 267 | Wie in Lua werden Tabellen mit geschweiften Klammern definiert. |
| 547 | 268 | ||
| 548 | ```yuescript | 269 | ```yuescript |
| 549 | some_values = [1, 2, 3, 4] | 270 | some_values = {1, 2, 3, 4} |
| 550 | ``` | ||
| 551 | |||
| 552 | <YueDisplay> | ||
| 553 | |||
| 554 | ```yue | ||
| 555 | some_values = [1, 2, 3, 4] | ||
| 556 | ``` | 271 | ``` |
| 557 | 272 | ||
| 558 | </YueDisplay> | ||
| 559 | |||
| 560 | Anders als in Lua weist man einem Schlüssel in einer Tabelle mit **:** (statt **=**) einen Wert zu. | 273 | Anders als in Lua weist man einem Schlüssel in einer Tabelle mit **:** (statt **=**) einen Wert zu. |
| 561 | 274 | ||
| 562 | ```yuescript | 275 | ```yuescript |
| @@ -567,18 +280,6 @@ some_values = { | |||
| 567 | } | 280 | } |
| 568 | ``` | 281 | ``` |
| 569 | 282 | ||
| 570 | <YueDisplay> | ||
| 571 | |||
| 572 | ```yue | ||
| 573 | some_values = { | ||
| 574 | name: "Bill", | ||
| 575 | age: 200, | ||
| 576 | ["Lieblingsessen"]: "Reis" | ||
| 577 | } | ||
| 578 | ``` | ||
| 579 | |||
| 580 | </YueDisplay> | ||
| 581 | |||
| 582 | Die geschweiften Klammern können weggelassen werden, wenn eine einzelne Tabelle aus Schlüssel-Wert-Paaren zugewiesen wird. | 283 | Die geschweiften Klammern können weggelassen werden, wenn eine einzelne Tabelle aus Schlüssel-Wert-Paaren zugewiesen wird. |
| 583 | 284 | ||
| 584 | ```yuescript | 285 | ```yuescript |
| @@ -588,17 +289,6 @@ profile = | |||
| 588 | favorite_foods: ["Eis", "Donuts"] | 289 | favorite_foods: ["Eis", "Donuts"] |
| 589 | ``` | 290 | ``` |
| 590 | 291 | ||
| 591 | <YueDisplay> | ||
| 592 | |||
| 593 | ```yue | ||
| 594 | profile = | ||
| 595 | height: "4 Fuß", | ||
| 596 | shoe_size: 13, | ||
| 597 | favorite_foods: ["Eis", "Donuts"] | ||
| 598 | ``` | ||
| 599 | |||
| 600 | </YueDisplay> | ||
| 601 | |||
| 602 | Zeilenumbrüche können Werte statt eines Kommas trennen (oder zusätzlich): | 292 | Zeilenumbrüche können Werte statt eines Kommas trennen (oder zusätzlich): |
| 603 | 293 | ||
| 604 | ```yuescript | 294 | ```yuescript |
| @@ -610,19 +300,6 @@ values = { | |||
| 610 | } | 300 | } |
| 611 | ``` | 301 | ``` |
| 612 | 302 | ||
| 613 | <YueDisplay> | ||
| 614 | |||
| 615 | ```yue | ||
| 616 | values = { | ||
| 617 | 1, 2, 3, 4 | ||
| 618 | 5, 6, 7, 8 | ||
| 619 | name: "Superman" | ||
| 620 | occupation: "Verbrechensbekämpfung" | ||
| 621 | } | ||
| 622 | ``` | ||
| 623 | |||
| 624 | </YueDisplay> | ||
| 625 | |||
| 626 | Beim Erstellen eines einzeiligen Tabellenliterals können die geschweiften Klammern ebenfalls weggelassen werden: | 303 | Beim Erstellen eines einzeiligen Tabellenliterals können die geschweiften Klammern ebenfalls weggelassen werden: |
| 627 | 304 | ||
| 628 | ```yuescript | 305 | ```yuescript |
| @@ -631,16 +308,6 @@ my_function dance: "Tango", partner: "keiner" | |||
| 631 | y = type: "Hund", legs: 4, tails: 1 | 308 | y = type: "Hund", legs: 4, tails: 1 |
| 632 | ``` | 309 | ``` |
| 633 | 310 | ||
| 634 | <YueDisplay> | ||
| 635 | |||
| 636 | ```yue | ||
| 637 | my_function dance: "Tango", partner: "keiner" | ||
| 638 | |||
| 639 | y = type: "Hund", legs: 4, tails: 1 | ||
| 640 | ``` | ||
| 641 | |||
| 642 | </YueDisplay> | ||
| 643 | |||
| 644 | Die Schlüssel eines Tabellenliterals können Sprach-Schlüsselwörter sein, ohne sie zu escapen: | 311 | Die Schlüssel eines Tabellenliterals können Sprach-Schlüsselwörter sein, ohne sie zu escapen: |
| 645 | 312 | ||
| 646 | ```yuescript | 313 | ```yuescript |
| @@ -650,17 +317,6 @@ tbl = { | |||
| 650 | } | 317 | } |
| 651 | ``` | 318 | ``` |
| 652 | 319 | ||
| 653 | <YueDisplay> | ||
| 654 | |||
| 655 | ```yue | ||
| 656 | tbl = { | ||
| 657 | do: "etwas" | ||
| 658 | end: "Hunger" | ||
| 659 | } | ||
| 660 | ``` | ||
| 661 | |||
| 662 | </YueDisplay> | ||
| 663 | |||
| 664 | Wenn du eine Tabelle aus Variablen konstruierst und die Schlüssel den Variablennamen entsprechen sollen, kannst du den Präfix-Operator **:** verwenden: | 320 | Wenn du eine Tabelle aus Variablen konstruierst und die Schlüssel den Variablennamen entsprechen sollen, kannst du den Präfix-Operator **:** verwenden: |
| 665 | 321 | ||
| 666 | ```yuescript | 322 | ```yuescript |
| @@ -671,18 +327,6 @@ person = { :hair, :height, shoe_size: 40 } | |||
| 671 | print_table :hair, :height | 327 | print_table :hair, :height |
| 672 | ``` | 328 | ``` |
| 673 | 329 | ||
| 674 | <YueDisplay> | ||
| 675 | |||
| 676 | ```yue | ||
| 677 | hair = "golden" | ||
| 678 | height = 200 | ||
| 679 | person = { :hair, :height, shoe_size: 40 } | ||
| 680 | |||
| 681 | print_table :hair, :height | ||
| 682 | ``` | ||
| 683 | |||
| 684 | </YueDisplay> | ||
| 685 | |||
| 686 | Wenn der Schlüssel eines Feldes das Ergebnis eines Ausdrucks sein soll, kannst du ihn wie in Lua in **[ ]** setzen. Du kannst auch ein String-Literal direkt als Schlüssel verwenden und die eckigen Klammern weglassen. Das ist nützlich, wenn dein Schlüssel Sonderzeichen enthält. | 330 | Wenn der Schlüssel eines Feldes das Ergebnis eines Ausdrucks sein soll, kannst du ihn wie in Lua in **[ ]** setzen. Du kannst auch ein String-Literal direkt als Schlüssel verwenden und die eckigen Klammern weglassen. Das ist nützlich, wenn dein Schlüssel Sonderzeichen enthält. |
| 687 | 331 | ||
| 688 | ```yuescript | 332 | ```yuescript |
| @@ -692,33 +336,13 @@ t = { | |||
| 692 | } | 336 | } |
| 693 | ``` | 337 | ``` |
| 694 | 338 | ||
| 695 | <YueDisplay> | 339 | Lua-Tabellen haben sowohl einen Array-Teil als auch einen Hash-Teil, aber manchmal ist es nützlich, hier eine semantische Unterscheidung zu treffen. Du kannst **[ ]** anstelle von **{ }** verwenden, um eine Tabelle explizit als Array zu deklarieren; dadurch wird verhindert, dass Schlüssel-Wert-Paare hineingeschrieben werden. |
| 696 | |||
| 697 | ```yue | ||
| 698 | t = { | ||
| 699 | [1 + 2]: "hallo" | ||
| 700 | "Hallo Welt": true | ||
| 701 | } | ||
| 702 | ``` | ||
| 703 | |||
| 704 | </YueDisplay> | ||
| 705 | |||
| 706 | Lua-Tabellen haben einen Array-Teil und einen Hash-Teil, aber manchmal möchte man beim Schreiben von Lua-Tabellen eine semantische Unterscheidung zwischen Array- und Hash-Nutzung machen. Dann kannst du eine Lua-Tabelle mit **[ ]** statt **{ }** schreiben, um eine Array-Tabelle darzustellen, und das Schreiben von Schlüssel-Wert-Paaren in einer Listentabelle ist nicht erlaubt. | ||
| 707 | 340 | ||
| 708 | ```yuescript | 341 | ```yuescript |
| 709 | some_values = [1, 2, 3, 4] | 342 | some_values = [1, 2, 3, 4] |
| 710 | list_with_one_element = [1, ] | 343 | list_with_one_element = [1, ] |
| 711 | ``` | 344 | ``` |
| 712 | 345 | ||
| 713 | <YueDisplay> | ||
| 714 | |||
| 715 | ```yue | ||
| 716 | some_values = [1, 2, 3, 4] | ||
| 717 | list_with_one_element = [1, ] | ||
| 718 | ``` | ||
| 719 | |||
| 720 | </YueDisplay> | ||
| 721 | |||
| 722 | # Comprehensions | 346 | # Comprehensions |
| 723 | 347 | ||
| 724 | Comprehensions bieten eine bequeme Syntax, um eine neue Tabelle zu erzeugen, indem man über ein bestehendes Objekt iteriert und einen Ausdruck auf seine Werte anwendet. Es gibt zwei Arten: Listen-Comprehensions und Tabellen-Comprehensions. Beide erzeugen Lua-Tabellen; Listen-Comprehensions sammeln Werte in einer array-ähnlichen Tabelle, und Tabellen-Comprehensions erlauben es, Schlüssel und Wert pro Iteration zu setzen. | 348 | Comprehensions bieten eine bequeme Syntax, um eine neue Tabelle zu erzeugen, indem man über ein bestehendes Objekt iteriert und einen Ausdruck auf seine Werte anwendet. Es gibt zwei Arten: Listen-Comprehensions und Tabellen-Comprehensions. Beide erzeugen Lua-Tabellen; Listen-Comprehensions sammeln Werte in einer array-ähnlichen Tabelle, und Tabellen-Comprehensions erlauben es, Schlüssel und Wert pro Iteration zu setzen. |
| @@ -732,43 +356,18 @@ items = [ 1, 2, 3, 4 ] | |||
| 732 | doubled = [item * 2 for i, item in ipairs items] | 356 | doubled = [item * 2 for i, item in ipairs items] |
| 733 | ``` | 357 | ``` |
| 734 | 358 | ||
| 735 | <YueDisplay> | ||
| 736 | |||
| 737 | ```yue | ||
| 738 | items = [ 1, 2, 3, 4 ] | ||
| 739 | doubled = [item * 2 for i, item in ipairs items] | ||
| 740 | ``` | ||
| 741 | |||
| 742 | </YueDisplay> | ||
| 743 | |||
| 744 | Die Elemente in der neuen Tabelle können mit einer `when`-Klausel eingeschränkt werden: | 359 | Die Elemente in der neuen Tabelle können mit einer `when`-Klausel eingeschränkt werden: |
| 745 | 360 | ||
| 746 | ```yuescript | 361 | ```yuescript |
| 747 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | 362 | slice = [item for i, item in ipairs items when i > 1 and i < 3] |
| 748 | ``` | 363 | ``` |
| 749 | 364 | ||
| 750 | <YueDisplay> | ||
| 751 | |||
| 752 | ```yue | ||
| 753 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | ||
| 754 | ``` | ||
| 755 | |||
| 756 | </YueDisplay> | ||
| 757 | |||
| 758 | Da es üblich ist, über die Werte einer numerisch indizierten Tabelle zu iterieren, gibt es den **\***-Operator. Das Verdopplungsbeispiel kann so umgeschrieben werden: | 365 | Da es üblich ist, über die Werte einer numerisch indizierten Tabelle zu iterieren, gibt es den **\***-Operator. Das Verdopplungsbeispiel kann so umgeschrieben werden: |
| 759 | 366 | ||
| 760 | ```yuescript | 367 | ```yuescript |
| 761 | doubled = [item * 2 for item in *items] | 368 | doubled = [item * 2 for item in *items] |
| 762 | ``` | 369 | ``` |
| 763 | 370 | ||
| 764 | <YueDisplay> | ||
| 765 | |||
| 766 | ```yue | ||
| 767 | doubled = [item * 2 for item in *items] | ||
| 768 | ``` | ||
| 769 | |||
| 770 | </YueDisplay> | ||
| 771 | |||
| 772 | In Listen-Comprehensions kannst du außerdem den Spread-Operator `...` verwenden, um verschachtelte Listen zu flatten und einen Flat-Map-Effekt zu erzielen: | 371 | In Listen-Comprehensions kannst du außerdem den Spread-Operator `...` verwenden, um verschachtelte Listen zu flatten und einen Flat-Map-Effekt zu erzielen: |
| 773 | 372 | ||
| 774 | ```yuescript | 373 | ```yuescript |
| @@ -780,19 +379,6 @@ flat = [...v for k,v in pairs data] | |||
| 780 | -- flat ist jetzt [1, 2, 3, 4, 5, 6] | 379 | -- flat ist jetzt [1, 2, 3, 4, 5, 6] |
| 781 | ``` | 380 | ``` |
| 782 | 381 | ||
| 783 | <YueDisplay> | ||
| 784 | |||
| 785 | ```yue | ||
| 786 | data = | ||
| 787 | a: [1, 2, 3] | ||
| 788 | b: [4, 5, 6] | ||
| 789 | |||
| 790 | flat = [...v for k,v in pairs data] | ||
| 791 | -- flat ist jetzt [1, 2, 3, 4, 5, 6] | ||
| 792 | ``` | ||
| 793 | |||
| 794 | </YueDisplay> | ||
| 795 | |||
| 796 | Die `for`- und `when`-Klauseln können beliebig oft verkettet werden. Die einzige Anforderung ist, dass eine Comprehension mindestens eine `for`-Klausel enthält. | 382 | Die `for`- und `when`-Klauseln können beliebig oft verkettet werden. Die einzige Anforderung ist, dass eine Comprehension mindestens eine `for`-Klausel enthält. |
| 797 | 383 | ||
| 798 | Mehrere `for`-Klauseln entsprechen verschachtelten Schleifen: | 384 | Mehrere `for`-Klauseln entsprechen verschachtelten Schleifen: |
| @@ -805,32 +391,12 @@ points = [ [x, y] for x in *x_coords \ | |||
| 805 | for y in *y_coords] | 391 | for y in *y_coords] |
| 806 | ``` | 392 | ``` |
| 807 | 393 | ||
| 808 | <YueDisplay> | ||
| 809 | |||
| 810 | ```yue | ||
| 811 | x_coords = [4, 5, 6, 7] | ||
| 812 | y_coords = [9, 2, 3] | ||
| 813 | |||
| 814 | points = [ [x, y] for x in *x_coords \ | ||
| 815 | for y in *y_coords] | ||
| 816 | ``` | ||
| 817 | |||
| 818 | </YueDisplay> | ||
| 819 | |||
| 820 | Numerische `for`-Schleifen können ebenfalls in Comprehensions verwendet werden: | 394 | Numerische `for`-Schleifen können ebenfalls in Comprehensions verwendet werden: |
| 821 | 395 | ||
| 822 | ```yuescript | 396 | ```yuescript |
| 823 | evens = [i for i = 1, 100 when i % 2 == 0] | 397 | evens = [i for i = 1, 100 when i % 2 == 0] |
| 824 | ``` | 398 | ``` |
| 825 | 399 | ||
| 826 | <YueDisplay> | ||
| 827 | |||
| 828 | ```yue | ||
| 829 | evens = [i for i = 1, 100 when i % 2 == 0] | ||
| 830 | ``` | ||
| 831 | |||
| 832 | </YueDisplay> | ||
| 833 | |||
| 834 | ## Tabellen-Comprehensions | 400 | ## Tabellen-Comprehensions |
| 835 | 401 | ||
| 836 | Die Syntax für Tabellen-Comprehensions ist sehr ähnlich, unterscheidet sich jedoch dadurch, dass **{** und **}** verwendet werden und pro Iteration zwei Werte erzeugt werden. | 402 | Die Syntax für Tabellen-Comprehensions ist sehr ähnlich, unterscheidet sich jedoch dadurch, dass **{** und **}** verwendet werden und pro Iteration zwei Werte erzeugt werden. |
| @@ -847,32 +413,10 @@ thing = { | |||
| 847 | thing_copy = {k, v for k, v in pairs thing} | 413 | thing_copy = {k, v for k, v in pairs thing} |
| 848 | ``` | 414 | ``` |
| 849 | 415 | ||
| 850 | <YueDisplay> | ||
| 851 | |||
| 852 | ```yue | ||
| 853 | thing = { | ||
| 854 | color: "rot" | ||
| 855 | name: "schnell" | ||
| 856 | width: 123 | ||
| 857 | } | ||
| 858 | |||
| 859 | thing_copy = {k, v for k, v in pairs thing} | ||
| 860 | ``` | ||
| 861 | |||
| 862 | </YueDisplay> | ||
| 863 | |||
| 864 | ```yuescript | 416 | ```yuescript |
| 865 | no_color = {k, v for k, v in pairs thing when k != "color"} | 417 | no_color = {k, v for k, v in pairs thing when k != "color"} |
| 866 | ``` | 418 | ``` |
| 867 | 419 | ||
| 868 | <YueDisplay> | ||
| 869 | |||
| 870 | ```yue | ||
| 871 | no_color = {k, v for k, v in pairs thing when k != "color"} | ||
| 872 | ``` | ||
| 873 | |||
| 874 | </YueDisplay> | ||
| 875 | |||
| 876 | Der **\***-Operator wird ebenfalls unterstützt. Hier erstellen wir eine Nachschlagetabelle für Quadratwurzeln einiger Zahlen. | 420 | Der **\***-Operator wird ebenfalls unterstützt. Hier erstellen wir eine Nachschlagetabelle für Quadratwurzeln einiger Zahlen. |
| 877 | 421 | ||
| 878 | ```yuescript | 422 | ```yuescript |
| @@ -880,15 +424,6 @@ numbers = [1, 2, 3, 4] | |||
| 880 | sqrts = {i, math.sqrt i for i in *numbers} | 424 | sqrts = {i, math.sqrt i for i in *numbers} |
| 881 | ``` | 425 | ``` |
| 882 | 426 | ||
| 883 | <YueDisplay> | ||
| 884 | |||
| 885 | ```yue | ||
| 886 | numbers = [1, 2, 3, 4] | ||
| 887 | sqrts = {i, math.sqrt i for i in *numbers} | ||
| 888 | ``` | ||
| 889 | |||
| 890 | </YueDisplay> | ||
| 891 | |||
| 892 | Das Schlüssel-Wert-Tupel in einer Tabellen-Comprehension kann auch aus einem einzelnen Ausdruck stammen; der Ausdruck muss dann zwei Werte zurückgeben. Der erste wird als Schlüssel und der zweite als Wert verwendet: | 427 | Das Schlüssel-Wert-Tupel in einer Tabellen-Comprehension kann auch aus einem einzelnen Ausdruck stammen; der Ausdruck muss dann zwei Werte zurückgeben. Der erste wird als Schlüssel und der zweite als Wert verwendet: |
| 893 | 428 | ||
| 894 | In diesem Beispiel konvertieren wir ein Array von Paaren in eine Tabelle, wobei das erste Element des Paars der Schlüssel und das zweite der Wert ist. | 429 | In diesem Beispiel konvertieren wir ein Array von Paaren in eine Tabelle, wobei das erste Element des Paars der Schlüssel und das zweite der Wert ist. |
| @@ -898,15 +433,6 @@ tuples = [ ["hallo", "Welt"], ["foo", "bar"]] | |||
| 898 | tbl = {unpack tuple for tuple in *tuples} | 433 | tbl = {unpack tuple for tuple in *tuples} |
| 899 | ``` | 434 | ``` |
| 900 | 435 | ||
| 901 | <YueDisplay> | ||
| 902 | |||
| 903 | ```yue | ||
| 904 | tuples = [ ["hallo", "Welt"], ["foo", "bar"]] | ||
| 905 | tbl = {unpack tuple for tuple in *tuples} | ||
| 906 | ``` | ||
| 907 | |||
| 908 | </YueDisplay> | ||
| 909 | |||
| 910 | ## Slicing | 436 | ## Slicing |
| 911 | 437 | ||
| 912 | Eine spezielle Syntax erlaubt es, die iterierten Elemente bei Verwendung des **\***-Operators einzuschränken. Das ist äquivalent zum Setzen von Iterationsgrenzen und Schrittweite in einer `for`-Schleife. | 438 | Eine spezielle Syntax erlaubt es, die iterierten Elemente bei Verwendung des **\***-Operators einzuschränken. Das ist äquivalent zum Setzen von Iterationsgrenzen und Schrittweite in einer `for`-Schleife. |
| @@ -917,42 +443,18 @@ Hier setzen wir die minimalen und maximalen Grenzen und nehmen alle Elemente mit | |||
| 917 | slice = [item for item in *items[1, 5]] | 443 | slice = [item for item in *items[1, 5]] |
| 918 | ``` | 444 | ``` |
| 919 | 445 | ||
| 920 | <YueDisplay> | ||
| 921 | |||
| 922 | ```yue | ||
| 923 | slice = [item for item in *items[1, 5]] | ||
| 924 | ``` | ||
| 925 | |||
| 926 | </YueDisplay> | ||
| 927 | |||
| 928 | Jedes der Slice-Argumente kann weggelassen werden, um einen sinnvollen Standard zu verwenden. Wenn der maximale Index weggelassen wird, entspricht er der Länge der Tabelle. Dieses Beispiel nimmt alles außer dem ersten Element: | 446 | Jedes der Slice-Argumente kann weggelassen werden, um einen sinnvollen Standard zu verwenden. Wenn der maximale Index weggelassen wird, entspricht er der Länge der Tabelle. Dieses Beispiel nimmt alles außer dem ersten Element: |
| 929 | 447 | ||
| 930 | ```yuescript | 448 | ```yuescript |
| 931 | slice = [item for item in *items[2,]] | 449 | slice = [item for item in *items[2,]] |
| 932 | ``` | 450 | ``` |
| 933 | 451 | ||
| 934 | <YueDisplay> | ||
| 935 | |||
| 936 | ```yue | ||
| 937 | slice = [item for item in *items[2,]] | ||
| 938 | ``` | ||
| 939 | |||
| 940 | </YueDisplay> | ||
| 941 | |||
| 942 | Wenn die Mindestgrenze weggelassen wird, ist sie standardmäßig 1. Hier geben wir nur die Schrittweite an und lassen die anderen Grenzen leer. Das nimmt alle ungerad indizierten Elemente (1, 3, 5, …): | 452 | Wenn die Mindestgrenze weggelassen wird, ist sie standardmäßig 1. Hier geben wir nur die Schrittweite an und lassen die anderen Grenzen leer. Das nimmt alle ungerad indizierten Elemente (1, 3, 5, …): |
| 943 | 453 | ||
| 944 | ```yuescript | 454 | ```yuescript |
| 945 | slice = [item for item in *items[,,2]] | 455 | slice = [item for item in *items[,,2]] |
| 946 | ``` | 456 | ``` |
| 947 | 457 | ||
| 948 | <YueDisplay> | ||
| 949 | |||
| 950 | ```yue | ||
| 951 | slice = [item for item in *items[,,2]] | ||
| 952 | ``` | ||
| 953 | |||
| 954 | </YueDisplay> | ||
| 955 | |||
| 956 | Sowohl die Mindest- als auch die Maximalgrenze können negativ sein; dann werden die Grenzen vom Ende der Tabelle gezählt. | 458 | Sowohl die Mindest- als auch die Maximalgrenze können negativ sein; dann werden die Grenzen vom Ende der Tabelle gezählt. |
| 957 | 459 | ||
| 958 | ```yuescript | 460 | ```yuescript |
| @@ -960,29 +462,12 @@ Sowohl die Mindest- als auch die Maximalgrenze können negativ sein; dann werden | |||
| 960 | slice = [item for item in *items[-4,-1]] | 462 | slice = [item for item in *items[-4,-1]] |
| 961 | ``` | 463 | ``` |
| 962 | 464 | ||
| 963 | <YueDisplay> | ||
| 964 | |||
| 965 | ```yue | ||
| 966 | -- die letzten 4 Elemente nehmen | ||
| 967 | slice = [item for item in *items[-4,-1]] | ||
| 968 | ``` | ||
| 969 | |||
| 970 | </YueDisplay> | ||
| 971 | |||
| 972 | Die Schrittweite kann ebenfalls negativ sein, wodurch die Elemente in umgekehrter Reihenfolge genommen werden. | 465 | Die Schrittweite kann ebenfalls negativ sein, wodurch die Elemente in umgekehrter Reihenfolge genommen werden. |
| 973 | 466 | ||
| 974 | ```yuescript | 467 | ```yuescript |
| 975 | reverse_slice = [item for item in *items[-1,1,-1]] | 468 | reverse_slice = [item for item in *items[-1,1,-1]] |
| 976 | ``` | 469 | ``` |
| 977 | 470 | ||
| 978 | <YueDisplay> | ||
| 979 | |||
| 980 | ```yue | ||
| 981 | reverse_slice = [item for item in *items[-1,1,-1]] | ||
| 982 | ``` | ||
| 983 | |||
| 984 | </YueDisplay> | ||
| 985 | |||
| 986 | ### Slicing-Ausdruck | 471 | ### Slicing-Ausdruck |
| 987 | 472 | ||
| 988 | Slicing kann auch als Ausdruck verwendet werden. Das ist nützlich, um eine Teilliste einer Tabelle zu erhalten. | 473 | Slicing kann auch als Ausdruck verwendet werden. Das ist nützlich, um eine Teilliste einer Tabelle zu erhalten. |
| @@ -995,18 +480,6 @@ sub_list = items[2, 4] | |||
| 995 | last_four_items = items[-4, -1] | 480 | last_four_items = items[-4, -1] |
| 996 | ``` | 481 | ``` |
| 997 | 482 | ||
| 998 | <YueDisplay> | ||
| 999 | |||
| 1000 | ```yue | ||
| 1001 | -- das 2. und 4. Element als neue Liste nehmen | ||
| 1002 | sub_list = items[2, 4] | ||
| 1003 | |||
| 1004 | -- die letzten 4 Elemente nehmen | ||
| 1005 | last_four_items = items[-4, -1] | ||
| 1006 | ``` | ||
| 1007 | |||
| 1008 | </YueDisplay> | ||
| 1009 | |||
| 1010 | # Objektorientierte Programmierung | 483 | # Objektorientierte Programmierung |
| 1011 | 484 | ||
| 1012 | In diesen Beispielen kann der generierte Lua-Code überwältigend wirken. Am besten konzentrierst du dich zunächst auf die Bedeutung des YueScript-Codes und schaust dir den Lua-Code nur an, wenn du die Implementierungsdetails wissen möchtest. | 485 | In diesen Beispielen kann der generierte Lua-Code überwältigend wirken. Am besten konzentrierst du dich zunächst auf die Bedeutung des YueScript-Codes und schaust dir den Lua-Code nur an, wenn du die Implementierungsdetails wissen möchtest. |
| @@ -1025,22 +498,6 @@ class Inventory | |||
| 1025 | @items[name] = 1 | 498 | @items[name] = 1 |
| 1026 | ``` | 499 | ``` |
| 1027 | 500 | ||
| 1028 | <YueDisplay> | ||
| 1029 | |||
| 1030 | ```yue | ||
| 1031 | class Inventory | ||
| 1032 | new: => | ||
| 1033 | @items = {} | ||
| 1034 | |||
| 1035 | add_item: (name) => | ||
| 1036 | if @items[name] | ||
| 1037 | @items[name] += 1 | ||
| 1038 | else | ||
| 1039 | @items[name] = 1 | ||
| 1040 | ``` | ||
| 1041 | |||
| 1042 | </YueDisplay> | ||
| 1043 | |||
| 1044 | Eine Klasse wird mit einem `class`-Statement deklariert, gefolgt von einer tabellenähnlichen Deklaration mit allen Methoden und Eigenschaften. | 501 | Eine Klasse wird mit einem `class`-Statement deklariert, gefolgt von einer tabellenähnlichen Deklaration mit allen Methoden und Eigenschaften. |
| 1045 | 502 | ||
| 1046 | Die Eigenschaft `new` ist besonders, da sie zum Konstruktor wird. | 503 | Die Eigenschaft `new` ist besonders, da sie zum Konstruktor wird. |
| @@ -1057,16 +514,6 @@ inv\add_item "T-Shirt" | |||
| 1057 | inv\add_item "Hose" | 514 | inv\add_item "Hose" |
| 1058 | ``` | 515 | ``` |
| 1059 | 516 | ||
| 1060 | <YueDisplay> | ||
| 1061 | |||
| 1062 | ```yue | ||
| 1063 | inv = Inventory! | ||
| 1064 | inv\add_item "T-Shirt" | ||
| 1065 | inv\add_item "Hose" | ||
| 1066 | ``` | ||
| 1067 | |||
| 1068 | </YueDisplay> | ||
| 1069 | |||
| 1070 | Da die Instanz bei Methodenaufrufen an die Methoden übergeben werden muss, wird der `\`-Operator verwendet. | 517 | Da die Instanz bei Methodenaufrufen an die Methoden übergeben werden muss, wird der `\`-Operator verwendet. |
| 1071 | 518 | ||
| 1072 | Alle Eigenschaften einer Klasse werden von allen Instanzen gemeinsam genutzt. Für Funktionen ist das ok, aber bei anderen Objekten kann das zu unerwünschten Ergebnissen führen. | 519 | Alle Eigenschaften einer Klasse werden von allen Instanzen gemeinsam genutzt. Für Funktionen ist das ok, aber bei anderen Objekten kann das zu unerwünschten Ergebnissen führen. |
| @@ -1089,26 +536,6 @@ b\give_item "Hemd" | |||
| 1089 | print item for item in *a.clothes | 536 | print item for item in *a.clothes |
| 1090 | ``` | 537 | ``` |
| 1091 | 538 | ||
| 1092 | <YueDisplay> | ||
| 1093 | |||
| 1094 | ```yue | ||
| 1095 | class Person | ||
| 1096 | clothes: [] | ||
| 1097 | give_item: (name) => | ||
| 1098 | table.insert @clothes, name | ||
| 1099 | |||
| 1100 | a = Person! | ||
| 1101 | b = Person! | ||
| 1102 | |||
| 1103 | a\give_item "Hose" | ||
| 1104 | b\give_item "Hemd" | ||
| 1105 | |||
| 1106 | -- gibt sowohl Hose als auch Hemd aus | ||
| 1107 | print item for item in *a.clothes | ||
| 1108 | ``` | ||
| 1109 | |||
| 1110 | </YueDisplay> | ||
| 1111 | |||
| 1112 | Der richtige Weg, das zu vermeiden, ist, den veränderlichen Zustand im Konstruktor zu erstellen: | 539 | Der richtige Weg, das zu vermeiden, ist, den veränderlichen Zustand im Konstruktor zu erstellen: |
| 1113 | 540 | ||
| 1114 | ```yuescript | 541 | ```yuescript |
| @@ -1117,16 +544,6 @@ class Person | |||
| 1117 | @clothes = [] | 544 | @clothes = [] |
| 1118 | ``` | 545 | ``` |
| 1119 | 546 | ||
| 1120 | <YueDisplay> | ||
| 1121 | |||
| 1122 | ```yue | ||
| 1123 | class Person | ||
| 1124 | new: => | ||
| 1125 | @clothes = [] | ||
| 1126 | ``` | ||
| 1127 | |||
| 1128 | </YueDisplay> | ||
| 1129 | |||
| 1130 | ## Vererbung | 547 | ## Vererbung |
| 1131 | 548 | ||
| 1132 | Das Schlüsselwort `extends` kann in einer Klassendeklaration verwendet werden, um Eigenschaften und Methoden von einer anderen Klasse zu erben. | 549 | Das Schlüsselwort `extends` kann in einer Klassendeklaration verwendet werden, um Eigenschaften und Methoden von einer anderen Klasse zu erben. |
| @@ -1139,18 +556,6 @@ class BackPack extends Inventory | |||
| 1139 | super name | 556 | super name |
| 1140 | ``` | 557 | ``` |
| 1141 | 558 | ||
| 1142 | <YueDisplay> | ||
| 1143 | |||
| 1144 | ```yue | ||
| 1145 | class BackPack extends Inventory | ||
| 1146 | size: 10 | ||
| 1147 | add_item: (name) => | ||
| 1148 | if #@items > size then error "Rucksack ist voll" | ||
| 1149 | super name | ||
| 1150 | ``` | ||
| 1151 | |||
| 1152 | </YueDisplay> | ||
| 1153 | |||
| 1154 | Hier erweitern wir unsere `Inventory`-Klasse und begrenzen die Anzahl der Elemente. | 559 | Hier erweitern wir unsere `Inventory`-Klasse und begrenzen die Anzahl der Elemente. |
| 1155 | 560 | ||
| 1156 | In diesem Beispiel definieren wir keinen Konstruktor in der Subklasse, daher wird der Konstruktor der Elternklasse beim Erstellen einer neuen Instanz aufgerufen. Definieren wir einen Konstruktor, können wir mit `super` den Elternkonstruktor aufrufen. | 561 | In diesem Beispiel definieren wir keinen Konstruktor in der Subklasse, daher wird der Konstruktor der Elternklasse beim Erstellen einer neuen Instanz aufgerufen. Definieren wir einen Konstruktor, können wir mit `super` den Elternkonstruktor aufrufen. |
| @@ -1166,19 +571,6 @@ class Shelf | |||
| 1166 | class Cupboard extends Shelf | 571 | class Cupboard extends Shelf |
| 1167 | ``` | 572 | ``` |
| 1168 | 573 | ||
| 1169 | <YueDisplay> | ||
| 1170 | |||
| 1171 | ```yue | ||
| 1172 | class Shelf | ||
| 1173 | @__inherited: (child) => | ||
| 1174 | print @__name, "wurde vererbt von", child.__name | ||
| 1175 | |||
| 1176 | -- gibt aus: Shelf wurde von Cupboard geerbt | ||
| 1177 | class Cupboard extends Shelf | ||
| 1178 | ``` | ||
| 1179 | |||
| 1180 | </YueDisplay> | ||
| 1181 | |||
| 1182 | ## Super | 574 | ## Super |
| 1183 | 575 | ||
| 1184 | **super** ist ein spezielles Schlüsselwort, das auf zwei Arten verwendet werden kann: als Objekt oder als Funktionsaufruf. Es hat besondere Funktionalität nur innerhalb einer Klasse. | 576 | **super** ist ein spezielles Schlüsselwort, das auf zwei Arten verwendet werden kann: als Objekt oder als Funktionsaufruf. Es hat besondere Funktionalität nur innerhalb einer Klasse. |
| @@ -1205,22 +597,6 @@ class MyClass extends ParentClass | |||
| 1205 | assert super == ParentClass | 597 | assert super == ParentClass |
| 1206 | ``` | 598 | ``` |
| 1207 | 599 | ||
| 1208 | <YueDisplay> | ||
| 1209 | |||
| 1210 | ```yue | ||
| 1211 | class MyClass extends ParentClass | ||
| 1212 | a_method: => | ||
| 1213 | -- Folgendes hat dieselbe Wirkung: | ||
| 1214 | super "hallo", "Welt" | ||
| 1215 | super\a_method "hallo", "Welt" | ||
| 1216 | super.a_method self, "hallo", "Welt" | ||
| 1217 | |||
| 1218 | -- super als Wert entspricht der Elternklasse: | ||
| 1219 | assert super == ParentClass | ||
| 1220 | ``` | ||
| 1221 | |||
| 1222 | </YueDisplay> | ||
| 1223 | |||
| 1224 | **super** kann auch links einer Funktions-Stub verwendet werden. Der einzige große Unterschied ist, dass die resultierende Funktion statt an `super` an `self` gebunden wird. | 600 | **super** kann auch links einer Funktions-Stub verwendet werden. Der einzige große Unterschied ist, dass die resultierende Funktion statt an `super` an `self` gebunden wird. |
| 1225 | 601 | ||
| 1226 | ## Typen | 602 | ## Typen |
| @@ -1234,17 +610,6 @@ assert b.__class == BackPack | |||
| 1234 | print BackPack.size -- gibt 10 aus | 610 | print BackPack.size -- gibt 10 aus |
| 1235 | ``` | 611 | ``` |
| 1236 | 612 | ||
| 1237 | <YueDisplay> | ||
| 1238 | |||
| 1239 | ```yue | ||
| 1240 | b = BackPack! | ||
| 1241 | assert b.__class == BackPack | ||
| 1242 | |||
| 1243 | print BackPack.size -- gibt 10 aus | ||
| 1244 | ``` | ||
| 1245 | |||
| 1246 | </YueDisplay> | ||
| 1247 | |||
| 1248 | ## Klassenobjekte | 613 | ## Klassenobjekte |
| 1249 | 614 | ||
| 1250 | Das Klassenobjekt entsteht, wenn wir ein `class`-Statement verwenden. Es wird in einer Variablen mit dem Klassennamen gespeichert. | 615 | Das Klassenobjekt entsteht, wenn wir ein `class`-Statement verwenden. Es wird in einer Variablen mit dem Klassennamen gespeichert. |
| @@ -1265,14 +630,6 @@ Der Name der Klasse, wie sie deklariert wurde, wird im Feld `__name` gespeichert | |||
| 1265 | print BackPack.__name -- gibt Backpack aus | 630 | print BackPack.__name -- gibt Backpack aus |
| 1266 | ``` | 631 | ``` |
| 1267 | 632 | ||
| 1268 | <YueDisplay> | ||
| 1269 | |||
| 1270 | ```yue | ||
| 1271 | print BackPack.__name -- gibt Backpack aus | ||
| 1272 | ``` | ||
| 1273 | |||
| 1274 | </YueDisplay> | ||
| 1275 | |||
| 1276 | Die Basistabelle ist in `__base` gespeichert. Du kannst diese Tabelle ändern, um Instanzen Funktionalität hinzuzufügen, die bereits existieren oder noch erstellt werden. | 633 | Die Basistabelle ist in `__base` gespeichert. Du kannst diese Tabelle ändern, um Instanzen Funktionalität hinzuzufügen, die bereits existieren oder noch erstellt werden. |
| 1277 | 634 | ||
| 1278 | Wenn die Klasse von etwas erbt, ist das Elternklassenobjekt in `__parent` gespeichert. | 635 | Wenn die Klasse von etwas erbt, ist das Elternklassenobjekt in `__parent` gespeichert. |
| @@ -1291,20 +648,6 @@ Things\some_func! | |||
| 1291 | assert Things().some_func == nil | 648 | assert Things().some_func == nil |
| 1292 | ``` | 649 | ``` |
| 1293 | 650 | ||
| 1294 | <YueDisplay> | ||
| 1295 | |||
| 1296 | ```yue | ||
| 1297 | class Things | ||
| 1298 | @some_func: => print "Hallo von", @__name | ||
| 1299 | |||
| 1300 | Things\some_func! | ||
| 1301 | |||
| 1302 | -- Klassenvariablen in Instanzen nicht sichtbar | ||
| 1303 | assert Things().some_func == nil | ||
| 1304 | ``` | ||
| 1305 | |||
| 1306 | </YueDisplay> | ||
| 1307 | |||
| 1308 | In Ausdrücken können wir `@@` verwenden, um auf einen Wert zuzugreifen, der in `self.__class` gespeichert ist. `@@hello` ist also eine Kurzform für `self.__class.hello`. | 651 | In Ausdrücken können wir `@@` verwenden, um auf einen Wert zuzugreifen, der in `self.__class` gespeichert ist. `@@hello` ist also eine Kurzform für `self.__class.hello`. |
| 1309 | 652 | ||
| 1310 | ```yuescript | 653 | ```yuescript |
| @@ -1320,37 +663,12 @@ Counter! | |||
| 1320 | print Counter.count -- gibt 2 aus | 663 | print Counter.count -- gibt 2 aus |
| 1321 | ``` | 664 | ``` |
| 1322 | 665 | ||
| 1323 | <YueDisplay> | ||
| 1324 | |||
| 1325 | ```yue | ||
| 1326 | class Counter | ||
| 1327 | @count: 0 | ||
| 1328 | |||
| 1329 | new: => | ||
| 1330 | @@count += 1 | ||
| 1331 | |||
| 1332 | Counter! | ||
| 1333 | Counter! | ||
| 1334 | |||
| 1335 | print Counter.count -- gibt 2 aus | ||
| 1336 | ``` | ||
| 1337 | |||
| 1338 | </YueDisplay> | ||
| 1339 | |||
| 1340 | Die Aufrufsemantik von `@@` ist ähnlich wie bei `@`. Wenn du einen `@@`-Namen aufrufst, wird die Klasse als erstes Argument übergeben (Lua-`:`-Syntax). | 666 | Die Aufrufsemantik von `@@` ist ähnlich wie bei `@`. Wenn du einen `@@`-Namen aufrufst, wird die Klasse als erstes Argument übergeben (Lua-`:`-Syntax). |
| 1341 | 667 | ||
| 1342 | ```yuescript | 668 | ```yuescript |
| 1343 | @@hello 1,2,3,4 | 669 | @@hello 1,2,3,4 |
| 1344 | ``` | 670 | ``` |
| 1345 | 671 | ||
| 1346 | <YueDisplay> | ||
| 1347 | |||
| 1348 | ```yue | ||
| 1349 | @@hello 1,2,3,4 | ||
| 1350 | ``` | ||
| 1351 | |||
| 1352 | </YueDisplay> | ||
| 1353 | |||
| 1354 | ## Klassendeklarations-Statements | 672 | ## Klassendeklarations-Statements |
| 1355 | 673 | ||
| 1356 | Im Rumpf einer Klassendeklaration können wir normale Ausdrücke zusätzlich zu Schlüssel/Wert-Paaren haben. In diesem Kontext ist `self` gleich dem Klassenobjekt. | 674 | Im Rumpf einer Klassendeklaration können wir normale Ausdrücke zusätzlich zu Schlüssel/Wert-Paaren haben. In diesem Kontext ist `self` gleich dem Klassenobjekt. |
| @@ -1362,15 +680,6 @@ class Things | |||
| 1362 | @class_var = "Hallo Welt" | 680 | @class_var = "Hallo Welt" |
| 1363 | ``` | 681 | ``` |
| 1364 | 682 | ||
| 1365 | <YueDisplay> | ||
| 1366 | |||
| 1367 | ```yue | ||
| 1368 | class Things | ||
| 1369 | @class_var = "Hallo Welt" | ||
| 1370 | ``` | ||
| 1371 | |||
| 1372 | </YueDisplay> | ||
| 1373 | |||
| 1374 | Diese Ausdrücke werden ausgeführt, nachdem alle Eigenschaften zur Basis hinzugefügt wurden. | 683 | Diese Ausdrücke werden ausgeführt, nachdem alle Eigenschaften zur Basis hinzugefügt wurden. |
| 1375 | 684 | ||
| 1376 | Alle Variablen, die im Klassenkörper deklariert werden, sind lokal zu den Klasseneigenschaften. Das ist praktisch, um private Werte oder Hilfsfunktionen zu platzieren, auf die nur die Klassenmethoden zugreifen können: | 685 | Alle Variablen, die im Klassenkörper deklariert werden, sind lokal zu den Klasseneigenschaften. Das ist praktisch, um private Werte oder Hilfsfunktionen zu platzieren, auf die nur die Klassenmethoden zugreifen können: |
| @@ -1384,19 +693,6 @@ class MoreThings | |||
| 1384 | log "Hallo Welt: " .. secret | 693 | log "Hallo Welt: " .. secret |
| 1385 | ``` | 694 | ``` |
| 1386 | 695 | ||
| 1387 | <YueDisplay> | ||
| 1388 | |||
| 1389 | ```yue | ||
| 1390 | class MoreThings | ||
| 1391 | secret = 123 | ||
| 1392 | log = (msg) -> print "LOG:", msg | ||
| 1393 | |||
| 1394 | some_method: => | ||
| 1395 | log "Hallo Welt: " .. secret | ||
| 1396 | ``` | ||
| 1397 | |||
| 1398 | </YueDisplay> | ||
| 1399 | |||
| 1400 | ## @- und @@-Werte | 696 | ## @- und @@-Werte |
| 1401 | 697 | ||
| 1402 | Wenn `@` und `@@` vor einem Namen stehen, repräsentieren sie den Namen in `self` bzw. `self.__class`. | 698 | Wenn `@` und `@@` vor einem Namen stehen, repräsentieren sie den Namen in `self` bzw. `self.__class`. |
| @@ -1408,29 +704,12 @@ assert @ == self | |||
| 1408 | assert @@ == self.__class | 704 | assert @@ == self.__class |
| 1409 | ``` | 705 | ``` |
| 1410 | 706 | ||
| 1411 | <YueDisplay> | ||
| 1412 | |||
| 1413 | ```yue | ||
| 1414 | assert @ == self | ||
| 1415 | assert @@ == self.__class | ||
| 1416 | ``` | ||
| 1417 | |||
| 1418 | </YueDisplay> | ||
| 1419 | |||
| 1420 | Zum Beispiel kannst du mit `@@` in einer Instanzmethode schnell eine neue Instanz derselben Klasse erzeugen: | 707 | Zum Beispiel kannst du mit `@@` in einer Instanzmethode schnell eine neue Instanz derselben Klasse erzeugen: |
| 1421 | 708 | ||
| 1422 | ```yuescript | 709 | ```yuescript |
| 1423 | some_instance_method = (...) => @@ ... | 710 | some_instance_method = (...) => @@ ... |
| 1424 | ``` | 711 | ``` |
| 1425 | 712 | ||
| 1426 | <YueDisplay> | ||
| 1427 | |||
| 1428 | ```yue | ||
| 1429 | some_instance_method = (...) => @@ ... | ||
| 1430 | ``` | ||
| 1431 | |||
| 1432 | </YueDisplay> | ||
| 1433 | |||
| 1434 | ## Konstruktor-Property-Promotion | 713 | ## Konstruktor-Property-Promotion |
| 1435 | 714 | ||
| 1436 | Um Boilerplate beim Definieren einfacher Value-Objekte zu reduzieren, kannst du eine Klasse so schreiben: | 715 | Um Boilerplate beim Definieren einfacher Value-Objekte zu reduzieren, kannst du eine Klasse so schreiben: |
| @@ -1449,24 +728,6 @@ class Something | |||
| 1449 | @@baz = baz | 728 | @@baz = baz |
| 1450 | ``` | 729 | ``` |
| 1451 | 730 | ||
| 1452 | <YueDisplay> | ||
| 1453 | |||
| 1454 | ```yue | ||
| 1455 | class Something | ||
| 1456 | new: (@foo, @bar, @@biz, @@baz) => | ||
| 1457 | |||
| 1458 | -- Kurzform für | ||
| 1459 | |||
| 1460 | class Something | ||
| 1461 | new: (foo, bar, biz, baz) => | ||
| 1462 | @foo = foo | ||
| 1463 | @bar = bar | ||
| 1464 | @@biz = biz | ||
| 1465 | @@baz = baz | ||
| 1466 | ``` | ||
| 1467 | |||
| 1468 | </YueDisplay> | ||
| 1469 | |||
| 1470 | Du kannst diese Syntax auch für eine gemeinsame Funktion verwenden, um Objektfelder zu initialisieren. | 731 | Du kannst diese Syntax auch für eine gemeinsame Funktion verwenden, um Objektfelder zu initialisieren. |
| 1471 | 732 | ||
| 1472 | ```yuescript | 733 | ```yuescript |
| @@ -1475,16 +736,6 @@ obj = new {}, 123, "abc" | |||
| 1475 | print obj | 736 | print obj |
| 1476 | ``` | 737 | ``` |
| 1477 | 738 | ||
| 1478 | <YueDisplay> | ||
| 1479 | |||
| 1480 | ```yue | ||
| 1481 | new = (@fieldA, @fieldB) => @ | ||
| 1482 | obj = new {}, 123, "abc" | ||
| 1483 | print obj | ||
| 1484 | ``` | ||
| 1485 | |||
| 1486 | </YueDisplay> | ||
| 1487 | |||
| 1488 | ## Klassenausdrücke | 739 | ## Klassenausdrücke |
| 1489 | 740 | ||
| 1490 | Die `class`-Syntax kann auch als Ausdruck verwendet werden, der einer Variable zugewiesen oder explizit zurückgegeben wird. | 741 | Die `class`-Syntax kann auch als Ausdruck verwendet werden, der einer Variable zugewiesen oder explizit zurückgegeben wird. |
| @@ -1495,16 +746,6 @@ x = class Bucket | |||
| 1495 | add_drop: => @drops += 1 | 746 | add_drop: => @drops += 1 |
| 1496 | ``` | 747 | ``` |
| 1497 | 748 | ||
| 1498 | <YueDisplay> | ||
| 1499 | |||
| 1500 | ```yue | ||
| 1501 | x = class Bucket | ||
| 1502 | drops: 0 | ||
| 1503 | add_drop: => @drops += 1 | ||
| 1504 | ``` | ||
| 1505 | |||
| 1506 | </YueDisplay> | ||
| 1507 | |||
| 1508 | ## Anonyme Klassen | 749 | ## Anonyme Klassen |
| 1509 | 750 | ||
| 1510 | Der Name kann beim Deklarieren einer Klasse weggelassen werden. Das `__name`-Attribut ist dann `nil`, es sei denn, der Klassenausdruck steht in einer Zuweisung. In diesem Fall wird der Name auf der linken Seite statt `nil` verwendet. | 751 | Der Name kann beim Deklarieren einer Klasse weggelassen werden. Das `__name`-Attribut ist dann `nil`, es sei denn, der Klassenausdruck steht in einer Zuweisung. In diesem Fall wird der Name auf der linken Seite statt `nil` verwendet. |
| @@ -1516,31 +757,12 @@ BigBucket = class extends Bucket | |||
| 1516 | assert Bucket.__name == "BigBucket" | 757 | assert Bucket.__name == "BigBucket" |
| 1517 | ``` | 758 | ``` |
| 1518 | 759 | ||
| 1519 | <YueDisplay> | ||
| 1520 | |||
| 1521 | ```yue | ||
| 1522 | BigBucket = class extends Bucket | ||
| 1523 | add_drop: => @drops += 10 | ||
| 1524 | |||
| 1525 | assert Bucket.__name == "BigBucket" | ||
| 1526 | ``` | ||
| 1527 | |||
| 1528 | </YueDisplay> | ||
| 1529 | |||
| 1530 | Du kannst sogar den Körper weglassen und eine leere anonyme Klasse schreiben: | 760 | Du kannst sogar den Körper weglassen und eine leere anonyme Klasse schreiben: |
| 1531 | 761 | ||
| 1532 | ```yuescript | 762 | ```yuescript |
| 1533 | x = class | 763 | x = class |
| 1534 | ``` | 764 | ``` |
| 1535 | 765 | ||
| 1536 | <YueDisplay> | ||
| 1537 | |||
| 1538 | ```yue | ||
| 1539 | x = class | ||
| 1540 | ``` | ||
| 1541 | |||
| 1542 | </YueDisplay> | ||
| 1543 | |||
| 1544 | ## Class Mixing | 766 | ## Class Mixing |
| 1545 | 767 | ||
| 1546 | Du kannst mit dem Schlüsselwort `using` mischen, um Funktionen aus einer einfachen Tabelle oder einem vordefinierten Klassenobjekt in deine neue Klasse zu kopieren. Beim Mischen mit einer einfachen Tabelle kannst du die Klassen-Indexing-Funktion (Metamethod `__index`) überschreiben. Beim Mischen mit einem bestehenden Klassenobjekt werden dessen Metamethoden nicht kopiert. | 768 | Du kannst mit dem Schlüsselwort `using` mischen, um Funktionen aus einer einfachen Tabelle oder einem vordefinierten Klassenobjekt in deine neue Klasse zu kopieren. Beim Mischen mit einer einfachen Tabelle kannst du die Klassen-Indexing-Funktion (Metamethod `__index`) überschreiben. Beim Mischen mit einem bestehenden Klassenobjekt werden dessen Metamethoden nicht kopiert. |
| @@ -1563,28 +785,6 @@ y\func! | |||
| 1563 | assert y.__class.__parent ~= X -- X ist nicht die Elternklasse von Y | 785 | assert y.__class.__parent ~= X -- X ist nicht die Elternklasse von Y |
| 1564 | ``` | 786 | ``` |
| 1565 | 787 | ||
| 1566 | <YueDisplay> | ||
| 1567 | |||
| 1568 | ```yue | ||
| 1569 | MyIndex = __index: var: 1 | ||
| 1570 | |||
| 1571 | class X using MyIndex | ||
| 1572 | func: => | ||
| 1573 | print 123 | ||
| 1574 | |||
| 1575 | x = X! | ||
| 1576 | print x.var | ||
| 1577 | |||
| 1578 | class Y using X | ||
| 1579 | |||
| 1580 | y = Y! | ||
| 1581 | y\func! | ||
| 1582 | |||
| 1583 | assert y.__class.__parent ~= X -- X ist nicht die Elternklasse von Y | ||
| 1584 | ``` | ||
| 1585 | |||
| 1586 | </YueDisplay> | ||
| 1587 | |||
| 1588 | # With-Statement | 788 | # With-Statement |
| 1589 | 789 | ||
| 1590 | Ein häufiges Muster bei der Erstellung eines Objekts ist, unmittelbar danach eine Reihe von Funktionen aufzurufen und Eigenschaften zu setzen. | 790 | Ein häufiges Muster bei der Erstellung eines Objekts ist, unmittelbar danach eine Reihe von Funktionen aufzurufen und Eigenschaften zu setzen. |
| @@ -1603,18 +803,6 @@ with Person! | |||
| 1603 | print .name | 803 | print .name |
| 1604 | ``` | 804 | ``` |
| 1605 | 805 | ||
| 1606 | <YueDisplay> | ||
| 1607 | |||
| 1608 | ```yue | ||
| 1609 | with Person! | ||
| 1610 | .name = "Oswald" | ||
| 1611 | \add_relative my_dad | ||
| 1612 | \save! | ||
| 1613 | print .name | ||
| 1614 | ``` | ||
| 1615 | |||
| 1616 | </YueDisplay> | ||
| 1617 | |||
| 1618 | Das `with`-Statement kann auch als Ausdruck verwendet werden und gibt den Wert zurück, auf den es Zugriff gewährt. | 806 | Das `with`-Statement kann auch als Ausdruck verwendet werden und gibt den Wert zurück, auf den es Zugriff gewährt. |
| 1619 | 807 | ||
| 1620 | ```yuescript | 808 | ```yuescript |
| @@ -1622,15 +810,6 @@ file = with File "Lieblingsessen.txt" | |||
| 1622 | \set_encoding "utf8" | 810 | \set_encoding "utf8" |
| 1623 | ``` | 811 | ``` |
| 1624 | 812 | ||
| 1625 | <YueDisplay> | ||
| 1626 | |||
| 1627 | ```yue | ||
| 1628 | file = with File "Lieblingsessen.txt" | ||
| 1629 | \set_encoding "utf8" | ||
| 1630 | ``` | ||
| 1631 | |||
| 1632 | </YueDisplay> | ||
| 1633 | |||
| 1634 | `with`-Ausdrücke unterstützen `break` mit genau einem Wert: | 813 | `with`-Ausdrücke unterstützen `break` mit genau einem Wert: |
| 1635 | 814 | ||
| 1636 | ```yuescript | 815 | ```yuescript |
| @@ -1638,15 +817,6 @@ result = with obj | |||
| 1638 | break .value | 817 | break .value |
| 1639 | ``` | 818 | ``` |
| 1640 | 819 | ||
| 1641 | <YueDisplay> | ||
| 1642 | |||
| 1643 | ```yue | ||
| 1644 | result = with obj | ||
| 1645 | break .value | ||
| 1646 | ``` | ||
| 1647 | |||
| 1648 | </YueDisplay> | ||
| 1649 | |||
| 1650 | Sobald `break value` in `with` verwendet wird, gibt der `with`-Ausdruck nicht mehr sein Zielobjekt zurück, sondern den von `break` gelieferten Wert. | 820 | Sobald `break value` in `with` verwendet wird, gibt der `with`-Ausdruck nicht mehr sein Zielobjekt zurück, sondern den von `break` gelieferten Wert. |
| 1651 | 821 | ||
| 1652 | ```yuescript | 822 | ```yuescript |
| @@ -1659,20 +829,6 @@ b = with obj | |||
| 1659 | -- b ist .x, nicht obj | 829 | -- b ist .x, nicht obj |
| 1660 | ``` | 830 | ``` |
| 1661 | 831 | ||
| 1662 | <YueDisplay> | ||
| 1663 | |||
| 1664 | ```yue | ||
| 1665 | a = with obj | ||
| 1666 | .x = 1 | ||
| 1667 | -- a ist obj | ||
| 1668 | |||
| 1669 | b = with obj | ||
| 1670 | break .x | ||
| 1671 | -- b ist .x, nicht obj | ||
| 1672 | ``` | ||
| 1673 | |||
| 1674 | </YueDisplay> | ||
| 1675 | |||
| 1676 | Im Unterschied zu `for` / `while` / `repeat` / `do` unterstützt `with` nur einen `break`-Wert. | 832 | Im Unterschied zu `for` / `while` / `repeat` / `do` unterstützt `with` nur einen `break`-Wert. |
| 1677 | 833 | ||
| 1678 | Oder … | 834 | Oder … |
| @@ -1686,19 +842,6 @@ create_person = (name, relatives) -> | |||
| 1686 | me = create_person "Leaf", [dad, mother, sister] | 842 | me = create_person "Leaf", [dad, mother, sister] |
| 1687 | ``` | 843 | ``` |
| 1688 | 844 | ||
| 1689 | <YueDisplay> | ||
| 1690 | |||
| 1691 | ```yue | ||
| 1692 | create_person = (name, relatives) -> | ||
| 1693 | with Person! | ||
| 1694 | .name = name | ||
| 1695 | \add_relative relative for relative in *relatives | ||
| 1696 | |||
| 1697 | me = create_person "Leaf", [dad, mother, sister] | ||
| 1698 | ``` | ||
| 1699 | |||
| 1700 | </YueDisplay> | ||
| 1701 | |||
| 1702 | In dieser Verwendung kann `with` als spezielle Form des K-Kombinators gesehen werden. | 845 | In dieser Verwendung kann `with` als spezielle Form des K-Kombinators gesehen werden. |
| 1703 | 846 | ||
| 1704 | Der Ausdruck im `with`-Statement kann auch eine Zuweisung sein, wenn du dem Ausdruck einen Namen geben willst. | 847 | Der Ausdruck im `with`-Statement kann auch eine Zuweisung sein, wenn du dem Ausdruck einen Namen geben willst. |
| @@ -1709,16 +852,6 @@ with str := "Hallo" | |||
| 1709 | print "Großbuchstaben:", \upper! | 852 | print "Großbuchstaben:", \upper! |
| 1710 | ``` | 853 | ``` |
| 1711 | 854 | ||
| 1712 | <YueDisplay> | ||
| 1713 | |||
| 1714 | ```yue | ||
| 1715 | with str := "Hallo" | ||
| 1716 | print "Original:", str | ||
| 1717 | print "Großbuchstaben:", \upper! | ||
| 1718 | ``` | ||
| 1719 | |||
| 1720 | </YueDisplay> | ||
| 1721 | |||
| 1722 | Du kannst in einem `with`-Statement über `[]` auf spezielle Schlüssel zugreifen. | 855 | Du kannst in einem `with`-Statement über `[]` auf spezielle Schlüssel zugreifen. |
| 1723 | 856 | ||
| 1724 | ```yuescript | 857 | ```yuescript |
| @@ -1731,20 +864,6 @@ with tb | |||
| 1731 | [] = "abc" -- an "tb" anhängen | 864 | [] = "abc" -- an "tb" anhängen |
| 1732 | ``` | 865 | ``` |
| 1733 | 866 | ||
| 1734 | <YueDisplay> | ||
| 1735 | |||
| 1736 | ```yue | ||
| 1737 | with tb | ||
| 1738 | [1] = 1 | ||
| 1739 | print [2] | ||
| 1740 | with [abc] | ||
| 1741 | [3] = [2]\func! | ||
| 1742 | ["key-name"] = value | ||
| 1743 | [] = "abc" -- an "tb" anhängen | ||
| 1744 | ``` | ||
| 1745 | |||
| 1746 | </YueDisplay> | ||
| 1747 | |||
| 1748 | `with?` ist eine erweiterte Version der `with`-Syntax, die einen Existenz-Check einführt, um Objekte, die `nil` sein könnten, sicher zuzugreifen, ohne explizite Nullprüfungen. | 867 | `with?` ist eine erweiterte Version der `with`-Syntax, die einen Existenz-Check einführt, um Objekte, die `nil` sein könnten, sicher zuzugreifen, ohne explizite Nullprüfungen. |
| 1749 | 868 | ||
| 1750 | ```yuescript | 869 | ```yuescript |
| @@ -1752,15 +871,6 @@ with? obj | |||
| 1752 | print obj.name | 871 | print obj.name |
| 1753 | ``` | 872 | ``` |
| 1754 | 873 | ||
| 1755 | <YueDisplay> | ||
| 1756 | |||
| 1757 | ```yue | ||
| 1758 | with? obj | ||
| 1759 | print obj.name | ||
| 1760 | ``` | ||
| 1761 | |||
| 1762 | </YueDisplay> | ||
| 1763 | |||
| 1764 | # Zuweisung | 874 | # Zuweisung |
| 1765 | 875 | ||
| 1766 | Variablen sind dynamisch typisiert und standardmäßig `local`. Du kannst den Geltungsbereich mit den Statements **local** und **global** ändern. | 876 | Variablen sind dynamisch typisiert und standardmäßig `local`. Du kannst den Geltungsbereich mit den Statements **local** und **global** ändern. |
| @@ -1771,16 +881,6 @@ a, b, c = 1, 2, 3 | |||
| 1771 | hello = 123 -- nutzt die bestehende Variable | 881 | hello = 123 -- nutzt die bestehende Variable |
| 1772 | ``` | 882 | ``` |
| 1773 | 883 | ||
| 1774 | <YueDisplay> | ||
| 1775 | |||
| 1776 | ```yue | ||
| 1777 | hello = "world" | ||
| 1778 | a, b, c = 1, 2, 3 | ||
| 1779 | hello = 123 -- nutzt die bestehende Variable | ||
| 1780 | ``` | ||
| 1781 | |||
| 1782 | </YueDisplay> | ||
| 1783 | |||
| 1784 | ## Update-Zuweisung | 884 | ## Update-Zuweisung |
| 1785 | 885 | ||
| 1786 | Du kannst Update-Zuweisungen mit vielen binären Operatoren durchführen. | 886 | Du kannst Update-Zuweisungen mit vielen binären Operatoren durchführen. |
| @@ -1796,21 +896,6 @@ s ..= "world" -- legt eine neue lokale Variable an, wenn sie nicht existiert | |||
| 1796 | arg or= "default value" | 896 | arg or= "default value" |
| 1797 | ``` | 897 | ``` |
| 1798 | 898 | ||
| 1799 | <YueDisplay> | ||
| 1800 | |||
| 1801 | ```yue | ||
| 1802 | x = 1 | ||
| 1803 | x += 1 | ||
| 1804 | x -= 1 | ||
| 1805 | x *= 10 | ||
| 1806 | x /= 10 | ||
| 1807 | x %= 10 | ||
| 1808 | s ..= "world" -- legt eine neue lokale Variable an, wenn sie nicht existiert | ||
| 1809 | arg or= "default value" | ||
| 1810 | ``` | ||
| 1811 | |||
| 1812 | </YueDisplay> | ||
| 1813 | |||
| 1814 | ## Verkettete Zuweisung | 899 | ## Verkettete Zuweisung |
| 1815 | 900 | ||
| 1816 | Mit verketteten Zuweisungen kannst du mehrere Variablen auf denselben Wert setzen. | 901 | Mit verketteten Zuweisungen kannst du mehrere Variablen auf denselben Wert setzen. |
| @@ -1820,15 +905,6 @@ a = b = c = d = e = 0 | |||
| 1820 | x = y = z = f! | 905 | x = y = z = f! |
| 1821 | ``` | 906 | ``` |
| 1822 | 907 | ||
| 1823 | <YueDisplay> | ||
| 1824 | |||
| 1825 | ```yue | ||
| 1826 | a = b = c = d = e = 0 | ||
| 1827 | x = y = z = f! | ||
| 1828 | ``` | ||
| 1829 | |||
| 1830 | </YueDisplay> | ||
| 1831 | |||
| 1832 | ## Explizite Locals | 908 | ## Explizite Locals |
| 1833 | 909 | ||
| 1834 | ```yuescript | 910 | ```yuescript |
| @@ -1848,27 +924,6 @@ do | |||
| 1848 | B = 2 | 924 | B = 2 |
| 1849 | ``` | 925 | ``` |
| 1850 | 926 | ||
| 1851 | <YueDisplay> | ||
| 1852 | |||
| 1853 | ```yue | ||
| 1854 | do | ||
| 1855 | local a = 1 | ||
| 1856 | local * | ||
| 1857 | print "forward declare all variables as locals" | ||
| 1858 | x = -> 1 + y + z | ||
| 1859 | y, z = 2, 3 | ||
| 1860 | global instance = Item\new! | ||
| 1861 | |||
| 1862 | do | ||
| 1863 | local X = 1 | ||
| 1864 | local ^ | ||
| 1865 | print "only forward declare upper case variables" | ||
| 1866 | a = 1 | ||
| 1867 | B = 2 | ||
| 1868 | ``` | ||
| 1869 | |||
| 1870 | </YueDisplay> | ||
| 1871 | |||
| 1872 | ## Explizite Globals | 927 | ## Explizite Globals |
| 1873 | 928 | ||
| 1874 | ```yuescript | 929 | ```yuescript |
| @@ -1888,27 +943,6 @@ do | |||
| 1888 | local Temp = "a local value" | 943 | local Temp = "a local value" |
| 1889 | ``` | 944 | ``` |
| 1890 | 945 | ||
| 1891 | <YueDisplay> | ||
| 1892 | |||
| 1893 | ```yue | ||
| 1894 | do | ||
| 1895 | global a = 1 | ||
| 1896 | global * | ||
| 1897 | print "declare all variables as globals" | ||
| 1898 | x = -> 1 + y + z | ||
| 1899 | y, z = 2, 3 | ||
| 1900 | |||
| 1901 | do | ||
| 1902 | global X = 1 | ||
| 1903 | global ^ | ||
| 1904 | print "only declare upper case variables as globals" | ||
| 1905 | a = 1 | ||
| 1906 | B = 2 | ||
| 1907 | local Temp = "a local value" | ||
| 1908 | ``` | ||
| 1909 | |||
| 1910 | </YueDisplay> | ||
| 1911 | |||
| 1912 | # Varargs-Zuweisung | 946 | # Varargs-Zuweisung |
| 1913 | 947 | ||
| 1914 | Du kannst Rückgabewerte einer Funktion dem Varargs-Symbol `...` zuweisen und dann den Inhalt auf die Lua-Weise auslesen. | 948 | Du kannst Rückgabewerte einer Funktion dem Varargs-Symbol `...` zuweisen und dann den Inhalt auf die Lua-Weise auslesen. |
| @@ -1922,19 +956,6 @@ first = select 1, ... | |||
| 1922 | print ok, count, first | 956 | print ok, count, first |
| 1923 | ``` | 957 | ``` |
| 1924 | 958 | ||
| 1925 | <YueDisplay> | ||
| 1926 | |||
| 1927 | ```yue | ||
| 1928 | list = [1, 2, 3, 4, 5] | ||
| 1929 | fn = (ok) -> ok, table.unpack list | ||
| 1930 | ok, ... = fn true | ||
| 1931 | count = select '#', ... | ||
| 1932 | first = select 1, ... | ||
| 1933 | print ok, count, first | ||
| 1934 | ``` | ||
| 1935 | |||
| 1936 | </YueDisplay> | ||
| 1937 | |||
| 1938 | # If-Zuweisung | 959 | # If-Zuweisung |
| 1939 | 960 | ||
| 1940 | `if`- und `elseif`-Blöcke können eine Zuweisung anstelle eines Bedingungsausdrucks enthalten. Beim Auswerten der Bedingung findet die Zuweisung statt, und der zugewiesene Wert wird als Bedingung verwendet. Die zugewiesene Variable ist nur im Geltungsbereich des Bedingungsblocks verfügbar, d. h. sie ist nicht verfügbar, wenn der Wert nicht truthy ist. Für die Zuweisung musst du den "Walrus-Operator" `:=` statt `=` verwenden. | 961 | `if`- und `elseif`-Blöcke können eine Zuweisung anstelle eines Bedingungsausdrucks enthalten. Beim Auswerten der Bedingung findet die Zuweisung statt, und der zugewiesene Wert wird als Bedingung verwendet. Die zugewiesene Variable ist nur im Geltungsbereich des Bedingungsblocks verfügbar, d. h. sie ist nicht verfügbar, wenn der Wert nicht truthy ist. Für die Zuweisung musst du den "Walrus-Operator" `:=` statt `=` verwenden. |
| @@ -1944,15 +965,6 @@ if user := database.find_user "moon" | |||
| 1944 | print user.name | 965 | print user.name |
| 1945 | ``` | 966 | ``` |
| 1946 | 967 | ||
| 1947 | <YueDisplay> | ||
| 1948 | |||
| 1949 | ```yue | ||
| 1950 | if user := database.find_user "moon" | ||
| 1951 | print user.name | ||
| 1952 | ``` | ||
| 1953 | |||
| 1954 | </YueDisplay> | ||
| 1955 | |||
| 1956 | ```yuescript | 968 | ```yuescript |
| 1957 | if hello := os.getenv "hello" | 969 | if hello := os.getenv "hello" |
| 1958 | print "Du hast hello", hello | 970 | print "Du hast hello", hello |
| @@ -1962,19 +974,6 @@ else | |||
| 1962 | print "nichts :(" | 974 | print "nichts :(" |
| 1963 | ``` | 975 | ``` |
| 1964 | 976 | ||
| 1965 | <YueDisplay> | ||
| 1966 | |||
| 1967 | ```yue | ||
| 1968 | if hello := os.getenv "hello" | ||
| 1969 | print "Du hast hello", hello | ||
| 1970 | elseif world := os.getenv "world" | ||
| 1971 | print "Du hast world", world | ||
| 1972 | else | ||
| 1973 | print "nichts :(" | ||
| 1974 | ``` | ||
| 1975 | |||
| 1976 | </YueDisplay> | ||
| 1977 | |||
| 1978 | If-Zuweisung mit mehreren Rückgabewerten. Nur der erste Wert wird geprüft, andere Werte bleiben im Scope. | 977 | If-Zuweisung mit mehreren Rückgabewerten. Nur der erste Wert wird geprüft, andere Werte bleiben im Scope. |
| 1979 | 978 | ||
| 1980 | ```yuescript | 979 | ```yuescript |
| @@ -1983,16 +982,6 @@ if success, result := pcall -> "Ergebnis ohne Probleme erhalten" | |||
| 1983 | print "OK" | 982 | print "OK" |
| 1984 | ``` | 983 | ``` |
| 1985 | 984 | ||
| 1986 | <YueDisplay> | ||
| 1987 | |||
| 1988 | ```yue | ||
| 1989 | if success, result := pcall -> "Ergebnis ohne Probleme erhalten" | ||
| 1990 | print result -- Variable result ist im Scope | ||
| 1991 | print "OK" | ||
| 1992 | ``` | ||
| 1993 | |||
| 1994 | </YueDisplay> | ||
| 1995 | |||
| 1996 | ## While-Zuweisung | 985 | ## While-Zuweisung |
| 1997 | 986 | ||
| 1998 | Du kannst if-Zuweisung auch in einer while-Schleife verwenden, um den Wert als Schleifenbedingung zu nutzen. | 987 | Du kannst if-Zuweisung auch in einer while-Schleife verwenden, um den Wert als Schleifenbedingung zu nutzen. |
| @@ -2003,16 +992,6 @@ while byte := stream\read_one! | |||
| 2003 | print byte | 992 | print byte |
| 2004 | ``` | 993 | ``` |
| 2005 | 994 | ||
| 2006 | <YueDisplay> | ||
| 2007 | |||
| 2008 | ```yue | ||
| 2009 | while byte := stream\read_one! | ||
| 2010 | -- mit dem Byte etwas anfangen | ||
| 2011 | print byte | ||
| 2012 | ``` | ||
| 2013 | |||
| 2014 | </YueDisplay> | ||
| 2015 | |||
| 2016 | # Destructuring-Zuweisung | 995 | # Destructuring-Zuweisung |
| 2017 | 996 | ||
| 2018 | Destructuring-Zuweisung ist eine Möglichkeit, schnell Werte aus einer Tabelle nach Name oder Position in array-basierten Tabellen zu extrahieren. | 997 | Destructuring-Zuweisung ist eine Möglichkeit, schnell Werte aus einer Tabelle nach Name oder Position in array-basierten Tabellen zu extrahieren. |
| @@ -2028,17 +1007,6 @@ thing = [1, 2] | |||
| 2028 | print a, b | 1007 | print a, b |
| 2029 | ``` | 1008 | ``` |
| 2030 | 1009 | ||
| 2031 | <YueDisplay> | ||
| 2032 | |||
| 2033 | ```yue | ||
| 2034 | thing = [1, 2] | ||
| 2035 | |||
| 2036 | [a, b] = thing | ||
| 2037 | print a, b | ||
| 2038 | ``` | ||
| 2039 | |||
| 2040 | </YueDisplay> | ||
| 2041 | |||
| 2042 | Im Destructuring-Tabellenliteral repräsentiert der Schlüssel den zu lesenden Schlüssel der rechten Seite, und der Wert ist der Name, dem der gelesene Wert zugewiesen wird. | 1010 | Im Destructuring-Tabellenliteral repräsentiert der Schlüssel den zu lesenden Schlüssel der rechten Seite, und der Wert ist der Name, dem der gelesene Wert zugewiesen wird. |
| 2043 | 1011 | ||
| 2044 | ```yuescript | 1012 | ```yuescript |
| @@ -2054,23 +1022,6 @@ print hello, the_day | |||
| 2054 | :day = obj -- einfache Destructuring-Zuweisung ohne Klammern ist ok | 1022 | :day = obj -- einfache Destructuring-Zuweisung ohne Klammern ist ok |
| 2055 | ``` | 1023 | ``` |
| 2056 | 1024 | ||
| 2057 | <YueDisplay> | ||
| 2058 | |||
| 2059 | ```yue | ||
| 2060 | obj = { | ||
| 2061 | hello: "Welt" | ||
| 2062 | day: "Dienstag" | ||
| 2063 | length: 20 | ||
| 2064 | } | ||
| 2065 | |||
| 2066 | {hello: hello, day: the_day} = obj | ||
| 2067 | print hello, the_day | ||
| 2068 | |||
| 2069 | :day = obj -- einfache Destructuring-Zuweisung ohne Klammern ist ok | ||
| 2070 | ``` | ||
| 2071 | |||
| 2072 | </YueDisplay> | ||
| 2073 | |||
| 2074 | Das funktioniert auch mit verschachtelten Datenstrukturen: | 1025 | Das funktioniert auch mit verschachtelten Datenstrukturen: |
| 2075 | 1026 | ||
| 2076 | ```yuescript | 1027 | ```yuescript |
| @@ -2086,23 +1037,6 @@ obj2 = { | |||
| 2086 | print first, second, color | 1037 | print first, second, color |
| 2087 | ``` | 1038 | ``` |
| 2088 | 1039 | ||
| 2089 | <YueDisplay> | ||
| 2090 | |||
| 2091 | ```yue | ||
| 2092 | obj2 = { | ||
| 2093 | numbers: [1, 2, 3, 4] | ||
| 2094 | properties: { | ||
| 2095 | color: "grün" | ||
| 2096 | height: 13.5 | ||
| 2097 | } | ||
| 2098 | } | ||
| 2099 | |||
| 2100 | {numbers: [first, second], properties: {color: color}} = obj2 | ||
| 2101 | print first, second, color | ||
| 2102 | ``` | ||
| 2103 | |||
| 2104 | </YueDisplay> | ||
| 2105 | |||
| 2106 | Wenn die Destructuring-Anweisung kompliziert ist, kannst du sie gerne auf mehrere Zeilen verteilen. Ein etwas komplexeres Beispiel: | 1040 | Wenn die Destructuring-Anweisung kompliziert ist, kannst du sie gerne auf mehrere Zeilen verteilen. Ein etwas komplexeres Beispiel: |
| 2107 | 1041 | ||
| 2108 | ```yuescript | 1042 | ```yuescript |
| @@ -2114,75 +1048,30 @@ Wenn die Destructuring-Anweisung kompliziert ist, kannst du sie gerne auf mehrer | |||
| 2114 | } = obj2 | 1048 | } = obj2 |
| 2115 | ``` | 1049 | ``` |
| 2116 | 1050 | ||
| 2117 | <YueDisplay> | ||
| 2118 | |||
| 2119 | ```yue | ||
| 2120 | { | ||
| 2121 | numbers: [first, second] | ||
| 2122 | properties: { | ||
| 2123 | color: color | ||
| 2124 | } | ||
| 2125 | } = obj2 | ||
| 2126 | ``` | ||
| 2127 | |||
| 2128 | </YueDisplay> | ||
| 2129 | |||
| 2130 | Es ist üblich, Werte aus einer Tabelle zu extrahieren und ihnen lokale Variablen mit demselben Namen wie der Schlüssel zuzuweisen. Um Wiederholungen zu vermeiden, kannst du den Präfix-Operator **:** verwenden: | 1051 | Es ist üblich, Werte aus einer Tabelle zu extrahieren und ihnen lokale Variablen mit demselben Namen wie der Schlüssel zuzuweisen. Um Wiederholungen zu vermeiden, kannst du den Präfix-Operator **:** verwenden: |
| 2131 | 1052 | ||
| 2132 | ```yuescript | 1053 | ```yuescript |
| 2133 | {:concat, :insert} = table | 1054 | {:concat, :insert} = table |
| 2134 | ``` | 1055 | ``` |
| 2135 | 1056 | ||
| 2136 | <YueDisplay> | ||
| 2137 | |||
| 2138 | ```yue | ||
| 2139 | {:concat, :insert} = table | ||
| 2140 | ``` | ||
| 2141 | |||
| 2142 | </YueDisplay> | ||
| 2143 | |||
| 2144 | Das ist effektiv dasselbe wie `import`, aber du kannst Felder umbenennen, indem du die Syntax mischst: | 1057 | Das ist effektiv dasselbe wie `import`, aber du kannst Felder umbenennen, indem du die Syntax mischst: |
| 2145 | 1058 | ||
| 2146 | ```yuescript | 1059 | ```yuescript |
| 2147 | {:mix, :max, random: rand} = math | 1060 | {:mix, :max, random: rand} = math |
| 2148 | ``` | 1061 | ``` |
| 2149 | 1062 | ||
| 2150 | <YueDisplay> | ||
| 2151 | |||
| 2152 | ```yue | ||
| 2153 | {:mix, :max, random: rand} = math | ||
| 2154 | ``` | ||
| 2155 | |||
| 2156 | </YueDisplay> | ||
| 2157 | |||
| 2158 | Du kannst Standardwerte beim Destructuring angeben, z. B.: | 1063 | Du kannst Standardwerte beim Destructuring angeben, z. B.: |
| 2159 | 1064 | ||
| 2160 | ```yuescript | 1065 | ```yuescript |
| 2161 | {:name = "namenlos", :job = "arbeitlos"} = person | 1066 | {:name = "namenlos", :job = "arbeitlos"} = person |
| 2162 | ``` | 1067 | ``` |
| 2163 | 1068 | ||
| 2164 | <YueDisplay> | ||
| 2165 | |||
| 2166 | ```yue | ||
| 2167 | {:name = "namenlos", :job = "arbeitlos"} = person | ||
| 2168 | ``` | ||
| 2169 | |||
| 2170 | </YueDisplay> | ||
| 2171 | |||
| 2172 | Du kannst `_` als Platzhalter verwenden, wenn du eine Listen-Destructuring-Zuweisung machst: | 1069 | Du kannst `_` als Platzhalter verwenden, wenn du eine Listen-Destructuring-Zuweisung machst: |
| 2173 | 1070 | ||
| 2174 | ```yuescript | 1071 | ```yuescript |
| 2175 | [_, two, _, four] = items | 1072 | [_, two, _, four] = items |
| 2176 | ``` | 1073 | ``` |
| 2177 | 1074 | ||
| 2178 | <YueDisplay> | ||
| 2179 | |||
| 2180 | ```yue | ||
| 2181 | [_, two, _, four] = items | ||
| 2182 | ``` | ||
| 2183 | |||
| 2184 | </YueDisplay> | ||
| 2185 | |||
| 2186 | ## Bereichs-Destructuring | 1075 | ## Bereichs-Destructuring |
| 2187 | 1076 | ||
| 2188 | Du kannst den Spread-Operator `...` in Listen-Destructuring verwenden, um einen Wertebereich zu erfassen. Das ist nützlich, wenn du bestimmte Elemente am Anfang und Ende einer Liste extrahieren und den Rest dazwischen sammeln willst. | 1077 | Du kannst den Spread-Operator `...` in Listen-Destructuring verwenden, um einen Wertebereich zu erfassen. Das ist nützlich, wenn du bestimmte Elemente am Anfang und Ende einer Liste extrahieren und den Rest dazwischen sammeln willst. |
| @@ -2195,18 +1084,6 @@ print bulk -- gibt aus: {"zweiter", "dritter", "vierter"} | |||
| 2195 | print last -- gibt aus: letzter | 1084 | print last -- gibt aus: letzter |
| 2196 | ``` | 1085 | ``` |
| 2197 | 1086 | ||
| 2198 | <YueDisplay> | ||
| 2199 | |||
| 2200 | ```yue | ||
| 2201 | orders = ["erster", "zweiter", "dritter", "vierter", "letzter"] | ||
| 2202 | [first, ...bulk, last] = orders | ||
| 2203 | print first -- gibt aus: erster | ||
| 2204 | print bulk -- gibt aus: {"zweiter", "dritter", "vierter"} | ||
| 2205 | print last -- gibt aus: letzter | ||
| 2206 | ``` | ||
| 2207 | |||
| 2208 | </YueDisplay> | ||
| 2209 | |||
| 2210 | Der Spread-Operator kann an unterschiedlichen Positionen verwendet werden, um unterschiedliche Bereiche zu erfassen, und du kannst `_` als Platzhalter für Werte verwenden, die du nicht erfassen willst: | 1087 | Der Spread-Operator kann an unterschiedlichen Positionen verwendet werden, um unterschiedliche Bereiche zu erfassen, und du kannst `_` als Platzhalter für Werte verwenden, die du nicht erfassen willst: |
| 2211 | 1088 | ||
| 2212 | ```yuescript | 1089 | ```yuescript |
| @@ -2220,21 +1097,6 @@ Der Spread-Operator kann an unterschiedlichen Positionen verwendet werden, um un | |||
| 2220 | [first, ..._, last] = orders | 1097 | [first, ..._, last] = orders |
| 2221 | ``` | 1098 | ``` |
| 2222 | 1099 | ||
| 2223 | <YueDisplay> | ||
| 2224 | |||
| 2225 | ```yue | ||
| 2226 | -- Alles nach dem ersten Element erfassen | ||
| 2227 | [first, ...rest] = orders | ||
| 2228 | |||
| 2229 | -- Alles vor dem letzten Element erfassen | ||
| 2230 | [...start, last] = orders | ||
| 2231 | |||
| 2232 | -- Alles außer den mittleren Elementen erfassen | ||
| 2233 | [first, ..._, last] = orders | ||
| 2234 | ``` | ||
| 2235 | |||
| 2236 | </YueDisplay> | ||
| 2237 | |||
| 2238 | ## Destructuring an anderen Stellen | 1100 | ## Destructuring an anderen Stellen |
| 2239 | 1101 | ||
| 2240 | Destructuring kann auch an Stellen vorkommen, an denen eine Zuweisung implizit erfolgt. Ein Beispiel ist eine `for`-Schleife: | 1102 | Destructuring kann auch an Stellen vorkommen, an denen eine Zuweisung implizit erfolgt. Ein Beispiel ist eine `for`-Schleife: |
| @@ -2249,20 +1111,6 @@ for [left, right] in *tuples | |||
| 2249 | print left, right | 1111 | print left, right |
| 2250 | ``` | 1112 | ``` |
| 2251 | 1113 | ||
| 2252 | <YueDisplay> | ||
| 2253 | |||
| 2254 | ```yue | ||
| 2255 | tuples = [ | ||
| 2256 | ["hallo", "Welt"] | ||
| 2257 | ["Ei", "Kopf"] | ||
| 2258 | ] | ||
| 2259 | |||
| 2260 | for [left, right] in *tuples | ||
| 2261 | print left, right | ||
| 2262 | ``` | ||
| 2263 | |||
| 2264 | </YueDisplay> | ||
| 2265 | |||
| 2266 | Wir wissen, dass jedes Element der Array-Tabelle ein 2er-Tupel ist, daher können wir es direkt in der Namensliste der `for`-Anweisung mittels Destructuring entpacken. | 1114 | Wir wissen, dass jedes Element der Array-Tabelle ein 2er-Tupel ist, daher können wir es direkt in der Namensliste der `for`-Anweisung mittels Destructuring entpacken. |
| 2267 | 1115 | ||
| 2268 | # Die Using-Klausel: Destruktive Zuweisung kontrollieren | 1116 | # Die Using-Klausel: Destruktive Zuweisung kontrollieren |
| @@ -2285,26 +1133,6 @@ my_func! | |||
| 2285 | print i -- wird 0 ausgeben | 1133 | print i -- wird 0 ausgeben |
| 2286 | ``` | 1134 | ``` |
| 2287 | 1135 | ||
| 2288 | <YueDisplay> | ||
| 2289 | |||
| 2290 | ```yue | ||
| 2291 | i = 100 | ||
| 2292 | |||
| 2293 | -- viele Zeilen Code... | ||
| 2294 | |||
| 2295 | my_func = -> | ||
| 2296 | i = 10 | ||
| 2297 | while i > 0 | ||
| 2298 | print i | ||
| 2299 | i -= 1 | ||
| 2300 | |||
| 2301 | my_func! | ||
| 2302 | |||
| 2303 | print i -- wird 0 ausgeben | ||
| 2304 | ``` | ||
| 2305 | |||
| 2306 | </YueDisplay> | ||
| 2307 | |||
| 2308 | In `my_func` haben wir den Wert von `i` versehentlich überschrieben. In diesem Beispiel ist es offensichtlich, aber in einer großen oder fremden Codebasis ist oft nicht klar, welche Namen bereits deklariert wurden. | 1136 | In `my_func` haben wir den Wert von `i` versehentlich überschrieben. In diesem Beispiel ist es offensichtlich, aber in einer großen oder fremden Codebasis ist oft nicht klar, welche Namen bereits deklariert wurden. |
| 2309 | 1137 | ||
| 2310 | Es wäre hilfreich, anzugeben, welche Variablen aus dem umschließenden Scope wir verändern wollen, um versehentliche Änderungen zu vermeiden. | 1138 | Es wäre hilfreich, anzugeben, welche Variablen aus dem umschließenden Scope wir verändern wollen, um versehentliche Änderungen zu vermeiden. |
| @@ -2321,20 +1149,6 @@ my_func! | |||
| 2321 | print i -- gibt 100 aus, i bleibt unverändert | 1149 | print i -- gibt 100 aus, i bleibt unverändert |
| 2322 | ``` | 1150 | ``` |
| 2323 | 1151 | ||
| 2324 | <YueDisplay> | ||
| 2325 | |||
| 2326 | ```yue | ||
| 2327 | i = 100 | ||
| 2328 | |||
| 2329 | my_func = (using nil) -> | ||
| 2330 | i = "hello" -- hier wird eine neue lokale Variable erstellt | ||
| 2331 | |||
| 2332 | my_func! | ||
| 2333 | print i -- gibt 100 aus, i bleibt unverändert | ||
| 2334 | ``` | ||
| 2335 | |||
| 2336 | </YueDisplay> | ||
| 2337 | |||
| 2338 | Mehrere Namen können durch Kommas getrennt werden. Closure-Werte können weiterhin gelesen, aber nicht verändert werden: | 1152 | Mehrere Namen können durch Kommas getrennt werden. Closure-Werte können weiterhin gelesen, aber nicht verändert werden: |
| 2339 | 1153 | ||
| 2340 | ```yuescript | 1154 | ```yuescript |
| @@ -2350,23 +1164,6 @@ my_func(22) | |||
| 2350 | print i, k -- diese wurden aktualisiert | 1164 | print i, k -- diese wurden aktualisiert |
| 2351 | ``` | 1165 | ``` |
| 2352 | 1166 | ||
| 2353 | <YueDisplay> | ||
| 2354 | |||
| 2355 | ```yue | ||
| 2356 | tmp = 1213 | ||
| 2357 | i, k = 100, 50 | ||
| 2358 | |||
| 2359 | my_func = (add using k, i) -> | ||
| 2360 | tmp = tmp + add -- ein neues lokales tmp wird erstellt | ||
| 2361 | i += tmp | ||
| 2362 | k += tmp | ||
| 2363 | |||
| 2364 | my_func(22) | ||
| 2365 | print i, k -- diese wurden aktualisiert | ||
| 2366 | ``` | ||
| 2367 | |||
| 2368 | </YueDisplay> | ||
| 2369 | |||
| 2370 | # Verwendung | 1167 | # Verwendung |
| 2371 | 1168 | ||
| 2372 | ## Lua-Modul | 1169 | ## Lua-Modul |
| @@ -2536,55 +1333,6 @@ with apple | |||
| 2536 | export 🌛 = "Skript des Mondes" | 1333 | export 🌛 = "Skript des Mondes" |
| 2537 | ``` | 1334 | ``` |
| 2538 | 1335 | ||
| 2539 | <YueDisplay> | ||
| 2540 | |||
| 2541 | ```yue | ||
| 2542 | -- Import-Syntax | ||
| 2543 | import p, to_lua from "yue" | ||
| 2544 | |||
| 2545 | -- Objekt-Literale | ||
| 2546 | inventory = | ||
| 2547 | equipment: | ||
| 2548 | - "Schwert" | ||
| 2549 | - "Schild" | ||
| 2550 | items: | ||
| 2551 | - name: "Trank" | ||
| 2552 | count: 10 | ||
| 2553 | - name: "Brot" | ||
| 2554 | count: 3 | ||
| 2555 | |||
| 2556 | -- Listen-Abstraktion | ||
| 2557 | map = (arr, action) -> | ||
| 2558 | [action item for item in *arr] | ||
| 2559 | |||
| 2560 | filter = (arr, cond) -> | ||
| 2561 | [item for item in *arr when cond item] | ||
| 2562 | |||
| 2563 | reduce = (arr, init, action): init -> | ||
| 2564 | init = action init, item for item in *arr | ||
| 2565 | |||
| 2566 | -- Pipe-Operator | ||
| 2567 | [1, 2, 3] | ||
| 2568 | |> map (x) -> x * 2 | ||
| 2569 | |> filter (x) -> x > 4 | ||
| 2570 | |> reduce 0, (a, b) -> a + b | ||
| 2571 | |||
| 2572 | |||
| 2573 | -- Metatable-Manipulation | ||
| 2574 | apple = | ||
| 2575 | size: 15 | ||
| 2576 | <index>: | ||
| 2577 | color: 0x00ffff | ||
| 2578 | |||
| 2579 | with apple | ||
| 2580 | p .size, .color, .<index> if .<>? | ||
| 2581 | |||
| 2582 | -- export-Syntax (ähnlich wie in JavaScript) | ||
| 2583 | export 🌛 = "Skript des Mondes" | ||
| 2584 | ``` | ||
| 2585 | |||
| 2586 | </YueDisplay> | ||
| 2587 | |||
| 2588 | ## Über Dora SSR | 1336 | ## Über Dora SSR |
| 2589 | 1337 | ||
| 2590 | YueScript wird zusammen mit der Open-Source-Spiel-Engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR) entwickelt und gepflegt. Es wird zum Erstellen von Engine-Tools, Spiel-Demos und Prototypen eingesetzt und hat seine Leistungsfähigkeit in realen Szenarien unter Beweis gestellt, während es gleichzeitig die Dora-SSR-Entwicklungserfahrung verbessert. | 1338 | YueScript wird zusammen mit der Open-Source-Spiel-Engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR) entwickelt und gepflegt. Es wird zum Erstellen von Engine-Tools, Spiel-Demos und Prototypen eingesetzt und hat seine Leistungsfähigkeit in realen Szenarien unter Beweis gestellt, während es gleichzeitig die Dora-SSR-Entwicklungserfahrung verbessert. |
| @@ -2643,18 +1391,6 @@ else | |||
| 2643 | print "Keine Münzen" | 1391 | print "Keine Münzen" |
| 2644 | ``` | 1392 | ``` |
| 2645 | 1393 | ||
| 2646 | <YueDisplay> | ||
| 2647 | |||
| 2648 | ```yue | ||
| 2649 | have_coins = false | ||
| 2650 | if have_coins | ||
| 2651 | print "Münzen erhalten" | ||
| 2652 | else | ||
| 2653 | print "Keine Münzen" | ||
| 2654 | ``` | ||
| 2655 | |||
| 2656 | </YueDisplay> | ||
| 2657 | |||
| 2658 | Eine Kurzsyntax für einzelne Anweisungen kann ebenfalls verwendet werden: | 1394 | Eine Kurzsyntax für einzelne Anweisungen kann ebenfalls verwendet werden: |
| 2659 | 1395 | ||
| 2660 | ```yuescript | 1396 | ```yuescript |
| @@ -2662,15 +1398,6 @@ have_coins = false | |||
| 2662 | if have_coins then print "Münzen erhalten" else print "Keine Münzen" | 1398 | if have_coins then print "Münzen erhalten" else print "Keine Münzen" |
| 2663 | ``` | 1399 | ``` |
| 2664 | 1400 | ||
| 2665 | <YueDisplay> | ||
| 2666 | |||
| 2667 | ```yue | ||
| 2668 | have_coins = false | ||
| 2669 | if have_coins then print "Münzen erhalten" else print "Keine Münzen" | ||
| 2670 | ``` | ||
| 2671 | |||
| 2672 | </YueDisplay> | ||
| 2673 | |||
| 2674 | Da `if`-Anweisungen als Ausdrücke verwendet werden können, kann man das auch so schreiben: | 1401 | Da `if`-Anweisungen als Ausdrücke verwendet werden können, kann man das auch so schreiben: |
| 2675 | 1402 | ||
| 2676 | ```yuescript | 1403 | ```yuescript |
| @@ -2678,15 +1405,6 @@ have_coins = false | |||
| 2678 | print if have_coins then "Münzen erhalten" else "Keine Münzen" | 1405 | print if have_coins then "Münzen erhalten" else "Keine Münzen" |
| 2679 | ``` | 1406 | ``` |
| 2680 | 1407 | ||
| 2681 | <YueDisplay> | ||
| 2682 | |||
| 2683 | ```yue | ||
| 2684 | have_coins = false | ||
| 2685 | print if have_coins then "Münzen erhalten" else "Keine Münzen" | ||
| 2686 | ``` | ||
| 2687 | |||
| 2688 | </YueDisplay> | ||
| 2689 | |||
| 2690 | Bedingungen können auch in `return`-Anweisungen und Zuweisungen verwendet werden: | 1408 | Bedingungen können auch in `return`-Anweisungen und Zuweisungen verwendet werden: |
| 2691 | 1409 | ||
| 2692 | ```yuescript | 1410 | ```yuescript |
| @@ -2704,25 +1422,6 @@ else | |||
| 2704 | print message -- gibt aus: Ich bin sehr groß | 1422 | print message -- gibt aus: Ich bin sehr groß |
| 2705 | ``` | 1423 | ``` |
| 2706 | 1424 | ||
| 2707 | <YueDisplay> | ||
| 2708 | |||
| 2709 | ```yue | ||
| 2710 | is_tall = (name) -> | ||
| 2711 | if name == "Rob" | ||
| 2712 | true | ||
| 2713 | else | ||
| 2714 | false | ||
| 2715 | |||
| 2716 | message = if is_tall "Rob" | ||
| 2717 | "Ich bin sehr groß" | ||
| 2718 | else | ||
| 2719 | "Ich bin nicht so groß" | ||
| 2720 | |||
| 2721 | print message -- gibt aus: Ich bin sehr groß | ||
| 2722 | ``` | ||
| 2723 | |||
| 2724 | </YueDisplay> | ||
| 2725 | |||
| 2726 | Das Gegenteil von `if` ist `unless`: | 1425 | Das Gegenteil von `if` ist `unless`: |
| 2727 | 1426 | ||
| 2728 | ```yuescript | 1427 | ```yuescript |
| @@ -2730,27 +1429,10 @@ unless os.date("%A") == "Monday" | |||
| 2730 | print "Es ist nicht Montag!" | 1429 | print "Es ist nicht Montag!" |
| 2731 | ``` | 1430 | ``` |
| 2732 | 1431 | ||
| 2733 | <YueDisplay> | ||
| 2734 | |||
| 2735 | ```yue | ||
| 2736 | unless os.date("%A") == "Monday" | ||
| 2737 | print "Es ist nicht Montag!" | ||
| 2738 | ``` | ||
| 2739 | |||
| 2740 | </YueDisplay> | ||
| 2741 | |||
| 2742 | ```yuescript | 1432 | ```yuescript |
| 2743 | print "You're lucky!" unless math.random! > 0.1 | 1433 | print "You're lucky!" unless math.random! > 0.1 |
| 2744 | ``` | 1434 | ``` |
| 2745 | 1435 | ||
| 2746 | <YueDisplay> | ||
| 2747 | |||
| 2748 | ```yue | ||
| 2749 | print "You're lucky!" unless math.random! > 0.1 | ||
| 2750 | ``` | ||
| 2751 | |||
| 2752 | </YueDisplay> | ||
| 2753 | |||
| 2754 | ## In-Ausdruck | 1436 | ## In-Ausdruck |
| 2755 | 1437 | ||
| 2756 | Mit einem `in`-Ausdruck kannst du Bereichsprüfungen schreiben. | 1438 | Mit einem `in`-Ausdruck kannst du Bereichsprüfungen schreiben. |
| @@ -2765,20 +1447,6 @@ if a in list | |||
| 2765 | print "Prüfen, ob `a` in einer Liste ist" | 1447 | print "Prüfen, ob `a` in einer Liste ist" |
| 2766 | ``` | 1448 | ``` |
| 2767 | 1449 | ||
| 2768 | <YueDisplay> | ||
| 2769 | |||
| 2770 | ```yue | ||
| 2771 | a = 5 | ||
| 2772 | |||
| 2773 | if a in [1, 3, 5, 7] | ||
| 2774 | print "Gleichheitsprüfung mit diskreten Werten" | ||
| 2775 | |||
| 2776 | if a in list | ||
| 2777 | print "Prüfen, ob `a` in einer Liste ist" | ||
| 2778 | ``` | ||
| 2779 | |||
| 2780 | </YueDisplay> | ||
| 2781 | |||
| 2782 | Der `in`-Operator kann auch mit Tabellen verwendet werden und unterstützt die Variante `not in` für Verneinungen: | 1450 | Der `in`-Operator kann auch mit Tabellen verwendet werden und unterstützt die Variante `not in` für Verneinungen: |
| 2783 | 1451 | ||
| 2784 | ```yuescript | 1452 | ```yuescript |
| @@ -2792,21 +1460,6 @@ not_exist = item not in list | |||
| 2792 | check = -> value not in table | 1460 | check = -> value not in table |
| 2793 | ``` | 1461 | ``` |
| 2794 | 1462 | ||
| 2795 | <YueDisplay> | ||
| 2796 | |||
| 2797 | ```yue | ||
| 2798 | has = "foo" in {"bar", "foo"} | ||
| 2799 | |||
| 2800 | if a in {1, 2, 3} | ||
| 2801 | print "a ist in der Tabelle" | ||
| 2802 | |||
| 2803 | not_exist = item not in list | ||
| 2804 | |||
| 2805 | check = -> value not in table | ||
| 2806 | ``` | ||
| 2807 | |||
| 2808 | </YueDisplay> | ||
| 2809 | |||
| 2810 | Eine Ein-Element-Liste oder Tabelle prüft auf Gleichheit mit diesem Element: | 1463 | Eine Ein-Element-Liste oder Tabelle prüft auf Gleichheit mit diesem Element: |
| 2811 | 1464 | ||
| 2812 | ```yuescript | 1465 | ```yuescript |
| @@ -2821,22 +1474,6 @@ with tb | |||
| 2821 | c = a in [1] | 1474 | c = a in [1] |
| 2822 | ``` | 1475 | ``` |
| 2823 | 1476 | ||
| 2824 | <YueDisplay> | ||
| 2825 | |||
| 2826 | ```yue | ||
| 2827 | -- [1,] prüft, ob wert == 1 | ||
| 2828 | c = a in [1,] | ||
| 2829 | |||
| 2830 | -- {1} prüft auch, ob wert == 1 | ||
| 2831 | c = a in {1} | ||
| 2832 | |||
| 2833 | -- Ohne Komma ist [1] ein Indexzugriff (tb[1]) | ||
| 2834 | with tb | ||
| 2835 | c = a in [1] | ||
| 2836 | ``` | ||
| 2837 | |||
| 2838 | </YueDisplay> | ||
| 2839 | |||
| 2840 | # For-Schleife | 1477 | # For-Schleife |
| 2841 | 1478 | ||
| 2842 | Es gibt zwei Formen der `for`-Schleife, genau wie in Lua: eine numerische und eine generische. | 1479 | Es gibt zwei Formen der `for`-Schleife, genau wie in Lua: eine numerische und eine generische. |
| @@ -2852,21 +1489,6 @@ for key, value in pairs object | |||
| 2852 | print key, value | 1489 | print key, value |
| 2853 | ``` | 1490 | ``` |
| 2854 | 1491 | ||
| 2855 | <YueDisplay> | ||
| 2856 | |||
| 2857 | ```yue | ||
| 2858 | for i = 10, 20 | ||
| 2859 | print i | ||
| 2860 | |||
| 2861 | for k = 1, 15, 2 -- ein optionaler Schritt | ||
| 2862 | print k | ||
| 2863 | |||
| 2864 | for key, value in pairs object | ||
| 2865 | print key, value | ||
| 2866 | ``` | ||
| 2867 | |||
| 2868 | </YueDisplay> | ||
| 2869 | |||
| 2870 | Die Slicing- und **\***-Operatoren können verwendet werden, genau wie bei Comprehensions: | 1492 | Die Slicing- und **\***-Operatoren können verwendet werden, genau wie bei Comprehensions: |
| 2871 | 1493 | ||
| 2872 | ```yuescript | 1494 | ```yuescript |
| @@ -2874,15 +1496,6 @@ for item in *items[2, 4] | |||
| 2874 | print item | 1496 | print item |
| 2875 | ``` | 1497 | ``` |
| 2876 | 1498 | ||
| 2877 | <YueDisplay> | ||
| 2878 | |||
| 2879 | ```yue | ||
| 2880 | for item in *items[2, 4] | ||
| 2881 | print item | ||
| 2882 | ``` | ||
| 2883 | |||
| 2884 | </YueDisplay> | ||
| 2885 | |||
| 2886 | Eine kürzere Syntax ist für alle Varianten verfügbar, wenn der Rumpf nur eine Zeile hat: | 1499 | Eine kürzere Syntax ist für alle Varianten verfügbar, wenn der Rumpf nur eine Zeile hat: |
| 2887 | 1500 | ||
| 2888 | ```yuescript | 1501 | ```yuescript |
| @@ -2891,16 +1504,6 @@ for item in *items do print item | |||
| 2891 | for j = 1, 10, 3 do print j | 1504 | for j = 1, 10, 3 do print j |
| 2892 | ``` | 1505 | ``` |
| 2893 | 1506 | ||
| 2894 | <YueDisplay> | ||
| 2895 | |||
| 2896 | ```yue | ||
| 2897 | for item in *items do print item | ||
| 2898 | |||
| 2899 | for j = 1, 10, 3 do print j | ||
| 2900 | ``` | ||
| 2901 | |||
| 2902 | </YueDisplay> | ||
| 2903 | |||
| 2904 | Eine `for`-Schleife kann auch als Ausdruck verwendet werden. Die letzte Anweisung im Schleifenrumpf wird in einen Ausdruck umgewandelt und an eine wachsende Array-Tabelle angehängt. | 1507 | Eine `for`-Schleife kann auch als Ausdruck verwendet werden. Die letzte Anweisung im Schleifenrumpf wird in einen Ausdruck umgewandelt und an eine wachsende Array-Tabelle angehängt. |
| 2905 | 1508 | ||
| 2906 | Alle geraden Zahlen verdoppeln: | 1509 | Alle geraden Zahlen verdoppeln: |
| @@ -2913,18 +1516,6 @@ doubled_evens = for i = 1, 20 | |||
| 2913 | i | 1516 | i |
| 2914 | ``` | 1517 | ``` |
| 2915 | 1518 | ||
| 2916 | <YueDisplay> | ||
| 2917 | |||
| 2918 | ```yue | ||
| 2919 | doubled_evens = for i = 1, 20 | ||
| 2920 | if i % 2 == 0 | ||
| 2921 | i * 2 | ||
| 2922 | else | ||
| 2923 | i | ||
| 2924 | ``` | ||
| 2925 | |||
| 2926 | </YueDisplay> | ||
| 2927 | |||
| 2928 | Zusätzlich unterstützen `for`-Schleifen `break` mit Rückgabewerten, sodass die Schleife selbst als Ausdruck verwendet werden kann, der früh mit einem sinnvollen Ergebnis endet. `for`-Ausdrücke unterstützen mehrere `break`-Werte. | 1519 | Zusätzlich unterstützen `for`-Schleifen `break` mit Rückgabewerten, sodass die Schleife selbst als Ausdruck verwendet werden kann, der früh mit einem sinnvollen Ergebnis endet. `for`-Ausdrücke unterstützen mehrere `break`-Werte. |
| 2929 | 1520 | ||
| 2930 | Beispiel: die erste Zahl größer als 10 finden: | 1521 | Beispiel: die erste Zahl größer als 10 finden: |
| @@ -2934,15 +1525,6 @@ first_large = for n in *numbers | |||
| 2934 | break n if n > 10 | 1525 | break n if n > 10 |
| 2935 | ``` | 1526 | ``` |
| 2936 | 1527 | ||
| 2937 | <YueDisplay> | ||
| 2938 | |||
| 2939 | ```yue | ||
| 2940 | first_large = for n in *numbers | ||
| 2941 | break n if n > 10 | ||
| 2942 | ``` | ||
| 2943 | |||
| 2944 | </YueDisplay> | ||
| 2945 | |||
| 2946 | Diese `break`-mit-Wert-Syntax ermöglicht knappe und ausdrucksstarke Such- bzw. Early-Exit-Muster direkt in Schleifenausdrücken. | 1528 | Diese `break`-mit-Wert-Syntax ermöglicht knappe und ausdrucksstarke Such- bzw. Early-Exit-Muster direkt in Schleifenausdrücken. |
| 2947 | 1529 | ||
| 2948 | ```yuescript | 1530 | ```yuescript |
| @@ -2950,15 +1532,6 @@ key, score = for k, v in pairs data | |||
| 2950 | break k, v * 10 if k == "target" | 1532 | break k, v * 10 if k == "target" |
| 2951 | ``` | 1533 | ``` |
| 2952 | 1534 | ||
| 2953 | <YueDisplay> | ||
| 2954 | |||
| 2955 | ```yue | ||
| 2956 | key, score = for k, v in pairs data | ||
| 2957 | break k, v * 10 if k == "target" | ||
| 2958 | ``` | ||
| 2959 | |||
| 2960 | </YueDisplay> | ||
| 2961 | |||
| 2962 | Du kannst Werte auch filtern, indem du den `for`-Ausdruck mit `continue` kombinierst. | 1535 | Du kannst Werte auch filtern, indem du den `for`-Ausdruck mit `continue` kombinierst. |
| 2963 | 1536 | ||
| 2964 | `for`-Schleifen am Ende eines Funktionsrumpfs werden nicht in eine Tabelle für einen Rückgabewert gesammelt (stattdessen gibt die Funktion `nil` zurück). Du kannst entweder explizit `return` verwenden oder die Schleife in eine Listen-Comprehension umwandeln. | 1537 | `for`-Schleifen am Ende eines Funktionsrumpfs werden nicht in eine Tabelle für einen Rückgabewert gesammelt (stattdessen gibt die Funktion `nil` zurück). Du kannst entweder explizit `return` verwenden oder die Schleife in eine Listen-Comprehension umwandeln. |
| @@ -2971,18 +1544,6 @@ print func_a! -- gibt nil aus | |||
| 2971 | print func_b! -- gibt Tabellenobjekt aus | 1544 | print func_b! -- gibt Tabellenobjekt aus |
| 2972 | ``` | 1545 | ``` |
| 2973 | 1546 | ||
| 2974 | <YueDisplay> | ||
| 2975 | |||
| 2976 | ```yue | ||
| 2977 | func_a = -> for i = 1, 10 do print i | ||
| 2978 | func_b = -> return for i = 1, 10 do i | ||
| 2979 | |||
| 2980 | print func_a! -- gibt nil aus | ||
| 2981 | print func_b! -- gibt Tabellenobjekt aus | ||
| 2982 | ``` | ||
| 2983 | |||
| 2984 | </YueDisplay> | ||
| 2985 | |||
| 2986 | Das verhindert die unnötige Erstellung von Tabellen in Funktionen, die die Ergebnisse der Schleife nicht zurückgeben müssen. | 1547 | Das verhindert die unnötige Erstellung von Tabellen in Funktionen, die die Ergebnisse der Schleife nicht zurückgeben müssen. |
| 2987 | 1548 | ||
| 2988 | # Continue | 1549 | # Continue |
| @@ -2997,18 +1558,6 @@ while i < 10 | |||
| 2997 | print i | 1558 | print i |
| 2998 | ``` | 1559 | ``` |
| 2999 | 1560 | ||
| 3000 | <YueDisplay> | ||
| 3001 | |||
| 3002 | ```yue | ||
| 3003 | i = 0 | ||
| 3004 | while i < 10 | ||
| 3005 | i += 1 | ||
| 3006 | continue if i % 2 == 0 | ||
| 3007 | print i | ||
| 3008 | ``` | ||
| 3009 | |||
| 3010 | </YueDisplay> | ||
| 3011 | |||
| 3012 | `continue` kann auch mit Schleifenausdrücken verwendet werden, um zu verhindern, dass diese Iteration in das Ergebnis akkumuliert wird. Dieses Beispiel filtert die Array-Tabelle auf gerade Zahlen: | 1561 | `continue` kann auch mit Schleifenausdrücken verwendet werden, um zu verhindern, dass diese Iteration in das Ergebnis akkumuliert wird. Dieses Beispiel filtert die Array-Tabelle auf gerade Zahlen: |
| 3013 | 1562 | ||
| 3014 | ```yuescript | 1563 | ```yuescript |
| @@ -3018,17 +1567,6 @@ odds = for x in *my_numbers | |||
| 3018 | x | 1567 | x |
| 3019 | ``` | 1568 | ``` |
| 3020 | 1569 | ||
| 3021 | <YueDisplay> | ||
| 3022 | |||
| 3023 | ```yue | ||
| 3024 | my_numbers = [1, 2, 3, 4, 5, 6] | ||
| 3025 | odds = for x in *my_numbers | ||
| 3026 | continue if x % 2 == 1 | ||
| 3027 | x | ||
| 3028 | ``` | ||
| 3029 | |||
| 3030 | </YueDisplay> | ||
| 3031 | |||
| 3032 | # Switch | 1570 | # Switch |
| 3033 | 1571 | ||
| 3034 | Die `switch`-Anweisung ist eine Kurzform für eine Reihe von `if`-Anweisungen, die gegen denselben Wert prüfen. Der Wert wird nur einmal ausgewertet. Wie bei `if` kann `switch` einen `else`-Block haben, wenn keine Übereinstimmung gefunden wird. Verglichen wird mit dem Operator `==`. In einer `switch`-Anweisung kannst du auch eine Zuweisung verwenden, um den temporären Wert zu speichern. | 1572 | Die `switch`-Anweisung ist eine Kurzform für eine Reihe von `if`-Anweisungen, die gegen denselben Wert prüfen. Der Wert wird nur einmal ausgewertet. Wie bei `if` kann `switch` einen `else`-Block haben, wenn keine Übereinstimmung gefunden wird. Verglichen wird mit dem Operator `==`. In einer `switch`-Anweisung kannst du auch eine Zuweisung verwenden, um den temporären Wert zu speichern. |
| @@ -3043,20 +1581,6 @@ switch name := "Dan" | |||
| 3043 | print "Ich kenne dich nicht mit dem Namen #{name}" | 1581 | print "Ich kenne dich nicht mit dem Namen #{name}" |
| 3044 | ``` | 1582 | ``` |
| 3045 | 1583 | ||
| 3046 | <YueDisplay> | ||
| 3047 | |||
| 3048 | ```yue | ||
| 3049 | switch name := "Dan" | ||
| 3050 | when "Robert" | ||
| 3051 | print "Du bist Robert" | ||
| 3052 | when "Dan", "Daniel" | ||
| 3053 | print "Dein Name ist Dan" | ||
| 3054 | else | ||
| 3055 | print "Ich kenne dich nicht mit dem Namen #{name}" | ||
| 3056 | ``` | ||
| 3057 | |||
| 3058 | </YueDisplay> | ||
| 3059 | |||
| 3060 | Eine `when`-Klausel kann mehrere Werte prüfen, indem sie kommasepariert aufgelistet werden. | 1584 | Eine `when`-Klausel kann mehrere Werte prüfen, indem sie kommasepariert aufgelistet werden. |
| 3061 | 1585 | ||
| 3062 | `switch` kann auch als Ausdruck verwendet werden. Hier wird das Ergebnis der `switch`-Anweisung einer Variable zugewiesen: | 1586 | `switch` kann auch als Ausdruck verwendet werden. Hier wird das Ergebnis der `switch`-Anweisung einer Variable zugewiesen: |
| @@ -3072,21 +1596,6 @@ next_number = switch b | |||
| 3072 | error "so hoch kann ich nicht zählen!" | 1596 | error "so hoch kann ich nicht zählen!" |
| 3073 | ``` | 1597 | ``` |
| 3074 | 1598 | ||
| 3075 | <YueDisplay> | ||
| 3076 | |||
| 3077 | ```yue | ||
| 3078 | b = 1 | ||
| 3079 | next_number = switch b | ||
| 3080 | when 1 | ||
| 3081 | 2 | ||
| 3082 | when 2 | ||
| 3083 | 3 | ||
| 3084 | else | ||
| 3085 | error "so hoch kann ich nicht zählen!" | ||
| 3086 | ``` | ||
| 3087 | |||
| 3088 | </YueDisplay> | ||
| 3089 | |||
| 3090 | Du kannst das Schlüsselwort `then` verwenden, um einen `when`-Block in einer Zeile zu schreiben. Für den `else`-Block braucht es kein zusätzliches Schlüsselwort. | 1599 | Du kannst das Schlüsselwort `then` verwenden, um einen `when`-Block in einer Zeile zu schreiben. Für den `else`-Block braucht es kein zusätzliches Schlüsselwort. |
| 3091 | 1600 | ||
| 3092 | ```yuescript | 1601 | ```yuescript |
| @@ -3096,17 +1605,6 @@ msg = switch math.random(1, 5) | |||
| 3096 | else "nicht so viel Glück" | 1605 | else "nicht so viel Glück" |
| 3097 | ``` | 1606 | ``` |
| 3098 | 1607 | ||
| 3099 | <YueDisplay> | ||
| 3100 | |||
| 3101 | ```yue | ||
| 3102 | msg = switch math.random(1, 5) | ||
| 3103 | when 1 then "Du hast Glück" | ||
| 3104 | when 2 then "Du hast fast Glück" | ||
| 3105 | else "nicht so viel Glück" | ||
| 3106 | ``` | ||
| 3107 | |||
| 3108 | </YueDisplay> | ||
| 3109 | |||
| 3110 | Wenn du eine Einrückung weniger möchtest, kannst du die erste `when`-Klausel in die Startzeile der Anweisung setzen und alle weiteren Klauseln mit einer Einrückung weniger schreiben. | 1608 | Wenn du eine Einrückung weniger möchtest, kannst du die erste `when`-Klausel in die Startzeile der Anweisung setzen und alle weiteren Klauseln mit einer Einrückung weniger schreiben. |
| 3111 | 1609 | ||
| 3112 | ```yuescript | 1610 | ```yuescript |
| @@ -3122,23 +1620,6 @@ else | |||
| 3122 | print "nicht so viel Glück" | 1620 | print "nicht so viel Glück" |
| 3123 | ``` | 1621 | ``` |
| 3124 | 1622 | ||
| 3125 | <YueDisplay> | ||
| 3126 | |||
| 3127 | ```yue | ||
| 3128 | switch math.random(1, 5) | ||
| 3129 | when 1 | ||
| 3130 | print "Du hast Glück" -- zwei Einrückungen | ||
| 3131 | else | ||
| 3132 | print "nicht so viel Glück" | ||
| 3133 | |||
| 3134 | switch math.random(1, 5) when 1 | ||
| 3135 | print "Du hast Glück" -- eine Einrückung | ||
| 3136 | else | ||
| 3137 | print "nicht so viel Glück" | ||
| 3138 | ``` | ||
| 3139 | |||
| 3140 | </YueDisplay> | ||
| 3141 | |||
| 3142 | Beachte die Reihenfolge des Case-Vergleichsausdrucks. Der Case-Ausdruck steht auf der linken Seite. Das kann nützlich sein, wenn der Case-Ausdruck die Vergleichslogik über eine `__eq`-Metamethod selbst definiert. | 1623 | Beachte die Reihenfolge des Case-Vergleichsausdrucks. Der Case-Ausdruck steht auf der linken Seite. Das kann nützlich sein, wenn der Case-Ausdruck die Vergleichslogik über eine `__eq`-Metamethod selbst definiert. |
| 3143 | 1624 | ||
| 3144 | ## Tabellen-Matching | 1625 | ## Tabellen-Matching |
| @@ -3160,25 +1641,6 @@ for item in *items | |||
| 3160 | print "Größe #{width}, #{height}" | 1641 | print "Größe #{width}, #{height}" |
| 3161 | ``` | 1642 | ``` |
| 3162 | 1643 | ||
| 3163 | <YueDisplay> | ||
| 3164 | |||
| 3165 | ```yue | ||
| 3166 | items = | ||
| 3167 | * x: 100 | ||
| 3168 | y: 200 | ||
| 3169 | * width: 300 | ||
| 3170 | height: 400 | ||
| 3171 | |||
| 3172 | for item in *items | ||
| 3173 | switch item | ||
| 3174 | when :x, :y | ||
| 3175 | print "Vec2 #{x}, #{y}" | ||
| 3176 | when :width, :height | ||
| 3177 | print "Größe #{width}, #{height}" | ||
| 3178 | ``` | ||
| 3179 | |||
| 3180 | </YueDisplay> | ||
| 3181 | |||
| 3182 | Du kannst Standardwerte verwenden, um bestimmte Felder optional zu destrukturieren. | 1644 | Du kannst Standardwerte verwenden, um bestimmte Felder optional zu destrukturieren. |
| 3183 | 1645 | ||
| 3184 | ```yuescript | 1646 | ```yuescript |
| @@ -3191,20 +1653,6 @@ switch item | |||
| 3191 | print "Vec2 #{x}, #{y}" -- Tabellen-Destrukturierung greift trotzdem | 1653 | print "Vec2 #{x}, #{y}" -- Tabellen-Destrukturierung greift trotzdem |
| 3192 | ``` | 1654 | ``` |
| 3193 | 1655 | ||
| 3194 | <YueDisplay> | ||
| 3195 | |||
| 3196 | ```yue | ||
| 3197 | item = {} | ||
| 3198 | |||
| 3199 | {pos: {:x = 50, :y = 200}} = item -- Fehler: Versuch, einen nil-Wert zu indexieren (Feld 'pos') | ||
| 3200 | |||
| 3201 | switch item | ||
| 3202 | when {pos: {:x = 50, :y = 200}} | ||
| 3203 | print "Vec2 #{x}, #{y}" -- Tabellen-Destrukturierung greift trotzdem | ||
| 3204 | ``` | ||
| 3205 | |||
| 3206 | </YueDisplay> | ||
| 3207 | |||
| 3208 | Du kannst auch gegen Array-Elemente, Tabellenfelder und sogar verschachtelte Strukturen mit Array- oder Tabellenliteralen matchen. | 1656 | Du kannst auch gegen Array-Elemente, Tabellenfelder und sogar verschachtelte Strukturen mit Array- oder Tabellenliteralen matchen. |
| 3209 | 1657 | ||
| 3210 | Matchen gegen Array-Elemente. | 1658 | Matchen gegen Array-Elemente. |
| @@ -3219,20 +1667,6 @@ switch tb | |||
| 3219 | print "1, 2, #{b}" | 1667 | print "1, 2, #{b}" |
| 3220 | ``` | 1668 | ``` |
| 3221 | 1669 | ||
| 3222 | <YueDisplay> | ||
| 3223 | |||
| 3224 | ```yue | ||
| 3225 | switch tb | ||
| 3226 | when [1, 2, 3] | ||
| 3227 | print "1, 2, 3" | ||
| 3228 | when [1, b, 3] | ||
| 3229 | print "1, #{b}, 3" | ||
| 3230 | when [1, 2, b = 3] -- b hat einen Standardwert | ||
| 3231 | print "1, 2, #{b}" | ||
| 3232 | ``` | ||
| 3233 | |||
| 3234 | </YueDisplay> | ||
| 3235 | |||
| 3236 | Matchen gegen Tabellenfelder mit Destructuring. | 1670 | Matchen gegen Tabellenfelder mit Destructuring. |
| 3237 | 1671 | ||
| 3238 | ```yuescript | 1672 | ```yuescript |
| @@ -3245,20 +1679,6 @@ switch tb | |||
| 3245 | print "ungültig" | 1679 | print "ungültig" |
| 3246 | ``` | 1680 | ``` |
| 3247 | 1681 | ||
| 3248 | <YueDisplay> | ||
| 3249 | |||
| 3250 | ```yue | ||
| 3251 | switch tb | ||
| 3252 | when success: true, :result | ||
| 3253 | print "Erfolg", result | ||
| 3254 | when success: false | ||
| 3255 | print "fehlgeschlagen", result | ||
| 3256 | else | ||
| 3257 | print "ungültig" | ||
| 3258 | ``` | ||
| 3259 | |||
| 3260 | </YueDisplay> | ||
| 3261 | |||
| 3262 | Matchen gegen verschachtelte Tabellenstrukturen. | 1682 | Matchen gegen verschachtelte Tabellenstrukturen. |
| 3263 | 1683 | ||
| 3264 | ```yuescript | 1684 | ```yuescript |
| @@ -3271,20 +1691,6 @@ switch tb | |||
| 3271 | print "ungültig" | 1691 | print "ungültig" |
| 3272 | ``` | 1692 | ``` |
| 3273 | 1693 | ||
| 3274 | <YueDisplay> | ||
| 3275 | |||
| 3276 | ```yue | ||
| 3277 | switch tb | ||
| 3278 | when data: {type: "success", :content} | ||
| 3279 | print "Erfolg", content | ||
| 3280 | when data: {type: "error", :content} | ||
| 3281 | print "fehlgeschlagen", content | ||
| 3282 | else | ||
| 3283 | print "ungültig" | ||
| 3284 | ``` | ||
| 3285 | |||
| 3286 | </YueDisplay> | ||
| 3287 | |||
| 3288 | Matchen gegen Array von Tabellen. | 1694 | Matchen gegen Array von Tabellen. |
| 3289 | 1695 | ||
| 3290 | ```yuescript | 1696 | ```yuescript |
| @@ -3298,21 +1704,6 @@ switch tb | |||
| 3298 | print "getroffen", fourth | 1704 | print "getroffen", fourth |
| 3299 | ``` | 1705 | ``` |
| 3300 | 1706 | ||
| 3301 | <YueDisplay> | ||
| 3302 | |||
| 3303 | ```yue | ||
| 3304 | switch tb | ||
| 3305 | when [ | ||
| 3306 | {a: 1, b: 2} | ||
| 3307 | {a: 3, b: 4} | ||
| 3308 | {a: 5, b: 6} | ||
| 3309 | fourth | ||
| 3310 | ] | ||
| 3311 | print "getroffen", fourth | ||
| 3312 | ``` | ||
| 3313 | |||
| 3314 | </YueDisplay> | ||
| 3315 | |||
| 3316 | Matchen gegen eine Liste und einen Bereich von Elementen erfassen. | 1707 | Matchen gegen eine Liste und einen Bereich von Elementen erfassen. |
| 3317 | 1708 | ||
| 3318 | ```yuescript | 1709 | ```yuescript |
| @@ -3324,19 +1715,6 @@ switch segments | |||
| 3324 | print "Aktion:", action -- gibt aus: "view" | 1715 | print "Aktion:", action -- gibt aus: "view" |
| 3325 | ``` | 1716 | ``` |
| 3326 | 1717 | ||
| 3327 | <YueDisplay> | ||
| 3328 | |||
| 3329 | ```yue | ||
| 3330 | segments = ["admin", "users", "logs", "view"] | ||
| 3331 | switch segments | ||
| 3332 | when [...groups, resource, action] | ||
| 3333 | print "Gruppe:", groups -- gibt aus: {"admin", "users"} | ||
| 3334 | print "Ressource:", resource -- gibt aus: "logs" | ||
| 3335 | print "Aktion:", action -- gibt aus: "view" | ||
| 3336 | ``` | ||
| 3337 | |||
| 3338 | </YueDisplay> | ||
| 3339 | |||
| 3340 | # While-Schleife | 1718 | # While-Schleife |
| 3341 | 1719 | ||
| 3342 | Die `while`-Schleife gibt es ebenfalls in vier Variationen: | 1720 | Die `while`-Schleife gibt es ebenfalls in vier Variationen: |
| @@ -3350,19 +1728,6 @@ while i > 0 | |||
| 3350 | while running == true do my_function! | 1728 | while running == true do my_function! |
| 3351 | ``` | 1729 | ``` |
| 3352 | 1730 | ||
| 3353 | <YueDisplay> | ||
| 3354 | |||
| 3355 | ```yue | ||
| 3356 | i = 10 | ||
| 3357 | while i > 0 | ||
| 3358 | print i | ||
| 3359 | i -= 1 | ||
| 3360 | |||
| 3361 | while running == true do my_function! | ||
| 3362 | ``` | ||
| 3363 | |||
| 3364 | </YueDisplay> | ||
| 3365 | |||
| 3366 | ```yuescript | 1731 | ```yuescript |
| 3367 | i = 10 | 1732 | i = 10 |
| 3368 | until i == 0 | 1733 | until i == 0 |
| @@ -3372,18 +1737,6 @@ until i == 0 | |||
| 3372 | until running == false do my_function! | 1737 | until running == false do my_function! |
| 3373 | ``` | 1738 | ``` |
| 3374 | 1739 | ||
| 3375 | <YueDisplay> | ||
| 3376 | |||
| 3377 | ```yue | ||
| 3378 | i = 10 | ||
| 3379 | until i == 0 | ||
| 3380 | print i | ||
| 3381 | i -= 1 | ||
| 3382 | until running == false do my_function! | ||
| 3383 | ``` | ||
| 3384 | |||
| 3385 | </YueDisplay> | ||
| 3386 | |||
| 3387 | Wie bei `for`-Schleifen kann die `while`-Schleife auch als Ausdruck verwendet werden. `while`- und `until`-Ausdrücke unterstützen `break` mit mehreren Rückgabewerten. | 1740 | Wie bei `for`-Schleifen kann die `while`-Schleife auch als Ausdruck verwendet werden. `while`- und `until`-Ausdrücke unterstützen `break` mit mehreren Rückgabewerten. |
| 3388 | 1741 | ||
| 3389 | ```yuescript | 1742 | ```yuescript |
| @@ -3392,16 +1745,6 @@ value, doubled = while true | |||
| 3392 | break n, n * 2 if n > 10 | 1745 | break n, n * 2 if n > 10 |
| 3393 | ``` | 1746 | ``` |
| 3394 | 1747 | ||
| 3395 | <YueDisplay> | ||
| 3396 | |||
| 3397 | ```yue | ||
| 3398 | value, doubled = while true | ||
| 3399 | n = get_next! | ||
| 3400 | break n, n * 2 if n > 10 | ||
| 3401 | ``` | ||
| 3402 | |||
| 3403 | </YueDisplay> | ||
| 3404 | |||
| 3405 | Damit eine Funktion den akkumulierten Wert einer `while`-Schleife zurückgibt, muss die Anweisung explizit mit `return` zurückgegeben werden. | 1748 | Damit eine Funktion den akkumulierten Wert einer `while`-Schleife zurückgibt, muss die Anweisung explizit mit `return` zurückgegeben werden. |
| 3406 | 1749 | ||
| 3407 | ## Repeat-Schleife | 1750 | ## Repeat-Schleife |
| @@ -3416,18 +1759,6 @@ repeat | |||
| 3416 | until i == 0 | 1759 | until i == 0 |
| 3417 | ``` | 1760 | ``` |
| 3418 | 1761 | ||
| 3419 | <YueDisplay> | ||
| 3420 | |||
| 3421 | ```yue | ||
| 3422 | i = 10 | ||
| 3423 | repeat | ||
| 3424 | print i | ||
| 3425 | i -= 1 | ||
| 3426 | until i == 0 | ||
| 3427 | ``` | ||
| 3428 | |||
| 3429 | </YueDisplay> | ||
| 3430 | |||
| 3431 | `repeat`-Ausdrücke unterstützen ebenfalls `break` mit mehreren Rückgabewerten: | 1762 | `repeat`-Ausdrücke unterstützen ebenfalls `break` mit mehreren Rückgabewerten: |
| 3432 | 1763 | ||
| 3433 | ```yuescript | 1764 | ```yuescript |
| @@ -3438,18 +1769,6 @@ value, scaled = repeat | |||
| 3438 | until false | 1769 | until false |
| 3439 | ``` | 1770 | ``` |
| 3440 | 1771 | ||
| 3441 | <YueDisplay> | ||
| 3442 | |||
| 3443 | ```yue | ||
| 3444 | i = 1 | ||
| 3445 | value, scaled = repeat | ||
| 3446 | break i, i * 100 if i > 3 | ||
| 3447 | i += 1 | ||
| 3448 | until false | ||
| 3449 | ``` | ||
| 3450 | |||
| 3451 | </YueDisplay> | ||
| 3452 | |||
| 3453 | # Funktions-Stubs | 1772 | # Funktions-Stubs |
| 3454 | 1773 | ||
| 3455 | Es ist üblich, eine Funktion eines Objekts als Wert weiterzureichen, z. B. eine Instanzmethode als Callback. Wenn die Funktion das Objekt, auf dem sie arbeitet, als erstes Argument erwartet, musst du dieses Objekt irgendwie mit der Funktion bündeln, damit sie korrekt aufgerufen werden kann. | 1774 | Es ist üblich, eine Funktion eines Objekts als Wert weiterzureichen, z. B. eine Instanzmethode als Callback. Wenn die Funktion das Objekt, auf dem sie arbeitet, als erstes Argument erwartet, musst du dieses Objekt irgendwie mit der Funktion bündeln, damit sie korrekt aufgerufen werden kann. |
| @@ -3477,29 +1796,6 @@ run_callback my_object.write | |||
| 3477 | run_callback my_object\write | 1796 | run_callback my_object\write |
| 3478 | ``` | 1797 | ``` |
| 3479 | 1798 | ||
| 3480 | <YueDisplay> | ||
| 3481 | |||
| 3482 | ```yue | ||
| 3483 | my_object = { | ||
| 3484 | value: 1000 | ||
| 3485 | write: => print "der Wert:", @value | ||
| 3486 | } | ||
| 3487 | |||
| 3488 | run_callback = (func) -> | ||
| 3489 | print "Callback wird ausgeführt..." | ||
| 3490 | func! | ||
| 3491 | |||
| 3492 | -- das funktioniert nicht: | ||
| 3493 | -- die Funktion darf keine Referenz auf my_object haben | ||
| 3494 | run_callback my_object.write | ||
| 3495 | |||
| 3496 | -- Funktions-Stub-Syntax | ||
| 3497 | -- bindet das Objekt in eine neue Funktion ein | ||
| 3498 | run_callback my_object\write | ||
| 3499 | ``` | ||
| 3500 | |||
| 3501 | </YueDisplay> | ||
| 3502 | |||
| 3503 | # Backcalls | 1799 | # Backcalls |
| 3504 | 1800 | ||
| 3505 | Backcalls werden verwendet, um Callbacks zu entkoppeln (unnesting). Sie werden mit Pfeilen nach links definiert und füllen standardmäßig als letzter Parameter einen Funktionsaufruf. Die Syntax ist weitgehend wie bei normalen Pfeilfunktionen, nur dass der Pfeil in die andere Richtung zeigt und der Funktionskörper keine Einrückung benötigt. | 1801 | Backcalls werden verwendet, um Callbacks zu entkoppeln (unnesting). Sie werden mit Pfeilen nach links definiert und füllen standardmäßig als letzter Parameter einen Funktionsaufruf. Die Syntax ist weitgehend wie bei normalen Pfeilfunktionen, nur dass der Pfeil in die andere Richtung zeigt und der Funktionskörper keine Einrückung benötigt. |
| @@ -3509,15 +1805,6 @@ x <- f | |||
| 3509 | print "hallo" .. x | 1805 | print "hallo" .. x |
| 3510 | ``` | 1806 | ``` |
| 3511 | 1807 | ||
| 3512 | <YueDisplay> | ||
| 3513 | |||
| 3514 | ```yue | ||
| 3515 | x <- f | ||
| 3516 | print "hallo" .. x | ||
| 3517 | ``` | ||
| 3518 | |||
| 3519 | </YueDisplay> | ||
| 3520 | |||
| 3521 | Fat-Arrow-Funktionen sind ebenfalls verfügbar. | 1808 | Fat-Arrow-Funktionen sind ebenfalls verfügbar. |
| 3522 | 1809 | ||
| 3523 | ```yuescript | 1810 | ```yuescript |
| @@ -3525,15 +1812,6 @@ Fat-Arrow-Funktionen sind ebenfalls verfügbar. | |||
| 3525 | print @value | 1812 | print @value |
| 3526 | ``` | 1813 | ``` |
| 3527 | 1814 | ||
| 3528 | <YueDisplay> | ||
| 3529 | |||
| 3530 | ```yue | ||
| 3531 | <= f | ||
| 3532 | print @value | ||
| 3533 | ``` | ||
| 3534 | |||
| 3535 | </YueDisplay> | ||
| 3536 | |||
| 3537 | Du kannst einen Platzhalter angeben, an welcher Stelle die Backcall-Funktion als Parameter eingesetzt werden soll. | 1815 | Du kannst einen Platzhalter angeben, an welcher Stelle die Backcall-Funktion als Parameter eingesetzt werden soll. |
| 3538 | 1816 | ||
| 3539 | ```yuescript | 1817 | ```yuescript |
| @@ -3541,15 +1819,6 @@ Du kannst einen Platzhalter angeben, an welcher Stelle die Backcall-Funktion als | |||
| 3541 | x * 2 | 1819 | x * 2 |
| 3542 | ``` | 1820 | ``` |
| 3543 | 1821 | ||
| 3544 | <YueDisplay> | ||
| 3545 | |||
| 3546 | ```yue | ||
| 3547 | (x) <- map _, [1, 2, 3] | ||
| 3548 | x * 2 | ||
| 3549 | ``` | ||
| 3550 | |||
| 3551 | </YueDisplay> | ||
| 3552 | |||
| 3553 | Wenn du nach deinen Backcalls weiteren Code haben willst, kannst du sie mit einem `do`-Statement absetzen. Bei Nicht-Fat-Arrow-Funktionen können die Klammern weggelassen werden. | 1822 | Wenn du nach deinen Backcalls weiteren Code haben willst, kannst du sie mit einem `do`-Statement absetzen. Bei Nicht-Fat-Arrow-Funktionen können die Klammern weggelassen werden. |
| 3554 | 1823 | ||
| 3555 | ```yuescript | 1824 | ```yuescript |
| @@ -3561,19 +1830,6 @@ result, msg = do | |||
| 3561 | print result, msg | 1830 | print result, msg |
| 3562 | ``` | 1831 | ``` |
| 3563 | 1832 | ||
| 3564 | <YueDisplay> | ||
| 3565 | |||
| 3566 | ```yue | ||
| 3567 | result, msg = do | ||
| 3568 | data <- readAsync "dateiname.txt" | ||
| 3569 | print data | ||
| 3570 | info <- processAsync data | ||
| 3571 | check info | ||
| 3572 | print result, msg | ||
| 3573 | ``` | ||
| 3574 | |||
| 3575 | </YueDisplay> | ||
| 3576 | |||
| 3577 | # Funktionsliterale | 1833 | # Funktionsliterale |
| 3578 | 1834 | ||
| 3579 | Alle Funktionen werden mit einem Funktionsausdruck erstellt. Eine einfache Funktion wird mit dem Pfeil **->** notiert. | 1835 | Alle Funktionen werden mit einem Funktionsausdruck erstellt. Eine einfache Funktion wird mit dem Pfeil **->** notiert. |
| @@ -3583,15 +1839,6 @@ my_function = -> | |||
| 3583 | my_function() -- leere Funktion aufrufen | 1839 | my_function() -- leere Funktion aufrufen |
| 3584 | ``` | 1840 | ``` |
| 3585 | 1841 | ||
| 3586 | <YueDisplay> | ||
| 3587 | |||
| 3588 | ```yue | ||
| 3589 | my_function = -> | ||
| 3590 | my_function() -- leere Funktion aufrufen | ||
| 3591 | ``` | ||
| 3592 | |||
| 3593 | </YueDisplay> | ||
| 3594 | |||
| 3595 | Der Funktionskörper kann entweder eine einzelne Anweisung direkt nach dem Pfeil sein oder aus mehreren Anweisungen bestehen, die in den folgenden Zeilen eingerückt werden: | 1842 | Der Funktionskörper kann entweder eine einzelne Anweisung direkt nach dem Pfeil sein oder aus mehreren Anweisungen bestehen, die in den folgenden Zeilen eingerückt werden: |
| 3596 | 1843 | ||
| 3597 | ```yuescript | 1844 | ```yuescript |
| @@ -3602,18 +1849,6 @@ func_b = -> | |||
| 3602 | print "Der Wert:", value | 1849 | print "Der Wert:", value |
| 3603 | ``` | 1850 | ``` |
| 3604 | 1851 | ||
| 3605 | <YueDisplay> | ||
| 3606 | |||
| 3607 | ```yue | ||
| 3608 | func_a = -> print "Hallo Welt" | ||
| 3609 | |||
| 3610 | func_b = -> | ||
| 3611 | value = 100 | ||
| 3612 | print "Der Wert:", value | ||
| 3613 | ``` | ||
| 3614 | |||
| 3615 | </YueDisplay> | ||
| 3616 | |||
| 3617 | Wenn eine Funktion keine Argumente hat, kann sie mit dem `!`-Operator statt leerer Klammern aufgerufen werden. Der `!`-Aufruf ist die bevorzugte Art, Funktionen ohne Argumente aufzurufen. | 1852 | Wenn eine Funktion keine Argumente hat, kann sie mit dem `!`-Operator statt leerer Klammern aufgerufen werden. Der `!`-Aufruf ist die bevorzugte Art, Funktionen ohne Argumente aufzurufen. |
| 3618 | 1853 | ||
| 3619 | ```yuescript | 1854 | ```yuescript |
| @@ -3621,29 +1856,12 @@ func_a! | |||
| 3621 | func_b() | 1856 | func_b() |
| 3622 | ``` | 1857 | ``` |
| 3623 | 1858 | ||
| 3624 | <YueDisplay> | ||
| 3625 | |||
| 3626 | ```yue | ||
| 3627 | func_a! | ||
| 3628 | func_b() | ||
| 3629 | ``` | ||
| 3630 | |||
| 3631 | </YueDisplay> | ||
| 3632 | |||
| 3633 | Funktionen mit Argumenten werden erstellt, indem der Pfeil von einer Argumentliste in Klammern eingeleitet wird: | 1859 | Funktionen mit Argumenten werden erstellt, indem der Pfeil von einer Argumentliste in Klammern eingeleitet wird: |
| 3634 | 1860 | ||
| 3635 | ```yuescript | 1861 | ```yuescript |
| 3636 | sum = (x, y) -> print "Summe", x + y | 1862 | sum = (x, y) -> print "Summe", x + y |
| 3637 | ``` | 1863 | ``` |
| 3638 | 1864 | ||
| 3639 | <YueDisplay> | ||
| 3640 | |||
| 3641 | ```yue | ||
| 3642 | sum = (x, y) -> print "Summe", x + y | ||
| 3643 | ``` | ||
| 3644 | |||
| 3645 | </YueDisplay> | ||
| 3646 | |||
| 3647 | Funktionen können aufgerufen werden, indem die Argumente hinter dem Namen eines Ausdrucks stehen, der zu einer Funktion evaluiert. Beim Verketten mehrerer Funktionsaufrufe werden die Argumente der nächstliegenden Funktion links zugeordnet. | 1865 | Funktionen können aufgerufen werden, indem die Argumente hinter dem Namen eines Ausdrucks stehen, der zu einer Funktion evaluiert. Beim Verketten mehrerer Funktionsaufrufe werden die Argumente der nächstliegenden Funktion links zugeordnet. |
| 3648 | 1866 | ||
| 3649 | ```yuescript | 1867 | ```yuescript |
| @@ -3653,31 +1871,12 @@ print sum 10, 20 | |||
| 3653 | a b c "a", "b", "c" | 1871 | a b c "a", "b", "c" |
| 3654 | ``` | 1872 | ``` |
| 3655 | 1873 | ||
| 3656 | <YueDisplay> | ||
| 3657 | |||
| 3658 | ```yue | ||
| 3659 | sum 10, 20 | ||
| 3660 | print sum 10, 20 | ||
| 3661 | |||
| 3662 | a b c "a", "b", "c" | ||
| 3663 | ``` | ||
| 3664 | |||
| 3665 | </YueDisplay> | ||
| 3666 | |||
| 3667 | Um Mehrdeutigkeiten beim Aufruf zu vermeiden, können die Argumente auch in Klammern gesetzt werden. Das ist hier nötig, damit die richtigen Argumente an die richtigen Funktionen gehen. | 1874 | Um Mehrdeutigkeiten beim Aufruf zu vermeiden, können die Argumente auch in Klammern gesetzt werden. Das ist hier nötig, damit die richtigen Argumente an die richtigen Funktionen gehen. |
| 3668 | 1875 | ||
| 3669 | ```yuescript | 1876 | ```yuescript |
| 3670 | print "x:", sum(10, 20), "y:", sum(30, 40) | 1877 | print "x:", sum(10, 20), "y:", sum(30, 40) |
| 3671 | ``` | 1878 | ``` |
| 3672 | 1879 | ||
| 3673 | <YueDisplay> | ||
| 3674 | |||
| 3675 | ```yue | ||
| 3676 | print "x:", sum(10, 20), "y:", sum(30, 40) | ||
| 3677 | ``` | ||
| 3678 | |||
| 3679 | </YueDisplay> | ||
| 3680 | |||
| 3681 | Zwischen öffnender Klammer und Funktionsname darf kein Leerzeichen stehen. | 1880 | Zwischen öffnender Klammer und Funktionsname darf kein Leerzeichen stehen. |
| 3682 | 1881 | ||
| 3683 | Funktionen wandeln die letzte Anweisung im Funktionskörper in ein `return` um. Das nennt sich implizites Return: | 1882 | Funktionen wandeln die letzte Anweisung im Funktionskörper in ein `return` um. Das nennt sich implizites Return: |
| @@ -3687,29 +1886,12 @@ sum = (x, y) -> x + y | |||
| 3687 | print "Die Summe ist ", sum 10, 20 | 1886 | print "Die Summe ist ", sum 10, 20 |
| 3688 | ``` | 1887 | ``` |
| 3689 | 1888 | ||
| 3690 | <YueDisplay> | ||
| 3691 | |||
| 3692 | ```yue | ||
| 3693 | sum = (x, y) -> x + y | ||
| 3694 | print "Die Summe ist ", sum 10, 20 | ||
| 3695 | ``` | ||
| 3696 | |||
| 3697 | </YueDisplay> | ||
| 3698 | |||
| 3699 | Wenn du explizit zurückgeben willst, verwende `return`: | 1889 | Wenn du explizit zurückgeben willst, verwende `return`: |
| 3700 | 1890 | ||
| 3701 | ```yuescript | 1891 | ```yuescript |
| 3702 | sum = (x, y) -> return x + y | 1892 | sum = (x, y) -> return x + y |
| 3703 | ``` | 1893 | ``` |
| 3704 | 1894 | ||
| 3705 | <YueDisplay> | ||
| 3706 | |||
| 3707 | ```yue | ||
| 3708 | sum = (x, y) -> return x + y | ||
| 3709 | ``` | ||
| 3710 | |||
| 3711 | </YueDisplay> | ||
| 3712 | |||
| 3713 | Wie in Lua können Funktionen mehrere Werte zurückgeben. Die letzte Anweisung muss eine Liste von Werten sein, getrennt durch Kommas: | 1895 | Wie in Lua können Funktionen mehrere Werte zurückgeben. Die letzte Anweisung muss eine Liste von Werten sein, getrennt durch Kommas: |
| 3714 | 1896 | ||
| 3715 | ```yuescript | 1897 | ```yuescript |
| @@ -3717,15 +1899,6 @@ mystery = (x, y) -> x + y, x - y | |||
| 3717 | a, b = mystery 10, 20 | 1899 | a, b = mystery 10, 20 |
| 3718 | ``` | 1900 | ``` |
| 3719 | 1901 | ||
| 3720 | <YueDisplay> | ||
| 3721 | |||
| 3722 | ```yue | ||
| 3723 | mystery = (x, y) -> x + y, x - y | ||
| 3724 | a, b = mystery 10, 20 | ||
| 3725 | ``` | ||
| 3726 | |||
| 3727 | </YueDisplay> | ||
| 3728 | |||
| 3729 | ## Fat Arrows | 1902 | ## Fat Arrows |
| 3730 | 1903 | ||
| 3731 | Da es in Lua üblich ist, beim Methodenaufruf ein Objekt als erstes Argument zu übergeben, gibt es eine spezielle Syntax zum Erstellen von Funktionen, die automatisch ein `self`-Argument enthalten. | 1904 | Da es in Lua üblich ist, beim Methodenaufruf ein Objekt als erstes Argument zu übergeben, gibt es eine spezielle Syntax zum Erstellen von Funktionen, die automatisch ein `self`-Argument enthalten. |
| @@ -3734,14 +1907,6 @@ Da es in Lua üblich ist, beim Methodenaufruf ein Objekt als erstes Argument zu | |||
| 3734 | func = (num) => @value + num | 1907 | func = (num) => @value + num |
| 3735 | ``` | 1908 | ``` |
| 3736 | 1909 | ||
| 3737 | <YueDisplay> | ||
| 3738 | |||
| 3739 | ```yue | ||
| 3740 | func = (num) => @value + num | ||
| 3741 | ``` | ||
| 3742 | |||
| 3743 | </YueDisplay> | ||
| 3744 | |||
| 3745 | ## Standardwerte für Argumente | 1910 | ## Standardwerte für Argumente |
| 3746 | 1911 | ||
| 3747 | Es ist möglich, Standardwerte für Funktionsargumente anzugeben. Ein Argument gilt als leer, wenn sein Wert `nil` ist. Alle `nil`-Argumente mit Standardwert werden vor Ausführung des Funktionskörpers ersetzt. | 1912 | Es ist möglich, Standardwerte für Funktionsargumente anzugeben. Ein Argument gilt als leer, wenn sein Wert `nil` ist. Alle `nil`-Argumente mit Standardwert werden vor Ausführung des Funktionskörpers ersetzt. |
| @@ -3752,16 +1917,6 @@ my_function = (name = "etwas", height = 100) -> | |||
| 3752 | print "Meine Größe ist", height | 1917 | print "Meine Größe ist", height |
| 3753 | ``` | 1918 | ``` |
| 3754 | 1919 | ||
| 3755 | <YueDisplay> | ||
| 3756 | |||
| 3757 | ```yue | ||
| 3758 | my_function = (name = "etwas", height = 100) -> | ||
| 3759 | print "Hallo, ich bin", name | ||
| 3760 | print "Meine Größe ist", height | ||
| 3761 | ``` | ||
| 3762 | |||
| 3763 | </YueDisplay> | ||
| 3764 | |||
| 3765 | Der Ausdruck für den Standardwert wird im Funktionskörper in der Reihenfolge der Argumentdeklarationen ausgewertet. Daher können Standardwerte auf zuvor deklarierte Argumente zugreifen. | 1920 | Der Ausdruck für den Standardwert wird im Funktionskörper in der Reihenfolge der Argumentdeklarationen ausgewertet. Daher können Standardwerte auf zuvor deklarierte Argumente zugreifen. |
| 3766 | 1921 | ||
| 3767 | ```yuescript | 1922 | ```yuescript |
| @@ -3769,15 +1924,6 @@ some_args = (x = 100, y = x + 1000) -> | |||
| 3769 | print x + y | 1924 | print x + y |
| 3770 | ``` | 1925 | ``` |
| 3771 | 1926 | ||
| 3772 | <YueDisplay> | ||
| 3773 | |||
| 3774 | ```yue | ||
| 3775 | some_args = (x = 100, y = x + 1000) -> | ||
| 3776 | print x + y | ||
| 3777 | ``` | ||
| 3778 | |||
| 3779 | </YueDisplay> | ||
| 3780 | |||
| 3781 | ## Hinweise | 1927 | ## Hinweise |
| 3782 | 1928 | ||
| 3783 | Aufgrund der ausdrucksstarken, klammerlosen Funktionsaufrufe müssen einige Einschränkungen gelten, um Parsing-Mehrdeutigkeiten mit Leerraum zu vermeiden. | 1929 | Aufgrund der ausdrucksstarken, klammerlosen Funktionsaufrufe müssen einige Einschränkungen gelten, um Parsing-Mehrdeutigkeiten mit Leerraum zu vermeiden. |
| @@ -3791,17 +1937,6 @@ c = x -y | |||
| 3791 | d = x- z | 1937 | d = x- z |
| 3792 | ``` | 1938 | ``` |
| 3793 | 1939 | ||
| 3794 | <YueDisplay> | ||
| 3795 | |||
| 3796 | ```yue | ||
| 3797 | a = x - 10 | ||
| 3798 | b = x-10 | ||
| 3799 | c = x -y | ||
| 3800 | d = x- z | ||
| 3801 | ``` | ||
| 3802 | |||
| 3803 | </YueDisplay> | ||
| 3804 | |||
| 3805 | Die Präzedenz des ersten Arguments eines Funktionsaufrufs kann mit Leerraum gesteuert werden, wenn das Argument ein String-Literal ist. In Lua lässt man bei Aufrufen mit einem einzelnen String- oder Tabellenliteral häufig die Klammern weg. | 1940 | Die Präzedenz des ersten Arguments eines Funktionsaufrufs kann mit Leerraum gesteuert werden, wenn das Argument ein String-Literal ist. In Lua lässt man bei Aufrufen mit einem einzelnen String- oder Tabellenliteral häufig die Klammern weg. |
| 3806 | 1941 | ||
| 3807 | Wenn kein Leerzeichen zwischen Variable und String-Literal steht, hat der Funktionsaufruf Vorrang vor nachfolgenden Ausdrücken. In dieser Form können keine weiteren Argumente übergeben werden. | 1942 | Wenn kein Leerzeichen zwischen Variable und String-Literal steht, hat der Funktionsaufruf Vorrang vor nachfolgenden Ausdrücken. In dieser Form können keine weiteren Argumente übergeben werden. |
| @@ -3813,15 +1948,6 @@ x = func"hallo" + 100 | |||
| 3813 | y = func "hallo" + 100 | 1948 | y = func "hallo" + 100 |
| 3814 | ``` | 1949 | ``` |
| 3815 | 1950 | ||
| 3816 | <YueDisplay> | ||
| 3817 | |||
| 3818 | ```yue | ||
| 3819 | x = func"hallo" + 100 | ||
| 3820 | y = func "hallo" + 100 | ||
| 3821 | ``` | ||
| 3822 | |||
| 3823 | </YueDisplay> | ||
| 3824 | |||
| 3825 | ## Mehrzeilige Argumente | 1951 | ## Mehrzeilige Argumente |
| 3826 | 1952 | ||
| 3827 | Wenn Funktionsaufrufe viele Argumente haben, ist es praktisch, die Argumentliste auf mehrere Zeilen zu verteilen. Wegen der whitespace-sensitiven Natur der Sprache muss man dabei sorgfältig sein. | 1953 | Wenn Funktionsaufrufe viele Argumente haben, ist es praktisch, die Argumentliste auf mehrere Zeilen zu verteilen. Wegen der whitespace-sensitiven Natur der Sprache muss man dabei sorgfältig sein. |
| @@ -3838,20 +1964,6 @@ cool_func 1, 2, | |||
| 3838 | 7, 8 | 1964 | 7, 8 |
| 3839 | ``` | 1965 | ``` |
| 3840 | 1966 | ||
| 3841 | <YueDisplay> | ||
| 3842 | |||
| 3843 | ```yue | ||
| 3844 | my_func 5, 4, 3, | ||
| 3845 | 8, 9, 10 | ||
| 3846 | |||
| 3847 | cool_func 1, 2, | ||
| 3848 | 3, 4, | ||
| 3849 | 5, 6, | ||
| 3850 | 7, 8 | ||
| 3851 | ``` | ||
| 3852 | |||
| 3853 | </YueDisplay> | ||
| 3854 | |||
| 3855 | Diese Art des Aufrufs kann verschachtelt werden. Die Einrückungsebene bestimmt, zu welcher Funktion die Argumente gehören. | 1967 | Diese Art des Aufrufs kann verschachtelt werden. Die Einrückungsebene bestimmt, zu welcher Funktion die Argumente gehören. |
| 3856 | 1968 | ||
| 3857 | ```yuescript | 1969 | ```yuescript |
| @@ -3861,17 +1973,6 @@ my_func 5, 6, 7, | |||
| 3861 | 5, 4 | 1973 | 5, 4 |
| 3862 | ``` | 1974 | ``` |
| 3863 | 1975 | ||
| 3864 | <YueDisplay> | ||
| 3865 | |||
| 3866 | ```yue | ||
| 3867 | my_func 5, 6, 7, | ||
| 3868 | 6, another_func 6, 7, 8, | ||
| 3869 | 9, 1, 2, | ||
| 3870 | 5, 4 | ||
| 3871 | ``` | ||
| 3872 | |||
| 3873 | </YueDisplay> | ||
| 3874 | |||
| 3875 | Da Tabellen ebenfalls das Komma als Trennzeichen verwenden, hilft diese Einrückungssyntax dabei, Werte zur Argumentliste gehören zu lassen, statt zur Tabelle. | 1976 | Da Tabellen ebenfalls das Komma als Trennzeichen verwenden, hilft diese Einrückungssyntax dabei, Werte zur Argumentliste gehören zu lassen, statt zur Tabelle. |
| 3876 | 1977 | ||
| 3877 | ```yuescript | 1978 | ```yuescript |
| @@ -3882,18 +1983,6 @@ x = [ | |||
| 3882 | ] | 1983 | ] |
| 3883 | ``` | 1984 | ``` |
| 3884 | 1985 | ||
| 3885 | <YueDisplay> | ||
| 3886 | |||
| 3887 | ```yue | ||
| 3888 | x = [ | ||
| 3889 | 1, 2, 3, 4, a_func 4, 5, | ||
| 3890 | 5, 6, | ||
| 3891 | 8, 9, 10 | ||
| 3892 | ] | ||
| 3893 | ``` | ||
| 3894 | |||
| 3895 | </YueDisplay> | ||
| 3896 | |||
| 3897 | Obwohl es selten ist: Du kannst Funktionsargumente tiefer einrücken, wenn du weißt, dass du später eine geringere Einrückungsebene verwenden wirst. | 1986 | Obwohl es selten ist: Du kannst Funktionsargumente tiefer einrücken, wenn du weißt, dass du später eine geringere Einrückungsebene verwenden wirst. |
| 3898 | 1987 | ||
| 3899 | ```yuescript | 1988 | ```yuescript |
| @@ -3903,17 +1992,6 @@ y = [ my_func 1, 2, 3, | |||
| 3903 | ] | 1992 | ] |
| 3904 | ``` | 1993 | ``` |
| 3905 | 1994 | ||
| 3906 | <YueDisplay> | ||
| 3907 | |||
| 3908 | ```yue | ||
| 3909 | y = [ my_func 1, 2, 3, | ||
| 3910 | 4, 5, | ||
| 3911 | 5, 6, 7 | ||
| 3912 | ] | ||
| 3913 | ``` | ||
| 3914 | |||
| 3915 | </YueDisplay> | ||
| 3916 | |||
| 3917 | Dasselbe lässt sich mit anderen Block-Statements wie Bedingungen machen. Wir können die Einrückungsebene verwenden, um zu bestimmen, zu welcher Anweisung ein Wert gehört: | 1995 | Dasselbe lässt sich mit anderen Block-Statements wie Bedingungen machen. Wir können die Einrückungsebene verwenden, um zu bestimmen, zu welcher Anweisung ein Wert gehört: |
| 3918 | 1996 | ||
| 3919 | ```yuescript | 1997 | ```yuescript |
| @@ -3930,24 +2008,6 @@ if func 1, 2, 3, | |||
| 3930 | print "Ich bin innerhalb der if-Bedingung" | 2008 | print "Ich bin innerhalb der if-Bedingung" |
| 3931 | ``` | 2009 | ``` |
| 3932 | 2010 | ||
| 3933 | <YueDisplay> | ||
| 3934 | |||
| 3935 | ```yue | ||
| 3936 | if func 1, 2, 3, | ||
| 3937 | "hallo", | ||
| 3938 | "Welt" | ||
| 3939 | print "hallo" | ||
| 3940 | print "Ich bin innerhalb der if-Bedingung" | ||
| 3941 | |||
| 3942 | if func 1, 2, 3, | ||
| 3943 | "hallo", | ||
| 3944 | "Welt" | ||
| 3945 | print "hallo" | ||
| 3946 | print "Ich bin innerhalb der if-Bedingung" | ||
| 3947 | ``` | ||
| 3948 | |||
| 3949 | </YueDisplay> | ||
| 3950 | |||
| 3951 | ## Parameter-Destructuring | 2011 | ## Parameter-Destructuring |
| 3952 | 2012 | ||
| 3953 | YueScript unterstützt jetzt Destructuring von Funktionsparametern, wenn das Argument ein Objekt ist. Es gibt zwei Formen von Destructuring-Tabellenliteralen: | 2013 | YueScript unterstützt jetzt Destructuring von Funktionsparametern, wenn das Argument ein Objekt ist. Es gibt zwei Formen von Destructuring-Tabellenliteralen: |
| @@ -3968,23 +2028,6 @@ arg1 = {a: 0} | |||
| 3968 | f2 arg1, arg2 | 2028 | f2 arg1, arg2 |
| 3969 | ``` | 2029 | ``` |
| 3970 | 2030 | ||
| 3971 | <YueDisplay> | ||
| 3972 | |||
| 3973 | ```yue | ||
| 3974 | f1 = (:a, :b, :c) -> | ||
| 3975 | print a, b, c | ||
| 3976 | |||
| 3977 | f1 a: 1, b: "2", c: {} | ||
| 3978 | |||
| 3979 | f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) -> | ||
| 3980 | print a1, b, c | ||
| 3981 | |||
| 3982 | arg1 = {a: 0} | ||
| 3983 | f2 arg1, arg2 | ||
| 3984 | ``` | ||
| 3985 | |||
| 3986 | </YueDisplay> | ||
| 3987 | |||
| 3988 | ## Präfixiertes Return-Expression | 2031 | ## Präfixiertes Return-Expression |
| 3989 | 2032 | ||
| 3990 | Wenn du mit tief verschachtelten Funktionskörpern arbeitest, kann es mühsam sein, die Lesbarkeit und Konsistenz des Rückgabewerts zu erhalten. Dafür führt YueScript die Syntax der **präfixierten Return-Expression** ein. Sie hat folgende Form: | 2033 | Wenn du mit tief verschachtelten Funktionskörpern arbeitest, kann es mühsam sein, die Lesbarkeit und Konsistenz des Rückgabewerts zu erhalten. Dafür führt YueScript die Syntax der **präfixierten Return-Expression** ein. Sie hat folgende Form: |
| @@ -3998,19 +2041,6 @@ findFirstEven = (list): nil -> | |||
| 3998 | return sub | 2041 | return sub |
| 3999 | ``` | 2042 | ``` |
| 4000 | 2043 | ||
| 4001 | <YueDisplay> | ||
| 4002 | |||
| 4003 | ```yue | ||
| 4004 | findFirstEven = (list): nil -> | ||
| 4005 | for item in *list | ||
| 4006 | if type(item) == "table" | ||
| 4007 | for sub in *item | ||
| 4008 | if sub % 2 == 0 | ||
| 4009 | return sub | ||
| 4010 | ``` | ||
| 4011 | |||
| 4012 | </YueDisplay> | ||
| 4013 | |||
| 4014 | Das ist äquivalent zu: | 2044 | Das ist äquivalent zu: |
| 4015 | 2045 | ||
| 4016 | ```yuescript | 2046 | ```yuescript |
| @@ -4023,20 +2053,6 @@ findFirstEven = (list) -> | |||
| 4023 | nil | 2053 | nil |
| 4024 | ``` | 2054 | ``` |
| 4025 | 2055 | ||
| 4026 | <YueDisplay> | ||
| 4027 | |||
| 4028 | ```yue | ||
| 4029 | findFirstEven = (list) -> | ||
| 4030 | for item in *list | ||
| 4031 | if type(item) == "table" | ||
| 4032 | for sub in *item | ||
| 4033 | if sub % 2 == 0 | ||
| 4034 | return sub | ||
| 4035 | nil | ||
| 4036 | ``` | ||
| 4037 | |||
| 4038 | </YueDisplay> | ||
| 4039 | |||
| 4040 | Der einzige Unterschied ist, dass du den finalen Rückgabeausdruck vor das `->`- oder `=>`-Token ziehen kannst, um den impliziten Rückgabewert der Funktion als letzte Anweisung zu kennzeichnen. So musst du selbst bei Funktionen mit mehreren verschachtelten Schleifen oder bedingten Zweigen kein abschließendes `return` am Ende des Funktionskörpers mehr schreiben, was die Logikstruktur klarer und leichter nachvollziehbar macht. | 2056 | Der einzige Unterschied ist, dass du den finalen Rückgabeausdruck vor das `->`- oder `=>`-Token ziehen kannst, um den impliziten Rückgabewert der Funktion als letzte Anweisung zu kennzeichnen. So musst du selbst bei Funktionen mit mehreren verschachtelten Schleifen oder bedingten Zweigen kein abschließendes `return` am Ende des Funktionskörpers mehr schreiben, was die Logikstruktur klarer und leichter nachvollziehbar macht. |
| 4041 | 2057 | ||
| 4042 | ## Benannte Varargs | 2058 | ## Benannte Varargs |
| @@ -4065,32 +2081,6 @@ process = (...args) -> | |||
| 4065 | process 1, nil, 3, nil, 5 | 2081 | process 1, nil, 3, nil, 5 |
| 4066 | ``` | 2082 | ``` |
| 4067 | 2083 | ||
| 4068 | <YueDisplay> | ||
| 4069 | |||
| 4070 | ```yue | ||
| 4071 | f = (...t) -> | ||
| 4072 | print "Anzahl der Argumente:", t.n | ||
| 4073 | print "Tabellenlänge:", #t | ||
| 4074 | for i = 1, t.n | ||
| 4075 | print t[i] | ||
| 4076 | |||
| 4077 | f 1, 2, 3 | ||
| 4078 | f "a", "b", "c", "d" | ||
| 4079 | f! | ||
| 4080 | |||
| 4081 | -- Fälle mit nil-Werten behandeln | ||
| 4082 | process = (...args) -> | ||
| 4083 | sum = 0 | ||
| 4084 | for i = 1, args.n | ||
| 4085 | if args[i] != nil and type(args[i]) == "number" | ||
| 4086 | sum += args[i] | ||
| 4087 | sum | ||
| 4088 | |||
| 4089 | process 1, nil, 3, nil, 5 | ||
| 4090 | ``` | ||
| 4091 | |||
| 4092 | </YueDisplay> | ||
| 4093 | |||
| 4094 | # Leerraum | 2084 | # Leerraum |
| 4095 | 2085 | ||
| 4096 | YueScript ist eine whitespace-sensible Sprache. Du musst bestimmte Code-Blöcke mit derselben Einrückung (Leerzeichen **' '** oder Tab **'\t'**) schreiben, z. B. Funktionskörper, Wertelisten und Kontrollblöcke. Ausdrücke mit unterschiedlichem Leerraum können unterschiedliche Bedeutungen haben. Ein Tab wird wie 4 Leerzeichen behandelt, aber es ist besser, Leerzeichen und Tabs nicht zu mischen. | 2086 | YueScript ist eine whitespace-sensible Sprache. Du musst bestimmte Code-Blöcke mit derselben Einrückung (Leerzeichen **' '** oder Tab **'\t'**) schreiben, z. B. Funktionskörper, Wertelisten und Kontrollblöcke. Ausdrücke mit unterschiedlichem Leerraum können unterschiedliche Bedeutungen haben. Ein Tab wird wie 4 Leerzeichen behandelt, aber es ist besser, Leerzeichen und Tabs nicht zu mischen. |
| @@ -4103,14 +2093,6 @@ Eine Anweisung endet normalerweise an einem Zeilenumbruch. Du kannst auch ein Se | |||
| 4103 | a = 1; b = 2; print a + b | 2093 | a = 1; b = 2; print a + b |
| 4104 | ``` | 2094 | ``` |
| 4105 | 2095 | ||
| 4106 | <YueDisplay> | ||
| 4107 | |||
| 4108 | ```yue | ||
| 4109 | a = 1; b = 2; print a + b | ||
| 4110 | ``` | ||
| 4111 | |||
| 4112 | </YueDisplay> | ||
| 4113 | |||
| 4114 | ## Mehrzeiliges Chaining | 2096 | ## Mehrzeiliges Chaining |
| 4115 | 2097 | ||
| 4116 | Du kannst mehrzeilige, verkettete Funktionsaufrufe mit derselben Einrückung schreiben. | 2098 | Du kannst mehrzeilige, verkettete Funktionsaufrufe mit derselben Einrückung schreiben. |
| @@ -4124,19 +2106,6 @@ Rx.Observable | |||
| 4124 | \subscribe print | 2106 | \subscribe print |
| 4125 | ``` | 2107 | ``` |
| 4126 | 2108 | ||
| 4127 | <YueDisplay> | ||
| 4128 | |||
| 4129 | ```yue | ||
| 4130 | Rx.Observable | ||
| 4131 | .fromRange 1, 8 | ||
| 4132 | \filter (x) -> x % 2 == 0 | ||
| 4133 | \concat Rx.Observable.of 'who do we appreciate' | ||
| 4134 | \map (value) -> value .. '!' | ||
| 4135 | \subscribe print | ||
| 4136 | ``` | ||
| 4137 | |||
| 4138 | </YueDisplay> | ||
| 4139 | |||
| 4140 | # Kommentare | 2109 | # Kommentare |
| 4141 | 2110 | ||
| 4142 | ```yuescript | 2111 | ```yuescript |
| @@ -4152,23 +2121,6 @@ Alles okay. | |||
| 4152 | func --[[Port]] 3000, --[[IP]] "192.168.1.1" | 2121 | func --[[Port]] 3000, --[[IP]] "192.168.1.1" |
| 4153 | ``` | 2122 | ``` |
| 4154 | 2123 | ||
| 4155 | <YueDisplay> | ||
| 4156 | |||
| 4157 | ```yue | ||
| 4158 | -- Ich bin ein Kommentar | ||
| 4159 | |||
| 4160 | str = --[[ | ||
| 4161 | Dies ist ein mehrzeiliger Kommentar. | ||
| 4162 | Alles okay. | ||
| 4163 | ]] strA \ -- Kommentar 1 | ||
| 4164 | .. strB \ -- Kommentar 2 | ||
| 4165 | .. strC | ||
| 4166 | |||
| 4167 | func --[[Port]] 3000, --[[IP]] "192.168.1.1" | ||
| 4168 | ``` | ||
| 4169 | |||
| 4170 | </YueDisplay> | ||
| 4171 | |||
| 4172 | # Attribute | 2124 | # Attribute |
| 4173 | 2125 | ||
| 4174 | Syntax-Unterstützung für Lua-5.4-Attribute. Du kannst weiterhin die Deklarationen `const` und `close` verwenden und erhältst Konstantenprüfung sowie Scoped-Callbacks, wenn du auf Lua-Versionen unter 5.4 zielst. | 2126 | Syntax-Unterstützung für Lua-5.4-Attribute. Du kannst weiterhin die Deklarationen `const` und `close` verwenden und erhältst Konstantenprüfung sowie Scoped-Callbacks, wenn du auf Lua-Versionen unter 5.4 zielst. |
| @@ -4178,15 +2130,6 @@ const a = 123 | |||
| 4178 | close _ = <close>: -> print "Außerhalb des Gültigkeitsbereichs." | 2130 | close _ = <close>: -> print "Außerhalb des Gültigkeitsbereichs." |
| 4179 | ``` | 2131 | ``` |
| 4180 | 2132 | ||
| 4181 | <YueDisplay> | ||
| 4182 | |||
| 4183 | ```yue | ||
| 4184 | const a = 123 | ||
| 4185 | close _ = <close>: -> print "Außerhalb des Gültigkeitsbereichs." | ||
| 4186 | ``` | ||
| 4187 | |||
| 4188 | </YueDisplay> | ||
| 4189 | |||
| 4190 | Du kannst Destructuring mit als konstant markierten Variablen verwenden. | 2133 | Du kannst Destructuring mit als konstant markierten Variablen verwenden. |
| 4191 | 2134 | ||
| 4192 | ```yuescript | 2135 | ```yuescript |
| @@ -4194,15 +2137,6 @@ const {:a, :b, c, d} = tb | |||
| 4194 | -- a = 1 | 2137 | -- a = 1 |
| 4195 | ``` | 2138 | ``` |
| 4196 | 2139 | ||
| 4197 | <YueDisplay> | ||
| 4198 | |||
| 4199 | ```yue | ||
| 4200 | const {:a, :b, c, d} = tb | ||
| 4201 | -- a = 1 | ||
| 4202 | ``` | ||
| 4203 | |||
| 4204 | </YueDisplay> | ||
| 4205 | |||
| 4206 | Du kannst auch eine globale Variable als `const` deklarieren. | 2140 | Du kannst auch eine globale Variable als `const` deklarieren. |
| 4207 | 2141 | ||
| 4208 | ```yuescript | 2142 | ```yuescript |
| @@ -4210,15 +2144,6 @@ global const Constant = 123 | |||
| 4210 | -- Constant = 1 | 2144 | -- Constant = 1 |
| 4211 | ``` | 2145 | ``` |
| 4212 | 2146 | ||
| 4213 | <YueDisplay> | ||
| 4214 | |||
| 4215 | ```yue | ||
| 4216 | global const Constant = 123 | ||
| 4217 | -- Constant = 1 | ||
| 4218 | ``` | ||
| 4219 | |||
| 4220 | </YueDisplay> | ||
| 4221 | |||
| 4222 | # Operatoren | 2147 | # Operatoren |
| 4223 | 2148 | ||
| 4224 | Alle binären und unären Operatoren von Lua sind verfügbar. Zusätzlich ist **!=** ein Alias für **~=**, und entweder **\*\* oder **::\*\* kann für verkettete Funktionsaufrufe wie `tb\func!` oder `tb::func!` verwendet werden. Außerdem bietet YueScript einige spezielle Operatoren für ausdrucksstärkeren Code. | 2149 | Alle binären und unären Operatoren von Lua sind verfügbar. Zusätzlich ist **!=** ein Alias für **~=**, und entweder **\*\* oder **::\*\* kann für verkettete Funktionsaufrufe wie `tb\func!` oder `tb::func!` verwendet werden. Außerdem bietet YueScript einige spezielle Operatoren für ausdrucksstärkeren Code. |
| @@ -4228,15 +2153,6 @@ tb\func! if tb ~= nil | |||
| 4228 | tb::func! if tb != nil | 2153 | tb::func! if tb != nil |
| 4229 | ``` | 2154 | ``` |
| 4230 | 2155 | ||
| 4231 | <YueDisplay> | ||
| 4232 | |||
| 4233 | ```yue | ||
| 4234 | tb\func! if tb ~= nil | ||
| 4235 | tb::func! if tb != nil | ||
| 4236 | ``` | ||
| 4237 | |||
| 4238 | </YueDisplay> | ||
| 4239 | |||
| 4240 | ## Verkettete Vergleiche | 2156 | ## Verkettete Vergleiche |
| 4241 | 2157 | ||
| 4242 | Vergleiche können beliebig verkettet werden: | 2158 | Vergleiche können beliebig verkettet werden: |
| @@ -4250,19 +2166,6 @@ print 1 <= a <= 10 | |||
| 4250 | -- Ausgabe: true | 2166 | -- Ausgabe: true |
| 4251 | ``` | 2167 | ``` |
| 4252 | 2168 | ||
| 4253 | <YueDisplay> | ||
| 4254 | |||
| 4255 | ```yue | ||
| 4256 | print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 | ||
| 4257 | -- Ausgabe: true | ||
| 4258 | |||
| 4259 | a = 5 | ||
| 4260 | print 1 <= a <= 10 | ||
| 4261 | -- Ausgabe: true | ||
| 4262 | ``` | ||
| 4263 | |||
| 4264 | </YueDisplay> | ||
| 4265 | |||
| 4266 | Beachte das Auswertungsverhalten verketteter Vergleiche: | 2169 | Beachte das Auswertungsverhalten verketteter Vergleiche: |
| 4267 | 2170 | ||
| 4268 | ```yuescript | 2171 | ```yuescript |
| @@ -4288,33 +2191,6 @@ print v(1) > v(2) <= v(3) | |||
| 4288 | ]] | 2191 | ]] |
| 4289 | ``` | 2192 | ``` |
| 4290 | 2193 | ||
| 4291 | <YueDisplay> | ||
| 4292 | |||
| 4293 | ```yue | ||
| 4294 | v = (x) -> | ||
| 4295 | print x | ||
| 4296 | x | ||
| 4297 | |||
| 4298 | print v(1) < v(2) <= v(3) | ||
| 4299 | --[[ | ||
| 4300 | Ausgabe: | ||
| 4301 | 2 | ||
| 4302 | 1 | ||
| 4303 | 3 | ||
| 4304 | true | ||
| 4305 | ]] | ||
| 4306 | |||
| 4307 | print v(1) > v(2) <= v(3) | ||
| 4308 | --[[ | ||
| 4309 | Ausgabe: | ||
| 4310 | 2 | ||
| 4311 | 1 | ||
| 4312 | false | ||
| 4313 | ]] | ||
| 4314 | ``` | ||
| 4315 | |||
| 4316 | </YueDisplay> | ||
| 4317 | |||
| 4318 | Der mittlere Ausdruck wird nur einmal ausgewertet, nicht zweimal wie bei `v(1) < v(2) and v(2) <= v(3)`. Die Auswertungsreihenfolge in verketteten Vergleichen ist jedoch undefiniert. Es wird dringend empfohlen, in verketteten Vergleichen keine Ausdrücke mit Seiteneffekten (z. B. `print`) zu verwenden. Wenn Seiteneffekte nötig sind, sollte der Short-Circuit-Operator `and` explizit verwendet werden. | 2194 | Der mittlere Ausdruck wird nur einmal ausgewertet, nicht zweimal wie bei `v(1) < v(2) and v(2) <= v(3)`. Die Auswertungsreihenfolge in verketteten Vergleichen ist jedoch undefiniert. Es wird dringend empfohlen, in verketteten Vergleichen keine Ausdrücke mit Seiteneffekten (z. B. `print`) zu verwenden. Wenn Seiteneffekte nötig sind, sollte der Short-Circuit-Operator `and` explizit verwendet werden. |
| 4319 | 2195 | ||
| 4320 | ## Tabellenerweiterung | 2196 | ## Tabellenerweiterung |
| @@ -4326,15 +2202,6 @@ tab = [] | |||
| 4326 | tab[] = "Wert" | 2202 | tab[] = "Wert" |
| 4327 | ``` | 2203 | ``` |
| 4328 | 2204 | ||
| 4329 | <YueDisplay> | ||
| 4330 | |||
| 4331 | ```yue | ||
| 4332 | tab = [] | ||
| 4333 | tab[] = "Wert" | ||
| 4334 | ``` | ||
| 4335 | |||
| 4336 | </YueDisplay> | ||
| 4337 | |||
| 4338 | Du kannst auch den Spread-Operator `...` verwenden, um alle Elemente einer Liste an eine andere anzuhängen: | 2205 | Du kannst auch den Spread-Operator `...` verwenden, um alle Elemente einer Liste an eine andere anzuhängen: |
| 4339 | 2206 | ||
| 4340 | ```yuescript | 2207 | ```yuescript |
| @@ -4344,17 +2211,6 @@ tbA[] = ...tbB | |||
| 4344 | -- tbA ist jetzt [1, 2, 3, 4, 5, 6] | 2211 | -- tbA ist jetzt [1, 2, 3, 4, 5, 6] |
| 4345 | ``` | 2212 | ``` |
| 4346 | 2213 | ||
| 4347 | <YueDisplay> | ||
| 4348 | |||
| 4349 | ```yue | ||
| 4350 | tbA = [1, 2, 3] | ||
| 4351 | tbB = [4, 5, 6] | ||
| 4352 | tbA[] = ...tbB | ||
| 4353 | -- tbA ist jetzt [1, 2, 3, 4, 5, 6] | ||
| 4354 | ``` | ||
| 4355 | |||
| 4356 | </YueDisplay> | ||
| 4357 | |||
| 4358 | ## Tabellen-Spread | 2214 | ## Tabellen-Spread |
| 4359 | 2215 | ||
| 4360 | Du kannst Array-Tabellen oder Hash-Tabellen mit dem Spread-Operator `...` vor Ausdrücken in Tabellenliteralen zusammenführen. | 2216 | Du kannst Array-Tabellen oder Hash-Tabellen mit dem Spread-Operator `...` vor Ausdrücken in Tabellenliteralen zusammenführen. |
| @@ -4376,27 +2232,6 @@ b = {4, 5, y: 1} | |||
| 4376 | merge = {...a, ...b} | 2232 | merge = {...a, ...b} |
| 4377 | ``` | 2233 | ``` |
| 4378 | 2234 | ||
| 4379 | <YueDisplay> | ||
| 4380 | |||
| 4381 | ```yue | ||
| 4382 | parts = | ||
| 4383 | * "Schultern" | ||
| 4384 | * "Knie" | ||
| 4385 | lyrics = | ||
| 4386 | * "Kopf" | ||
| 4387 | * ...parts | ||
| 4388 | * "und" | ||
| 4389 | * "Zehen" | ||
| 4390 | |||
| 4391 | copy = {...other} | ||
| 4392 | |||
| 4393 | a = {1, 2, 3, x: 1} | ||
| 4394 | b = {4, 5, y: 1} | ||
| 4395 | merge = {...a, ...b} | ||
| 4396 | ``` | ||
| 4397 | |||
| 4398 | </YueDisplay> | ||
| 4399 | |||
| 4400 | ## Umgekehrter Tabellenindex | 2235 | ## Umgekehrter Tabellenindex |
| 4401 | 2236 | ||
| 4402 | Mit dem Operator **#** kannst du auf die letzten Elemente einer Tabelle zugreifen. | 2237 | Mit dem Operator **#** kannst du auf die letzten Elemente einer Tabelle zugreifen. |
| @@ -4407,16 +2242,6 @@ second_last = data.items[#-1] | |||
| 4407 | data.items[#] = 1 | 2242 | data.items[#] = 1 |
| 4408 | ``` | 2243 | ``` |
| 4409 | 2244 | ||
| 4410 | <YueDisplay> | ||
| 4411 | |||
| 4412 | ```yue | ||
| 4413 | last = data.items[#] | ||
| 4414 | second_last = data.items[#-1] | ||
| 4415 | data.items[#] = 1 | ||
| 4416 | ``` | ||
| 4417 | |||
| 4418 | </YueDisplay> | ||
| 4419 | |||
| 4420 | ## Metatable | 2245 | ## Metatable |
| 4421 | 2246 | ||
| 4422 | Der Operator **<>** kann als Abkürzung für Metatable-Manipulation verwendet werden. | 2247 | Der Operator **<>** kann als Abkürzung für Metatable-Manipulation verwendet werden. |
| @@ -4441,26 +2266,6 @@ print d.value | |||
| 4441 | close _ = <close>: -> print "Außerhalb des Gültigkeitsbereichs" | 2266 | close _ = <close>: -> print "Außerhalb des Gültigkeitsbereichs" |
| 4442 | ``` | 2267 | ``` |
| 4443 | 2268 | ||
| 4444 | <YueDisplay> | ||
| 4445 | |||
| 4446 | ```yue | ||
| 4447 | mt = {} | ||
| 4448 | add = (right) => <>: mt, value: @value + right.value | ||
| 4449 | mt.__add = add | ||
| 4450 | |||
| 4451 | a = <>: mt, value: 1 | ||
| 4452 | -- Feld mit gleichnamiger Variable setzen | ||
| 4453 | b = :<add>, value: 2 | ||
| 4454 | c = <add>: mt.__add, value: 3 | ||
| 4455 | |||
| 4456 | d = a + b + c | ||
| 4457 | print d.value | ||
| 4458 | |||
| 4459 | close _ = <close>: -> print "Außerhalb des Gültigkeitsbereichs" | ||
| 4460 | ``` | ||
| 4461 | |||
| 4462 | </YueDisplay> | ||
| 4463 | |||
| 4464 | ### Metatable-Zugriff | 2269 | ### Metatable-Zugriff |
| 4465 | 2270 | ||
| 4466 | Metatable mit **<>** oder einem von **<>** umschlossenen Metamethod-Namen aufrufen oder einen Ausdruck in **<>** schreiben. | 2271 | Metatable mit **<>** oder einem von **<>** umschlossenen Metamethod-Namen aufrufen oder einen Ausdruck in **<>** schreiben. |
| @@ -4475,19 +2280,6 @@ tb.<> = __index: {item: "hallo"} | |||
| 4475 | print tb.item | 2280 | print tb.item |
| 4476 | ``` | 2281 | ``` |
| 4477 | 2282 | ||
| 4478 | <YueDisplay> | ||
| 4479 | |||
| 4480 | ```yue | ||
| 4481 | -- erstellen mit Metatable, das das Feld "value" enthält | ||
| 4482 | tb = <"value">: 123 | ||
| 4483 | tb.<index> = tb.<> | ||
| 4484 | print tb.value | ||
| 4485 | tb.<> = __index: {item: "hallo"} | ||
| 4486 | print tb.item | ||
| 4487 | ``` | ||
| 4488 | |||
| 4489 | </YueDisplay> | ||
| 4490 | |||
| 4491 | ### Metatable-Destrukturierung | 2283 | ### Metatable-Destrukturierung |
| 4492 | 2284 | ||
| 4493 | Destrukturiere Metatable mit Metamethoden-Schlüssel, der von **<>** umschlossen ist. | 2285 | Destrukturiere Metatable mit Metamethoden-Schlüssel, der von **<>** umschlossen ist. |
| @@ -4497,15 +2289,6 @@ Destrukturiere Metatable mit Metamethoden-Schlüssel, der von **<>** umschlossen | |||
| 4497 | print item, new, close, getter | 2289 | print item, new, close, getter |
| 4498 | ``` | 2290 | ``` |
| 4499 | 2291 | ||
| 4500 | <YueDisplay> | ||
| 4501 | |||
| 4502 | ```yue | ||
| 4503 | {item, :new, :<close>, <index>: getter} = tb | ||
| 4504 | print item, new, close, getter | ||
| 4505 | ``` | ||
| 4506 | |||
| 4507 | </YueDisplay> | ||
| 4508 | |||
| 4509 | ## Existenz | 2292 | ## Existenz |
| 4510 | 2293 | ||
| 4511 | Der Operator **?** kann in verschiedenen Kontexten verwendet werden, um die Existenz zu prüfen. | 2294 | Der Operator **?** kann in verschiedenen Kontexten verwendet werden, um die Existenz zu prüfen. |
| @@ -4525,25 +2308,6 @@ with? io.open "test.txt", "w" | |||
| 4525 | \close! | 2308 | \close! |
| 4526 | ``` | 2309 | ``` |
| 4527 | 2310 | ||
| 4528 | <YueDisplay> | ||
| 4529 | |||
| 4530 | ```yue | ||
| 4531 | func?! | ||
| 4532 | print abc?["hello world"]?.xyz | ||
| 4533 | |||
| 4534 | x = tab?.value | ||
| 4535 | len = utf8?.len or string?.len or (o) -> #o | ||
| 4536 | |||
| 4537 | if print and x? | ||
| 4538 | print x | ||
| 4539 | |||
| 4540 | with? io.open "test.txt", "w" | ||
| 4541 | \write "hello" | ||
| 4542 | \close! | ||
| 4543 | ``` | ||
| 4544 | |||
| 4545 | </YueDisplay> | ||
| 4546 | |||
| 4547 | ## Piping | 2311 | ## Piping |
| 4548 | 2312 | ||
| 4549 | Anstelle einer Reihe verschachtelter Funktionsaufrufe kannst du Werte mit dem Operator **|>** weiterleiten. | 2313 | Anstelle einer Reihe verschachtelter Funktionsaufrufe kannst du Werte mit dem Operator **|>** weiterleiten. |
| @@ -4562,24 +2326,6 @@ readFile "example.txt" | |||
| 4562 | 2326 | ||
| 4563 | ``` | 2327 | ``` |
| 4564 | 2328 | ||
| 4565 | <YueDisplay> | ||
| 4566 | |||
| 4567 | ```yue | ||
| 4568 | "hello" |> print | ||
| 4569 | 1 |> print 2 -- Pipe-Element als erstes Argument einfügen | ||
| 4570 | 2 |> print 1, _, 3 -- Pipe mit Platzhalter | ||
| 4571 | |||
| 4572 | -- Pipe-Ausdruck über mehrere Zeilen | ||
| 4573 | readFile "example.txt" | ||
| 4574 | |> extract language, {} | ||
| 4575 | |> parse language | ||
| 4576 | |> emit | ||
| 4577 | |> render | ||
| 4578 | |||
| 4579 | ``` | ||
| 4580 | |||
| 4581 | </YueDisplay> | ||
| 4582 | |||
| 4583 | ## Nil-Coalescing | 2329 | ## Nil-Coalescing |
| 4584 | 2330 | ||
| 4585 | Der Nil-Coalescing-Operator **??** gibt den Wert des linken Operanden zurück, wenn er nicht **nil** ist; andernfalls wird der rechte Operand ausgewertet und sein Ergebnis zurückgegeben. Der **??**-Operator wertet seinen rechten Operanden nicht aus, wenn der linke Operand nicht nil ergibt. | 2331 | Der Nil-Coalescing-Operator **??** gibt den Wert des linken Operanden zurück, wenn er nicht **nil** ist; andernfalls wird der rechte Operand ausgewertet und sein Ergebnis zurückgegeben. Der **??**-Operator wertet seinen rechten Operanden nicht aus, wenn der linke Operand nicht nil ergibt. |
| @@ -4592,17 +2338,6 @@ func a ?? {} | |||
| 4592 | a ??= false | 2338 | a ??= false |
| 4593 | ``` | 2339 | ``` |
| 4594 | 2340 | ||
| 4595 | <YueDisplay> | ||
| 4596 | |||
| 4597 | ```yue | ||
| 4598 | local a, b, c, d | ||
| 4599 | a = b ?? c ?? d | ||
| 4600 | func a ?? {} | ||
| 4601 | a ??= false | ||
| 4602 | ``` | ||
| 4603 | |||
| 4604 | </YueDisplay> | ||
| 4605 | |||
| 4606 | ## Implizites Objekt | 2341 | ## Implizites Objekt |
| 4607 | 2342 | ||
| 4608 | Du kannst innerhalb eines Tabellenblocks eine Liste impliziter Strukturen schreiben, die mit dem Symbol **\*** oder **-** beginnt. Beim Erstellen eines impliziten Objekts müssen die Felder des Objekts dieselbe Einrückung haben. | 2343 | Du kannst innerhalb eines Tabellenblocks eine Liste impliziter Strukturen schreiben, die mit dem Symbol **\*** oder **-** beginnt. Beim Erstellen eines impliziten Objekts müssen die Felder des Objekts dieselbe Einrückung haben. |
| @@ -4650,52 +2385,6 @@ tb = | |||
| 4650 | 2385 | ||
| 4651 | ``` | 2386 | ``` |
| 4652 | 2387 | ||
| 4653 | <YueDisplay> | ||
| 4654 | |||
| 4655 | ```yue | ||
| 4656 | -- Zuweisung mit implizitem Objekt | ||
| 4657 | list = | ||
| 4658 | * 1 | ||
| 4659 | * 2 | ||
| 4660 | * 3 | ||
| 4661 | |||
| 4662 | -- Funktionsaufruf mit implizitem Objekt | ||
| 4663 | func | ||
| 4664 | * 1 | ||
| 4665 | * 2 | ||
| 4666 | * 3 | ||
| 4667 | |||
| 4668 | -- Rückgabe mit implizitem Objekt | ||
| 4669 | f = -> | ||
| 4670 | return | ||
| 4671 | * 1 | ||
| 4672 | * 2 | ||
| 4673 | * 3 | ||
| 4674 | |||
| 4675 | -- Tabelle mit implizitem Objekt | ||
| 4676 | tb = | ||
| 4677 | name: "abc" | ||
| 4678 | |||
| 4679 | values: | ||
| 4680 | - "a" | ||
| 4681 | - "b" | ||
| 4682 | - "c" | ||
| 4683 | |||
| 4684 | objects: | ||
| 4685 | - name: "a" | ||
| 4686 | value: 1 | ||
| 4687 | func: => @value + 1 | ||
| 4688 | tb: | ||
| 4689 | fieldA: 1 | ||
| 4690 | |||
| 4691 | - name: "b" | ||
| 4692 | value: 2 | ||
| 4693 | func: => @value + 2 | ||
| 4694 | tb: { } | ||
| 4695 | ``` | ||
| 4696 | |||
| 4697 | </YueDisplay> | ||
| 4698 | |||
| 4699 | # Literale | 2388 | # Literale |
| 4700 | 2389 | ||
| 4701 | Alle primitiven Literale in Lua können verwendet werden. Das gilt für Zahlen, Strings, Booleans und **nil**. | 2390 | Alle primitiven Literale in Lua können verwendet werden. Das gilt für Zahlen, Strings, Booleans und **nil**. |
| @@ -4711,19 +2400,6 @@ some_string = "Hier ist ein String | |||
| 4711 | print "Ich bin mir zu #{math.random! * 100}% sicher." | 2400 | print "Ich bin mir zu #{math.random! * 100}% sicher." |
| 4712 | ``` | 2401 | ``` |
| 4713 | 2402 | ||
| 4714 | <YueDisplay> | ||
| 4715 | |||
| 4716 | ```yue | ||
| 4717 | some_string = "Hier ist ein String | ||
| 4718 | mit einem Zeilenumbruch." | ||
| 4719 | |||
| 4720 | -- Mit der #{}-Syntax kannst du Ausdrücke in String-Literale einbinden. | ||
| 4721 | -- String-Interpolation gibt es nur in doppelt angeführten Strings. | ||
| 4722 | print "Ich bin mir zu #{math.random! * 100}% sicher." | ||
| 4723 | ``` | ||
| 4724 | |||
| 4725 | </YueDisplay> | ||
| 4726 | |||
| 4727 | ## Zahlenliterale | 2403 | ## Zahlenliterale |
| 4728 | 2404 | ||
| 4729 | Du kannst Unterstriche in Zahlenliteralen verwenden, um die Lesbarkeit zu erhöhen. | 2405 | Du kannst Unterstriche in Zahlenliteralen verwenden, um die Lesbarkeit zu erhöhen. |
| @@ -4734,16 +2410,6 @@ hex = 0xEF_BB_BF | |||
| 4734 | binary = 0B10011 | 2410 | binary = 0B10011 |
| 4735 | ``` | 2411 | ``` |
| 4736 | 2412 | ||
| 4737 | <YueDisplay> | ||
| 4738 | |||
| 4739 | ```yue | ||
| 4740 | integer = 1_000_000 | ||
| 4741 | hex = 0xEF_BB_BF | ||
| 4742 | binary = 0B10011 | ||
| 4743 | ``` | ||
| 4744 | |||
| 4745 | </YueDisplay> | ||
| 4746 | |||
| 4747 | ## YAML-Mehrzeilen-String | 2413 | ## YAML-Mehrzeilen-String |
| 4748 | 2414 | ||
| 4749 | Das Präfix `|` führt ein mehrzeiliges String-Literal im YAML-Stil ein: | 2415 | Das Präfix `|` führt ein mehrzeiliges String-Literal im YAML-Stil ein: |
| @@ -4756,18 +2422,6 @@ str = | | |||
| 4756 | - #{expr} | 2422 | - #{expr} |
| 4757 | ``` | 2423 | ``` |
| 4758 | 2424 | ||
| 4759 | <YueDisplay> | ||
| 4760 | |||
| 4761 | ```yue | ||
| 4762 | str = | | ||
| 4763 | key: value | ||
| 4764 | list: | ||
| 4765 | - item1 | ||
| 4766 | - #{expr} | ||
| 4767 | ``` | ||
| 4768 | |||
| 4769 | </YueDisplay> | ||
| 4770 | |||
| 4771 | Damit lässt sich strukturierter, mehrzeiliger Text bequem schreiben. Alle Zeilenumbrüche und Einrückungen bleiben relativ zur ersten nicht-leeren Zeile erhalten, und Ausdrücke innerhalb von `#{...}` werden automatisch als `tostring(expr)` interpoliert. | 2425 | Damit lässt sich strukturierter, mehrzeiliger Text bequem schreiben. Alle Zeilenumbrüche und Einrückungen bleiben relativ zur ersten nicht-leeren Zeile erhalten, und Ausdrücke innerhalb von `#{...}` werden automatisch als `tostring(expr)` interpoliert. |
| 4772 | 2426 | ||
| 4773 | Der YAML-Mehrzeilen-String erkennt automatisch das gemeinsame führende Leerraumpräfix (minimale Einrückung über alle nicht-leeren Zeilen) und entfernt es aus allen Zeilen. So kannst du deinen Code optisch einrücken, ohne den resultierenden String zu verändern. | 2427 | Der YAML-Mehrzeilen-String erkennt automatisch das gemeinsame führende Leerraumpräfix (minimale Einrückung über alle nicht-leeren Zeilen) und entfernt es aus allen Zeilen. So kannst du deinen Code optisch einrücken, ohne den resultierenden String zu verändern. |
| @@ -4780,18 +2434,6 @@ fn = -> | |||
| 4780 | return str | 2434 | return str |
| 4781 | ``` | 2435 | ``` |
| 4782 | 2436 | ||
| 4783 | <YueDisplay> | ||
| 4784 | |||
| 4785 | ```yue | ||
| 4786 | fn = -> | ||
| 4787 | str = | | ||
| 4788 | foo: | ||
| 4789 | bar: baz | ||
| 4790 | return str | ||
| 4791 | ``` | ||
| 4792 | |||
| 4793 | </YueDisplay> | ||
| 4794 | |||
| 4795 | Die interne Einrückung bleibt relativ zum entfernten gemeinsamen Präfix erhalten, wodurch saubere, verschachtelte Strukturen möglich sind. | 2437 | Die interne Einrückung bleibt relativ zum entfernten gemeinsamen Präfix erhalten, wodurch saubere, verschachtelte Strukturen möglich sind. |
| 4796 | 2438 | ||
| 4797 | Alle Sonderzeichen wie Anführungszeichen (`"`) und Backslashes (`\`) im YAML-Mehrzeilen-Block werden automatisch escaped, sodass der erzeugte Lua-String syntaktisch korrekt ist und wie erwartet funktioniert. | 2439 | Alle Sonderzeichen wie Anführungszeichen (`"`) und Backslashes (`\`) im YAML-Mehrzeilen-Block werden automatisch escaped, sodass der erzeugte Lua-String syntaktisch korrekt ist und wie erwartet funktioniert. |
| @@ -4802,16 +2444,6 @@ str = | | |||
| 4802 | note: 'He said: "#{Hello}!"' | 2444 | note: 'He said: "#{Hello}!"' |
| 4803 | ``` | 2445 | ``` |
| 4804 | 2446 | ||
| 4805 | <YueDisplay> | ||
| 4806 | |||
| 4807 | ```yue | ||
| 4808 | str = | | ||
| 4809 | path: "C:\Program Files\App" | ||
| 4810 | note: 'He said: "#{Hello}!"' | ||
| 4811 | ``` | ||
| 4812 | |||
| 4813 | </YueDisplay> | ||
| 4814 | |||
| 4815 | # Module | 2447 | # Module |
| 4816 | 2448 | ||
| 4817 | ## Import | 2449 | ## Import |
| @@ -4843,35 +2475,6 @@ do | |||
| 4843 | import "export" as {one, two, Something:{umm:{ch}}} | 2475 | import "export" as {one, two, Something:{umm:{ch}}} |
| 4844 | ``` | 2476 | ``` |
| 4845 | 2477 | ||
| 4846 | <YueDisplay> | ||
| 4847 | |||
| 4848 | ```yue | ||
| 4849 | -- als Tabellen-Destrukturierung | ||
| 4850 | do | ||
| 4851 | import insert, concat from table | ||
| 4852 | -- Fehler beim Zuweisen zu insert, concat | ||
| 4853 | import C, Ct, Cmt from require "lpeg" | ||
| 4854 | -- Kurzform für implizites Require | ||
| 4855 | import x, y, z from 'mymodule' | ||
| 4856 | -- Import im Python-Stil | ||
| 4857 | from 'module' import a, b, c | ||
| 4858 | |||
| 4859 | -- Kurzform zum Laden eines Moduls | ||
| 4860 | do | ||
| 4861 | import 'module' | ||
| 4862 | import 'module_x' | ||
| 4863 | import "d-a-s-h-e-s" | ||
| 4864 | import "module.part" | ||
| 4865 | |||
| 4866 | -- Modul mit Alias oder Tabellen-Destrukturierung laden | ||
| 4867 | do | ||
| 4868 | import "player" as PlayerModule | ||
| 4869 | import "lpeg" as :C, :Ct, :Cmt | ||
| 4870 | import "export" as {one, two, Something:{umm:{ch}}} | ||
| 4871 | ``` | ||
| 4872 | |||
| 4873 | </YueDisplay> | ||
| 4874 | |||
| 4875 | ## Import von Globals | 2478 | ## Import von Globals |
| 4876 | 2479 | ||
| 4877 | Du kannst mit `import` bestimmte Globals in lokale Variablen importieren. Wenn du eine Kette von Globalzugriffen importierst, wird das letzte Feld der lokalen Variable zugewiesen. | 2480 | Du kannst mit `import` bestimmte Globals in lokale Variablen importieren. Wenn du eine Kette von Globalzugriffen importierst, wird das letzte Feld der lokalen Variable zugewiesen. |
| @@ -4883,17 +2486,6 @@ do | |||
| 4883 | print concat ["a", tostring 1] | 2486 | print concat ["a", tostring 1] |
| 4884 | ``` | 2487 | ``` |
| 4885 | 2488 | ||
| 4886 | <YueDisplay> | ||
| 4887 | |||
| 4888 | ```yue | ||
| 4889 | do | ||
| 4890 | import tostring | ||
| 4891 | import table.concat | ||
| 4892 | print concat ["a", tostring 1] | ||
| 4893 | ``` | ||
| 4894 | |||
| 4895 | </YueDisplay> | ||
| 4896 | |||
| 4897 | ### Automatischer Global-Import | 2489 | ### Automatischer Global-Import |
| 4898 | 2490 | ||
| 4899 | Du kannst `import global` am Anfang eines Blocks platzieren, um automatisch alle Namen zu importieren, die im aktuellen Scope nicht explizit deklariert oder zugewiesen sind. Diese impliziten Importe werden als lokale `const` behandelt, die an die entsprechenden Globals zum Zeitpunkt der Anweisung gebunden sind. | 2491 | Du kannst `import global` am Anfang eines Blocks platzieren, um automatisch alle Namen zu importieren, die im aktuellen Scope nicht explizit deklariert oder zugewiesen sind. Diese impliziten Importe werden als lokale `const` behandelt, die an die entsprechenden Globals zum Zeitpunkt der Anweisung gebunden sind. |
| @@ -4915,25 +2507,6 @@ do | |||
| 4915 | FLAG = 123 | 2507 | FLAG = 123 |
| 4916 | ``` | 2508 | ``` |
| 4917 | 2509 | ||
| 4918 | <YueDisplay> | ||
| 4919 | |||
| 4920 | ```yue | ||
| 4921 | do | ||
| 4922 | import global | ||
| 4923 | print "hallo" | ||
| 4924 | math.random 3 | ||
| 4925 | -- print = nil -- Fehler: importierte Globals sind const | ||
| 4926 | |||
| 4927 | do | ||
| 4928 | -- explizite globale Variable wird nicht importiert | ||
| 4929 | import global | ||
| 4930 | global FLAG | ||
| 4931 | print FLAG | ||
| 4932 | FLAG = 123 | ||
| 4933 | ``` | ||
| 4934 | |||
| 4935 | </YueDisplay> | ||
| 4936 | |||
| 4937 | ## Export | 2510 | ## Export |
| 4938 | 2511 | ||
| 4939 | Die `export`-Anweisung bietet eine knappe Möglichkeit, Module zu definieren. | 2512 | Die `export`-Anweisung bietet eine knappe Möglichkeit, Module zu definieren. |
| @@ -4958,26 +2531,6 @@ export class Something | |||
| 4958 | umm: "cool" | 2531 | umm: "cool" |
| 4959 | ``` | 2532 | ``` |
| 4960 | 2533 | ||
| 4961 | <YueDisplay> | ||
| 4962 | |||
| 4963 | ```yue | ||
| 4964 | export a, b, c = 1, 2, 3 | ||
| 4965 | export cool = "Katze" | ||
| 4966 | |||
| 4967 | export What = if this | ||
| 4968 | "abc" | ||
| 4969 | else | ||
| 4970 | "def" | ||
| 4971 | |||
| 4972 | export y = -> | ||
| 4973 | hallo = 3434 | ||
| 4974 | |||
| 4975 | export class Something | ||
| 4976 | umm: "cool" | ||
| 4977 | ``` | ||
| 4978 | |||
| 4979 | </YueDisplay> | ||
| 4980 | |||
| 4981 | Benannter Export mit Destructuring. | 2534 | Benannter Export mit Destructuring. |
| 4982 | 2535 | ||
| 4983 | ```yuescript | 2536 | ```yuescript |
| @@ -4985,15 +2538,6 @@ export :loadstring, to_lua: tolua = yue | |||
| 4985 | export {itemA: {:fieldA = 'default'}} = tb | 2538 | export {itemA: {:fieldA = 'default'}} = tb |
| 4986 | ``` | 2539 | ``` |
| 4987 | 2540 | ||
| 4988 | <YueDisplay> | ||
| 4989 | |||
| 4990 | ```yue | ||
| 4991 | export :loadstring, to_lua: tolua = yue | ||
| 4992 | export {itemA: {:fieldA = 'default'}} = tb | ||
| 4993 | ``` | ||
| 4994 | |||
| 4995 | </YueDisplay> | ||
| 4996 | |||
| 4997 | Benannte Elemente aus dem Modul exportieren, ohne lokale Variablen zu erstellen. | 2541 | Benannte Elemente aus dem Modul exportieren, ohne lokale Variablen zu erstellen. |
| 4998 | 2542 | ||
| 4999 | ```yuescript | 2543 | ```yuescript |
| @@ -5002,16 +2546,6 @@ export.<index> = items | |||
| 5002 | export["a-b-c"] = 123 | 2546 | export["a-b-c"] = 123 |
| 5003 | ``` | 2547 | ``` |
| 5004 | 2548 | ||
| 5005 | <YueDisplay> | ||
| 5006 | |||
| 5007 | ```yue | ||
| 5008 | export.itemA = tb | ||
| 5009 | export.<index> = items | ||
| 5010 | export["a-b-c"] = 123 | ||
| 5011 | ``` | ||
| 5012 | |||
| 5013 | </YueDisplay> | ||
| 5014 | |||
| 5015 | ### Unbenannter Export | 2549 | ### Unbenannter Export |
| 5016 | 2550 | ||
| 5017 | Unbenannter Export fügt das Ziel-Element in den Array-Teil der exportierten Tabelle ein. | 2551 | Unbenannter Export fügt das Ziel-Element in den Array-Teil der exportierten Tabelle ein. |
| @@ -5029,23 +2563,6 @@ export with tmp | |||
| 5029 | j = 2000 | 2563 | j = 2000 |
| 5030 | ``` | 2564 | ``` |
| 5031 | 2565 | ||
| 5032 | <YueDisplay> | ||
| 5033 | |||
| 5034 | ```yue | ||
| 5035 | d, e, f = 3, 2, 1 | ||
| 5036 | export d, e, f | ||
| 5037 | |||
| 5038 | export if this | ||
| 5039 | 123 | ||
| 5040 | else | ||
| 5041 | 456 | ||
| 5042 | |||
| 5043 | export with tmp | ||
| 5044 | j = 2000 | ||
| 5045 | ``` | ||
| 5046 | |||
| 5047 | </YueDisplay> | ||
| 5048 | |||
| 5049 | ### Default-Export | 2566 | ### Default-Export |
| 5050 | 2567 | ||
| 5051 | Mit dem Schlüsselwort **default** in einer `export`-Anweisung wird die exportierte Tabelle durch ein beliebiges Objekt ersetzt. | 2568 | Mit dem Schlüsselwort **default** in einer `export`-Anweisung wird die exportierte Tabelle durch ein beliebiges Objekt ersetzt. |
| @@ -5056,16 +2573,6 @@ export default -> | |||
| 5056 | 123 | 2573 | 123 |
| 5057 | ``` | 2574 | ``` |
| 5058 | 2575 | ||
| 5059 | <YueDisplay> | ||
| 5060 | |||
| 5061 | ```yue | ||
| 5062 | export default -> | ||
| 5063 | print "hallo" | ||
| 5064 | 123 | ||
| 5065 | ``` | ||
| 5066 | |||
| 5067 | </YueDisplay> | ||
| 5068 | |||
| 5069 | # Lizenz: MIT | 2576 | # Lizenz: MIT |
| 5070 | 2577 | ||
| 5071 | Hinweis: Die MIT-Lizenz ist unten im englischen Originaltext wiedergegeben. | 2578 | Hinweis: Die MIT-Lizenz ist unten im englischen Originaltext wiedergegeben. |
diff --git a/doc/yue-en.md b/doc/yue-en.md index 3f8546a..764bc1a 100644 --- a/doc/yue-en.md +++ b/doc/yue-en.md | |||
| @@ -1,11 +1,5 @@ | |||
| 1 | --- | ||
| 2 | title: Reference | ||
| 3 | --- | ||
| 4 | |||
| 5 | # YueScript Documentation | 1 | # YueScript Documentation |
| 6 | 2 | ||
| 7 | <img src="/image/yuescript.svg" width="250px" height="250px" alt="logo" style="padding-top: 3em; padding-bottom: 2em;"/> | ||
| 8 | |||
| 9 | Welcome to the <b>YueScript</b> official documentation!<br/> | 3 | Welcome to the <b>YueScript</b> official documentation!<br/> |
| 10 | Here you can find the language features, usage, reference examples and resources.<br/> | 4 | Here you can find the language features, usage, reference examples and resources.<br/> |
| 11 | Please select a chapter from the sidebar to start learning about YueScript. | 5 | Please select a chapter from the sidebar to start learning about YueScript. |
| @@ -21,17 +15,6 @@ do | |||
| 21 | print var -- nil here | 15 | print var -- nil here |
| 22 | ``` | 16 | ``` |
| 23 | 17 | ||
| 24 | <YueDisplay> | ||
| 25 | |||
| 26 | ```yue | ||
| 27 | do | ||
| 28 | var = "hello" | ||
| 29 | print var | ||
| 30 | print var -- nil here | ||
| 31 | ``` | ||
| 32 | |||
| 33 | </YueDisplay> | ||
| 34 | |||
| 35 | YueScript's **do** can also be used an expression . Allowing you to combine multiple lines into one. The result of the do expression is the last statement in its body. | 18 | YueScript's **do** can also be used an expression . Allowing you to combine multiple lines into one. The result of the do expression is the last statement in its body. |
| 36 | 19 | ||
| 37 | `do` expressions also support using `break` to interrupt control flow and return multiple values early: | 20 | `do` expressions also support using `break` to interrupt control flow and return multiple values early: |
| @@ -44,18 +27,6 @@ status, value = do | |||
| 44 | break "small", n | 27 | break "small", n |
| 45 | ``` | 28 | ``` |
| 46 | 29 | ||
| 47 | <YueDisplay> | ||
| 48 | |||
| 49 | ```yue | ||
| 50 | status, value = do | ||
| 51 | n = 12 | ||
| 52 | if n > 10 | ||
| 53 | break "large", n | ||
| 54 | break "small", n | ||
| 55 | ``` | ||
| 56 | |||
| 57 | </YueDisplay> | ||
| 58 | |||
| 59 | ```yuescript | 30 | ```yuescript |
| 60 | counter = do | 31 | counter = do |
| 61 | i = 0 | 32 | i = 0 |
| @@ -67,21 +38,6 @@ print counter! | |||
| 67 | print counter! | 38 | print counter! |
| 68 | ``` | 39 | ``` |
| 69 | 40 | ||
| 70 | <YueDisplay> | ||
| 71 | |||
| 72 | ```yue | ||
| 73 | counter = do | ||
| 74 | i = 0 | ||
| 75 | -> | ||
| 76 | i += 1 | ||
| 77 | i | ||
| 78 | |||
| 79 | print counter! | ||
| 80 | print counter! | ||
| 81 | ``` | ||
| 82 | |||
| 83 | </YueDisplay> | ||
| 84 | |||
| 85 | ```yuescript | 41 | ```yuescript |
| 86 | tbl = { | 42 | tbl = { |
| 87 | key: do | 43 | key: do |
| @@ -90,18 +46,6 @@ tbl = { | |||
| 90 | } | 46 | } |
| 91 | ``` | 47 | ``` |
| 92 | 48 | ||
| 93 | <YueDisplay> | ||
| 94 | |||
| 95 | ```yue | ||
| 96 | tbl = { | ||
| 97 | key: do | ||
| 98 | print "assigning key!" | ||
| 99 | 1234 | ||
| 100 | } | ||
| 101 | ``` | ||
| 102 | |||
| 103 | </YueDisplay> | ||
| 104 | |||
| 105 | # Line Decorators | 49 | # Line Decorators |
| 106 | 50 | ||
| 107 | For convenience, the for loop and if statement can be applied to single statements at the end of the line: | 51 | For convenience, the for loop and if statement can be applied to single statements at the end of the line: |
| @@ -110,28 +54,12 @@ For convenience, the for loop and if statement can be applied to single statemen | |||
| 110 | print "hello world" if name == "Rob" | 54 | print "hello world" if name == "Rob" |
| 111 | ``` | 55 | ``` |
| 112 | 56 | ||
| 113 | <YueDisplay> | ||
| 114 | |||
| 115 | ```yue | ||
| 116 | print "hello world" if name == "Rob" | ||
| 117 | ``` | ||
| 118 | |||
| 119 | </YueDisplay> | ||
| 120 | |||
| 121 | And with basic loops: | 57 | And with basic loops: |
| 122 | 58 | ||
| 123 | ```yuescript | 59 | ```yuescript |
| 124 | print "item: ", item for item in *items | 60 | print "item: ", item for item in *items |
| 125 | ``` | 61 | ``` |
| 126 | 62 | ||
| 127 | <YueDisplay> | ||
| 128 | |||
| 129 | ```yue | ||
| 130 | print "item: ", item for item in *items | ||
| 131 | ``` | ||
| 132 | |||
| 133 | </YueDisplay> | ||
| 134 | |||
| 135 | And with while loops: | 63 | And with while loops: |
| 136 | 64 | ||
| 137 | ```yuescript | 65 | ```yuescript |
| @@ -140,16 +68,6 @@ game\update! while game\isRunning! | |||
| 140 | reader\parse_line! until reader\eof! | 68 | reader\parse_line! until reader\eof! |
| 141 | ``` | 69 | ``` |
| 142 | 70 | ||
| 143 | <YueDisplay> | ||
| 144 | |||
| 145 | ```yue | ||
| 146 | game\update! while game\isRunning! | ||
| 147 | |||
| 148 | reader\parse_line! until reader\eof! | ||
| 149 | ``` | ||
| 150 | |||
| 151 | </YueDisplay> | ||
| 152 | |||
| 153 | # Macro | 71 | # Macro |
| 154 | 72 | ||
| 155 | ## Common Usage | 73 | ## Common Usage |
| @@ -185,39 +103,6 @@ if $and f1!, f2!, f3! | |||
| 185 | print "OK" | 103 | print "OK" |
| 186 | ``` | 104 | ``` |
| 187 | 105 | ||
| 188 | <YueDisplay> | ||
| 189 | |||
| 190 | ```yue | ||
| 191 | macro PI2 = -> math.pi * 2 | ||
| 192 | area = $PI2 * 5 | ||
| 193 | |||
| 194 | macro HELLO = -> "'hello world'" | ||
| 195 | print $HELLO | ||
| 196 | |||
| 197 | macro config = (debugging) -> | ||
| 198 | global debugMode = debugging == "true" | ||
| 199 | "" | ||
| 200 | |||
| 201 | macro asserts = (cond) -> | ||
| 202 | debugMode and "assert #{cond}" or "" | ||
| 203 | |||
| 204 | macro assert = (cond) -> | ||
| 205 | debugMode and "assert #{cond}" or "#{cond}" | ||
| 206 | |||
| 207 | $config true | ||
| 208 | $asserts item ~= nil | ||
| 209 | |||
| 210 | $config false | ||
| 211 | value = $assert item | ||
| 212 | |||
| 213 | -- the passed expressions are treated as strings | ||
| 214 | macro and = (...) -> "#{ table.concat {...}, ' and ' }" | ||
| 215 | if $and f1!, f2!, f3! | ||
| 216 | print "OK" | ||
| 217 | ``` | ||
| 218 | |||
| 219 | </YueDisplay> | ||
| 220 | |||
| 221 | ## Insert Raw Codes | 106 | ## Insert Raw Codes |
| 222 | 107 | ||
| 223 | A macro function can either return a YueScript string or a config table containing Lua codes. | 108 | A macro function can either return a YueScript string or a config table containing Lua codes. |
| @@ -248,36 +133,6 @@ end | |||
| 248 | ]==] | 133 | ]==] |
| 249 | ``` | 134 | ``` |
| 250 | 135 | ||
| 251 | <YueDisplay> | ||
| 252 | |||
| 253 | ```yue | ||
| 254 | macro yueFunc = (var) -> "local #{var} = ->" | ||
| 255 | $yueFunc funcA | ||
| 256 | funcA = -> "fail to assign to the Yue macro defined variable" | ||
| 257 | |||
| 258 | macro luaFunc = (var) -> { | ||
| 259 | code: "local function #{var}() end" | ||
| 260 | type: "lua" | ||
| 261 | } | ||
| 262 | $luaFunc funcB | ||
| 263 | funcB = -> "fail to assign to the Lua macro defined variable" | ||
| 264 | |||
| 265 | macro lua = (code) -> { | ||
| 266 | :code | ||
| 267 | type: "lua" | ||
| 268 | } | ||
| 269 | |||
| 270 | -- the raw string leading and ending symbols are auto trimed | ||
| 271 | $lua[==[ | ||
| 272 | -- raw Lua codes insertion | ||
| 273 | if cond then | ||
| 274 | print("output") | ||
| 275 | end | ||
| 276 | ]==] | ||
| 277 | ``` | ||
| 278 | |||
| 279 | </YueDisplay> | ||
| 280 | |||
| 281 | ## Export Macro | 136 | ## Export Macro |
| 282 | 137 | ||
| 283 | Macro functions can be exported from a module and get imported in another module. You have to put export macro functions in a single file to be used, and only macro definition, macro importing and macro expansion in place can be put into the macro exporting module. | 138 | Macro functions can be exported from a module and get imported in another module. You have to put export macro functions in a single file to be used, and only macro definition, macro importing and macro expansion in place can be put into the macro exporting module. |
| @@ -297,28 +152,6 @@ import "utils" as { | |||
| 297 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | 152 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ |
| 298 | ``` | 153 | ``` |
| 299 | 154 | ||
| 300 | <YueDisplay> | ||
| 301 | |||
| 302 | ```yue | ||
| 303 | -- file: utils.yue | ||
| 304 | export macro map = (items, action) -> "[#{action} for _ in *#{items}]" | ||
| 305 | export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" | ||
| 306 | export macro foreach = (items, action) -> "for _ in *#{items} | ||
| 307 | #{action}" | ||
| 308 | |||
| 309 | -- file main.yue | ||
| 310 | -- import function is not available in browser, try it in a real environment | ||
| 311 | --[[ | ||
| 312 | import "utils" as { | ||
| 313 | $, -- symbol to import all macros | ||
| 314 | $foreach: $each -- rename macro $foreach to $each | ||
| 315 | } | ||
| 316 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | ||
| 317 | ]] | ||
| 318 | ``` | ||
| 319 | |||
| 320 | </YueDisplay> | ||
| 321 | |||
| 322 | ## Builtin Macro | 155 | ## Builtin Macro |
| 323 | 156 | ||
| 324 | There are some builtin macros but you can override them by declaring macros with the same names. | 157 | There are some builtin macros but you can override them by declaring macros with the same names. |
| @@ -328,15 +161,6 @@ print $FILE -- get string of current module name | |||
| 328 | print $LINE -- get number 2 | 161 | print $LINE -- get number 2 |
| 329 | ``` | 162 | ``` |
| 330 | 163 | ||
| 331 | <YueDisplay> | ||
| 332 | |||
| 333 | ```yue | ||
| 334 | print $FILE -- get string of current module name | ||
| 335 | print $LINE -- get number 2 | ||
| 336 | ``` | ||
| 337 | |||
| 338 | </YueDisplay> | ||
| 339 | |||
| 340 | ## Generating Macros with Macros | 164 | ## Generating Macros with Macros |
| 341 | 165 | ||
| 342 | In YueScript, macro functions allow you to generate code at compile time. By nesting macro functions, you can create more complex generation patterns. This feature enables you to define a macro function that generates another macro function, allowing for more dynamic code generation. | 166 | In YueScript, macro functions allow you to generate code at compile time. By nesting macro functions, you can create more complex generation patterns. This feature enables you to define a macro function that generates another macro function, allowing for more dynamic code generation. |
| @@ -359,28 +183,6 @@ print "Valid enum type:", $BodyType Static | |||
| 359 | -- print "Compilation error with enum type:", $BodyType Unknown | 183 | -- print "Compilation error with enum type:", $BodyType Unknown |
| 360 | ``` | 184 | ``` |
| 361 | 185 | ||
| 362 | <YueDisplay> | ||
| 363 | |||
| 364 | ```yue | ||
| 365 | macro Enum = (...) -> | ||
| 366 | items = {...} | ||
| 367 | itemSet = {item, true for item in *items} | ||
| 368 | (item) -> | ||
| 369 | error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] | ||
| 370 | "\"#{item}\"" | ||
| 371 | |||
| 372 | macro BodyType = $Enum( | ||
| 373 | Static | ||
| 374 | Dynamic | ||
| 375 | Kinematic | ||
| 376 | ) | ||
| 377 | |||
| 378 | print "Valid enum type:", $BodyType Static | ||
| 379 | -- print "Compilation error with enum type:", $BodyType Unknown | ||
| 380 | ``` | ||
| 381 | |||
| 382 | </YueDisplay> | ||
| 383 | |||
| 384 | ## Argument Validation | 186 | ## Argument Validation |
| 385 | 187 | ||
| 386 | You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time. | 188 | You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time. |
| @@ -395,20 +197,6 @@ macro printNumAndStr = (num `Num, str `String) -> | | |||
| 395 | $printNumAndStr 123, "hello" | 197 | $printNumAndStr 123, "hello" |
| 396 | ``` | 198 | ``` |
| 397 | 199 | ||
| 398 | <YueDisplay> | ||
| 399 | |||
| 400 | ```yue | ||
| 401 | macro printNumAndStr = (num `Num, str `String) -> | | ||
| 402 | print( | ||
| 403 | #{num} | ||
| 404 | #{str} | ||
| 405 | ) | ||
| 406 | |||
| 407 | $printNumAndStr 123, "hello" | ||
| 408 | ``` | ||
| 409 | |||
| 410 | </YueDisplay> | ||
| 411 | |||
| 412 | If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. | 200 | If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. |
| 413 | 201 | ||
| 414 | ```yuescript | 202 | ```yuescript |
| @@ -420,19 +208,6 @@ macro printNumAndStr = (num, str) -> | |||
| 420 | $printNumAndStr 123, "hello" | 208 | $printNumAndStr 123, "hello" |
| 421 | ``` | 209 | ``` |
| 422 | 210 | ||
| 423 | <YueDisplay> | ||
| 424 | |||
| 425 | ```yue | ||
| 426 | macro printNumAndStr = (num, str) -> | ||
| 427 | error "expected Num as first argument" unless $is_ast Num, num | ||
| 428 | error "expected String as second argument" unless $is_ast String, str | ||
| 429 | "print(#{num}, #{str})" | ||
| 430 | |||
| 431 | $printNumAndStr 123, "hello" | ||
| 432 | ``` | ||
| 433 | |||
| 434 | </YueDisplay> | ||
| 435 | |||
| 436 | For more details about available AST nodes, please refer to the uppercased definitions in [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). | 211 | For more details about available AST nodes, please refer to the uppercased definitions in [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). |
| 437 | 212 | ||
| 438 | # Try | 213 | # Try |
| @@ -467,38 +242,6 @@ catch err | |||
| 467 | print result | 242 | print result |
| 468 | ``` | 243 | ``` |
| 469 | 244 | ||
| 470 | <YueDisplay> | ||
| 471 | |||
| 472 | ```yue | ||
| 473 | try | ||
| 474 | func 1, 2, 3 | ||
| 475 | catch err | ||
| 476 | print yue.traceback err | ||
| 477 | |||
| 478 | success, result = try | ||
| 479 | func 1, 2, 3 | ||
| 480 | catch err | ||
| 481 | yue.traceback err | ||
| 482 | |||
| 483 | try func 1, 2, 3 | ||
| 484 | catch err | ||
| 485 | print yue.traceback err | ||
| 486 | |||
| 487 | success, result = try func 1, 2, 3 | ||
| 488 | |||
| 489 | try | ||
| 490 | print "trying" | ||
| 491 | func 1, 2, 3 | ||
| 492 | |||
| 493 | -- working with if assignment pattern | ||
| 494 | if success, result := try func 1, 2, 3 | ||
| 495 | catch err | ||
| 496 | print yue.traceback err | ||
| 497 | print result | ||
| 498 | ``` | ||
| 499 | |||
| 500 | </YueDisplay> | ||
| 501 | |||
| 502 | ## Try? | 245 | ## Try? |
| 503 | 246 | ||
| 504 | `try?` is a simplified use for error handling syntax that omit the boolean status from the `try` statement, and it will return the result from the try block when success, return nil instead of error object otherwise. | 247 | `try?` is a simplified use for error handling syntax that omit the boolean status from the `try` statement, and it will return the result from the try block when success, return nil instead of error object otherwise. |
| @@ -521,44 +264,14 @@ catch e | |||
| 521 | e | 264 | e |
| 522 | ``` | 265 | ``` |
| 523 | 266 | ||
| 524 | <YueDisplay> | ||
| 525 | |||
| 526 | ```yue | ||
| 527 | a, b, c = try? func! | ||
| 528 | |||
| 529 | -- with nil coalescing operator | ||
| 530 | a = (try? func!) ?? "default" | ||
| 531 | |||
| 532 | -- as function argument | ||
| 533 | f try? func! | ||
| 534 | |||
| 535 | -- with catch block | ||
| 536 | f try? | ||
| 537 | print 123 | ||
| 538 | func! | ||
| 539 | catch e | ||
| 540 | print e | ||
| 541 | e | ||
| 542 | ``` | ||
| 543 | |||
| 544 | </YueDisplay> | ||
| 545 | |||
| 546 | # Table Literals | 267 | # Table Literals |
| 547 | 268 | ||
| 548 | Like in Lua, tables are delimited in curly braces. | 269 | Like in Lua, tables are delimited in curly braces. |
| 549 | 270 | ||
| 550 | ```yuescript | 271 | ```yuescript |
| 551 | some_values = [1, 2, 3, 4] | 272 | some_values = {1, 2, 3, 4} |
| 552 | ``` | ||
| 553 | |||
| 554 | <YueDisplay> | ||
| 555 | |||
| 556 | ```yue | ||
| 557 | some_values = [1, 2, 3, 4] | ||
| 558 | ``` | 273 | ``` |
| 559 | 274 | ||
| 560 | </YueDisplay> | ||
| 561 | |||
| 562 | Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). | 275 | Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). |
| 563 | 276 | ||
| 564 | ```yuescript | 277 | ```yuescript |
| @@ -569,18 +282,6 @@ some_values = { | |||
| 569 | } | 282 | } |
| 570 | ``` | 283 | ``` |
| 571 | 284 | ||
| 572 | <YueDisplay> | ||
| 573 | |||
| 574 | ```yue | ||
| 575 | some_values = { | ||
| 576 | name: "Bill", | ||
| 577 | age: 200, | ||
| 578 | ["favorite food"]: "rice" | ||
| 579 | } | ||
| 580 | ``` | ||
| 581 | |||
| 582 | </YueDisplay> | ||
| 583 | |||
| 584 | The curly braces can be left off if a single table of key value pairs is being assigned. | 285 | The curly braces can be left off if a single table of key value pairs is being assigned. |
| 585 | 286 | ||
| 586 | ```yuescript | 287 | ```yuescript |
| @@ -590,17 +291,6 @@ profile = | |||
| 590 | favorite_foods: ["ice cream", "donuts"] | 291 | favorite_foods: ["ice cream", "donuts"] |
| 591 | ``` | 292 | ``` |
| 592 | 293 | ||
| 593 | <YueDisplay> | ||
| 594 | |||
| 595 | ```yue | ||
| 596 | profile = | ||
| 597 | height: "4 feet", | ||
| 598 | shoe_size: 13, | ||
| 599 | favorite_foods: ["ice cream", "donuts"] | ||
| 600 | ``` | ||
| 601 | |||
| 602 | </YueDisplay> | ||
| 603 | |||
| 604 | Newlines can be used to delimit values instead of a comma (or both): | 294 | Newlines can be used to delimit values instead of a comma (or both): |
| 605 | 295 | ||
| 606 | ```yuescript | 296 | ```yuescript |
| @@ -612,19 +302,6 @@ values = { | |||
| 612 | } | 302 | } |
| 613 | ``` | 303 | ``` |
| 614 | 304 | ||
| 615 | <YueDisplay> | ||
| 616 | |||
| 617 | ```yue | ||
| 618 | values = { | ||
| 619 | 1, 2, 3, 4 | ||
| 620 | 5, 6, 7, 8 | ||
| 621 | name: "superman" | ||
| 622 | occupation: "crime fighting" | ||
| 623 | } | ||
| 624 | ``` | ||
| 625 | |||
| 626 | </YueDisplay> | ||
| 627 | |||
| 628 | When creating a single line table literal, the curly braces can also be left off: | 305 | When creating a single line table literal, the curly braces can also be left off: |
| 629 | 306 | ||
| 630 | ```yuescript | 307 | ```yuescript |
| @@ -633,16 +310,6 @@ my_function dance: "Tango", partner: "none" | |||
| 633 | y = type: "dog", legs: 4, tails: 1 | 310 | y = type: "dog", legs: 4, tails: 1 |
| 634 | ``` | 311 | ``` |
| 635 | 312 | ||
| 636 | <YueDisplay> | ||
| 637 | |||
| 638 | ```yue | ||
| 639 | my_function dance: "Tango", partner: "none" | ||
| 640 | |||
| 641 | y = type: "dog", legs: 4, tails: 1 | ||
| 642 | ``` | ||
| 643 | |||
| 644 | </YueDisplay> | ||
| 645 | |||
| 646 | The keys of a table literal can be language keywords without being escaped: | 313 | The keys of a table literal can be language keywords without being escaped: |
| 647 | 314 | ||
| 648 | ```yuescript | 315 | ```yuescript |
| @@ -652,17 +319,6 @@ tbl = { | |||
| 652 | } | 319 | } |
| 653 | ``` | 320 | ``` |
| 654 | 321 | ||
| 655 | <YueDisplay> | ||
| 656 | |||
| 657 | ```yue | ||
| 658 | tbl = { | ||
| 659 | do: "something" | ||
| 660 | end: "hunger" | ||
| 661 | } | ||
| 662 | ``` | ||
| 663 | |||
| 664 | </YueDisplay> | ||
| 665 | |||
| 666 | If you are constructing a table out of variables and wish the keys to be the same as the variable names, then the **:** prefix operator can be used: | 322 | If you are constructing a table out of variables and wish the keys to be the same as the variable names, then the **:** prefix operator can be used: |
| 667 | 323 | ||
| 668 | ```yuescript | 324 | ```yuescript |
| @@ -673,18 +329,6 @@ person = { :hair, :height, shoe_size: 40 } | |||
| 673 | print_table :hair, :height | 329 | print_table :hair, :height |
| 674 | ``` | 330 | ``` |
| 675 | 331 | ||
| 676 | <YueDisplay> | ||
| 677 | |||
| 678 | ```yue | ||
| 679 | hair = "golden" | ||
| 680 | height = 200 | ||
| 681 | person = { :hair, :height, shoe_size: 40 } | ||
| 682 | |||
| 683 | print_table :hair, :height | ||
| 684 | ``` | ||
| 685 | |||
| 686 | </YueDisplay> | ||
| 687 | |||
| 688 | If you want the key of a field in the table to to be result of an expression, then you can wrap it in **[ ]**, just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters. | 332 | If you want the key of a field in the table to to be result of an expression, then you can wrap it in **[ ]**, just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters. |
| 689 | 333 | ||
| 690 | ```yuescript | 334 | ```yuescript |
| @@ -694,33 +338,13 @@ t = { | |||
| 694 | } | 338 | } |
| 695 | ``` | 339 | ``` |
| 696 | 340 | ||
| 697 | <YueDisplay> | 341 | Lua tables have both an array part and a hash part, but sometimes it's useful to make a semantic distinction between the two. You can use **[ ]** instead of **{ }** to explicitly declare a table as an array, doing so will prevent any key-value pairs from being written inside it. |
| 698 | |||
| 699 | ```yue | ||
| 700 | t = { | ||
| 701 | [1 + 2]: "hello" | ||
| 702 | "hello world": true | ||
| 703 | } | ||
| 704 | ``` | ||
| 705 | |||
| 706 | </YueDisplay> | ||
| 707 | |||
| 708 | Lua tables have both an array part and a hash part, but sometimes you want to make a semantic distinction between array and hash usage when writing Lua tables. Then you can write Lua table with **[ ]** instead of **{ }** to represent an array table and writing any key value pair in a list table won't be allowed. | ||
| 709 | 342 | ||
| 710 | ```yuescript | 343 | ```yuescript |
| 711 | some_values = [1, 2, 3, 4] | 344 | some_values = [1, 2, 3, 4] |
| 712 | list_with_one_element = [1, ] | 345 | list_with_one_element = [1, ] |
| 713 | ``` | 346 | ``` |
| 714 | 347 | ||
| 715 | <YueDisplay> | ||
| 716 | |||
| 717 | ```yue | ||
| 718 | some_values = [1, 2, 3, 4] | ||
| 719 | list_with_one_element = [1, ] | ||
| 720 | ``` | ||
| 721 | |||
| 722 | </YueDisplay> | ||
| 723 | |||
| 724 | # Comprehensions | 348 | # Comprehensions |
| 725 | 349 | ||
| 726 | Comprehensions provide a convenient syntax for constructing a new table by iterating over some existing object and applying an expression to its values. There are two kinds of comprehensions: list comprehensions and table comprehensions. They both produce Lua tables; list comprehensions accumulate values into an array-like table, and table comprehensions let you set both the key and the value on each iteration. | 350 | Comprehensions provide a convenient syntax for constructing a new table by iterating over some existing object and applying an expression to its values. There are two kinds of comprehensions: list comprehensions and table comprehensions. They both produce Lua tables; list comprehensions accumulate values into an array-like table, and table comprehensions let you set both the key and the value on each iteration. |
| @@ -734,43 +358,18 @@ items = [ 1, 2, 3, 4 ] | |||
| 734 | doubled = [item * 2 for i, item in ipairs items] | 358 | doubled = [item * 2 for i, item in ipairs items] |
| 735 | ``` | 359 | ``` |
| 736 | 360 | ||
| 737 | <YueDisplay> | ||
| 738 | |||
| 739 | ```yue | ||
| 740 | items = [ 1, 2, 3, 4 ] | ||
| 741 | doubled = [item * 2 for i, item in ipairs items] | ||
| 742 | ``` | ||
| 743 | |||
| 744 | </YueDisplay> | ||
| 745 | |||
| 746 | The items included in the new table can be restricted with a when clause: | 361 | The items included in the new table can be restricted with a when clause: |
| 747 | 362 | ||
| 748 | ```yuescript | 363 | ```yuescript |
| 749 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | 364 | slice = [item for i, item in ipairs items when i > 1 and i < 3] |
| 750 | ``` | 365 | ``` |
| 751 | 366 | ||
| 752 | <YueDisplay> | ||
| 753 | |||
| 754 | ```yue | ||
| 755 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | ||
| 756 | ``` | ||
| 757 | |||
| 758 | </YueDisplay> | ||
| 759 | |||
| 760 | Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as: | 367 | Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as: |
| 761 | 368 | ||
| 762 | ```yuescript | 369 | ```yuescript |
| 763 | doubled = [item * 2 for item in *items] | 370 | doubled = [item * 2 for item in *items] |
| 764 | ``` | 371 | ``` |
| 765 | 372 | ||
| 766 | <YueDisplay> | ||
| 767 | |||
| 768 | ```yue | ||
| 769 | doubled = [item * 2 for item in *items] | ||
| 770 | ``` | ||
| 771 | |||
| 772 | </YueDisplay> | ||
| 773 | |||
| 774 | In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: | 373 | In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: |
| 775 | 374 | ||
| 776 | ```yuescript | 375 | ```yuescript |
| @@ -782,19 +381,6 @@ flat = [...v for k,v in pairs data] | |||
| 782 | -- flat is now [1, 2, 3, 4, 5, 6] | 381 | -- flat is now [1, 2, 3, 4, 5, 6] |
| 783 | ``` | 382 | ``` |
| 784 | 383 | ||
| 785 | <YueDisplay> | ||
| 786 | |||
| 787 | ```yue | ||
| 788 | data = | ||
| 789 | a: [1, 2, 3] | ||
| 790 | b: [4, 5, 6] | ||
| 791 | |||
| 792 | flat = [...v for k,v in pairs data] | ||
| 793 | -- flat is now [1, 2, 3, 4, 5, 6] | ||
| 794 | ``` | ||
| 795 | |||
| 796 | </YueDisplay> | ||
| 797 | |||
| 798 | The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause. | 384 | The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause. |
| 799 | 385 | ||
| 800 | Using multiple for clauses is the same as using nested loops: | 386 | Using multiple for clauses is the same as using nested loops: |
| @@ -807,32 +393,12 @@ points = [ [x, y] for x in *x_coords \ | |||
| 807 | for y in *y_coords] | 393 | for y in *y_coords] |
| 808 | ``` | 394 | ``` |
| 809 | 395 | ||
| 810 | <YueDisplay> | ||
| 811 | |||
| 812 | ```yue | ||
| 813 | x_coords = [4, 5, 6, 7] | ||
| 814 | y_coords = [9, 2, 3] | ||
| 815 | |||
| 816 | points = [ [x, y] for x in *x_coords \ | ||
| 817 | for y in *y_coords] | ||
| 818 | ``` | ||
| 819 | |||
| 820 | </YueDisplay> | ||
| 821 | |||
| 822 | Numeric for loops can also be used in comprehensions: | 396 | Numeric for loops can also be used in comprehensions: |
| 823 | 397 | ||
| 824 | ```yuescript | 398 | ```yuescript |
| 825 | evens = [i for i = 1, 100 when i % 2 == 0] | 399 | evens = [i for i = 1, 100 when i % 2 == 0] |
| 826 | ``` | 400 | ``` |
| 827 | 401 | ||
| 828 | <YueDisplay> | ||
| 829 | |||
| 830 | ```yue | ||
| 831 | evens = [i for i = 1, 100 when i % 2 == 0] | ||
| 832 | ``` | ||
| 833 | |||
| 834 | </YueDisplay> | ||
| 835 | |||
| 836 | ## Table Comprehensions | 402 | ## Table Comprehensions |
| 837 | 403 | ||
| 838 | The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. | 404 | The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. |
| @@ -849,32 +415,10 @@ thing = { | |||
| 849 | thing_copy = {k, v for k, v in pairs thing} | 415 | thing_copy = {k, v for k, v in pairs thing} |
| 850 | ``` | 416 | ``` |
| 851 | 417 | ||
| 852 | <YueDisplay> | ||
| 853 | |||
| 854 | ```yue | ||
| 855 | thing = { | ||
| 856 | color: "red" | ||
| 857 | name: "fast" | ||
| 858 | width: 123 | ||
| 859 | } | ||
| 860 | |||
| 861 | thing_copy = {k, v for k, v in pairs thing} | ||
| 862 | ``` | ||
| 863 | |||
| 864 | </YueDisplay> | ||
| 865 | |||
| 866 | ```yuescript | 418 | ```yuescript |
| 867 | no_color = {k, v for k, v in pairs thing when k != "color"} | 419 | no_color = {k, v for k, v in pairs thing when k != "color"} |
| 868 | ``` | 420 | ``` |
| 869 | 421 | ||
| 870 | <YueDisplay> | ||
| 871 | |||
| 872 | ```yue | ||
| 873 | no_color = {k, v for k, v in pairs thing when k != "color"} | ||
| 874 | ``` | ||
| 875 | |||
| 876 | </YueDisplay> | ||
| 877 | |||
| 878 | The **\*** operator is also supported. Here we create a square root look up table for a few numbers. | 422 | The **\*** operator is also supported. Here we create a square root look up table for a few numbers. |
| 879 | 423 | ||
| 880 | ```yuescript | 424 | ```yuescript |
| @@ -882,15 +426,6 @@ numbers = [1, 2, 3, 4] | |||
| 882 | sqrts = {i, math.sqrt i for i in *numbers} | 426 | sqrts = {i, math.sqrt i for i in *numbers} |
| 883 | ``` | 427 | ``` |
| 884 | 428 | ||
| 885 | <YueDisplay> | ||
| 886 | |||
| 887 | ```yue | ||
| 888 | numbers = [1, 2, 3, 4] | ||
| 889 | sqrts = {i, math.sqrt i for i in *numbers} | ||
| 890 | ``` | ||
| 891 | |||
| 892 | </YueDisplay> | ||
| 893 | |||
| 894 | The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value: | 429 | The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value: |
| 895 | 430 | ||
| 896 | In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value. | 431 | In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value. |
| @@ -900,15 +435,6 @@ tuples = [ ["hello", "world"], ["foo", "bar"]] | |||
| 900 | tbl = {unpack tuple for tuple in *tuples} | 435 | tbl = {unpack tuple for tuple in *tuples} |
| 901 | ``` | 436 | ``` |
| 902 | 437 | ||
| 903 | <YueDisplay> | ||
| 904 | |||
| 905 | ```yue | ||
| 906 | tuples = [ ["hello", "world"], ["foo", "bar"]] | ||
| 907 | tbl = {unpack tuple for tuple in *tuples} | ||
| 908 | ``` | ||
| 909 | |||
| 910 | </YueDisplay> | ||
| 911 | |||
| 912 | ## Slicing | 438 | ## Slicing |
| 913 | 439 | ||
| 914 | A special syntax is provided to restrict the items that are iterated over when using the **\*** operator. This is equivalent to setting the iteration bounds and a step size in a for loop. | 440 | A special syntax is provided to restrict the items that are iterated over when using the **\*** operator. This is equivalent to setting the iteration bounds and a step size in a for loop. |
| @@ -919,42 +445,18 @@ Here we can set the minimum and maximum bounds, taking all items with indexes be | |||
| 919 | slice = [item for item in *items[1, 5]] | 445 | slice = [item for item in *items[1, 5]] |
| 920 | ``` | 446 | ``` |
| 921 | 447 | ||
| 922 | <YueDisplay> | ||
| 923 | |||
| 924 | ```yue | ||
| 925 | slice = [item for item in *items[1, 5]] | ||
| 926 | ``` | ||
| 927 | |||
| 928 | </YueDisplay> | ||
| 929 | |||
| 930 | Any of the slice arguments can be left off to use a sensible default. In this example, if the max index is left off it defaults to the length of the table. This will take everything but the first element: | 448 | Any of the slice arguments can be left off to use a sensible default. In this example, if the max index is left off it defaults to the length of the table. This will take everything but the first element: |
| 931 | 449 | ||
| 932 | ```yuescript | 450 | ```yuescript |
| 933 | slice = [item for item in *items[2,]] | 451 | slice = [item for item in *items[2,]] |
| 934 | ``` | 452 | ``` |
| 935 | 453 | ||
| 936 | <YueDisplay> | ||
| 937 | |||
| 938 | ```yue | ||
| 939 | slice = [item for item in *items[2,]] | ||
| 940 | ``` | ||
| 941 | |||
| 942 | </YueDisplay> | ||
| 943 | |||
| 944 | If the minimum bound is left out, it defaults to 1. Here we only provide a step size and leave the other bounds blank. This takes all odd indexed items: (1, 3, 5, …) | 454 | If the minimum bound is left out, it defaults to 1. Here we only provide a step size and leave the other bounds blank. This takes all odd indexed items: (1, 3, 5, …) |
| 945 | 455 | ||
| 946 | ```yuescript | 456 | ```yuescript |
| 947 | slice = [item for item in *items[,,2]] | 457 | slice = [item for item in *items[,,2]] |
| 948 | ``` | 458 | ``` |
| 949 | 459 | ||
| 950 | <YueDisplay> | ||
| 951 | |||
| 952 | ```yue | ||
| 953 | slice = [item for item in *items[,,2]] | ||
| 954 | ``` | ||
| 955 | |||
| 956 | </YueDisplay> | ||
| 957 | |||
| 958 | Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. | 460 | Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. |
| 959 | 461 | ||
| 960 | ```yuescript | 462 | ```yuescript |
| @@ -962,29 +464,12 @@ Both the minimum and maximum bounds can be negative, which means that the bounds | |||
| 962 | slice = [item for item in *items[-4,-1]] | 464 | slice = [item for item in *items[-4,-1]] |
| 963 | ``` | 465 | ``` |
| 964 | 466 | ||
| 965 | <YueDisplay> | ||
| 966 | |||
| 967 | ```yue | ||
| 968 | -- take the last 4 items | ||
| 969 | slice = [item for item in *items[-4,-1]] | ||
| 970 | ``` | ||
| 971 | |||
| 972 | </YueDisplay> | ||
| 973 | |||
| 974 | The step size can also be negative, which means that the items are taken in reverse order. | 467 | The step size can also be negative, which means that the items are taken in reverse order. |
| 975 | 468 | ||
| 976 | ```yuescript | 469 | ```yuescript |
| 977 | reverse_slice = [item for item in *items[-1,1,-1]] | 470 | reverse_slice = [item for item in *items[-1,1,-1]] |
| 978 | ``` | 471 | ``` |
| 979 | 472 | ||
| 980 | <YueDisplay> | ||
| 981 | |||
| 982 | ```yue | ||
| 983 | reverse_slice = [item for item in *items[-1,1,-1]] | ||
| 984 | ``` | ||
| 985 | |||
| 986 | </YueDisplay> | ||
| 987 | |||
| 988 | ### Slicing Expression | 473 | ### Slicing Expression |
| 989 | 474 | ||
| 990 | Slicing can also be used as an expression. This is useful for getting a sub-list of a table. | 475 | Slicing can also be used as an expression. This is useful for getting a sub-list of a table. |
| @@ -997,18 +482,6 @@ sub_list = items[2, 4] | |||
| 997 | last_four_items = items[-4, -1] | 482 | last_four_items = items[-4, -1] |
| 998 | ``` | 483 | ``` |
| 999 | 484 | ||
| 1000 | <YueDisplay> | ||
| 1001 | |||
| 1002 | ```yue | ||
| 1003 | -- take the 2nd and 4th items as a new list | ||
| 1004 | sub_list = items[2, 4] | ||
| 1005 | |||
| 1006 | -- take the last 4 items | ||
| 1007 | last_four_items = items[-4, -1] | ||
| 1008 | ``` | ||
| 1009 | |||
| 1010 | </YueDisplay> | ||
| 1011 | |||
| 1012 | # Object Oriented Programming | 485 | # Object Oriented Programming |
| 1013 | 486 | ||
| 1014 | In these examples, the generated Lua code may appear overwhelming. It is best to focus on the meaning of the YueScript code at first, then look into the Lua code if you wish to know the implementation details. | 487 | In these examples, the generated Lua code may appear overwhelming. It is best to focus on the meaning of the YueScript code at first, then look into the Lua code if you wish to know the implementation details. |
| @@ -1027,22 +500,6 @@ class Inventory | |||
| 1027 | @items[name] = 1 | 500 | @items[name] = 1 |
| 1028 | ``` | 501 | ``` |
| 1029 | 502 | ||
| 1030 | <YueDisplay> | ||
| 1031 | |||
| 1032 | ```yue | ||
| 1033 | class Inventory | ||
| 1034 | new: => | ||
| 1035 | @items = {} | ||
| 1036 | |||
| 1037 | add_item: (name) => | ||
| 1038 | if @items[name] | ||
| 1039 | @items[name] += 1 | ||
| 1040 | else | ||
| 1041 | @items[name] = 1 | ||
| 1042 | ``` | ||
| 1043 | |||
| 1044 | </YueDisplay> | ||
| 1045 | |||
| 1046 | A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. | 503 | A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. |
| 1047 | 504 | ||
| 1048 | The new property is special in that it will become the constructor. | 505 | The new property is special in that it will become the constructor. |
| @@ -1059,16 +516,6 @@ inv\add_item "t-shirt" | |||
| 1059 | inv\add_item "pants" | 516 | inv\add_item "pants" |
| 1060 | ``` | 517 | ``` |
| 1061 | 518 | ||
| 1062 | <YueDisplay> | ||
| 1063 | |||
| 1064 | ```yue | ||
| 1065 | inv = Inventory! | ||
| 1066 | inv\add_item "t-shirt" | ||
| 1067 | inv\add_item "pants" | ||
| 1068 | ``` | ||
| 1069 | |||
| 1070 | </YueDisplay> | ||
| 1071 | |||
| 1072 | Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. | 519 | Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. |
| 1073 | 520 | ||
| 1074 | All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur. | 521 | All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur. |
| @@ -1091,26 +538,6 @@ b\give_item "shirt" | |||
| 1091 | print item for item in *a.clothes | 538 | print item for item in *a.clothes |
| 1092 | ``` | 539 | ``` |
| 1093 | 540 | ||
| 1094 | <YueDisplay> | ||
| 1095 | |||
| 1096 | ```yue | ||
| 1097 | class Person | ||
| 1098 | clothes: [] | ||
| 1099 | give_item: (name) => | ||
| 1100 | table.insert @clothes, name | ||
| 1101 | |||
| 1102 | a = Person! | ||
| 1103 | b = Person! | ||
| 1104 | |||
| 1105 | a\give_item "pants" | ||
| 1106 | b\give_item "shirt" | ||
| 1107 | |||
| 1108 | -- will print both pants and shirt | ||
| 1109 | print item for item in *a.clothes | ||
| 1110 | ``` | ||
| 1111 | |||
| 1112 | </YueDisplay> | ||
| 1113 | |||
| 1114 | The proper way to avoid this problem is to create the mutable state of the object in the constructor: | 541 | The proper way to avoid this problem is to create the mutable state of the object in the constructor: |
| 1115 | 542 | ||
| 1116 | ```yuescript | 543 | ```yuescript |
| @@ -1119,16 +546,6 @@ class Person | |||
| 1119 | @clothes = [] | 546 | @clothes = [] |
| 1120 | ``` | 547 | ``` |
| 1121 | 548 | ||
| 1122 | <YueDisplay> | ||
| 1123 | |||
| 1124 | ```yue | ||
| 1125 | class Person | ||
| 1126 | new: => | ||
| 1127 | @clothes = [] | ||
| 1128 | ``` | ||
| 1129 | |||
| 1130 | </YueDisplay> | ||
| 1131 | |||
| 1132 | ## Inheritance | 549 | ## Inheritance |
| 1133 | 550 | ||
| 1134 | The extends keyword can be used in a class declaration to inherit the properties and methods from another class. | 551 | The extends keyword can be used in a class declaration to inherit the properties and methods from another class. |
| @@ -1141,18 +558,6 @@ class BackPack extends Inventory | |||
| 1141 | super name | 558 | super name |
| 1142 | ``` | 559 | ``` |
| 1143 | 560 | ||
| 1144 | <YueDisplay> | ||
| 1145 | |||
| 1146 | ```yue | ||
| 1147 | class BackPack extends Inventory | ||
| 1148 | size: 10 | ||
| 1149 | add_item: (name) => | ||
| 1150 | if #@items > size then error "backpack is full" | ||
| 1151 | super name | ||
| 1152 | ``` | ||
| 1153 | |||
| 1154 | </YueDisplay> | ||
| 1155 | |||
| 1156 | Here we extend our Inventory class, and limit the amount of items it can carry. | 561 | Here we extend our Inventory class, and limit the amount of items it can carry. |
| 1157 | 562 | ||
| 1158 | In this example, we don't define a constructor on the subclass, so the parent class' constructor is called when we make a new instance. If we did define a constructor then we can use the super method to call the parent constructor. | 563 | In this example, we don't define a constructor on the subclass, so the parent class' constructor is called when we make a new instance. If we did define a constructor then we can use the super method to call the parent constructor. |
| @@ -1168,19 +573,6 @@ class Shelf | |||
| 1168 | class Cupboard extends Shelf | 573 | class Cupboard extends Shelf |
| 1169 | ``` | 574 | ``` |
| 1170 | 575 | ||
| 1171 | <YueDisplay> | ||
| 1172 | |||
| 1173 | ```yue | ||
| 1174 | class Shelf | ||
| 1175 | @__inherited: (child) => | ||
| 1176 | print @__name, "was inherited by", child.__name | ||
| 1177 | |||
| 1178 | -- will print: Shelf was inherited by Cupboard | ||
| 1179 | class Cupboard extends Shelf | ||
| 1180 | ``` | ||
| 1181 | |||
| 1182 | </YueDisplay> | ||
| 1183 | |||
| 1184 | ## Super | 576 | ## Super |
| 1185 | 577 | ||
| 1186 | **super** is a special keyword that can be used in two different ways: It can be treated as an object, or it can be called like a function. It only has special functionality when inside a class. | 578 | **super** is a special keyword that can be used in two different ways: It can be treated as an object, or it can be called like a function. It only has special functionality when inside a class. |
| @@ -1207,22 +599,6 @@ class MyClass extends ParentClass | |||
| 1207 | assert super == ParentClass | 599 | assert super == ParentClass |
| 1208 | ``` | 600 | ``` |
| 1209 | 601 | ||
| 1210 | <YueDisplay> | ||
| 1211 | |||
| 1212 | ```yue | ||
| 1213 | class MyClass extends ParentClass | ||
| 1214 | a_method: => | ||
| 1215 | -- the following have the same effect: | ||
| 1216 | super "hello", "world" | ||
| 1217 | super\a_method "hello", "world" | ||
| 1218 | super.a_method self, "hello", "world" | ||
| 1219 | |||
| 1220 | -- super as a value is equal to the parent class: | ||
| 1221 | assert super == ParentClass | ||
| 1222 | ``` | ||
| 1223 | |||
| 1224 | </YueDisplay> | ||
| 1225 | |||
| 1226 | **super** can also be used on left side of a Function Stub. The only major difference is that instead of the resulting function being bound to the value of super, it is bound to self. | 602 | **super** can also be used on left side of a Function Stub. The only major difference is that instead of the resulting function being bound to the value of super, it is bound to self. |
| 1227 | 603 | ||
| 1228 | ## Types | 604 | ## Types |
| @@ -1236,17 +612,6 @@ assert b.__class == BackPack | |||
| 1236 | print BackPack.size -- prints 10 | 612 | print BackPack.size -- prints 10 |
| 1237 | ``` | 613 | ``` |
| 1238 | 614 | ||
| 1239 | <YueDisplay> | ||
| 1240 | |||
| 1241 | ```yue | ||
| 1242 | b = BackPack! | ||
| 1243 | assert b.__class == BackPack | ||
| 1244 | |||
| 1245 | print BackPack.size -- prints 10 | ||
| 1246 | ``` | ||
| 1247 | |||
| 1248 | </YueDisplay> | ||
| 1249 | |||
| 1250 | ## Class Objects | 615 | ## Class Objects |
| 1251 | 616 | ||
| 1252 | The class object is what we create when we use a class statement. The class object is stored in a variable of the same name of the class. | 617 | The class object is what we create when we use a class statement. The class object is stored in a variable of the same name of the class. |
| @@ -1267,14 +632,6 @@ The name of the class as when it was declared is stored as a string in the \_\_n | |||
| 1267 | print BackPack.__name -- prints Backpack | 632 | print BackPack.__name -- prints Backpack |
| 1268 | ``` | 633 | ``` |
| 1269 | 634 | ||
| 1270 | <YueDisplay> | ||
| 1271 | |||
| 1272 | ```yue | ||
| 1273 | print BackPack.__name -- prints Backpack | ||
| 1274 | ``` | ||
| 1275 | |||
| 1276 | </YueDisplay> | ||
| 1277 | |||
| 1278 | The base object is stored in \_\_base. We can modify this table to add functionality to instances that have already been created and ones that are yet to be created. | 635 | The base object is stored in \_\_base. We can modify this table to add functionality to instances that have already been created and ones that are yet to be created. |
| 1279 | 636 | ||
| 1280 | If the class extends from anything, the parent class object is stored in \_\_parent. | 637 | If the class extends from anything, the parent class object is stored in \_\_parent. |
| @@ -1293,20 +650,6 @@ Things\some_func! | |||
| 1293 | assert Things().some_func == nil | 650 | assert Things().some_func == nil |
| 1294 | ``` | 651 | ``` |
| 1295 | 652 | ||
| 1296 | <YueDisplay> | ||
| 1297 | |||
| 1298 | ```yue | ||
| 1299 | class Things | ||
| 1300 | @some_func: => print "Hello from", @__name | ||
| 1301 | |||
| 1302 | Things\some_func! | ||
| 1303 | |||
| 1304 | -- class variables not visible in instances | ||
| 1305 | assert Things().some_func == nil | ||
| 1306 | ``` | ||
| 1307 | |||
| 1308 | </YueDisplay> | ||
| 1309 | |||
| 1310 | In expressions, we can use @@ to access a value that is stored in the **class of self. Thus, @@hello is shorthand for self.**class.hello. | 653 | In expressions, we can use @@ to access a value that is stored in the **class of self. Thus, @@hello is shorthand for self.**class.hello. |
| 1311 | 654 | ||
| 1312 | ```yuescript | 655 | ```yuescript |
| @@ -1322,37 +665,12 @@ Counter! | |||
| 1322 | print Counter.count -- prints 2 | 665 | print Counter.count -- prints 2 |
| 1323 | ``` | 666 | ``` |
| 1324 | 667 | ||
| 1325 | <YueDisplay> | ||
| 1326 | |||
| 1327 | ```yue | ||
| 1328 | class Counter | ||
| 1329 | @count: 0 | ||
| 1330 | |||
| 1331 | new: => | ||
| 1332 | @@count += 1 | ||
| 1333 | |||
| 1334 | Counter! | ||
| 1335 | Counter! | ||
| 1336 | |||
| 1337 | print Counter.count -- prints 2 | ||
| 1338 | ``` | ||
| 1339 | |||
| 1340 | </YueDisplay> | ||
| 1341 | |||
| 1342 | The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. | 668 | The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. |
| 1343 | 669 | ||
| 1344 | ```yuescript | 670 | ```yuescript |
| 1345 | @@hello 1,2,3,4 | 671 | @@hello 1,2,3,4 |
| 1346 | ``` | 672 | ``` |
| 1347 | 673 | ||
| 1348 | <YueDisplay> | ||
| 1349 | |||
| 1350 | ```yue | ||
| 1351 | @@hello 1,2,3,4 | ||
| 1352 | ``` | ||
| 1353 | |||
| 1354 | </YueDisplay> | ||
| 1355 | |||
| 1356 | ## Class Declaration Statements | 674 | ## Class Declaration Statements |
| 1357 | 675 | ||
| 1358 | In the body of a class declaration, we can have normal expressions in addition to key/value pairs. In this context, self is equal to the class object. | 676 | In the body of a class declaration, we can have normal expressions in addition to key/value pairs. In this context, self is equal to the class object. |
| @@ -1364,15 +682,6 @@ class Things | |||
| 1364 | @class_var = "hello world" | 682 | @class_var = "hello world" |
| 1365 | ``` | 683 | ``` |
| 1366 | 684 | ||
| 1367 | <YueDisplay> | ||
| 1368 | |||
| 1369 | ```yue | ||
| 1370 | class Things | ||
| 1371 | @class_var = "hello world" | ||
| 1372 | ``` | ||
| 1373 | |||
| 1374 | </YueDisplay> | ||
| 1375 | |||
| 1376 | These expressions are executed after all the properties have been added to the base. | 685 | These expressions are executed after all the properties have been added to the base. |
| 1377 | 686 | ||
| 1378 | All variables declared in the body of the class are local to the classes properties. This is convenient for placing private values or helper functions that only the class methods can access: | 687 | All variables declared in the body of the class are local to the classes properties. This is convenient for placing private values or helper functions that only the class methods can access: |
| @@ -1386,19 +695,6 @@ class MoreThings | |||
| 1386 | log "hello world: " .. secret | 695 | log "hello world: " .. secret |
| 1387 | ``` | 696 | ``` |
| 1388 | 697 | ||
| 1389 | <YueDisplay> | ||
| 1390 | |||
| 1391 | ```yue | ||
| 1392 | class MoreThings | ||
| 1393 | secret = 123 | ||
| 1394 | log = (msg) -> print "LOG:", msg | ||
| 1395 | |||
| 1396 | some_method: => | ||
| 1397 | log "hello world: " .. secret | ||
| 1398 | ``` | ||
| 1399 | |||
| 1400 | </YueDisplay> | ||
| 1401 | |||
| 1402 | ## @ and @@ Values | 698 | ## @ and @@ Values |
| 1403 | 699 | ||
| 1404 | When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.\_\_class. | 700 | When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.\_\_class. |
| @@ -1410,29 +706,12 @@ assert @ == self | |||
| 1410 | assert @@ == self.__class | 706 | assert @@ == self.__class |
| 1411 | ``` | 707 | ``` |
| 1412 | 708 | ||
| 1413 | <YueDisplay> | ||
| 1414 | |||
| 1415 | ```yue | ||
| 1416 | assert @ == self | ||
| 1417 | assert @@ == self.__class | ||
| 1418 | ``` | ||
| 1419 | |||
| 1420 | </YueDisplay> | ||
| 1421 | |||
| 1422 | For example, a quick way to create a new instance of the same class from an instance method using @@: | 709 | For example, a quick way to create a new instance of the same class from an instance method using @@: |
| 1423 | 710 | ||
| 1424 | ```yuescript | 711 | ```yuescript |
| 1425 | some_instance_method = (...) => @@ ... | 712 | some_instance_method = (...) => @@ ... |
| 1426 | ``` | 713 | ``` |
| 1427 | 714 | ||
| 1428 | <YueDisplay> | ||
| 1429 | |||
| 1430 | ```yue | ||
| 1431 | some_instance_method = (...) => @@ ... | ||
| 1432 | ``` | ||
| 1433 | |||
| 1434 | </YueDisplay> | ||
| 1435 | |||
| 1436 | ## Constructor Property Promotion | 715 | ## Constructor Property Promotion |
| 1437 | 716 | ||
| 1438 | To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: | 717 | To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: |
| @@ -1451,24 +730,6 @@ class Something | |||
| 1451 | @@baz = baz | 730 | @@baz = baz |
| 1452 | ``` | 731 | ``` |
| 1453 | 732 | ||
| 1454 | <YueDisplay> | ||
| 1455 | |||
| 1456 | ```yue | ||
| 1457 | class Something | ||
| 1458 | new: (@foo, @bar, @@biz, @@baz) => | ||
| 1459 | |||
| 1460 | -- Which is short for | ||
| 1461 | |||
| 1462 | class Something | ||
| 1463 | new: (foo, bar, biz, baz) => | ||
| 1464 | @foo = foo | ||
| 1465 | @bar = bar | ||
| 1466 | @@biz = biz | ||
| 1467 | @@baz = baz | ||
| 1468 | ``` | ||
| 1469 | |||
| 1470 | </YueDisplay> | ||
| 1471 | |||
| 1472 | You can also use this syntax for a common function to initialize a object's fields. | 733 | You can also use this syntax for a common function to initialize a object's fields. |
| 1473 | 734 | ||
| 1474 | ```yuescript | 735 | ```yuescript |
| @@ -1477,16 +738,6 @@ obj = new {}, 123, "abc" | |||
| 1477 | print obj | 738 | print obj |
| 1478 | ``` | 739 | ``` |
| 1479 | 740 | ||
| 1480 | <YueDisplay> | ||
| 1481 | |||
| 1482 | ```yue | ||
| 1483 | new = (@fieldA, @fieldB) => @ | ||
| 1484 | obj = new {}, 123, "abc" | ||
| 1485 | print obj | ||
| 1486 | ``` | ||
| 1487 | |||
| 1488 | </YueDisplay> | ||
| 1489 | |||
| 1490 | ## Class Expressions | 741 | ## Class Expressions |
| 1491 | 742 | ||
| 1492 | The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. | 743 | The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. |
| @@ -1497,16 +748,6 @@ x = class Bucket | |||
| 1497 | add_drop: => @drops += 1 | 748 | add_drop: => @drops += 1 |
| 1498 | ``` | 749 | ``` |
| 1499 | 750 | ||
| 1500 | <YueDisplay> | ||
| 1501 | |||
| 1502 | ```yue | ||
| 1503 | x = class Bucket | ||
| 1504 | drops: 0 | ||
| 1505 | add_drop: => @drops += 1 | ||
| 1506 | ``` | ||
| 1507 | |||
| 1508 | </YueDisplay> | ||
| 1509 | |||
| 1510 | ## Anonymous classes | 751 | ## Anonymous classes |
| 1511 | 752 | ||
| 1512 | The name can be left out when declaring a class. The \_\_name attribute will be nil, unless the class expression is in an assignment. The name on the left hand side of the assignment is used instead of nil. | 753 | The name can be left out when declaring a class. The \_\_name attribute will be nil, unless the class expression is in an assignment. The name on the left hand side of the assignment is used instead of nil. |
| @@ -1518,31 +759,12 @@ BigBucket = class extends Bucket | |||
| 1518 | assert Bucket.__name == "BigBucket" | 759 | assert Bucket.__name == "BigBucket" |
| 1519 | ``` | 760 | ``` |
| 1520 | 761 | ||
| 1521 | <YueDisplay> | ||
| 1522 | |||
| 1523 | ```yue | ||
| 1524 | BigBucket = class extends Bucket | ||
| 1525 | add_drop: => @drops += 10 | ||
| 1526 | |||
| 1527 | assert Bucket.__name == "BigBucket" | ||
| 1528 | ``` | ||
| 1529 | |||
| 1530 | </YueDisplay> | ||
| 1531 | |||
| 1532 | You can even leave off the body, meaning you can write a blank anonymous class like this: | 762 | You can even leave off the body, meaning you can write a blank anonymous class like this: |
| 1533 | 763 | ||
| 1534 | ```yuescript | 764 | ```yuescript |
| 1535 | x = class | 765 | x = class |
| 1536 | ``` | 766 | ``` |
| 1537 | 767 | ||
| 1538 | <YueDisplay> | ||
| 1539 | |||
| 1540 | ```yue | ||
| 1541 | x = class | ||
| 1542 | ``` | ||
| 1543 | |||
| 1544 | </YueDisplay> | ||
| 1545 | |||
| 1546 | ## Class Mixing | 768 | ## Class Mixing |
| 1547 | 769 | ||
| 1548 | You can do mixing with keyword `using` to copy functions from either a plain table or a predefined class object into your new class. When doing mixing with a plain table, you can override the class indexing function (metamethod `__index`) to your customized implementation. When doing mixing with an existing class object, the class object's metamethods won't be copied. | 770 | You can do mixing with keyword `using` to copy functions from either a plain table or a predefined class object into your new class. When doing mixing with a plain table, you can override the class indexing function (metamethod `__index`) to your customized implementation. When doing mixing with an existing class object, the class object's metamethods won't be copied. |
| @@ -1565,28 +787,6 @@ y\func! | |||
| 1565 | assert y.__class.__parent ~= X -- X is not parent of Y | 787 | assert y.__class.__parent ~= X -- X is not parent of Y |
| 1566 | ``` | 788 | ``` |
| 1567 | 789 | ||
| 1568 | <YueDisplay> | ||
| 1569 | |||
| 1570 | ```yue | ||
| 1571 | MyIndex = __index: var: 1 | ||
| 1572 | |||
| 1573 | class X using MyIndex | ||
| 1574 | func: => | ||
| 1575 | print 123 | ||
| 1576 | |||
| 1577 | x = X! | ||
| 1578 | print x.var | ||
| 1579 | |||
| 1580 | class Y using X | ||
| 1581 | |||
| 1582 | y = Y! | ||
| 1583 | y\func! | ||
| 1584 | |||
| 1585 | assert y.__class.__parent ~= X -- X is not parent of Y | ||
| 1586 | ``` | ||
| 1587 | |||
| 1588 | </YueDisplay> | ||
| 1589 | |||
| 1590 | # With Statement | 790 | # With Statement |
| 1591 | 791 | ||
| 1592 | A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it. | 792 | A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it. |
| @@ -1605,18 +805,6 @@ with Person! | |||
| 1605 | print .name | 805 | print .name |
| 1606 | ``` | 806 | ``` |
| 1607 | 807 | ||
| 1608 | <YueDisplay> | ||
| 1609 | |||
| 1610 | ```yue | ||
| 1611 | with Person! | ||
| 1612 | .name = "Oswald" | ||
| 1613 | \add_relative my_dad | ||
| 1614 | \save! | ||
| 1615 | print .name | ||
| 1616 | ``` | ||
| 1617 | |||
| 1618 | </YueDisplay> | ||
| 1619 | |||
| 1620 | The with statement can also be used as an expression which returns the value it has been giving access to. | 808 | The with statement can also be used as an expression which returns the value it has been giving access to. |
| 1621 | 809 | ||
| 1622 | ```yuescript | 810 | ```yuescript |
| @@ -1624,15 +812,6 @@ file = with File "favorite_foods.txt" | |||
| 1624 | \set_encoding "utf8" | 812 | \set_encoding "utf8" |
| 1625 | ``` | 813 | ``` |
| 1626 | 814 | ||
| 1627 | <YueDisplay> | ||
| 1628 | |||
| 1629 | ```yue | ||
| 1630 | file = with File "favorite_foods.txt" | ||
| 1631 | \set_encoding "utf8" | ||
| 1632 | ``` | ||
| 1633 | |||
| 1634 | </YueDisplay> | ||
| 1635 | |||
| 1636 | `with` expressions support `break` with one value: | 815 | `with` expressions support `break` with one value: |
| 1637 | 816 | ||
| 1638 | ```yuescript | 817 | ```yuescript |
| @@ -1640,15 +819,6 @@ result = with obj | |||
| 1640 | break .value | 819 | break .value |
| 1641 | ``` | 820 | ``` |
| 1642 | 821 | ||
| 1643 | <YueDisplay> | ||
| 1644 | |||
| 1645 | ```yue | ||
| 1646 | result = with obj | ||
| 1647 | break .value | ||
| 1648 | ``` | ||
| 1649 | |||
| 1650 | </YueDisplay> | ||
| 1651 | |||
| 1652 | After `break value` is used inside `with`, the `with` expression no longer returns its target object. Instead, it returns the value from `break`. | 822 | After `break value` is used inside `with`, the `with` expression no longer returns its target object. Instead, it returns the value from `break`. |
| 1653 | 823 | ||
| 1654 | ```yuescript | 824 | ```yuescript |
| @@ -1661,20 +831,6 @@ b = with obj | |||
| 1661 | -- b is .x, not obj | 831 | -- b is .x, not obj |
| 1662 | ``` | 832 | ``` |
| 1663 | 833 | ||
| 1664 | <YueDisplay> | ||
| 1665 | |||
| 1666 | ```yue | ||
| 1667 | a = with obj | ||
| 1668 | .x = 1 | ||
| 1669 | -- a is obj | ||
| 1670 | |||
| 1671 | b = with obj | ||
| 1672 | break .x | ||
| 1673 | -- b is .x, not obj | ||
| 1674 | ``` | ||
| 1675 | |||
| 1676 | </YueDisplay> | ||
| 1677 | |||
| 1678 | Unlike `for` / `while` / `repeat` / `do`, `with` only supports one break value. | 834 | Unlike `for` / `while` / `repeat` / `do`, `with` only supports one break value. |
| 1679 | 835 | ||
| 1680 | Or… | 836 | Or… |
| @@ -1688,19 +844,6 @@ create_person = (name, relatives) -> | |||
| 1688 | me = create_person "Leaf", [dad, mother, sister] | 844 | me = create_person "Leaf", [dad, mother, sister] |
| 1689 | ``` | 845 | ``` |
| 1690 | 846 | ||
| 1691 | <YueDisplay> | ||
| 1692 | |||
| 1693 | ```yue | ||
| 1694 | create_person = (name, relatives) -> | ||
| 1695 | with Person! | ||
| 1696 | .name = name | ||
| 1697 | \add_relative relative for relative in *relatives | ||
| 1698 | |||
| 1699 | me = create_person "Leaf", [dad, mother, sister] | ||
| 1700 | ``` | ||
| 1701 | |||
| 1702 | </YueDisplay> | ||
| 1703 | |||
| 1704 | In this usage, with can be seen as a special form of the K combinator. | 847 | In this usage, with can be seen as a special form of the K combinator. |
| 1705 | 848 | ||
| 1706 | The expression in the with statement can also be an assignment, if you want to give a name to the expression. | 849 | The expression in the with statement can also be an assignment, if you want to give a name to the expression. |
| @@ -1711,16 +854,6 @@ with str := "Hello" | |||
| 1711 | print "upper:", \upper! | 854 | print "upper:", \upper! |
| 1712 | ``` | 855 | ``` |
| 1713 | 856 | ||
| 1714 | <YueDisplay> | ||
| 1715 | |||
| 1716 | ```yue | ||
| 1717 | with str := "Hello" | ||
| 1718 | print "original:", str | ||
| 1719 | print "upper:", \upper! | ||
| 1720 | ``` | ||
| 1721 | |||
| 1722 | </YueDisplay> | ||
| 1723 | |||
| 1724 | You can access special keys with `[]` in a `with` statement. | 857 | You can access special keys with `[]` in a `with` statement. |
| 1725 | 858 | ||
| 1726 | ```yuescript | 859 | ```yuescript |
| @@ -1733,20 +866,6 @@ with tb | |||
| 1733 | [] = "abc" -- appending to "tb" | 866 | [] = "abc" -- appending to "tb" |
| 1734 | ``` | 867 | ``` |
| 1735 | 868 | ||
| 1736 | <YueDisplay> | ||
| 1737 | |||
| 1738 | ```yue | ||
| 1739 | with tb | ||
| 1740 | [1] = 1 | ||
| 1741 | print [2] | ||
| 1742 | with [abc] | ||
| 1743 | [3] = [2]\func! | ||
| 1744 | ["key-name"] = value | ||
| 1745 | [] = "abc" -- appending to "tb" | ||
| 1746 | ``` | ||
| 1747 | |||
| 1748 | </YueDisplay> | ||
| 1749 | |||
| 1750 | `with?` is an enhanced version of `with` syntax, which introduces an existential check to safely access objects that may be nil without explicit null checks. | 869 | `with?` is an enhanced version of `with` syntax, which introduces an existential check to safely access objects that may be nil without explicit null checks. |
| 1751 | 870 | ||
| 1752 | ```yuescript | 871 | ```yuescript |
| @@ -1754,15 +873,6 @@ with? obj | |||
| 1754 | print obj.name | 873 | print obj.name |
| 1755 | ``` | 874 | ``` |
| 1756 | 875 | ||
| 1757 | <YueDisplay> | ||
| 1758 | |||
| 1759 | ```yue | ||
| 1760 | with? obj | ||
| 1761 | print obj.name | ||
| 1762 | ``` | ||
| 1763 | |||
| 1764 | </YueDisplay> | ||
| 1765 | |||
| 1766 | # Assignment | 876 | # Assignment |
| 1767 | 877 | ||
| 1768 | The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement. | 878 | The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement. |
| @@ -1773,16 +883,6 @@ a, b, c = 1, 2, 3 | |||
| 1773 | hello = 123 -- uses the existing variable | 883 | hello = 123 -- uses the existing variable |
| 1774 | ``` | 884 | ``` |
| 1775 | 885 | ||
| 1776 | <YueDisplay> | ||
| 1777 | |||
| 1778 | ```yue | ||
| 1779 | hello = "world" | ||
| 1780 | a, b, c = 1, 2, 3 | ||
| 1781 | hello = 123 -- uses the existing variable | ||
| 1782 | ``` | ||
| 1783 | |||
| 1784 | </YueDisplay> | ||
| 1785 | |||
| 1786 | ## Perform Update | 886 | ## Perform Update |
| 1787 | 887 | ||
| 1788 | You can perform update assignment with many binary operators. | 888 | You can perform update assignment with many binary operators. |
| @@ -1798,21 +898,6 @@ s ..= "world" -- will add a new local if local variable is not exist | |||
| 1798 | arg or= "default value" | 898 | arg or= "default value" |
| 1799 | ``` | 899 | ``` |
| 1800 | 900 | ||
| 1801 | <YueDisplay> | ||
| 1802 | |||
| 1803 | ```yue | ||
| 1804 | x = 1 | ||
| 1805 | x += 1 | ||
| 1806 | x -= 1 | ||
| 1807 | x *= 10 | ||
| 1808 | x /= 10 | ||
| 1809 | x %= 10 | ||
| 1810 | s ..= "world" -- will add a new local if local variable is not exist | ||
| 1811 | arg or= "default value" | ||
| 1812 | ``` | ||
| 1813 | |||
| 1814 | </YueDisplay> | ||
| 1815 | |||
| 1816 | ## Chaining Assignment | 901 | ## Chaining Assignment |
| 1817 | 902 | ||
| 1818 | You can do chaining assignment to assign multiple items to hold the same value. | 903 | You can do chaining assignment to assign multiple items to hold the same value. |
| @@ -1822,15 +907,6 @@ a = b = c = d = e = 0 | |||
| 1822 | x = y = z = f! | 907 | x = y = z = f! |
| 1823 | ``` | 908 | ``` |
| 1824 | 909 | ||
| 1825 | <YueDisplay> | ||
| 1826 | |||
| 1827 | ```yue | ||
| 1828 | a = b = c = d = e = 0 | ||
| 1829 | x = y = z = f! | ||
| 1830 | ``` | ||
| 1831 | |||
| 1832 | </YueDisplay> | ||
| 1833 | |||
| 1834 | ## Explicit Locals | 910 | ## Explicit Locals |
| 1835 | 911 | ||
| 1836 | ```yuescript | 912 | ```yuescript |
| @@ -1850,27 +926,6 @@ do | |||
| 1850 | B = 2 | 926 | B = 2 |
| 1851 | ``` | 927 | ``` |
| 1852 | 928 | ||
| 1853 | <YueDisplay> | ||
| 1854 | |||
| 1855 | ```yue | ||
| 1856 | do | ||
| 1857 | local a = 1 | ||
| 1858 | local * | ||
| 1859 | print "forward declare all variables as locals" | ||
| 1860 | x = -> 1 + y + z | ||
| 1861 | y, z = 2, 3 | ||
| 1862 | global instance = Item\new! | ||
| 1863 | |||
| 1864 | do | ||
| 1865 | local X = 1 | ||
| 1866 | local ^ | ||
| 1867 | print "only forward declare upper case variables" | ||
| 1868 | a = 1 | ||
| 1869 | B = 2 | ||
| 1870 | ``` | ||
| 1871 | |||
| 1872 | </YueDisplay> | ||
| 1873 | |||
| 1874 | ## Explicit Globals | 929 | ## Explicit Globals |
| 1875 | 930 | ||
| 1876 | ```yuescript | 931 | ```yuescript |
| @@ -1890,27 +945,6 @@ do | |||
| 1890 | local Temp = "a local value" | 945 | local Temp = "a local value" |
| 1891 | ``` | 946 | ``` |
| 1892 | 947 | ||
| 1893 | <YueDisplay> | ||
| 1894 | |||
| 1895 | ```yue | ||
| 1896 | do | ||
| 1897 | global a = 1 | ||
| 1898 | global * | ||
| 1899 | print "declare all variables as globals" | ||
| 1900 | x = -> 1 + y + z | ||
| 1901 | y, z = 2, 3 | ||
| 1902 | |||
| 1903 | do | ||
| 1904 | global X = 1 | ||
| 1905 | global ^ | ||
| 1906 | print "only declare upper case variables as globals" | ||
| 1907 | a = 1 | ||
| 1908 | B = 2 | ||
| 1909 | local Temp = "a local value" | ||
| 1910 | ``` | ||
| 1911 | |||
| 1912 | </YueDisplay> | ||
| 1913 | |||
| 1914 | # Varargs Assignment | 948 | # Varargs Assignment |
| 1915 | 949 | ||
| 1916 | You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. | 950 | You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. |
| @@ -1924,19 +958,6 @@ first = select 1, ... | |||
| 1924 | print ok, count, first | 958 | print ok, count, first |
| 1925 | ``` | 959 | ``` |
| 1926 | 960 | ||
| 1927 | <YueDisplay> | ||
| 1928 | |||
| 1929 | ```yue | ||
| 1930 | list = [1, 2, 3, 4, 5] | ||
| 1931 | fn = (ok) -> ok, table.unpack list | ||
| 1932 | ok, ... = fn true | ||
| 1933 | count = select '#', ... | ||
| 1934 | first = select 1, ... | ||
| 1935 | print ok, count, first | ||
| 1936 | ``` | ||
| 1937 | |||
| 1938 | </YueDisplay> | ||
| 1939 | |||
| 1940 | # If Assignment | 961 | # If Assignment |
| 1941 | 962 | ||
| 1942 | `if` and `elseif` blocks can take an assignment in place of a conditional expression. Upon evaluating the conditional, the assignment will take place and the value that was assigned to will be used as the conditional expression. The assigned variable is only in scope for the body of the conditional, meaning it is never available if the value is not truthy. And you have to use "the walrus operator" `:=` instead of `=` to do assignment. | 963 | `if` and `elseif` blocks can take an assignment in place of a conditional expression. Upon evaluating the conditional, the assignment will take place and the value that was assigned to will be used as the conditional expression. The assigned variable is only in scope for the body of the conditional, meaning it is never available if the value is not truthy. And you have to use "the walrus operator" `:=` instead of `=` to do assignment. |
| @@ -1946,15 +967,6 @@ if user := database.find_user "moon" | |||
| 1946 | print user.name | 967 | print user.name |
| 1947 | ``` | 968 | ``` |
| 1948 | 969 | ||
| 1949 | <YueDisplay> | ||
| 1950 | |||
| 1951 | ```yue | ||
| 1952 | if user := database.find_user "moon" | ||
| 1953 | print user.name | ||
| 1954 | ``` | ||
| 1955 | |||
| 1956 | </YueDisplay> | ||
| 1957 | |||
| 1958 | ```yuescript | 970 | ```yuescript |
| 1959 | if hello := os.getenv "hello" | 971 | if hello := os.getenv "hello" |
| 1960 | print "You have hello", hello | 972 | print "You have hello", hello |
| @@ -1964,19 +976,6 @@ else | |||
| 1964 | print "nothing :(" | 976 | print "nothing :(" |
| 1965 | ``` | 977 | ``` |
| 1966 | 978 | ||
| 1967 | <YueDisplay> | ||
| 1968 | |||
| 1969 | ```yue | ||
| 1970 | if hello := os.getenv "hello" | ||
| 1971 | print "You have hello", hello | ||
| 1972 | elseif world := os.getenv "world" | ||
| 1973 | print "you have world", world | ||
| 1974 | else | ||
| 1975 | print "nothing :(" | ||
| 1976 | ``` | ||
| 1977 | |||
| 1978 | </YueDisplay> | ||
| 1979 | |||
| 1980 | If assignment with multiple return values. Only the first value is getting checked, other values are scoped. | 979 | If assignment with multiple return values. Only the first value is getting checked, other values are scoped. |
| 1981 | 980 | ||
| 1982 | ```yuescript | 981 | ```yuescript |
| @@ -1985,16 +984,6 @@ if success, result := pcall -> "get result without problems" | |||
| 1985 | print "OK" | 984 | print "OK" |
| 1986 | ``` | 985 | ``` |
| 1987 | 986 | ||
| 1988 | <YueDisplay> | ||
| 1989 | |||
| 1990 | ```yue | ||
| 1991 | if success, result := pcall -> "get result without problems" | ||
| 1992 | print result -- variable result is scoped | ||
| 1993 | print "OK" | ||
| 1994 | ``` | ||
| 1995 | |||
| 1996 | </YueDisplay> | ||
| 1997 | |||
| 1998 | ## While Assignment | 987 | ## While Assignment |
| 1999 | 988 | ||
| 2000 | You can also use if assignment in a while loop to get the value as the loop condition. | 989 | You can also use if assignment in a while loop to get the value as the loop condition. |
| @@ -2005,16 +994,6 @@ while byte := stream\read_one! | |||
| 2005 | print byte | 994 | print byte |
| 2006 | ``` | 995 | ``` |
| 2007 | 996 | ||
| 2008 | <YueDisplay> | ||
| 2009 | |||
| 2010 | ```yue | ||
| 2011 | while byte := stream\read_one! | ||
| 2012 | -- do something with the byte | ||
| 2013 | print byte | ||
| 2014 | ``` | ||
| 2015 | |||
| 2016 | </YueDisplay> | ||
| 2017 | |||
| 2018 | # Destructuring Assignment | 997 | # Destructuring Assignment |
| 2019 | 998 | ||
| 2020 | Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. | 999 | Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. |
| @@ -2030,17 +1009,6 @@ thing = [1, 2] | |||
| 2030 | print a, b | 1009 | print a, b |
| 2031 | ``` | 1010 | ``` |
| 2032 | 1011 | ||
| 2033 | <YueDisplay> | ||
| 2034 | |||
| 2035 | ```yue | ||
| 2036 | thing = [1, 2] | ||
| 2037 | |||
| 2038 | [a, b] = thing | ||
| 2039 | print a, b | ||
| 2040 | ``` | ||
| 2041 | |||
| 2042 | </YueDisplay> | ||
| 2043 | |||
| 2044 | In the destructuring table literal, the key represents the key to read from the right hand side, and the value represents the name the read value will be assigned to. | 1012 | In the destructuring table literal, the key represents the key to read from the right hand side, and the value represents the name the read value will be assigned to. |
| 2045 | 1013 | ||
| 2046 | ```yuescript | 1014 | ```yuescript |
| @@ -2056,23 +1024,6 @@ print hello, the_day | |||
| 2056 | :day = obj -- OK to do simple destructuring without braces | 1024 | :day = obj -- OK to do simple destructuring without braces |
| 2057 | ``` | 1025 | ``` |
| 2058 | 1026 | ||
| 2059 | <YueDisplay> | ||
| 2060 | |||
| 2061 | ```yue | ||
| 2062 | obj = { | ||
| 2063 | hello: "world" | ||
| 2064 | day: "tuesday" | ||
| 2065 | length: 20 | ||
| 2066 | } | ||
| 2067 | |||
| 2068 | {hello: hello, day: the_day} = obj | ||
| 2069 | print hello, the_day | ||
| 2070 | |||
| 2071 | :day = obj -- OK to do simple destructuring without braces | ||
| 2072 | ``` | ||
| 2073 | |||
| 2074 | </YueDisplay> | ||
| 2075 | |||
| 2076 | This also works with nested data structures as well: | 1027 | This also works with nested data structures as well: |
| 2077 | 1028 | ||
| 2078 | ```yuescript | 1029 | ```yuescript |
| @@ -2088,23 +1039,6 @@ obj2 = { | |||
| 2088 | print first, second, color | 1039 | print first, second, color |
| 2089 | ``` | 1040 | ``` |
| 2090 | 1041 | ||
| 2091 | <YueDisplay> | ||
| 2092 | |||
| 2093 | ```yue | ||
| 2094 | obj2 = { | ||
| 2095 | numbers: [1, 2, 3, 4] | ||
| 2096 | properties: { | ||
| 2097 | color: "green" | ||
| 2098 | height: 13.5 | ||
| 2099 | } | ||
| 2100 | } | ||
| 2101 | |||
| 2102 | {numbers: [first, second], properties: {color: color}} = obj2 | ||
| 2103 | print first, second, color | ||
| 2104 | ``` | ||
| 2105 | |||
| 2106 | </YueDisplay> | ||
| 2107 | |||
| 2108 | If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: | 1042 | If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: |
| 2109 | 1043 | ||
| 2110 | ```yuescript | 1044 | ```yuescript |
| @@ -2116,75 +1050,30 @@ If the destructuring statement is complicated, feel free to spread it out over a | |||
| 2116 | } = obj2 | 1050 | } = obj2 |
| 2117 | ``` | 1051 | ``` |
| 2118 | 1052 | ||
| 2119 | <YueDisplay> | ||
| 2120 | |||
| 2121 | ```yue | ||
| 2122 | { | ||
| 2123 | numbers: [first, second] | ||
| 2124 | properties: { | ||
| 2125 | color: color | ||
| 2126 | } | ||
| 2127 | } = obj2 | ||
| 2128 | ``` | ||
| 2129 | |||
| 2130 | </YueDisplay> | ||
| 2131 | |||
| 2132 | It's common to extract values from at table and assign them the local variables that have the same name as the key. In order to avoid repetition we can use the **:** prefix operator: | 1053 | It's common to extract values from at table and assign them the local variables that have the same name as the key. In order to avoid repetition we can use the **:** prefix operator: |
| 2133 | 1054 | ||
| 2134 | ```yuescript | 1055 | ```yuescript |
| 2135 | {:concat, :insert} = table | 1056 | {:concat, :insert} = table |
| 2136 | ``` | 1057 | ``` |
| 2137 | 1058 | ||
| 2138 | <YueDisplay> | ||
| 2139 | |||
| 2140 | ```yue | ||
| 2141 | {:concat, :insert} = table | ||
| 2142 | ``` | ||
| 2143 | |||
| 2144 | </YueDisplay> | ||
| 2145 | |||
| 2146 | This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: | 1059 | This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: |
| 2147 | 1060 | ||
| 2148 | ```yuescript | 1061 | ```yuescript |
| 2149 | {:mix, :max, random: rand} = math | 1062 | {:mix, :max, random: rand} = math |
| 2150 | ``` | 1063 | ``` |
| 2151 | 1064 | ||
| 2152 | <YueDisplay> | ||
| 2153 | |||
| 2154 | ```yue | ||
| 2155 | {:mix, :max, random: rand} = math | ||
| 2156 | ``` | ||
| 2157 | |||
| 2158 | </YueDisplay> | ||
| 2159 | |||
| 2160 | You can write default values while doing destructuring like: | 1065 | You can write default values while doing destructuring like: |
| 2161 | 1066 | ||
| 2162 | ```yuescript | 1067 | ```yuescript |
| 2163 | {:name = "nameless", :job = "jobless"} = person | 1068 | {:name = "nameless", :job = "jobless"} = person |
| 2164 | ``` | 1069 | ``` |
| 2165 | 1070 | ||
| 2166 | <YueDisplay> | ||
| 2167 | |||
| 2168 | ```yue | ||
| 2169 | {:name = "nameless", :job = "jobless"} = person | ||
| 2170 | ``` | ||
| 2171 | |||
| 2172 | </YueDisplay> | ||
| 2173 | |||
| 2174 | You can use `_` as placeholder when doing a list destructuring: | 1071 | You can use `_` as placeholder when doing a list destructuring: |
| 2175 | 1072 | ||
| 2176 | ```yuescript | 1073 | ```yuescript |
| 2177 | [_, two, _, four] = items | 1074 | [_, two, _, four] = items |
| 2178 | ``` | 1075 | ``` |
| 2179 | 1076 | ||
| 2180 | <YueDisplay> | ||
| 2181 | |||
| 2182 | ```yue | ||
| 2183 | [_, two, _, four] = items | ||
| 2184 | ``` | ||
| 2185 | |||
| 2186 | </YueDisplay> | ||
| 2187 | |||
| 2188 | ## Range Destructuring | 1077 | ## Range Destructuring |
| 2189 | 1078 | ||
| 2190 | You can use the spread operator `...` in list destructuring to capture a range of values. This is useful when you want to extract specific elements from the beginning and end of a list while collecting the rest in between. | 1079 | You can use the spread operator `...` in list destructuring to capture a range of values. This is useful when you want to extract specific elements from the beginning and end of a list while collecting the rest in between. |
| @@ -2197,18 +1086,6 @@ print bulk -- prints: {"second", "third", "fourth"} | |||
| 2197 | print last -- prints: last | 1086 | print last -- prints: last |
| 2198 | ``` | 1087 | ``` |
| 2199 | 1088 | ||
| 2200 | <YueDisplay> | ||
| 2201 | |||
| 2202 | ```yue | ||
| 2203 | orders = ["first", "second", "third", "fourth", "last"] | ||
| 2204 | [first, ...bulk, last] = orders | ||
| 2205 | print first -- prints: first | ||
| 2206 | print bulk -- prints: {"second", "third", "fourth"} | ||
| 2207 | print last -- prints: last | ||
| 2208 | ``` | ||
| 2209 | |||
| 2210 | </YueDisplay> | ||
| 2211 | |||
| 2212 | The spread operator can be used in different positions to capture different ranges, and you can use `_` as a placeholder for the values you don't want to capture: | 1089 | The spread operator can be used in different positions to capture different ranges, and you can use `_` as a placeholder for the values you don't want to capture: |
| 2213 | 1090 | ||
| 2214 | ```yuescript | 1091 | ```yuescript |
| @@ -2222,21 +1099,6 @@ The spread operator can be used in different positions to capture different rang | |||
| 2222 | [first, ..._, last] = orders | 1099 | [first, ..._, last] = orders |
| 2223 | ``` | 1100 | ``` |
| 2224 | 1101 | ||
| 2225 | <YueDisplay> | ||
| 2226 | |||
| 2227 | ```yue | ||
| 2228 | -- Capture everything after first element | ||
| 2229 | [first, ...rest] = orders | ||
| 2230 | |||
| 2231 | -- Capture everything before last element | ||
| 2232 | [...start, last] = orders | ||
| 2233 | |||
| 2234 | -- Capture things except the middle elements | ||
| 2235 | [first, ..._, last] = orders | ||
| 2236 | ``` | ||
| 2237 | |||
| 2238 | </YueDisplay> | ||
| 2239 | |||
| 2240 | ## Destructuring In Other Places | 1102 | ## Destructuring In Other Places |
| 2241 | 1103 | ||
| 2242 | Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: | 1104 | Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: |
| @@ -2251,20 +1113,6 @@ for [left, right] in *tuples | |||
| 2251 | print left, right | 1113 | print left, right |
| 2252 | ``` | 1114 | ``` |
| 2253 | 1115 | ||
| 2254 | <YueDisplay> | ||
| 2255 | |||
| 2256 | ```yue | ||
| 2257 | tuples = [ | ||
| 2258 | ["hello", "world"] | ||
| 2259 | ["egg", "head"] | ||
| 2260 | ] | ||
| 2261 | |||
| 2262 | for [left, right] in *tuples | ||
| 2263 | print left, right | ||
| 2264 | ``` | ||
| 2265 | |||
| 2266 | </YueDisplay> | ||
| 2267 | |||
| 2268 | We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure. | 1116 | We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure. |
| 2269 | 1117 | ||
| 2270 | # The Using Clause; Controlling Destructive Assignment | 1118 | # The Using Clause; Controlling Destructive Assignment |
| @@ -2287,26 +1135,6 @@ my_func! | |||
| 2287 | print i -- will print 0 | 1135 | print i -- will print 0 |
| 2288 | ``` | 1136 | ``` |
| 2289 | 1137 | ||
| 2290 | <YueDisplay> | ||
| 2291 | |||
| 2292 | ```yue | ||
| 2293 | i = 100 | ||
| 2294 | |||
| 2295 | -- many lines of code... | ||
| 2296 | |||
| 2297 | my_func = -> | ||
| 2298 | i = 10 | ||
| 2299 | while i > 0 | ||
| 2300 | print i | ||
| 2301 | i -= 1 | ||
| 2302 | |||
| 2303 | my_func! | ||
| 2304 | |||
| 2305 | print i -- will print 0 | ||
| 2306 | ``` | ||
| 2307 | |||
| 2308 | </YueDisplay> | ||
| 2309 | |||
| 2310 | In my_func, we've overwritten the value of i mistakenly. In this example it is quite obvious, but consider a large, or foreign code base where it isn't clear what names have already been declared. | 1138 | In my_func, we've overwritten the value of i mistakenly. In this example it is quite obvious, but consider a large, or foreign code base where it isn't clear what names have already been declared. |
| 2311 | 1139 | ||
| 2312 | It would be helpful to say which variables from the enclosing scope we intend on change, in order to prevent us from changing others by accident. | 1140 | It would be helpful to say which variables from the enclosing scope we intend on change, in order to prevent us from changing others by accident. |
| @@ -2323,20 +1151,6 @@ my_func! | |||
| 2323 | print i -- prints 100, i is unaffected | 1151 | print i -- prints 100, i is unaffected |
| 2324 | ``` | 1152 | ``` |
| 2325 | 1153 | ||
| 2326 | <YueDisplay> | ||
| 2327 | |||
| 2328 | ```yue | ||
| 2329 | i = 100 | ||
| 2330 | |||
| 2331 | my_func = (using nil) -> | ||
| 2332 | i = "hello" -- a new local variable is created here | ||
| 2333 | |||
| 2334 | my_func! | ||
| 2335 | print i -- prints 100, i is unaffected | ||
| 2336 | ``` | ||
| 2337 | |||
| 2338 | </YueDisplay> | ||
| 2339 | |||
| 2340 | Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: | 1154 | Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: |
| 2341 | 1155 | ||
| 2342 | ```yuescript | 1156 | ```yuescript |
| @@ -2352,23 +1166,6 @@ my_func(22) | |||
| 2352 | print i, k -- these have been updated | 1166 | print i, k -- these have been updated |
| 2353 | ``` | 1167 | ``` |
| 2354 | 1168 | ||
| 2355 | <YueDisplay> | ||
| 2356 | |||
| 2357 | ```yue | ||
| 2358 | tmp = 1213 | ||
| 2359 | i, k = 100, 50 | ||
| 2360 | |||
| 2361 | my_func = (add using k, i) -> | ||
| 2362 | tmp = tmp + add -- a new local tmp is created | ||
| 2363 | i += tmp | ||
| 2364 | k += tmp | ||
| 2365 | |||
| 2366 | my_func(22) | ||
| 2367 | print i, k -- these have been updated | ||
| 2368 | ``` | ||
| 2369 | |||
| 2370 | </YueDisplay> | ||
| 2371 | |||
| 2372 | # Usage | 1169 | # Usage |
| 2373 | 1170 | ||
| 2374 | ## Lua Module | 1171 | ## Lua Module |
| @@ -2537,55 +1334,6 @@ with apple | |||
| 2537 | export 🌛 = "Script of Moon" | 1334 | export 🌛 = "Script of Moon" |
| 2538 | ``` | 1335 | ``` |
| 2539 | 1336 | ||
| 2540 | <YueDisplay> | ||
| 2541 | |||
| 2542 | ```yue | ||
| 2543 | -- import syntax | ||
| 2544 | import p, to_lua from "yue" | ||
| 2545 | |||
| 2546 | -- object literals | ||
| 2547 | inventory = | ||
| 2548 | equipment: | ||
| 2549 | - "sword" | ||
| 2550 | - "shield" | ||
| 2551 | items: | ||
| 2552 | - name: "potion" | ||
| 2553 | count: 10 | ||
| 2554 | - name: "bread" | ||
| 2555 | count: 3 | ||
| 2556 | |||
| 2557 | -- list comprehension | ||
| 2558 | map = (arr, action) -> | ||
| 2559 | [action item for item in *arr] | ||
| 2560 | |||
| 2561 | filter = (arr, cond) -> | ||
| 2562 | [item for item in *arr when cond item] | ||
| 2563 | |||
| 2564 | reduce = (arr, init, action): init -> | ||
| 2565 | init = action init, item for item in *arr | ||
| 2566 | |||
| 2567 | -- pipe operator | ||
| 2568 | [1, 2, 3] | ||
| 2569 | |> map (x) -> x * 2 | ||
| 2570 | |> filter (x) -> x > 4 | ||
| 2571 | |> reduce 0, (a, b) -> a + b | ||
| 2572 | |||
| 2573 | |||
| 2574 | -- metatable manipulation | ||
| 2575 | apple = | ||
| 2576 | size: 15 | ||
| 2577 | <index>: | ||
| 2578 | color: 0x00ffff | ||
| 2579 | |||
| 2580 | with apple | ||
| 2581 | p .size, .color, .<index> if .<>? | ||
| 2582 | |||
| 2583 | -- js-like export syntax | ||
| 2584 | export 🌛 = "Script of Moon" | ||
| 2585 | ``` | ||
| 2586 | |||
| 2587 | </YueDisplay> | ||
| 2588 | |||
| 2589 | ## About Dora SSR | 1337 | ## About Dora SSR |
| 2590 | 1338 | ||
| 2591 | YueScript is being developed and maintained alongside the open-source game engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). It has been used to create engine tools, game demos and prototypes, validating its capabilities in real-world scenarios while enhancing the Dora SSR development experience. | 1339 | YueScript is being developed and maintained alongside the open-source game engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). It has been used to create engine tools, game demos and prototypes, validating its capabilities in real-world scenarios while enhancing the Dora SSR development experience. |
| @@ -2644,18 +1392,6 @@ else | |||
| 2644 | print "No coins" | 1392 | print "No coins" |
| 2645 | ``` | 1393 | ``` |
| 2646 | 1394 | ||
| 2647 | <YueDisplay> | ||
| 2648 | |||
| 2649 | ```yue | ||
| 2650 | have_coins = false | ||
| 2651 | if have_coins | ||
| 2652 | print "Got coins" | ||
| 2653 | else | ||
| 2654 | print "No coins" | ||
| 2655 | ``` | ||
| 2656 | |||
| 2657 | </YueDisplay> | ||
| 2658 | |||
| 2659 | A short syntax for single statements can also be used: | 1395 | A short syntax for single statements can also be used: |
| 2660 | 1396 | ||
| 2661 | ```yuescript | 1397 | ```yuescript |
| @@ -2663,15 +1399,6 @@ have_coins = false | |||
| 2663 | if have_coins then print "Got coins" else print "No coins" | 1399 | if have_coins then print "Got coins" else print "No coins" |
| 2664 | ``` | 1400 | ``` |
| 2665 | 1401 | ||
| 2666 | <YueDisplay> | ||
| 2667 | |||
| 2668 | ```yue | ||
| 2669 | have_coins = false | ||
| 2670 | if have_coins then print "Got coins" else print "No coins" | ||
| 2671 | ``` | ||
| 2672 | |||
| 2673 | </YueDisplay> | ||
| 2674 | |||
| 2675 | Because if statements can be used as expressions, this can also be written as: | 1402 | Because if statements can be used as expressions, this can also be written as: |
| 2676 | 1403 | ||
| 2677 | ```yuescript | 1404 | ```yuescript |
| @@ -2679,15 +1406,6 @@ have_coins = false | |||
| 2679 | print if have_coins then "Got coins" else "No coins" | 1406 | print if have_coins then "Got coins" else "No coins" |
| 2680 | ``` | 1407 | ``` |
| 2681 | 1408 | ||
| 2682 | <YueDisplay> | ||
| 2683 | |||
| 2684 | ```yue | ||
| 2685 | have_coins = false | ||
| 2686 | print if have_coins then "Got coins" else "No coins" | ||
| 2687 | ``` | ||
| 2688 | |||
| 2689 | </YueDisplay> | ||
| 2690 | |||
| 2691 | Conditionals can also be used in return statements and assignments: | 1409 | Conditionals can also be used in return statements and assignments: |
| 2692 | 1410 | ||
| 2693 | ```yuescript | 1411 | ```yuescript |
| @@ -2705,25 +1423,6 @@ else | |||
| 2705 | print message -- prints: I am very tall | 1423 | print message -- prints: I am very tall |
| 2706 | ``` | 1424 | ``` |
| 2707 | 1425 | ||
| 2708 | <YueDisplay> | ||
| 2709 | |||
| 2710 | ```yue | ||
| 2711 | is_tall = (name) -> | ||
| 2712 | if name == "Rob" | ||
| 2713 | true | ||
| 2714 | else | ||
| 2715 | false | ||
| 2716 | |||
| 2717 | message = if is_tall "Rob" | ||
| 2718 | "I am very tall" | ||
| 2719 | else | ||
| 2720 | "I am not so tall" | ||
| 2721 | |||
| 2722 | print message -- prints: I am very tall | ||
| 2723 | ``` | ||
| 2724 | |||
| 2725 | </YueDisplay> | ||
| 2726 | |||
| 2727 | The opposite of if is unless: | 1426 | The opposite of if is unless: |
| 2728 | 1427 | ||
| 2729 | ```yuescript | 1428 | ```yuescript |
| @@ -2731,27 +1430,10 @@ unless os.date("%A") == "Monday" | |||
| 2731 | print "it is not Monday!" | 1430 | print "it is not Monday!" |
| 2732 | ``` | 1431 | ``` |
| 2733 | 1432 | ||
| 2734 | <YueDisplay> | ||
| 2735 | |||
| 2736 | ```yue | ||
| 2737 | unless os.date("%A") == "Monday" | ||
| 2738 | print "it is not Monday!" | ||
| 2739 | ``` | ||
| 2740 | |||
| 2741 | </YueDisplay> | ||
| 2742 | |||
| 2743 | ```yuescript | 1433 | ```yuescript |
| 2744 | print "You're lucky!" unless math.random! > 0.1 | 1434 | print "You're lucky!" unless math.random! > 0.1 |
| 2745 | ``` | 1435 | ``` |
| 2746 | 1436 | ||
| 2747 | <YueDisplay> | ||
| 2748 | |||
| 2749 | ```yue | ||
| 2750 | print "You're lucky!" unless math.random! > 0.1 | ||
| 2751 | ``` | ||
| 2752 | |||
| 2753 | </YueDisplay> | ||
| 2754 | |||
| 2755 | ## In Expression | 1437 | ## In Expression |
| 2756 | 1438 | ||
| 2757 | You can write range checking code with an `in-expression`. | 1439 | You can write range checking code with an `in-expression`. |
| @@ -2766,20 +1448,6 @@ if a in list | |||
| 2766 | print "checking if `a` is in a list" | 1448 | print "checking if `a` is in a list" |
| 2767 | ``` | 1449 | ``` |
| 2768 | 1450 | ||
| 2769 | <YueDisplay> | ||
| 2770 | |||
| 2771 | ```yue | ||
| 2772 | a = 5 | ||
| 2773 | |||
| 2774 | if a in [1, 3, 5, 7] | ||
| 2775 | print "checking equality with discrete values" | ||
| 2776 | |||
| 2777 | if a in list | ||
| 2778 | print "checking if `a` is in a list" | ||
| 2779 | ``` | ||
| 2780 | |||
| 2781 | </YueDisplay> | ||
| 2782 | |||
| 2783 | The `in` operator can also be used with tables and supports the `not in` variant for negation: | 1451 | The `in` operator can also be used with tables and supports the `not in` variant for negation: |
| 2784 | 1452 | ||
| 2785 | ```yuescript | 1453 | ```yuescript |
| @@ -2793,21 +1461,6 @@ not_exist = item not in list | |||
| 2793 | check = -> value not in table | 1461 | check = -> value not in table |
| 2794 | ``` | 1462 | ``` |
| 2795 | 1463 | ||
| 2796 | <YueDisplay> | ||
| 2797 | |||
| 2798 | ```yue | ||
| 2799 | has = "foo" in {"bar", "foo"} | ||
| 2800 | |||
| 2801 | if a in {1, 2, 3} | ||
| 2802 | print "a is in the table" | ||
| 2803 | |||
| 2804 | not_exist = item not in list | ||
| 2805 | |||
| 2806 | check = -> value not in table | ||
| 2807 | ``` | ||
| 2808 | |||
| 2809 | </YueDisplay> | ||
| 2810 | |||
| 2811 | A single-element list or table checks for equality with that element: | 1464 | A single-element list or table checks for equality with that element: |
| 2812 | 1465 | ||
| 2813 | ```yuescript | 1466 | ```yuescript |
| @@ -2822,22 +1475,6 @@ with tb | |||
| 2822 | c = a in [1] | 1475 | c = a in [1] |
| 2823 | ``` | 1476 | ``` |
| 2824 | 1477 | ||
| 2825 | <YueDisplay> | ||
| 2826 | |||
| 2827 | ```yue | ||
| 2828 | -- [1,] checks if value == 1 | ||
| 2829 | c = a in [1,] | ||
| 2830 | |||
| 2831 | -- {1} also checks if value == 1 | ||
| 2832 | c = a in {1} | ||
| 2833 | |||
| 2834 | -- Without comma, [1] is indexing (tb[1]) | ||
| 2835 | with tb | ||
| 2836 | c = a in [1] | ||
| 2837 | ``` | ||
| 2838 | |||
| 2839 | </YueDisplay> | ||
| 2840 | |||
| 2841 | # For Loop | 1478 | # For Loop |
| 2842 | 1479 | ||
| 2843 | There are two for loop forms, just like in Lua. A numeric one and a generic one: | 1480 | There are two for loop forms, just like in Lua. A numeric one and a generic one: |
| @@ -2853,21 +1490,6 @@ for key, value in pairs object | |||
| 2853 | print key, value | 1490 | print key, value |
| 2854 | ``` | 1491 | ``` |
| 2855 | 1492 | ||
| 2856 | <YueDisplay> | ||
| 2857 | |||
| 2858 | ```yue | ||
| 2859 | for i = 10, 20 | ||
| 2860 | print i | ||
| 2861 | |||
| 2862 | for k = 1, 15, 2 -- an optional step provided | ||
| 2863 | print k | ||
| 2864 | |||
| 2865 | for key, value in pairs object | ||
| 2866 | print key, value | ||
| 2867 | ``` | ||
| 2868 | |||
| 2869 | </YueDisplay> | ||
| 2870 | |||
| 2871 | The slicing and **\*** operators can be used, just like with comprehensions: | 1493 | The slicing and **\*** operators can be used, just like with comprehensions: |
| 2872 | 1494 | ||
| 2873 | ```yuescript | 1495 | ```yuescript |
| @@ -2875,15 +1497,6 @@ for item in *items[2, 4] | |||
| 2875 | print item | 1497 | print item |
| 2876 | ``` | 1498 | ``` |
| 2877 | 1499 | ||
| 2878 | <YueDisplay> | ||
| 2879 | |||
| 2880 | ```yue | ||
| 2881 | for item in *items[2, 4] | ||
| 2882 | print item | ||
| 2883 | ``` | ||
| 2884 | |||
| 2885 | </YueDisplay> | ||
| 2886 | |||
| 2887 | A shorter syntax is also available for all variations when the body is only a single line: | 1500 | A shorter syntax is also available for all variations when the body is only a single line: |
| 2888 | 1501 | ||
| 2889 | ```yuescript | 1502 | ```yuescript |
| @@ -2892,16 +1505,6 @@ for item in *items do print item | |||
| 2892 | for j = 1, 10, 3 do print j | 1505 | for j = 1, 10, 3 do print j |
| 2893 | ``` | 1506 | ``` |
| 2894 | 1507 | ||
| 2895 | <YueDisplay> | ||
| 2896 | |||
| 2897 | ```yue | ||
| 2898 | for item in *items do print item | ||
| 2899 | |||
| 2900 | for j = 1, 10, 3 do print j | ||
| 2901 | ``` | ||
| 2902 | |||
| 2903 | </YueDisplay> | ||
| 2904 | |||
| 2905 | A for loop can also be used as an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating array table. | 1508 | A for loop can also be used as an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating array table. |
| 2906 | 1509 | ||
| 2907 | Doubling every even number: | 1510 | Doubling every even number: |
| @@ -2914,18 +1517,6 @@ doubled_evens = for i = 1, 20 | |||
| 2914 | i | 1517 | i |
| 2915 | ``` | 1518 | ``` |
| 2916 | 1519 | ||
| 2917 | <YueDisplay> | ||
| 2918 | |||
| 2919 | ```yue | ||
| 2920 | doubled_evens = for i = 1, 20 | ||
| 2921 | if i % 2 == 0 | ||
| 2922 | i * 2 | ||
| 2923 | else | ||
| 2924 | i | ||
| 2925 | ``` | ||
| 2926 | |||
| 2927 | </YueDisplay> | ||
| 2928 | |||
| 2929 | In addition, for loops support break with return values, allowing the loop itself to be used as an expression that exits early with meaningful results. | 1520 | In addition, for loops support break with return values, allowing the loop itself to be used as an expression that exits early with meaningful results. |
| 2930 | 1521 | ||
| 2931 | For example, to find the first number greater than 10: | 1522 | For example, to find the first number greater than 10: |
| @@ -2935,15 +1526,6 @@ first_large = for n in *numbers | |||
| 2935 | break n if n > 10 | 1526 | break n if n > 10 |
| 2936 | ``` | 1527 | ``` |
| 2937 | 1528 | ||
| 2938 | <YueDisplay> | ||
| 2939 | |||
| 2940 | ```yue | ||
| 2941 | first_large = for n in *numbers | ||
| 2942 | break n if n > 10 | ||
| 2943 | ``` | ||
| 2944 | |||
| 2945 | </YueDisplay> | ||
| 2946 | |||
| 2947 | This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. | 1529 | This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. |
| 2948 | 1530 | ||
| 2949 | For loop expressions can break with multiple values: | 1531 | For loop expressions can break with multiple values: |
| @@ -2953,15 +1535,6 @@ key, score = for k, v in pairs data | |||
| 2953 | break k, v * 10 if k == "target" | 1535 | break k, v * 10 if k == "target" |
| 2954 | ``` | 1536 | ``` |
| 2955 | 1537 | ||
| 2956 | <YueDisplay> | ||
| 2957 | |||
| 2958 | ```yue | ||
| 2959 | key, score = for k, v in pairs data | ||
| 2960 | break k, v * 10 if k == "target" | ||
| 2961 | ``` | ||
| 2962 | |||
| 2963 | </YueDisplay> | ||
| 2964 | |||
| 2965 | You can also filter values by combining the for loop expression with the continue statement. | 1538 | You can also filter values by combining the for loop expression with the continue statement. |
| 2966 | 1539 | ||
| 2967 | For loops at the end of a function body are not accumulated into a table for a return value (Instead the function will return nil). Either an explicit return statement can be used, or the loop can be converted into a list comprehension. | 1540 | For loops at the end of a function body are not accumulated into a table for a return value (Instead the function will return nil). Either an explicit return statement can be used, or the loop can be converted into a list comprehension. |
| @@ -2974,18 +1547,6 @@ print func_a! -- prints nil | |||
| 2974 | print func_b! -- prints table object | 1547 | print func_b! -- prints table object |
| 2975 | ``` | 1548 | ``` |
| 2976 | 1549 | ||
| 2977 | <YueDisplay> | ||
| 2978 | |||
| 2979 | ```yue | ||
| 2980 | func_a = -> for i = 1, 10 do print i | ||
| 2981 | func_b = -> return for i = 1, 10 do i | ||
| 2982 | |||
| 2983 | print func_a! -- prints nil | ||
| 2984 | print func_b! -- prints table object | ||
| 2985 | ``` | ||
| 2986 | |||
| 2987 | </YueDisplay> | ||
| 2988 | |||
| 2989 | This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. | 1550 | This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. |
| 2990 | 1551 | ||
| 2991 | # Continue | 1552 | # Continue |
| @@ -3000,18 +1561,6 @@ while i < 10 | |||
| 3000 | print i | 1561 | print i |
| 3001 | ``` | 1562 | ``` |
| 3002 | 1563 | ||
| 3003 | <YueDisplay> | ||
| 3004 | |||
| 3005 | ```yue | ||
| 3006 | i = 0 | ||
| 3007 | while i < 10 | ||
| 3008 | i += 1 | ||
| 3009 | continue if i % 2 == 0 | ||
| 3010 | print i | ||
| 3011 | ``` | ||
| 3012 | |||
| 3013 | </YueDisplay> | ||
| 3014 | |||
| 3015 | continue can also be used with loop expressions to prevent that iteration from accumulating into the result. This examples filters the array table into just even numbers: | 1564 | continue can also be used with loop expressions to prevent that iteration from accumulating into the result. This examples filters the array table into just even numbers: |
| 3016 | 1565 | ||
| 3017 | ```yuescript | 1566 | ```yuescript |
| @@ -3021,17 +1570,6 @@ odds = for x in *my_numbers | |||
| 3021 | x | 1570 | x |
| 3022 | ``` | 1571 | ``` |
| 3023 | 1572 | ||
| 3024 | <YueDisplay> | ||
| 3025 | |||
| 3026 | ```yue | ||
| 3027 | my_numbers = [1, 2, 3, 4, 5, 6] | ||
| 3028 | odds = for x in *my_numbers | ||
| 3029 | continue if x % 2 == 1 | ||
| 3030 | x | ||
| 3031 | ``` | ||
| 3032 | |||
| 3033 | </YueDisplay> | ||
| 3034 | |||
| 3035 | # Switch | 1573 | # Switch |
| 3036 | 1574 | ||
| 3037 | The switch statement is shorthand for writing a series of if statements that check against the same value. Note that the value is only evaluated once. Like if statements, switches can have an else block to handle no matches. Comparison is done with the == operator. In switch statement, you can also use assignment expression to store temporary variable value. | 1575 | The switch statement is shorthand for writing a series of if statements that check against the same value. Note that the value is only evaluated once. Like if statements, switches can have an else block to handle no matches. Comparison is done with the == operator. In switch statement, you can also use assignment expression to store temporary variable value. |
| @@ -3046,20 +1584,6 @@ switch name := "Dan" | |||
| 3046 | print "I don't know about you with name #{name}" | 1584 | print "I don't know about you with name #{name}" |
| 3047 | ``` | 1585 | ``` |
| 3048 | 1586 | ||
| 3049 | <YueDisplay> | ||
| 3050 | |||
| 3051 | ```yue | ||
| 3052 | switch name := "Dan" | ||
| 3053 | when "Robert" | ||
| 3054 | print "You are Robert" | ||
| 3055 | when "Dan", "Daniel" | ||
| 3056 | print "Your name, it's Dan" | ||
| 3057 | else | ||
| 3058 | print "I don't know about you with name #{name}" | ||
| 3059 | ``` | ||
| 3060 | |||
| 3061 | </YueDisplay> | ||
| 3062 | |||
| 3063 | A switch when clause can match against multiple values by listing them out comma separated. | 1587 | A switch when clause can match against multiple values by listing them out comma separated. |
| 3064 | 1588 | ||
| 3065 | Switches can be used as expressions as well, here we can assign the result of the switch to a variable: | 1589 | Switches can be used as expressions as well, here we can assign the result of the switch to a variable: |
| @@ -3075,21 +1599,6 @@ next_number = switch b | |||
| 3075 | error "can't count that high!" | 1599 | error "can't count that high!" |
| 3076 | ``` | 1600 | ``` |
| 3077 | 1601 | ||
| 3078 | <YueDisplay> | ||
| 3079 | |||
| 3080 | ```yue | ||
| 3081 | b = 1 | ||
| 3082 | next_number = switch b | ||
| 3083 | when 1 | ||
| 3084 | 2 | ||
| 3085 | when 2 | ||
| 3086 | 3 | ||
| 3087 | else | ||
| 3088 | error "can't count that high!" | ||
| 3089 | ``` | ||
| 3090 | |||
| 3091 | </YueDisplay> | ||
| 3092 | |||
| 3093 | We can use the then keyword to write a switch's when block on a single line. No extra keyword is needed to write the else block on a single line. | 1602 | We can use the then keyword to write a switch's when block on a single line. No extra keyword is needed to write the else block on a single line. |
| 3094 | 1603 | ||
| 3095 | ```yuescript | 1604 | ```yuescript |
| @@ -3099,17 +1608,6 @@ msg = switch math.random(1, 5) | |||
| 3099 | else "not so lucky" | 1608 | else "not so lucky" |
| 3100 | ``` | 1609 | ``` |
| 3101 | 1610 | ||
| 3102 | <YueDisplay> | ||
| 3103 | |||
| 3104 | ```yue | ||
| 3105 | msg = switch math.random(1, 5) | ||
| 3106 | when 1 then "you are lucky" | ||
| 3107 | when 2 then "you are almost lucky" | ||
| 3108 | else "not so lucky" | ||
| 3109 | ``` | ||
| 3110 | |||
| 3111 | </YueDisplay> | ||
| 3112 | |||
| 3113 | If you want to write code with one less indent when writing a switch statement, you can put the first when clause on the statement start line, and then all other clauses can be written with one less indent. | 1611 | If you want to write code with one less indent when writing a switch statement, you can put the first when clause on the statement start line, and then all other clauses can be written with one less indent. |
| 3114 | 1612 | ||
| 3115 | ```yuescript | 1613 | ```yuescript |
| @@ -3125,23 +1623,6 @@ else | |||
| 3125 | print "not so lucky" | 1623 | print "not so lucky" |
| 3126 | ``` | 1624 | ``` |
| 3127 | 1625 | ||
| 3128 | <YueDisplay> | ||
| 3129 | |||
| 3130 | ```yue | ||
| 3131 | switch math.random(1, 5) | ||
| 3132 | when 1 | ||
| 3133 | print "you are lucky" -- two indents | ||
| 3134 | else | ||
| 3135 | print "not so lucky" | ||
| 3136 | |||
| 3137 | switch math.random(1, 5) when 1 | ||
| 3138 | print "you are lucky" -- one indent | ||
| 3139 | else | ||
| 3140 | print "not so lucky" | ||
| 3141 | ``` | ||
| 3142 | |||
| 3143 | </YueDisplay> | ||
| 3144 | |||
| 3145 | It is worth noting the order of the case comparison expression. The case's expression is on the left hand side. This can be useful if the case's expression wants to overwrite how the comparison is done by defining an eq metamethod. | 1626 | It is worth noting the order of the case comparison expression. The case's expression is on the left hand side. This can be useful if the case's expression wants to overwrite how the comparison is done by defining an eq metamethod. |
| 3146 | 1627 | ||
| 3147 | ## Table Matching | 1628 | ## Table Matching |
| @@ -3163,25 +1644,6 @@ for item in *items | |||
| 3163 | print "size #{width}, #{height}" | 1644 | print "size #{width}, #{height}" |
| 3164 | ``` | 1645 | ``` |
| 3165 | 1646 | ||
| 3166 | <YueDisplay> | ||
| 3167 | |||
| 3168 | ```yue | ||
| 3169 | items = | ||
| 3170 | * x: 100 | ||
| 3171 | y: 200 | ||
| 3172 | * width: 300 | ||
| 3173 | height: 400 | ||
| 3174 | |||
| 3175 | for item in *items | ||
| 3176 | switch item | ||
| 3177 | when :x, :y | ||
| 3178 | print "Vec2 #{x}, #{y}" | ||
| 3179 | when :width, :height | ||
| 3180 | print "size #{width}, #{height}" | ||
| 3181 | ``` | ||
| 3182 | |||
| 3183 | </YueDisplay> | ||
| 3184 | |||
| 3185 | You can use default values to optionally destructure the table for some fields. | 1647 | You can use default values to optionally destructure the table for some fields. |
| 3186 | 1648 | ||
| 3187 | ```yuescript | 1649 | ```yuescript |
| @@ -3194,20 +1656,6 @@ switch item | |||
| 3194 | print "Vec2 #{x}, #{y}" -- table destructuring will still pass | 1656 | print "Vec2 #{x}, #{y}" -- table destructuring will still pass |
| 3195 | ``` | 1657 | ``` |
| 3196 | 1658 | ||
| 3197 | <YueDisplay> | ||
| 3198 | |||
| 3199 | ```yue | ||
| 3200 | item = {} | ||
| 3201 | |||
| 3202 | {pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') | ||
| 3203 | |||
| 3204 | switch item | ||
| 3205 | when {pos: {:x = 50, :y = 200}} | ||
| 3206 | print "Vec2 #{x}, #{y}" -- table destructuring will still pass | ||
| 3207 | ``` | ||
| 3208 | |||
| 3209 | </YueDisplay> | ||
| 3210 | |||
| 3211 | You can also match against array elements, table fields, and even nested structures with array or table literals. | 1659 | You can also match against array elements, table fields, and even nested structures with array or table literals. |
| 3212 | 1660 | ||
| 3213 | Match against array elements. | 1661 | Match against array elements. |
| @@ -3222,20 +1670,6 @@ switch tb | |||
| 3222 | print "1, 2, #{b}" | 1670 | print "1, 2, #{b}" |
| 3223 | ``` | 1671 | ``` |
| 3224 | 1672 | ||
| 3225 | <YueDisplay> | ||
| 3226 | |||
| 3227 | ```yue | ||
| 3228 | switch tb | ||
| 3229 | when [1, 2, 3] | ||
| 3230 | print "1, 2, 3" | ||
| 3231 | when [1, b, 3] | ||
| 3232 | print "1, #{b}, 3" | ||
| 3233 | when [1, 2, b = 3] -- b has a default value | ||
| 3234 | print "1, 2, #{b}" | ||
| 3235 | ``` | ||
| 3236 | |||
| 3237 | </YueDisplay> | ||
| 3238 | |||
| 3239 | Match against table fields with destructuring. | 1673 | Match against table fields with destructuring. |
| 3240 | 1674 | ||
| 3241 | ```yuescript | 1675 | ```yuescript |
| @@ -3248,20 +1682,6 @@ switch tb | |||
| 3248 | print "invalid" | 1682 | print "invalid" |
| 3249 | ``` | 1683 | ``` |
| 3250 | 1684 | ||
| 3251 | <YueDisplay> | ||
| 3252 | |||
| 3253 | ```yue | ||
| 3254 | switch tb | ||
| 3255 | when success: true, :result | ||
| 3256 | print "success", result | ||
| 3257 | when success: false | ||
| 3258 | print "failed", result | ||
| 3259 | else | ||
| 3260 | print "invalid" | ||
| 3261 | ``` | ||
| 3262 | |||
| 3263 | </YueDisplay> | ||
| 3264 | |||
| 3265 | Match against nested table structures. | 1685 | Match against nested table structures. |
| 3266 | 1686 | ||
| 3267 | ```yuescript | 1687 | ```yuescript |
| @@ -3274,20 +1694,6 @@ switch tb | |||
| 3274 | print "invalid" | 1694 | print "invalid" |
| 3275 | ``` | 1695 | ``` |
| 3276 | 1696 | ||
| 3277 | <YueDisplay> | ||
| 3278 | |||
| 3279 | ```yue | ||
| 3280 | switch tb | ||
| 3281 | when data: {type: "success", :content} | ||
| 3282 | print "success", content | ||
| 3283 | when data: {type: "error", :content} | ||
| 3284 | print "failed", content | ||
| 3285 | else | ||
| 3286 | print "invalid" | ||
| 3287 | ``` | ||
| 3288 | |||
| 3289 | </YueDisplay> | ||
| 3290 | |||
| 3291 | Match against array of tables. | 1697 | Match against array of tables. |
| 3292 | 1698 | ||
| 3293 | ```yuescript | 1699 | ```yuescript |
| @@ -3301,21 +1707,6 @@ switch tb | |||
| 3301 | print "matched", fourth | 1707 | print "matched", fourth |
| 3302 | ``` | 1708 | ``` |
| 3303 | 1709 | ||
| 3304 | <YueDisplay> | ||
| 3305 | |||
| 3306 | ```yue | ||
| 3307 | switch tb | ||
| 3308 | when [ | ||
| 3309 | {a: 1, b: 2} | ||
| 3310 | {a: 3, b: 4} | ||
| 3311 | {a: 5, b: 6} | ||
| 3312 | fourth | ||
| 3313 | ] | ||
| 3314 | print "matched", fourth | ||
| 3315 | ``` | ||
| 3316 | |||
| 3317 | </YueDisplay> | ||
| 3318 | |||
| 3319 | Match against a list and capture a range of elements. | 1710 | Match against a list and capture a range of elements. |
| 3320 | 1711 | ||
| 3321 | ```yuescript | 1712 | ```yuescript |
| @@ -3327,19 +1718,6 @@ switch segments | |||
| 3327 | print "Action:", action -- prints: "view" | 1718 | print "Action:", action -- prints: "view" |
| 3328 | ``` | 1719 | ``` |
| 3329 | 1720 | ||
| 3330 | <YueDisplay> | ||
| 3331 | |||
| 3332 | ```yue | ||
| 3333 | segments = ["admin", "users", "logs", "view"] | ||
| 3334 | switch segments | ||
| 3335 | when [...groups, resource, action] | ||
| 3336 | print "Group:", groups -- prints: {"admin", "users"} | ||
| 3337 | print "Resource:", resource -- prints: "logs" | ||
| 3338 | print "Action:", action -- prints: "view" | ||
| 3339 | ``` | ||
| 3340 | |||
| 3341 | </YueDisplay> | ||
| 3342 | |||
| 3343 | # While Loop | 1721 | # While Loop |
| 3344 | 1722 | ||
| 3345 | The while loop also comes in four variations: | 1723 | The while loop also comes in four variations: |
| @@ -3353,19 +1731,6 @@ while i > 0 | |||
| 3353 | while running == true do my_function! | 1731 | while running == true do my_function! |
| 3354 | ``` | 1732 | ``` |
| 3355 | 1733 | ||
| 3356 | <YueDisplay> | ||
| 3357 | |||
| 3358 | ```yue | ||
| 3359 | i = 10 | ||
| 3360 | while i > 0 | ||
| 3361 | print i | ||
| 3362 | i -= 1 | ||
| 3363 | |||
| 3364 | while running == true do my_function! | ||
| 3365 | ``` | ||
| 3366 | |||
| 3367 | </YueDisplay> | ||
| 3368 | |||
| 3369 | ```yuescript | 1734 | ```yuescript |
| 3370 | i = 10 | 1735 | i = 10 |
| 3371 | until i == 0 | 1736 | until i == 0 |
| @@ -3375,18 +1740,6 @@ until i == 0 | |||
| 3375 | until running == false do my_function! | 1740 | until running == false do my_function! |
| 3376 | ``` | 1741 | ``` |
| 3377 | 1742 | ||
| 3378 | <YueDisplay> | ||
| 3379 | |||
| 3380 | ```yue | ||
| 3381 | i = 10 | ||
| 3382 | until i == 0 | ||
| 3383 | print i | ||
| 3384 | i -= 1 | ||
| 3385 | until running == false do my_function! | ||
| 3386 | ``` | ||
| 3387 | |||
| 3388 | </YueDisplay> | ||
| 3389 | |||
| 3390 | Like for loops, the while loop can also be used as an expression. While and until loop expressions support `break` with multiple return values. | 1743 | Like for loops, the while loop can also be used as an expression. While and until loop expressions support `break` with multiple return values. |
| 3391 | 1744 | ||
| 3392 | ```yuescript | 1745 | ```yuescript |
| @@ -3395,16 +1748,6 @@ value, doubled = while true | |||
| 3395 | break n, n * 2 if n > 10 | 1748 | break n, n * 2 if n > 10 |
| 3396 | ``` | 1749 | ``` |
| 3397 | 1750 | ||
| 3398 | <YueDisplay> | ||
| 3399 | |||
| 3400 | ```yue | ||
| 3401 | value, doubled = while true | ||
| 3402 | n = get_next! | ||
| 3403 | break n, n * 2 if n > 10 | ||
| 3404 | ``` | ||
| 3405 | |||
| 3406 | </YueDisplay> | ||
| 3407 | |||
| 3408 | Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. | 1751 | Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. |
| 3409 | 1752 | ||
| 3410 | ## Repeat Loop | 1753 | ## Repeat Loop |
| @@ -3419,18 +1762,6 @@ repeat | |||
| 3419 | until i == 0 | 1762 | until i == 0 |
| 3420 | ``` | 1763 | ``` |
| 3421 | 1764 | ||
| 3422 | <YueDisplay> | ||
| 3423 | |||
| 3424 | ```yue | ||
| 3425 | i = 10 | ||
| 3426 | repeat | ||
| 3427 | print i | ||
| 3428 | i -= 1 | ||
| 3429 | until i == 0 | ||
| 3430 | ``` | ||
| 3431 | |||
| 3432 | </YueDisplay> | ||
| 3433 | |||
| 3434 | Repeat loop expressions also support `break` with multiple return values: | 1765 | Repeat loop expressions also support `break` with multiple return values: |
| 3435 | 1766 | ||
| 3436 | ```yuescript | 1767 | ```yuescript |
| @@ -3441,18 +1772,6 @@ value, scaled = repeat | |||
| 3441 | until false | 1772 | until false |
| 3442 | ``` | 1773 | ``` |
| 3443 | 1774 | ||
| 3444 | <YueDisplay> | ||
| 3445 | |||
| 3446 | ```yue | ||
| 3447 | i = 1 | ||
| 3448 | value, scaled = repeat | ||
| 3449 | break i, i * 100 if i > 3 | ||
| 3450 | i += 1 | ||
| 3451 | until false | ||
| 3452 | ``` | ||
| 3453 | |||
| 3454 | </YueDisplay> | ||
| 3455 | |||
| 3456 | # Function Stubs | 1775 | # Function Stubs |
| 3457 | 1776 | ||
| 3458 | It is common to pass a function from an object around as a value, for example, passing an instance method into a function as a callback. If the function expects the object it is operating on as the first argument then you must somehow bundle that object with the function so it can be called properly. | 1777 | It is common to pass a function from an object around as a value, for example, passing an instance method into a function as a callback. If the function expects the object it is operating on as the first argument then you must somehow bundle that object with the function so it can be called properly. |
| @@ -3480,29 +1799,6 @@ run_callback my_object.write | |||
| 3480 | run_callback my_object\write | 1799 | run_callback my_object\write |
| 3481 | ``` | 1800 | ``` |
| 3482 | 1801 | ||
| 3483 | <YueDisplay> | ||
| 3484 | |||
| 3485 | ```yue | ||
| 3486 | my_object = { | ||
| 3487 | value: 1000 | ||
| 3488 | write: => print "the value:", @value | ||
| 3489 | } | ||
| 3490 | |||
| 3491 | run_callback = (func) -> | ||
| 3492 | print "running callback..." | ||
| 3493 | func! | ||
| 3494 | |||
| 3495 | -- this will not work: | ||
| 3496 | -- the function has to no reference to my_object | ||
| 3497 | run_callback my_object.write | ||
| 3498 | |||
| 3499 | -- function stub syntax | ||
| 3500 | -- lets us bundle the object into a new function | ||
| 3501 | run_callback my_object\write | ||
| 3502 | ``` | ||
| 3503 | |||
| 3504 | </YueDisplay> | ||
| 3505 | |||
| 3506 | # Backcalls | 1802 | # Backcalls |
| 3507 | 1803 | ||
| 3508 | Backcalls are used for unnesting callbacks. They are defined using arrows pointed to the left as the last parameter by default filling in a function call. All the syntax is mostly the same as regular arrow functions except that it is just pointing the other way and the function body does not require indent. | 1804 | Backcalls are used for unnesting callbacks. They are defined using arrows pointed to the left as the last parameter by default filling in a function call. All the syntax is mostly the same as regular arrow functions except that it is just pointing the other way and the function body does not require indent. |
| @@ -3512,15 +1808,6 @@ x <- f | |||
| 3512 | print "hello" .. x | 1808 | print "hello" .. x |
| 3513 | ``` | 1809 | ``` |
| 3514 | 1810 | ||
| 3515 | <YueDisplay> | ||
| 3516 | |||
| 3517 | ```yue | ||
| 3518 | x <- f | ||
| 3519 | print "hello" .. x | ||
| 3520 | ``` | ||
| 3521 | |||
| 3522 | </YueDisplay> | ||
| 3523 | |||
| 3524 | Fat arrow functions are also available. | 1811 | Fat arrow functions are also available. |
| 3525 | 1812 | ||
| 3526 | ```yuescript | 1813 | ```yuescript |
| @@ -3528,15 +1815,6 @@ Fat arrow functions are also available. | |||
| 3528 | print @value | 1815 | print @value |
| 3529 | ``` | 1816 | ``` |
| 3530 | 1817 | ||
| 3531 | <YueDisplay> | ||
| 3532 | |||
| 3533 | ```yue | ||
| 3534 | <= f | ||
| 3535 | print @value | ||
| 3536 | ``` | ||
| 3537 | |||
| 3538 | </YueDisplay> | ||
| 3539 | |||
| 3540 | You can specify a placeholder for where you want the backcall function to go as a parameter. | 1818 | You can specify a placeholder for where you want the backcall function to go as a parameter. |
| 3541 | 1819 | ||
| 3542 | ```yuescript | 1820 | ```yuescript |
| @@ -3544,15 +1822,6 @@ You can specify a placeholder for where you want the backcall function to go as | |||
| 3544 | x * 2 | 1822 | x * 2 |
| 3545 | ``` | 1823 | ``` |
| 3546 | 1824 | ||
| 3547 | <YueDisplay> | ||
| 3548 | |||
| 3549 | ```yue | ||
| 3550 | (x) <- map _, [1, 2, 3] | ||
| 3551 | x * 2 | ||
| 3552 | ``` | ||
| 3553 | |||
| 3554 | </YueDisplay> | ||
| 3555 | |||
| 3556 | If you wish to have further code after your backcalls, you can set them aside with a do statement. And the parentheses can be omitted with non-fat arrow functions. | 1825 | If you wish to have further code after your backcalls, you can set them aside with a do statement. And the parentheses can be omitted with non-fat arrow functions. |
| 3557 | 1826 | ||
| 3558 | ```yuescript | 1827 | ```yuescript |
| @@ -3564,19 +1833,6 @@ result, msg = do | |||
| 3564 | print result, msg | 1833 | print result, msg |
| 3565 | ``` | 1834 | ``` |
| 3566 | 1835 | ||
| 3567 | <YueDisplay> | ||
| 3568 | |||
| 3569 | ```yue | ||
| 3570 | result, msg = do | ||
| 3571 | data <- readAsync "filename.txt" | ||
| 3572 | print data | ||
| 3573 | info <- processAsync data | ||
| 3574 | check info | ||
| 3575 | print result, msg | ||
| 3576 | ``` | ||
| 3577 | |||
| 3578 | </YueDisplay> | ||
| 3579 | |||
| 3580 | # Function Literals | 1836 | # Function Literals |
| 3581 | 1837 | ||
| 3582 | All functions are created using a function expression. A simple function is denoted using the arrow: **->**. | 1838 | All functions are created using a function expression. A simple function is denoted using the arrow: **->**. |
| @@ -3586,15 +1842,6 @@ my_function = -> | |||
| 3586 | my_function() -- call the empty function | 1842 | my_function() -- call the empty function |
| 3587 | ``` | 1843 | ``` |
| 3588 | 1844 | ||
| 3589 | <YueDisplay> | ||
| 3590 | |||
| 3591 | ```yue | ||
| 3592 | my_function = -> | ||
| 3593 | my_function() -- call the empty function | ||
| 3594 | ``` | ||
| 3595 | |||
| 3596 | </YueDisplay> | ||
| 3597 | |||
| 3598 | The body of the function can either be one statement placed directly after the arrow, or it can be a series of statements indented on the following lines: | 1845 | The body of the function can either be one statement placed directly after the arrow, or it can be a series of statements indented on the following lines: |
| 3599 | 1846 | ||
| 3600 | ```yuescript | 1847 | ```yuescript |
| @@ -3605,18 +1852,6 @@ func_b = -> | |||
| 3605 | print "The value:", value | 1852 | print "The value:", value |
| 3606 | ``` | 1853 | ``` |
| 3607 | 1854 | ||
| 3608 | <YueDisplay> | ||
| 3609 | |||
| 3610 | ```yue | ||
| 3611 | func_a = -> print "hello world" | ||
| 3612 | |||
| 3613 | func_b = -> | ||
| 3614 | value = 100 | ||
| 3615 | print "The value:", value | ||
| 3616 | ``` | ||
| 3617 | |||
| 3618 | </YueDisplay> | ||
| 3619 | |||
| 3620 | If a function has no arguments, it can be called using the ! operator, instead of empty parentheses. The ! invocation is the preferred way to call functions with no arguments. | 1855 | If a function has no arguments, it can be called using the ! operator, instead of empty parentheses. The ! invocation is the preferred way to call functions with no arguments. |
| 3621 | 1856 | ||
| 3622 | ```yuescript | 1857 | ```yuescript |
| @@ -3624,29 +1859,12 @@ func_a! | |||
| 3624 | func_b() | 1859 | func_b() |
| 3625 | ``` | 1860 | ``` |
| 3626 | 1861 | ||
| 3627 | <YueDisplay> | ||
| 3628 | |||
| 3629 | ```yue | ||
| 3630 | func_a! | ||
| 3631 | func_b() | ||
| 3632 | ``` | ||
| 3633 | |||
| 3634 | </YueDisplay> | ||
| 3635 | |||
| 3636 | Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: | 1862 | Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: |
| 3637 | 1863 | ||
| 3638 | ```yuescript | 1864 | ```yuescript |
| 3639 | sum = (x, y) -> print "sum", x + y | 1865 | sum = (x, y) -> print "sum", x + y |
| 3640 | ``` | 1866 | ``` |
| 3641 | 1867 | ||
| 3642 | <YueDisplay> | ||
| 3643 | |||
| 3644 | ```yue | ||
| 3645 | sum = (x, y) -> print "sum", x + y | ||
| 3646 | ``` | ||
| 3647 | |||
| 3648 | </YueDisplay> | ||
| 3649 | |||
| 3650 | Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left. | 1868 | Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left. |
| 3651 | 1869 | ||
| 3652 | ```yuescript | 1870 | ```yuescript |
| @@ -3656,31 +1874,12 @@ print sum 10, 20 | |||
| 3656 | a b c "a", "b", "c" | 1874 | a b c "a", "b", "c" |
| 3657 | ``` | 1875 | ``` |
| 3658 | 1876 | ||
| 3659 | <YueDisplay> | ||
| 3660 | |||
| 3661 | ```yue | ||
| 3662 | sum 10, 20 | ||
| 3663 | print sum 10, 20 | ||
| 3664 | |||
| 3665 | a b c "a", "b", "c" | ||
| 3666 | ``` | ||
| 3667 | |||
| 3668 | </YueDisplay> | ||
| 3669 | |||
| 3670 | In order to avoid ambiguity in when calling functions, parentheses can also be used to surround the arguments. This is required here in order to make sure the right arguments get sent to the right functions. | 1877 | In order to avoid ambiguity in when calling functions, parentheses can also be used to surround the arguments. This is required here in order to make sure the right arguments get sent to the right functions. |
| 3671 | 1878 | ||
| 3672 | ```yuescript | 1879 | ```yuescript |
| 3673 | print "x:", sum(10, 20), "y:", sum(30, 40) | 1880 | print "x:", sum(10, 20), "y:", sum(30, 40) |
| 3674 | ``` | 1881 | ``` |
| 3675 | 1882 | ||
| 3676 | <YueDisplay> | ||
| 3677 | |||
| 3678 | ```yue | ||
| 3679 | print "x:", sum(10, 20), "y:", sum(30, 40) | ||
| 3680 | ``` | ||
| 3681 | |||
| 3682 | </YueDisplay> | ||
| 3683 | |||
| 3684 | There must not be any space between the opening parenthesis and the function. | 1883 | There must not be any space between the opening parenthesis and the function. |
| 3685 | 1884 | ||
| 3686 | Functions will coerce the last statement in their body into a return statement, this is called implicit return: | 1885 | Functions will coerce the last statement in their body into a return statement, this is called implicit return: |
| @@ -3690,29 +1889,12 @@ sum = (x, y) -> x + y | |||
| 3690 | print "The sum is ", sum 10, 20 | 1889 | print "The sum is ", sum 10, 20 |
| 3691 | ``` | 1890 | ``` |
| 3692 | 1891 | ||
| 3693 | <YueDisplay> | ||
| 3694 | |||
| 3695 | ```yue | ||
| 3696 | sum = (x, y) -> x + y | ||
| 3697 | print "The sum is ", sum 10, 20 | ||
| 3698 | ``` | ||
| 3699 | |||
| 3700 | </YueDisplay> | ||
| 3701 | |||
| 3702 | And if you need to explicitly return, you can use the return keyword: | 1892 | And if you need to explicitly return, you can use the return keyword: |
| 3703 | 1893 | ||
| 3704 | ```yuescript | 1894 | ```yuescript |
| 3705 | sum = (x, y) -> return x + y | 1895 | sum = (x, y) -> return x + y |
| 3706 | ``` | 1896 | ``` |
| 3707 | 1897 | ||
| 3708 | <YueDisplay> | ||
| 3709 | |||
| 3710 | ```yue | ||
| 3711 | sum = (x, y) -> return x + y | ||
| 3712 | ``` | ||
| 3713 | |||
| 3714 | </YueDisplay> | ||
| 3715 | |||
| 3716 | Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: | 1898 | Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: |
| 3717 | 1899 | ||
| 3718 | ```yuescript | 1900 | ```yuescript |
| @@ -3720,15 +1902,6 @@ mystery = (x, y) -> x + y, x - y | |||
| 3720 | a, b = mystery 10, 20 | 1902 | a, b = mystery 10, 20 |
| 3721 | ``` | 1903 | ``` |
| 3722 | 1904 | ||
| 3723 | <YueDisplay> | ||
| 3724 | |||
| 3725 | ```yue | ||
| 3726 | mystery = (x, y) -> x + y, x - y | ||
| 3727 | a, b = mystery 10, 20 | ||
| 3728 | ``` | ||
| 3729 | |||
| 3730 | </YueDisplay> | ||
| 3731 | |||
| 3732 | ## Fat Arrows | 1905 | ## Fat Arrows |
| 3733 | 1906 | ||
| 3734 | Because it is an idiom in Lua to send an object as the first argument when calling a method, a special syntax is provided for creating functions which automatically includes a self argument. | 1907 | Because it is an idiom in Lua to send an object as the first argument when calling a method, a special syntax is provided for creating functions which automatically includes a self argument. |
| @@ -3737,14 +1910,6 @@ Because it is an idiom in Lua to send an object as the first argument when calli | |||
| 3737 | func = (num) => @value + num | 1910 | func = (num) => @value + num |
| 3738 | ``` | 1911 | ``` |
| 3739 | 1912 | ||
| 3740 | <YueDisplay> | ||
| 3741 | |||
| 3742 | ```yue | ||
| 3743 | func = (num) => @value + num | ||
| 3744 | ``` | ||
| 3745 | |||
| 3746 | </YueDisplay> | ||
| 3747 | |||
| 3748 | ## Argument Defaults | 1913 | ## Argument Defaults |
| 3749 | 1914 | ||
| 3750 | It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run. | 1915 | It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run. |
| @@ -3755,16 +1920,6 @@ my_function = (name = "something", height = 100) -> | |||
| 3755 | print "My height is", height | 1920 | print "My height is", height |
| 3756 | ``` | 1921 | ``` |
| 3757 | 1922 | ||
| 3758 | <YueDisplay> | ||
| 3759 | |||
| 3760 | ```yue | ||
| 3761 | my_function = (name = "something", height = 100) -> | ||
| 3762 | print "Hello I am", name | ||
| 3763 | print "My height is", height | ||
| 3764 | ``` | ||
| 3765 | |||
| 3766 | </YueDisplay> | ||
| 3767 | |||
| 3768 | An argument default value expression is evaluated in the body of the function in the order of the argument declarations. For this reason default values have access to previously declared arguments. | 1923 | An argument default value expression is evaluated in the body of the function in the order of the argument declarations. For this reason default values have access to previously declared arguments. |
| 3769 | 1924 | ||
| 3770 | ```yuescript | 1925 | ```yuescript |
| @@ -3772,15 +1927,6 @@ some_args = (x = 100, y = x + 1000) -> | |||
| 3772 | print x + y | 1927 | print x + y |
| 3773 | ``` | 1928 | ``` |
| 3774 | 1929 | ||
| 3775 | <YueDisplay> | ||
| 3776 | |||
| 3777 | ```yue | ||
| 3778 | some_args = (x = 100, y = x + 1000) -> | ||
| 3779 | print x + y | ||
| 3780 | ``` | ||
| 3781 | |||
| 3782 | </YueDisplay> | ||
| 3783 | |||
| 3784 | ## Considerations | 1930 | ## Considerations |
| 3785 | 1931 | ||
| 3786 | Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. | 1932 | Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. |
| @@ -3794,17 +1940,6 @@ c = x -y | |||
| 3794 | d = x- z | 1940 | d = x- z |
| 3795 | ``` | 1941 | ``` |
| 3796 | 1942 | ||
| 3797 | <YueDisplay> | ||
| 3798 | |||
| 3799 | ```yue | ||
| 3800 | a = x - 10 | ||
| 3801 | b = x-10 | ||
| 3802 | c = x -y | ||
| 3803 | d = x- z | ||
| 3804 | ``` | ||
| 3805 | |||
| 3806 | </YueDisplay> | ||
| 3807 | |||
| 3808 | The precedence of the first argument of a function call can be controlled using whitespace if the argument is a literal string. In Lua, it is common to leave off parentheses when calling a function with a single string or table literal. | 1943 | The precedence of the first argument of a function call can be controlled using whitespace if the argument is a literal string. In Lua, it is common to leave off parentheses when calling a function with a single string or table literal. |
| 3809 | 1944 | ||
| 3810 | When there is no space between a variable and a string literal, the function call takes precedence over any following expressions. No other arguments can be passed to the function when it is called this way. | 1945 | When there is no space between a variable and a string literal, the function call takes precedence over any following expressions. No other arguments can be passed to the function when it is called this way. |
| @@ -3816,15 +1951,6 @@ x = func"hello" + 100 | |||
| 3816 | y = func "hello" + 100 | 1951 | y = func "hello" + 100 |
| 3817 | ``` | 1952 | ``` |
| 3818 | 1953 | ||
| 3819 | <YueDisplay> | ||
| 3820 | |||
| 3821 | ```yue | ||
| 3822 | x = func"hello" + 100 | ||
| 3823 | y = func "hello" + 100 | ||
| 3824 | ``` | ||
| 3825 | |||
| 3826 | </YueDisplay> | ||
| 3827 | |||
| 3828 | ## Multi-line arguments | 1954 | ## Multi-line arguments |
| 3829 | 1955 | ||
| 3830 | When calling functions that take a large number of arguments, it is convenient to split the argument list over multiple lines. Because of the white-space sensitive nature of the language, care must be taken when splitting up the argument list. | 1956 | When calling functions that take a large number of arguments, it is convenient to split the argument list over multiple lines. Because of the white-space sensitive nature of the language, care must be taken when splitting up the argument list. |
| @@ -3841,20 +1967,6 @@ cool_func 1, 2, | |||
| 3841 | 7, 8 | 1967 | 7, 8 |
| 3842 | ``` | 1968 | ``` |
| 3843 | 1969 | ||
| 3844 | <YueDisplay> | ||
| 3845 | |||
| 3846 | ```yue | ||
| 3847 | my_func 5, 4, 3, | ||
| 3848 | 8, 9, 10 | ||
| 3849 | |||
| 3850 | cool_func 1, 2, | ||
| 3851 | 3, 4, | ||
| 3852 | 5, 6, | ||
| 3853 | 7, 8 | ||
| 3854 | ``` | ||
| 3855 | |||
| 3856 | </YueDisplay> | ||
| 3857 | |||
| 3858 | This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. | 1970 | This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. |
| 3859 | 1971 | ||
| 3860 | ```yuescript | 1972 | ```yuescript |
| @@ -3864,17 +1976,6 @@ my_func 5, 6, 7, | |||
| 3864 | 5, 4 | 1976 | 5, 4 |
| 3865 | ``` | 1977 | ``` |
| 3866 | 1978 | ||
| 3867 | <YueDisplay> | ||
| 3868 | |||
| 3869 | ```yue | ||
| 3870 | my_func 5, 6, 7, | ||
| 3871 | 6, another_func 6, 7, 8, | ||
| 3872 | 9, 1, 2, | ||
| 3873 | 5, 4 | ||
| 3874 | ``` | ||
| 3875 | |||
| 3876 | </YueDisplay> | ||
| 3877 | |||
| 3878 | Because tables also use the comma as a delimiter, this indentation syntax is helpful for letting values be part of the argument list instead of being part of the table. | 1979 | Because tables also use the comma as a delimiter, this indentation syntax is helpful for letting values be part of the argument list instead of being part of the table. |
| 3879 | 1980 | ||
| 3880 | ```yuescript | 1981 | ```yuescript |
| @@ -3885,18 +1986,6 @@ x = [ | |||
| 3885 | ] | 1986 | ] |
| 3886 | ``` | 1987 | ``` |
| 3887 | 1988 | ||
| 3888 | <YueDisplay> | ||
| 3889 | |||
| 3890 | ```yue | ||
| 3891 | x = [ | ||
| 3892 | 1, 2, 3, 4, a_func 4, 5, | ||
| 3893 | 5, 6, | ||
| 3894 | 8, 9, 10 | ||
| 3895 | ] | ||
| 3896 | ``` | ||
| 3897 | |||
| 3898 | </YueDisplay> | ||
| 3899 | |||
| 3900 | Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on. | 1989 | Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on. |
| 3901 | 1990 | ||
| 3902 | ```yuescript | 1991 | ```yuescript |
| @@ -3906,17 +1995,6 @@ y = [ my_func 1, 2, 3, | |||
| 3906 | ] | 1995 | ] |
| 3907 | ``` | 1996 | ``` |
| 3908 | 1997 | ||
| 3909 | <YueDisplay> | ||
| 3910 | |||
| 3911 | ```yue | ||
| 3912 | y = [ my_func 1, 2, 3, | ||
| 3913 | 4, 5, | ||
| 3914 | 5, 6, 7 | ||
| 3915 | ] | ||
| 3916 | ``` | ||
| 3917 | |||
| 3918 | </YueDisplay> | ||
| 3919 | |||
| 3920 | The same thing can be done with other block level statements like conditionals. We can use indentation level to determine what statement a value belongs to: | 1998 | The same thing can be done with other block level statements like conditionals. We can use indentation level to determine what statement a value belongs to: |
| 3921 | 1999 | ||
| 3922 | ```yuescript | 2000 | ```yuescript |
| @@ -3933,24 +2011,6 @@ if func 1, 2, 3, | |||
| 3933 | print "I am inside if" | 2011 | print "I am inside if" |
| 3934 | ``` | 2012 | ``` |
| 3935 | 2013 | ||
| 3936 | <YueDisplay> | ||
| 3937 | |||
| 3938 | ```yue | ||
| 3939 | if func 1, 2, 3, | ||
| 3940 | "hello", | ||
| 3941 | "world" | ||
| 3942 | print "hello" | ||
| 3943 | print "I am inside if" | ||
| 3944 | |||
| 3945 | if func 1, 2, 3, | ||
| 3946 | "hello", | ||
| 3947 | "world" | ||
| 3948 | print "hello" | ||
| 3949 | print "I am inside if" | ||
| 3950 | ``` | ||
| 3951 | |||
| 3952 | </YueDisplay> | ||
| 3953 | |||
| 3954 | ## Parameter Destructuring | 2014 | ## Parameter Destructuring |
| 3955 | 2015 | ||
| 3956 | YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: | 2016 | YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: |
| @@ -3972,23 +2032,6 @@ arg1 = {a: 0} | |||
| 3972 | f2 arg1, arg2 | 2032 | f2 arg1, arg2 |
| 3973 | ``` | 2033 | ``` |
| 3974 | 2034 | ||
| 3975 | <YueDisplay> | ||
| 3976 | |||
| 3977 | ```yue | ||
| 3978 | f1 = (:a, :b, :c) -> | ||
| 3979 | print a, b, c | ||
| 3980 | |||
| 3981 | f1 a: 1, b: "2", c: {} | ||
| 3982 | |||
| 3983 | f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) -> | ||
| 3984 | print a1, b, c | ||
| 3985 | |||
| 3986 | arg1 = {a: 0} | ||
| 3987 | f2 arg1, arg2 | ||
| 3988 | ``` | ||
| 3989 | |||
| 3990 | </YueDisplay> | ||
| 3991 | |||
| 3992 | ## Prefixed Return Expression | 2035 | ## Prefixed Return Expression |
| 3993 | 2036 | ||
| 3994 | When working with deeply nested function bodies, it can be tedious to maintain readability and consistency of the return value. To address this, YueScript introduces the **Prefixed Return Expression** syntax. Its form is as follows: | 2037 | When working with deeply nested function bodies, it can be tedious to maintain readability and consistency of the return value. To address this, YueScript introduces the **Prefixed Return Expression** syntax. Its form is as follows: |
| @@ -4002,19 +2045,6 @@ findFirstEven = (list): nil -> | |||
| 4002 | return sub | 2045 | return sub |
| 4003 | ``` | 2046 | ``` |
| 4004 | 2047 | ||
| 4005 | <YueDisplay> | ||
| 4006 | |||
| 4007 | ```yue | ||
| 4008 | findFirstEven = (list): nil -> | ||
| 4009 | for item in *list | ||
| 4010 | if type(item) == "table" | ||
| 4011 | for sub in *item | ||
| 4012 | if sub % 2 == 0 | ||
| 4013 | return sub | ||
| 4014 | ``` | ||
| 4015 | |||
| 4016 | </YueDisplay> | ||
| 4017 | |||
| 4018 | This is equivalent to: | 2048 | This is equivalent to: |
| 4019 | 2049 | ||
| 4020 | ```yuescript | 2050 | ```yuescript |
| @@ -4027,20 +2057,6 @@ findFirstEven = (list) -> | |||
| 4027 | nil | 2057 | nil |
| 4028 | ``` | 2058 | ``` |
| 4029 | 2059 | ||
| 4030 | <YueDisplay> | ||
| 4031 | |||
| 4032 | ```yue | ||
| 4033 | findFirstEven = (list) -> | ||
| 4034 | for item in *list | ||
| 4035 | if type(item) == "table" | ||
| 4036 | for sub in *item | ||
| 4037 | if sub % 2 == 0 | ||
| 4038 | return sub | ||
| 4039 | nil | ||
| 4040 | ``` | ||
| 4041 | |||
| 4042 | </YueDisplay> | ||
| 4043 | |||
| 4044 | The only difference is that you can move the final return expression before the `->` or `=>` token to indicate the function’s implicit return value as the last statement. This way, even in functions with multiple nested loops or conditional branches, you no longer need to write a trailing return expression at the end of the function body, making the logic structure more straightforward and easier to follow. | 2060 | The only difference is that you can move the final return expression before the `->` or `=>` token to indicate the function’s implicit return value as the last statement. This way, even in functions with multiple nested loops or conditional branches, you no longer need to write a trailing return expression at the end of the function body, making the logic structure more straightforward and easier to follow. |
| 4045 | 2061 | ||
| 4046 | ## Named Varargs | 2062 | ## Named Varargs |
| @@ -4069,32 +2085,6 @@ process = (...args) -> | |||
| 4069 | process 1, nil, 3, nil, 5 | 2085 | process 1, nil, 3, nil, 5 |
| 4070 | ``` | 2086 | ``` |
| 4071 | 2087 | ||
| 4072 | <YueDisplay> | ||
| 4073 | |||
| 4074 | ```yue | ||
| 4075 | f = (...t) -> | ||
| 4076 | print "argument count:", t.n | ||
| 4077 | print "table length:", #t | ||
| 4078 | for i = 1, t.n | ||
| 4079 | print t[i] | ||
| 4080 | |||
| 4081 | f 1, 2, 3 | ||
| 4082 | f "a", "b", "c", "d" | ||
| 4083 | f! | ||
| 4084 | |||
| 4085 | -- Handling cases with nil values | ||
| 4086 | process = (...args) -> | ||
| 4087 | sum = 0 | ||
| 4088 | for i = 1, args.n | ||
| 4089 | if args[i] != nil and type(args[i]) == "number" | ||
| 4090 | sum += args[i] | ||
| 4091 | sum | ||
| 4092 | |||
| 4093 | process 1, nil, 3, nil, 5 | ||
| 4094 | ``` | ||
| 4095 | |||
| 4096 | </YueDisplay> | ||
| 4097 | |||
| 4098 | # Whitespace | 2088 | # Whitespace |
| 4099 | 2089 | ||
| 4100 | YueScript is a whitespace significant language. You have to write some code block in the same indent with space **' '** or tab **'\t'** like function body, value list and some control blocks. And expressions containing different whitespaces might mean different things. Tab is treated like 4 space, but it's better not mix the use of spaces and tabs. | 2090 | YueScript is a whitespace significant language. You have to write some code block in the same indent with space **' '** or tab **'\t'** like function body, value list and some control blocks. And expressions containing different whitespaces might mean different things. Tab is treated like 4 space, but it's better not mix the use of spaces and tabs. |
| @@ -4107,14 +2097,6 @@ A statement normally ends at a line break. You can also use a semicolon `;` to e | |||
| 4107 | a = 1; b = 2; print a + b | 2097 | a = 1; b = 2; print a + b |
| 4108 | ``` | 2098 | ``` |
| 4109 | 2099 | ||
| 4110 | <YueDisplay> | ||
| 4111 | |||
| 4112 | ```yue | ||
| 4113 | a = 1; b = 2; print a + b | ||
| 4114 | ``` | ||
| 4115 | |||
| 4116 | </YueDisplay> | ||
| 4117 | |||
| 4118 | ## Multiline Chaining | 2100 | ## Multiline Chaining |
| 4119 | 2101 | ||
| 4120 | You can write multi-line chaining function calls with a same indent. | 2102 | You can write multi-line chaining function calls with a same indent. |
| @@ -4128,19 +2110,6 @@ Rx.Observable | |||
| 4128 | \subscribe print | 2110 | \subscribe print |
| 4129 | ``` | 2111 | ``` |
| 4130 | 2112 | ||
| 4131 | <YueDisplay> | ||
| 4132 | |||
| 4133 | ```yue | ||
| 4134 | Rx.Observable | ||
| 4135 | .fromRange 1, 8 | ||
| 4136 | \filter (x) -> x % 2 == 0 | ||
| 4137 | \concat Rx.Observable.of 'who do we appreciate' | ||
| 4138 | \map (value) -> value .. '!' | ||
| 4139 | \subscribe print | ||
| 4140 | ``` | ||
| 4141 | |||
| 4142 | </YueDisplay> | ||
| 4143 | |||
| 4144 | # Comment | 2113 | # Comment |
| 4145 | 2114 | ||
| 4146 | ```yuescript | 2115 | ```yuescript |
| @@ -4156,23 +2125,6 @@ It's OK. | |||
| 4156 | func --[[port]] 3000, --[[ip]] "192.168.1.1" | 2125 | func --[[port]] 3000, --[[ip]] "192.168.1.1" |
| 4157 | ``` | 2126 | ``` |
| 4158 | 2127 | ||
| 4159 | <YueDisplay> | ||
| 4160 | |||
| 4161 | ```yue | ||
| 4162 | -- I am a comment | ||
| 4163 | |||
| 4164 | str = --[[ | ||
| 4165 | This is a multi-line comment. | ||
| 4166 | It's OK. | ||
| 4167 | ]] strA \ -- comment 1 | ||
| 4168 | .. strB \ -- comment 2 | ||
| 4169 | .. strC | ||
| 4170 | |||
| 4171 | func --[[port]] 3000, --[[ip]] "192.168.1.1" | ||
| 4172 | ``` | ||
| 4173 | |||
| 4174 | </YueDisplay> | ||
| 4175 | |||
| 4176 | # Attributes | 2128 | # Attributes |
| 4177 | 2129 | ||
| 4178 | Syntax support for Lua 5.4 attributes. And you can still use both the `const` and `close` declaration and get constant check and scoped callback working when targeting Lua versions below 5.4. | 2130 | Syntax support for Lua 5.4 attributes. And you can still use both the `const` and `close` declaration and get constant check and scoped callback working when targeting Lua versions below 5.4. |
| @@ -4182,15 +2134,6 @@ const a = 123 | |||
| 4182 | close _ = <close>: -> print "Out of scope." | 2134 | close _ = <close>: -> print "Out of scope." |
| 4183 | ``` | 2135 | ``` |
| 4184 | 2136 | ||
| 4185 | <YueDisplay> | ||
| 4186 | |||
| 4187 | ```yue | ||
| 4188 | const a = 123 | ||
| 4189 | close _ = <close>: -> print "Out of scope." | ||
| 4190 | ``` | ||
| 4191 | |||
| 4192 | </YueDisplay> | ||
| 4193 | |||
| 4194 | You can do desctructuring with variables attributed as constant. | 2137 | You can do desctructuring with variables attributed as constant. |
| 4195 | 2138 | ||
| 4196 | ```yuescript | 2139 | ```yuescript |
| @@ -4198,15 +2141,6 @@ const {:a, :b, c, d} = tb | |||
| 4198 | -- a = 1 | 2141 | -- a = 1 |
| 4199 | ``` | 2142 | ``` |
| 4200 | 2143 | ||
| 4201 | <YueDisplay> | ||
| 4202 | |||
| 4203 | ```yue | ||
| 4204 | const {:a, :b, c, d} = tb | ||
| 4205 | -- a = 1 | ||
| 4206 | ``` | ||
| 4207 | |||
| 4208 | </YueDisplay> | ||
| 4209 | |||
| 4210 | You can also declare a global variable to be `const`. | 2144 | You can also declare a global variable to be `const`. |
| 4211 | 2145 | ||
| 4212 | ```yuescript | 2146 | ```yuescript |
| @@ -4214,15 +2148,6 @@ global const Constant = 123 | |||
| 4214 | -- Constant = 1 | 2148 | -- Constant = 1 |
| 4215 | ``` | 2149 | ``` |
| 4216 | 2150 | ||
| 4217 | <YueDisplay> | ||
| 4218 | |||
| 4219 | ```yue | ||
| 4220 | global const Constant = 123 | ||
| 4221 | -- Constant = 1 | ||
| 4222 | ``` | ||
| 4223 | |||
| 4224 | </YueDisplay> | ||
| 4225 | |||
| 4226 | # Operator | 2151 | # Operator |
| 4227 | 2152 | ||
| 4228 | All of Lua's binary and unary operators are available. Additionally **!=** is as an alias for **~=**, and either **\\** or **::** can be used to write a chaining function call like `tb\func!` or `tb::func!`. And Yuescipt offers some other special operators to write more expressive codes. | 2153 | All of Lua's binary and unary operators are available. Additionally **!=** is as an alias for **~=**, and either **\\** or **::** can be used to write a chaining function call like `tb\func!` or `tb::func!`. And Yuescipt offers some other special operators to write more expressive codes. |
| @@ -4232,15 +2157,6 @@ tb\func! if tb ~= nil | |||
| 4232 | tb::func! if tb != nil | 2157 | tb::func! if tb != nil |
| 4233 | ``` | 2158 | ``` |
| 4234 | 2159 | ||
| 4235 | <YueDisplay> | ||
| 4236 | |||
| 4237 | ```yue | ||
| 4238 | tb\func! if tb ~= nil | ||
| 4239 | tb::func! if tb != nil | ||
| 4240 | ``` | ||
| 4241 | |||
| 4242 | </YueDisplay> | ||
| 4243 | |||
| 4244 | ## Chaining Comparisons | 2160 | ## Chaining Comparisons |
| 4245 | 2161 | ||
| 4246 | Comparisons can be arbitrarily chained: | 2162 | Comparisons can be arbitrarily chained: |
| @@ -4254,19 +2170,6 @@ print 1 <= a <= 10 | |||
| 4254 | -- output: true | 2170 | -- output: true |
| 4255 | ``` | 2171 | ``` |
| 4256 | 2172 | ||
| 4257 | <YueDisplay> | ||
| 4258 | |||
| 4259 | ```yue | ||
| 4260 | print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 | ||
| 4261 | -- output: true | ||
| 4262 | |||
| 4263 | a = 5 | ||
| 4264 | print 1 <= a <= 10 | ||
| 4265 | -- output: true | ||
| 4266 | ``` | ||
| 4267 | |||
| 4268 | </YueDisplay> | ||
| 4269 | |||
| 4270 | Note the evaluation behavior of chained comparisons: | 2173 | Note the evaluation behavior of chained comparisons: |
| 4271 | 2174 | ||
| 4272 | ```yuescript | 2175 | ```yuescript |
| @@ -4292,33 +2195,6 @@ print v(1) > v(2) <= v(3) | |||
| 4292 | ]] | 2195 | ]] |
| 4293 | ``` | 2196 | ``` |
| 4294 | 2197 | ||
| 4295 | <YueDisplay> | ||
| 4296 | |||
| 4297 | ```yue | ||
| 4298 | v = (x) -> | ||
| 4299 | print x | ||
| 4300 | x | ||
| 4301 | |||
| 4302 | print v(1) < v(2) <= v(3) | ||
| 4303 | --[[ | ||
| 4304 | output: | ||
| 4305 | 2 | ||
| 4306 | 1 | ||
| 4307 | 3 | ||
| 4308 | true | ||
| 4309 | ]] | ||
| 4310 | |||
| 4311 | print v(1) > v(2) <= v(3) | ||
| 4312 | --[[ | ||
| 4313 | output: | ||
| 4314 | 2 | ||
| 4315 | 1 | ||
| 4316 | false | ||
| 4317 | ]] | ||
| 4318 | ``` | ||
| 4319 | |||
| 4320 | </YueDisplay> | ||
| 4321 | |||
| 4322 | The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) and v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `and` operator should be used explicitly. | 2198 | The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) and v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `and` operator should be used explicitly. |
| 4323 | 2199 | ||
| 4324 | ## Table Appending | 2200 | ## Table Appending |
| @@ -4330,15 +2206,6 @@ tab = [] | |||
| 4330 | tab[] = "Value" | 2206 | tab[] = "Value" |
| 4331 | ``` | 2207 | ``` |
| 4332 | 2208 | ||
| 4333 | <YueDisplay> | ||
| 4334 | |||
| 4335 | ```yue | ||
| 4336 | tab = [] | ||
| 4337 | tab[] = "Value" | ||
| 4338 | ``` | ||
| 4339 | |||
| 4340 | </YueDisplay> | ||
| 4341 | |||
| 4342 | You can also use the spread operator `...` to append all elements from one list to another: | 2209 | You can also use the spread operator `...` to append all elements from one list to another: |
| 4343 | 2210 | ||
| 4344 | ```yuescript | 2211 | ```yuescript |
| @@ -4348,17 +2215,6 @@ tbA[] = ...tbB | |||
| 4348 | -- tbA is now [1, 2, 3, 4, 5, 6] | 2215 | -- tbA is now [1, 2, 3, 4, 5, 6] |
| 4349 | ``` | 2216 | ``` |
| 4350 | 2217 | ||
| 4351 | <YueDisplay> | ||
| 4352 | |||
| 4353 | ```yue | ||
| 4354 | tbA = [1, 2, 3] | ||
| 4355 | tbB = [4, 5, 6] | ||
| 4356 | tbA[] = ...tbB | ||
| 4357 | -- tbA is now [1, 2, 3, 4, 5, 6] | ||
| 4358 | ``` | ||
| 4359 | |||
| 4360 | </YueDisplay> | ||
| 4361 | |||
| 4362 | ## Table Spreading | 2218 | ## Table Spreading |
| 4363 | 2219 | ||
| 4364 | You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. | 2220 | You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. |
| @@ -4380,27 +2236,6 @@ b = {4, 5, y: 1} | |||
| 4380 | merge = {...a, ...b} | 2236 | merge = {...a, ...b} |
| 4381 | ``` | 2237 | ``` |
| 4382 | 2238 | ||
| 4383 | <YueDisplay> | ||
| 4384 | |||
| 4385 | ```yue | ||
| 4386 | parts = | ||
| 4387 | * "shoulders" | ||
| 4388 | * "knees" | ||
| 4389 | lyrics = | ||
| 4390 | * "head" | ||
| 4391 | * ...parts | ||
| 4392 | * "and" | ||
| 4393 | * "toes" | ||
| 4394 | |||
| 4395 | copy = {...other} | ||
| 4396 | |||
| 4397 | a = {1, 2, 3, x: 1} | ||
| 4398 | b = {4, 5, y: 1} | ||
| 4399 | merge = {...a, ...b} | ||
| 4400 | ``` | ||
| 4401 | |||
| 4402 | </YueDisplay> | ||
| 4403 | |||
| 4404 | ## Table Reversed Indexing | 2239 | ## Table Reversed Indexing |
| 4405 | 2240 | ||
| 4406 | You can use the **#** operator to get the last elements of a table. | 2241 | You can use the **#** operator to get the last elements of a table. |
| @@ -4411,16 +2246,6 @@ second_last = data.items[#-1] | |||
| 4411 | data.items[#] = 1 | 2246 | data.items[#] = 1 |
| 4412 | ``` | 2247 | ``` |
| 4413 | 2248 | ||
| 4414 | <YueDisplay> | ||
| 4415 | |||
| 4416 | ```yue | ||
| 4417 | last = data.items[#] | ||
| 4418 | second_last = data.items[#-1] | ||
| 4419 | data.items[#] = 1 | ||
| 4420 | ``` | ||
| 4421 | |||
| 4422 | </YueDisplay> | ||
| 4423 | |||
| 4424 | ## Metatable | 2249 | ## Metatable |
| 4425 | 2250 | ||
| 4426 | The **<>** operator can be used as a shortcut for metatable manipulation. | 2251 | The **<>** operator can be used as a shortcut for metatable manipulation. |
| @@ -4445,26 +2270,6 @@ print d.value | |||
| 4445 | close _ = <close>: -> print "out of scope" | 2270 | close _ = <close>: -> print "out of scope" |
| 4446 | ``` | 2271 | ``` |
| 4447 | 2272 | ||
| 4448 | <YueDisplay> | ||
| 4449 | |||
| 4450 | ```yue | ||
| 4451 | mt = {} | ||
| 4452 | add = (right) => <>: mt, value: @value + right.value | ||
| 4453 | mt.__add = add | ||
| 4454 | |||
| 4455 | a = <>: mt, value: 1 | ||
| 4456 | -- set field with variable of the same name | ||
| 4457 | b = :<add>, value: 2 | ||
| 4458 | c = <add>: mt.__add, value: 3 | ||
| 4459 | |||
| 4460 | d = a + b + c | ||
| 4461 | print d.value | ||
| 4462 | |||
| 4463 | close _ = <close>: -> print "out of scope" | ||
| 4464 | ``` | ||
| 4465 | |||
| 4466 | </YueDisplay> | ||
| 4467 | |||
| 4468 | ### Metatable Accessing | 2273 | ### Metatable Accessing |
| 4469 | 2274 | ||
| 4470 | Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. | 2275 | Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. |
| @@ -4479,19 +2284,6 @@ tb.<> = __index: {item: "hello"} | |||
| 4479 | print tb.item | 2284 | print tb.item |
| 4480 | ``` | 2285 | ``` |
| 4481 | 2286 | ||
| 4482 | <YueDisplay> | ||
| 4483 | |||
| 4484 | ```yue | ||
| 4485 | -- create with metatable containing field "value" | ||
| 4486 | tb = <"value">: 123 | ||
| 4487 | tb.<index> = tb.<> | ||
| 4488 | print tb.value | ||
| 4489 | tb.<> = __index: {item: "hello"} | ||
| 4490 | print tb.item | ||
| 4491 | ``` | ||
| 4492 | |||
| 4493 | </YueDisplay> | ||
| 4494 | |||
| 4495 | ### Metatable Destructure | 2287 | ### Metatable Destructure |
| 4496 | 2288 | ||
| 4497 | Destruct metatable with metamethod key surrounded by **<>**. | 2289 | Destruct metatable with metamethod key surrounded by **<>**. |
| @@ -4501,15 +2293,6 @@ Destruct metatable with metamethod key surrounded by **<>**. | |||
| 4501 | print item, new, close, getter | 2293 | print item, new, close, getter |
| 4502 | ``` | 2294 | ``` |
| 4503 | 2295 | ||
| 4504 | <YueDisplay> | ||
| 4505 | |||
| 4506 | ```yue | ||
| 4507 | {item, :new, :<close>, <index>: getter} = tb | ||
| 4508 | print item, new, close, getter | ||
| 4509 | ``` | ||
| 4510 | |||
| 4511 | </YueDisplay> | ||
| 4512 | |||
| 4513 | ## Existence | 2296 | ## Existence |
| 4514 | 2297 | ||
| 4515 | The **?** operator can be used in a variety of contexts to check for existence. | 2298 | The **?** operator can be used in a variety of contexts to check for existence. |
| @@ -4529,25 +2312,6 @@ with? io.open "test.txt", "w" | |||
| 4529 | \close! | 2312 | \close! |
| 4530 | ``` | 2313 | ``` |
| 4531 | 2314 | ||
| 4532 | <YueDisplay> | ||
| 4533 | |||
| 4534 | ```yue | ||
| 4535 | func?! | ||
| 4536 | print abc?["hello world"]?.xyz | ||
| 4537 | |||
| 4538 | x = tab?.value | ||
| 4539 | len = utf8?.len or string?.len or (o) -> #o | ||
| 4540 | |||
| 4541 | if print and x? | ||
| 4542 | print x | ||
| 4543 | |||
| 4544 | with? io.open "test.txt", "w" | ||
| 4545 | \write "hello" | ||
| 4546 | \close! | ||
| 4547 | ``` | ||
| 4548 | |||
| 4549 | </YueDisplay> | ||
| 4550 | |||
| 4551 | ## Piping | 2315 | ## Piping |
| 4552 | 2316 | ||
| 4553 | Instead of a series of nested function calls, you can pipe values with operator **|>**. | 2317 | Instead of a series of nested function calls, you can pipe values with operator **|>**. |
| @@ -4566,24 +2330,6 @@ readFile "example.txt" | |||
| 4566 | 2330 | ||
| 4567 | ``` | 2331 | ``` |
| 4568 | 2332 | ||
| 4569 | <YueDisplay> | ||
| 4570 | |||
| 4571 | ```yue | ||
| 4572 | "hello" |> print | ||
| 4573 | 1 |> print 2 -- insert pipe item as the first argument | ||
| 4574 | 2 |> print 1, _, 3 -- pipe with a placeholder | ||
| 4575 | |||
| 4576 | -- pipe expression in multiline | ||
| 4577 | readFile "example.txt" | ||
| 4578 | |> extract language, {} | ||
| 4579 | |> parse language | ||
| 4580 | |> emit | ||
| 4581 | |> render | ||
| 4582 | |||
| 4583 | ``` | ||
| 4584 | |||
| 4585 | </YueDisplay> | ||
| 4586 | |||
| 4587 | ## Nil Coalescing | 2333 | ## Nil Coalescing |
| 4588 | 2334 | ||
| 4589 | The nil-coalescing operator **??** returns the value of its left-hand operand if it isn't **nil**; otherwise, it evaluates the right-hand operand and returns its result. The **??** operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-nil. | 2335 | The nil-coalescing operator **??** returns the value of its left-hand operand if it isn't **nil**; otherwise, it evaluates the right-hand operand and returns its result. The **??** operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-nil. |
| @@ -4596,17 +2342,6 @@ func a ?? {} | |||
| 4596 | a ??= false | 2342 | a ??= false |
| 4597 | ``` | 2343 | ``` |
| 4598 | 2344 | ||
| 4599 | <YueDisplay> | ||
| 4600 | |||
| 4601 | ```yue | ||
| 4602 | local a, b, c, d | ||
| 4603 | a = b ?? c ?? d | ||
| 4604 | func a ?? {} | ||
| 4605 | a ??= false | ||
| 4606 | ``` | ||
| 4607 | |||
| 4608 | </YueDisplay> | ||
| 4609 | |||
| 4610 | ## Implicit Object | 2345 | ## Implicit Object |
| 4611 | 2346 | ||
| 4612 | You can write a list of implicit structures that starts with the symbol **\*** or **-** inside a table block. If you are creating implicit object, the fields of the object must be with the same indent. | 2347 | You can write a list of implicit structures that starts with the symbol **\*** or **-** inside a table block. If you are creating implicit object, the fields of the object must be with the same indent. |
| @@ -4654,52 +2389,6 @@ tb = | |||
| 4654 | 2389 | ||
| 4655 | ``` | 2390 | ``` |
| 4656 | 2391 | ||
| 4657 | <YueDisplay> | ||
| 4658 | |||
| 4659 | ```yue | ||
| 4660 | -- assignment with implicit object | ||
| 4661 | list = | ||
| 4662 | * 1 | ||
| 4663 | * 2 | ||
| 4664 | * 3 | ||
| 4665 | |||
| 4666 | -- function call with implicit object | ||
| 4667 | func | ||
| 4668 | * 1 | ||
| 4669 | * 2 | ||
| 4670 | * 3 | ||
| 4671 | |||
| 4672 | -- return with implicit object | ||
| 4673 | f = -> | ||
| 4674 | return | ||
| 4675 | * 1 | ||
| 4676 | * 2 | ||
| 4677 | * 3 | ||
| 4678 | |||
| 4679 | -- table with implicit object | ||
| 4680 | tb = | ||
| 4681 | name: "abc" | ||
| 4682 | |||
| 4683 | values: | ||
| 4684 | - "a" | ||
| 4685 | - "b" | ||
| 4686 | - "c" | ||
| 4687 | |||
| 4688 | objects: | ||
| 4689 | - name: "a" | ||
| 4690 | value: 1 | ||
| 4691 | func: => @value + 1 | ||
| 4692 | tb: | ||
| 4693 | fieldA: 1 | ||
| 4694 | |||
| 4695 | - name: "b" | ||
| 4696 | value: 2 | ||
| 4697 | func: => @value + 2 | ||
| 4698 | tb: { } | ||
| 4699 | ``` | ||
| 4700 | |||
| 4701 | </YueDisplay> | ||
| 4702 | |||
| 4703 | # Literals | 2392 | # Literals |
| 4704 | 2393 | ||
| 4705 | All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. | 2394 | All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. |
| @@ -4715,19 +2404,6 @@ some_string = "Here is a string | |||
| 4715 | print "I am #{math.random! * 100}% sure." | 2404 | print "I am #{math.random! * 100}% sure." |
| 4716 | ``` | 2405 | ``` |
| 4717 | 2406 | ||
| 4718 | <YueDisplay> | ||
| 4719 | |||
| 4720 | ```yue | ||
| 4721 | some_string = "Here is a string | ||
| 4722 | that has a line break in it." | ||
| 4723 | |||
| 4724 | -- You can mix expressions into string literals using #{} syntax. | ||
| 4725 | -- String interpolation is only available in double quoted strings. | ||
| 4726 | print "I am #{math.random! * 100}% sure." | ||
| 4727 | ``` | ||
| 4728 | |||
| 4729 | </YueDisplay> | ||
| 4730 | |||
| 4731 | ## Number Literals | 2407 | ## Number Literals |
| 4732 | 2408 | ||
| 4733 | You can use underscores in a number literal to increase readability. | 2409 | You can use underscores in a number literal to increase readability. |
| @@ -4738,16 +2414,6 @@ hex = 0xEF_BB_BF | |||
| 4738 | binary = 0B10011 | 2414 | binary = 0B10011 |
| 4739 | ``` | 2415 | ``` |
| 4740 | 2416 | ||
| 4741 | <YueDisplay> | ||
| 4742 | |||
| 4743 | ```yue | ||
| 4744 | integer = 1_000_000 | ||
| 4745 | hex = 0xEF_BB_BF | ||
| 4746 | binary = 0B10011 | ||
| 4747 | ``` | ||
| 4748 | |||
| 4749 | </YueDisplay> | ||
| 4750 | |||
| 4751 | ## YAML Multiline String | 2417 | ## YAML Multiline String |
| 4752 | 2418 | ||
| 4753 | The `|` prefix introduces a YAML-style multiline string literal: | 2419 | The `|` prefix introduces a YAML-style multiline string literal: |
| @@ -4760,18 +2426,6 @@ str = | | |||
| 4760 | - #{expr} | 2426 | - #{expr} |
| 4761 | ``` | 2427 | ``` |
| 4762 | 2428 | ||
| 4763 | <YueDisplay> | ||
| 4764 | |||
| 4765 | ```yue | ||
| 4766 | str = | | ||
| 4767 | key: value | ||
| 4768 | list: | ||
| 4769 | - item1 | ||
| 4770 | - #{expr} | ||
| 4771 | ``` | ||
| 4772 | |||
| 4773 | </YueDisplay> | ||
| 4774 | |||
| 4775 | This allows writing structured multiline text conveniently. All line breaks and indentation are preserved relative to the first non-empty line, and expressions inside `#{...}` are interpolated automatically as `tostring(expr)`. | 2429 | This allows writing structured multiline text conveniently. All line breaks and indentation are preserved relative to the first non-empty line, and expressions inside `#{...}` are interpolated automatically as `tostring(expr)`. |
| 4776 | 2430 | ||
| 4777 | YAML Multiline String automatically detects the common leading whitespace prefix (minimum indentation across all non-empty lines) and removes it from all lines. This makes it easy to indent your code visually without affecting the resulting string content. | 2431 | YAML Multiline String automatically detects the common leading whitespace prefix (minimum indentation across all non-empty lines) and removes it from all lines. This makes it easy to indent your code visually without affecting the resulting string content. |
| @@ -4784,18 +2438,6 @@ fn = -> | |||
| 4784 | return str | 2438 | return str |
| 4785 | ``` | 2439 | ``` |
| 4786 | 2440 | ||
| 4787 | <YueDisplay> | ||
| 4788 | |||
| 4789 | ```yue | ||
| 4790 | fn = -> | ||
| 4791 | str = | | ||
| 4792 | foo: | ||
| 4793 | bar: baz | ||
| 4794 | return str | ||
| 4795 | ``` | ||
| 4796 | |||
| 4797 | </YueDisplay> | ||
| 4798 | |||
| 4799 | Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. | 2441 | Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. |
| 4800 | 2442 | ||
| 4801 | All special characters like quotes (`"`) and backslashes (`\`) in the YAMLMultiline block are automatically escaped so that the generated Lua string is syntactically valid and behaves as expected. | 2443 | All special characters like quotes (`"`) and backslashes (`\`) in the YAMLMultiline block are automatically escaped so that the generated Lua string is syntactically valid and behaves as expected. |
| @@ -4806,16 +2448,6 @@ str = | | |||
| 4806 | note: 'He said: "#{Hello}!"' | 2448 | note: 'He said: "#{Hello}!"' |
| 4807 | ``` | 2449 | ``` |
| 4808 | 2450 | ||
| 4809 | <YueDisplay> | ||
| 4810 | |||
| 4811 | ```yue | ||
| 4812 | str = | | ||
| 4813 | path: "C:\Program Files\App" | ||
| 4814 | note: 'He said: "#{Hello}!"' | ||
| 4815 | ``` | ||
| 4816 | |||
| 4817 | </YueDisplay> | ||
| 4818 | |||
| 4819 | # Module | 2451 | # Module |
| 4820 | 2452 | ||
| 4821 | ## Import | 2453 | ## Import |
| @@ -4847,35 +2479,6 @@ do | |||
| 4847 | import "export" as {one, two, Something:{umm:{ch}}} | 2479 | import "export" as {one, two, Something:{umm:{ch}}} |
| 4848 | ``` | 2480 | ``` |
| 4849 | 2481 | ||
| 4850 | <YueDisplay> | ||
| 4851 | |||
| 4852 | ```yue | ||
| 4853 | -- used as table destructuring | ||
| 4854 | do | ||
| 4855 | import insert, concat from table | ||
| 4856 | -- report error when assigning to insert, concat | ||
| 4857 | import C, Ct, Cmt from require "lpeg" | ||
| 4858 | -- shortcut for implicit requiring | ||
| 4859 | import x, y, z from 'mymodule' | ||
| 4860 | -- import with Python style | ||
| 4861 | from 'module' import a, b, c | ||
| 4862 | |||
| 4863 | -- shortcut for requring a module | ||
| 4864 | do | ||
| 4865 | import 'module' | ||
| 4866 | import 'module_x' | ||
| 4867 | import "d-a-s-h-e-s" | ||
| 4868 | import "module.part" | ||
| 4869 | |||
| 4870 | -- requring module with aliasing or table destructuring | ||
| 4871 | do | ||
| 4872 | import "player" as PlayerModule | ||
| 4873 | import "lpeg" as :C, :Ct, :Cmt | ||
| 4874 | import "export" as {one, two, Something:{umm:{ch}}} | ||
| 4875 | ``` | ||
| 4876 | |||
| 4877 | </YueDisplay> | ||
| 4878 | |||
| 4879 | ## Import Global | 2482 | ## Import Global |
| 4880 | 2483 | ||
| 4881 | You can import specific globals into local variables with `import`. When importing a chain of global variable accessings, the last field will be assigned to the local variable. | 2484 | You can import specific globals into local variables with `import`. When importing a chain of global variable accessings, the last field will be assigned to the local variable. |
| @@ -4887,17 +2490,6 @@ do | |||
| 4887 | print concat ["a", tostring 1] | 2490 | print concat ["a", tostring 1] |
| 4888 | ``` | 2491 | ``` |
| 4889 | 2492 | ||
| 4890 | <YueDisplay> | ||
| 4891 | |||
| 4892 | ```yue | ||
| 4893 | do | ||
| 4894 | import tostring | ||
| 4895 | import table.concat | ||
| 4896 | print concat ["a", tostring 1] | ||
| 4897 | ``` | ||
| 4898 | |||
| 4899 | </YueDisplay> | ||
| 4900 | |||
| 4901 | ### Automatic Global Variable Import | 2493 | ### Automatic Global Variable Import |
| 4902 | 2494 | ||
| 4903 | You can place `import global` at the top of a block to automatically import all names that have not been explicitly declared or assigned in the current scope as globals. These implicit imports are treated as local consts that reference the corresponding globals at the position of the statement. | 2495 | You can place `import global` at the top of a block to automatically import all names that have not been explicitly declared or assigned in the current scope as globals. These implicit imports are treated as local consts that reference the corresponding globals at the position of the statement. |
| @@ -4919,25 +2511,6 @@ do | |||
| 4919 | FLAG = 123 | 2511 | FLAG = 123 |
| 4920 | ``` | 2512 | ``` |
| 4921 | 2513 | ||
| 4922 | <YueDisplay> | ||
| 4923 | |||
| 4924 | ```yue | ||
| 4925 | do | ||
| 4926 | import global | ||
| 4927 | print "hello" | ||
| 4928 | math.random 3 | ||
| 4929 | -- print = nil -- error: imported globals are const | ||
| 4930 | |||
| 4931 | do | ||
| 4932 | -- explicit global variable will not be imported | ||
| 4933 | import global | ||
| 4934 | global FLAG | ||
| 4935 | print FLAG | ||
| 4936 | FLAG = 123 | ||
| 4937 | ``` | ||
| 4938 | |||
| 4939 | </YueDisplay> | ||
| 4940 | |||
| 4941 | ## Export | 2514 | ## Export |
| 4942 | 2515 | ||
| 4943 | The export statement offers a concise way to define modules. | 2516 | The export statement offers a concise way to define modules. |
| @@ -4962,26 +2535,6 @@ export class Something | |||
| 4962 | umm: "cool" | 2535 | umm: "cool" |
| 4963 | ``` | 2536 | ``` |
| 4964 | 2537 | ||
| 4965 | <YueDisplay> | ||
| 4966 | |||
| 4967 | ```yue | ||
| 4968 | export a, b, c = 1, 2, 3 | ||
| 4969 | export cool = "cat" | ||
| 4970 | |||
| 4971 | export What = if this | ||
| 4972 | "abc" | ||
| 4973 | else | ||
| 4974 | "def" | ||
| 4975 | |||
| 4976 | export y = -> | ||
| 4977 | hallo = 3434 | ||
| 4978 | |||
| 4979 | export class Something | ||
| 4980 | umm: "cool" | ||
| 4981 | ``` | ||
| 4982 | |||
| 4983 | </YueDisplay> | ||
| 4984 | |||
| 4985 | Doing named export with destructuring. | 2538 | Doing named export with destructuring. |
| 4986 | 2539 | ||
| 4987 | ```yuescript | 2540 | ```yuescript |
| @@ -4989,15 +2542,6 @@ export :loadstring, to_lua: tolua = yue | |||
| 4989 | export {itemA: {:fieldA = 'default'}} = tb | 2542 | export {itemA: {:fieldA = 'default'}} = tb |
| 4990 | ``` | 2543 | ``` |
| 4991 | 2544 | ||
| 4992 | <YueDisplay> | ||
| 4993 | |||
| 4994 | ```yue | ||
| 4995 | export :loadstring, to_lua: tolua = yue | ||
| 4996 | export {itemA: {:fieldA = 'default'}} = tb | ||
| 4997 | ``` | ||
| 4998 | |||
| 4999 | </YueDisplay> | ||
| 5000 | |||
| 5001 | Export named items from module without creating local variables. | 2545 | Export named items from module without creating local variables. |
| 5002 | 2546 | ||
| 5003 | ```yuescript | 2547 | ```yuescript |
| @@ -5006,16 +2550,6 @@ export.<index> = items | |||
| 5006 | export["a-b-c"] = 123 | 2550 | export["a-b-c"] = 123 |
| 5007 | ``` | 2551 | ``` |
| 5008 | 2552 | ||
| 5009 | <YueDisplay> | ||
| 5010 | |||
| 5011 | ```yue | ||
| 5012 | export.itemA = tb | ||
| 5013 | export.<index> = items | ||
| 5014 | export["a-b-c"] = 123 | ||
| 5015 | ``` | ||
| 5016 | |||
| 5017 | </YueDisplay> | ||
| 5018 | |||
| 5019 | ### Unnamed Export | 2553 | ### Unnamed Export |
| 5020 | 2554 | ||
| 5021 | Unnamed export will add the target item into the array part of the exported table. | 2555 | Unnamed export will add the target item into the array part of the exported table. |
| @@ -5033,23 +2567,6 @@ export with tmp | |||
| 5033 | j = 2000 | 2567 | j = 2000 |
| 5034 | ``` | 2568 | ``` |
| 5035 | 2569 | ||
| 5036 | <YueDisplay> | ||
| 5037 | |||
| 5038 | ```yue | ||
| 5039 | d, e, f = 3, 2, 1 | ||
| 5040 | export d, e, f | ||
| 5041 | |||
| 5042 | export if this | ||
| 5043 | 123 | ||
| 5044 | else | ||
| 5045 | 456 | ||
| 5046 | |||
| 5047 | export with tmp | ||
| 5048 | j = 2000 | ||
| 5049 | ``` | ||
| 5050 | |||
| 5051 | </YueDisplay> | ||
| 5052 | |||
| 5053 | ### Default Export | 2570 | ### Default Export |
| 5054 | 2571 | ||
| 5055 | Using the **default** keyword in export statement to replace the exported table with any thing. | 2572 | Using the **default** keyword in export statement to replace the exported table with any thing. |
| @@ -5060,16 +2577,6 @@ export default -> | |||
| 5060 | 123 | 2577 | 123 |
| 5061 | ``` | 2578 | ``` |
| 5062 | 2579 | ||
| 5063 | <YueDisplay> | ||
| 5064 | |||
| 5065 | ```yue | ||
| 5066 | export default -> | ||
| 5067 | print "hello" | ||
| 5068 | 123 | ||
| 5069 | ``` | ||
| 5070 | |||
| 5071 | </YueDisplay> | ||
| 5072 | |||
| 5073 | # License: MIT | 2580 | # License: MIT |
| 5074 | 2581 | ||
| 5075 | Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\> | 2582 | Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\> |
diff --git a/doc/yue-id-id.md b/doc/yue-id-id.md index ca90d85..200438e 100644 --- a/doc/yue-id-id.md +++ b/doc/yue-id-id.md | |||
| @@ -1,11 +1,5 @@ | |||
| 1 | --- | ||
| 2 | title: Referensi | ||
| 3 | --- | ||
| 4 | |||
| 5 | # Dokumentasi YueScript | 1 | # Dokumentasi YueScript |
| 6 | 2 | ||
| 7 | <img src="/image/yuescript.svg" width="250px" height="250px" alt="logo" style="padding-top: 3em; padding-bottom: 2em;"/> | ||
| 8 | |||
| 9 | Selamat datang di dokumentasi resmi <b>YueScript</b>!<br/> | 3 | Selamat datang di dokumentasi resmi <b>YueScript</b>!<br/> |
| 10 | Di sini Anda dapat menemukan fitur bahasa, penggunaan, contoh referensi, dan sumber daya.<br/> | 4 | Di sini Anda dapat menemukan fitur bahasa, penggunaan, contoh referensi, dan sumber daya.<br/> |
| 11 | Silakan pilih bab dari sidebar untuk mulai mempelajari YueScript. | 5 | Silakan pilih bab dari sidebar untuk mulai mempelajari YueScript. |
| @@ -21,17 +15,6 @@ do | |||
| 21 | print var -- nil di sini | 15 | print var -- nil di sini |
| 22 | ``` | 16 | ``` |
| 23 | 17 | ||
| 24 | <YueDisplay> | ||
| 25 | |||
| 26 | ```yue | ||
| 27 | do | ||
| 28 | var = "hello" | ||
| 29 | print var | ||
| 30 | print var -- nil di sini | ||
| 31 | ``` | ||
| 32 | |||
| 33 | </YueDisplay> | ||
| 34 | |||
| 35 | `do` di YueScript juga bisa digunakan sebagai ekspresi, memungkinkan Anda menggabungkan beberapa baris menjadi satu. Hasil ekspresi `do` adalah pernyataan terakhir di badannya. Ekspresi `do` mendukung penggunaan `break` untuk memutus alur eksekusi dan mengembalikan banyak nilai lebih awal. | 18 | `do` di YueScript juga bisa digunakan sebagai ekspresi, memungkinkan Anda menggabungkan beberapa baris menjadi satu. Hasil ekspresi `do` adalah pernyataan terakhir di badannya. Ekspresi `do` mendukung penggunaan `break` untuk memutus alur eksekusi dan mengembalikan banyak nilai lebih awal. |
| 36 | 19 | ||
| 37 | ```yuescript | 20 | ```yuescript |
| @@ -42,18 +25,6 @@ status, value = do | |||
| 42 | break "small", n | 25 | break "small", n |
| 43 | ``` | 26 | ``` |
| 44 | 27 | ||
| 45 | <YueDisplay> | ||
| 46 | |||
| 47 | ```yue | ||
| 48 | status, value = do | ||
| 49 | n = 12 | ||
| 50 | if n > 10 | ||
| 51 | break "large", n | ||
| 52 | break "small", n | ||
| 53 | ``` | ||
| 54 | |||
| 55 | </YueDisplay> | ||
| 56 | |||
| 57 | ```yuescript | 28 | ```yuescript |
| 58 | counter = do | 29 | counter = do |
| 59 | i = 0 | 30 | i = 0 |
| @@ -65,21 +36,6 @@ print counter! | |||
| 65 | print counter! | 36 | print counter! |
| 66 | ``` | 37 | ``` |
| 67 | 38 | ||
| 68 | <YueDisplay> | ||
| 69 | |||
| 70 | ```yue | ||
| 71 | counter = do | ||
| 72 | i = 0 | ||
| 73 | -> | ||
| 74 | i += 1 | ||
| 75 | i | ||
| 76 | |||
| 77 | print counter! | ||
| 78 | print counter! | ||
| 79 | ``` | ||
| 80 | |||
| 81 | </YueDisplay> | ||
| 82 | |||
| 83 | ```yuescript | 39 | ```yuescript |
| 84 | tbl = { | 40 | tbl = { |
| 85 | key: do | 41 | key: do |
| @@ -88,18 +44,6 @@ tbl = { | |||
| 88 | } | 44 | } |
| 89 | ``` | 45 | ``` |
| 90 | 46 | ||
| 91 | <YueDisplay> | ||
| 92 | |||
| 93 | ```yue | ||
| 94 | tbl = { | ||
| 95 | key: do | ||
| 96 | print "assigning key!" | ||
| 97 | 1234 | ||
| 98 | } | ||
| 99 | ``` | ||
| 100 | |||
| 101 | </YueDisplay> | ||
| 102 | |||
| 103 | # Dekorator Baris | 47 | # Dekorator Baris |
| 104 | 48 | ||
| 105 | Untuk kemudahan, loop for dan pernyataan if dapat diterapkan pada pernyataan tunggal di akhir baris: | 49 | Untuk kemudahan, loop for dan pernyataan if dapat diterapkan pada pernyataan tunggal di akhir baris: |
| @@ -108,28 +52,12 @@ Untuk kemudahan, loop for dan pernyataan if dapat diterapkan pada pernyataan tun | |||
| 108 | print "hello world" if name == "Rob" | 52 | print "hello world" if name == "Rob" |
| 109 | ``` | 53 | ``` |
| 110 | 54 | ||
| 111 | <YueDisplay> | ||
| 112 | |||
| 113 | ```yue | ||
| 114 | print "hello world" if name == "Rob" | ||
| 115 | ``` | ||
| 116 | |||
| 117 | </YueDisplay> | ||
| 118 | |||
| 119 | Dan dengan loop dasar: | 55 | Dan dengan loop dasar: |
| 120 | 56 | ||
| 121 | ```yuescript | 57 | ```yuescript |
| 122 | print "item: ", item for item in *items | 58 | print "item: ", item for item in *items |
| 123 | ``` | 59 | ``` |
| 124 | 60 | ||
| 125 | <YueDisplay> | ||
| 126 | |||
| 127 | ```yue | ||
| 128 | print "item: ", item for item in *items | ||
| 129 | ``` | ||
| 130 | |||
| 131 | </YueDisplay> | ||
| 132 | |||
| 133 | Dan dengan loop while: | 61 | Dan dengan loop while: |
| 134 | 62 | ||
| 135 | ```yuescript | 63 | ```yuescript |
| @@ -138,16 +66,6 @@ game\update! while game\isRunning! | |||
| 138 | reader\parse_line! until reader\eof! | 66 | reader\parse_line! until reader\eof! |
| 139 | ``` | 67 | ``` |
| 140 | 68 | ||
| 141 | <YueDisplay> | ||
| 142 | |||
| 143 | ```yue | ||
| 144 | game\update! while game\isRunning! | ||
| 145 | |||
| 146 | reader\parse_line! until reader\eof! | ||
| 147 | ``` | ||
| 148 | |||
| 149 | </YueDisplay> | ||
| 150 | |||
| 151 | # Makro | 69 | # Makro |
| 152 | 70 | ||
| 153 | ## Penggunaan Umum | 71 | ## Penggunaan Umum |
| @@ -183,39 +101,6 @@ if $and f1!, f2!, f3! | |||
| 183 | print "OK" | 101 | print "OK" |
| 184 | ``` | 102 | ``` |
| 185 | 103 | ||
| 186 | <YueDisplay> | ||
| 187 | |||
| 188 | ```yue | ||
| 189 | macro PI2 = -> math.pi * 2 | ||
| 190 | area = $PI2 * 5 | ||
| 191 | |||
| 192 | macro HELLO = -> "'hello world'" | ||
| 193 | print $HELLO | ||
| 194 | |||
| 195 | macro config = (debugging) -> | ||
| 196 | global debugMode = debugging == "true" | ||
| 197 | "" | ||
| 198 | |||
| 199 | macro asserts = (cond) -> | ||
| 200 | debugMode and "assert #{cond}" or "" | ||
| 201 | |||
| 202 | macro assert = (cond) -> | ||
| 203 | debugMode and "assert #{cond}" or "#{cond}" | ||
| 204 | |||
| 205 | $config true | ||
| 206 | $asserts item ~= nil | ||
| 207 | |||
| 208 | $config false | ||
| 209 | value = $assert item | ||
| 210 | |||
| 211 | -- ekspresi yang dikirim diperlakukan sebagai string | ||
| 212 | macro and = (...) -> "#{ table.concat {...}, ' and ' }" | ||
| 213 | if $and f1!, f2!, f3! | ||
| 214 | print "OK" | ||
| 215 | ``` | ||
| 216 | |||
| 217 | </YueDisplay> | ||
| 218 | |||
| 219 | ## Menyisipkan Kode Mentah | 104 | ## Menyisipkan Kode Mentah |
| 220 | 105 | ||
| 221 | Fungsi macro bisa mengembalikan string YueScript atau tabel konfigurasi yang berisi kode Lua. | 106 | Fungsi macro bisa mengembalikan string YueScript atau tabel konfigurasi yang berisi kode Lua. |
| @@ -246,36 +131,6 @@ end | |||
| 246 | ]==] | 131 | ]==] |
| 247 | ``` | 132 | ``` |
| 248 | 133 | ||
| 249 | <YueDisplay> | ||
| 250 | |||
| 251 | ```yue | ||
| 252 | macro yueFunc = (var) -> "local #{var} = ->" | ||
| 253 | $yueFunc funcA | ||
| 254 | funcA = -> "gagal meng-assign ke variabel yang didefinisikan oleh macro Yue" | ||
| 255 | |||
| 256 | macro luaFunc = (var) -> { | ||
| 257 | code: "local function #{var}() end" | ||
| 258 | type: "lua" | ||
| 259 | } | ||
| 260 | $luaFunc funcB | ||
| 261 | funcB = -> "gagal meng-assign ke variabel yang didefinisikan oleh macro Lua" | ||
| 262 | |||
| 263 | macro lua = (code) -> { | ||
| 264 | :code | ||
| 265 | type: "lua" | ||
| 266 | } | ||
| 267 | |||
| 268 | -- simbol awal dan akhir string mentah otomatis di-trim | ||
| 269 | $lua[==[ | ||
| 270 | -- penyisipan kode Lua mentah | ||
| 271 | if cond then | ||
| 272 | print("output") | ||
| 273 | end | ||
| 274 | ]==] | ||
| 275 | ``` | ||
| 276 | |||
| 277 | </YueDisplay> | ||
| 278 | |||
| 279 | ## Export Macro | 134 | ## Export Macro |
| 280 | 135 | ||
| 281 | Fungsi macro dapat diekspor dari modul dan diimpor di modul lain. Anda harus menaruh fungsi macro export dalam satu file agar dapat digunakan, dan hanya definisi macro, impor macro, dan ekspansi macro yang boleh ada di modul export macro. | 136 | Fungsi macro dapat diekspor dari modul dan diimpor di modul lain. Anda harus menaruh fungsi macro export dalam satu file agar dapat digunakan, dan hanya definisi macro, impor macro, dan ekspansi macro yang boleh ada di modul export macro. |
| @@ -295,28 +150,6 @@ import "utils" as { | |||
| 295 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | 150 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ |
| 296 | ``` | 151 | ``` |
| 297 | 152 | ||
| 298 | <YueDisplay> | ||
| 299 | |||
| 300 | ```yue | ||
| 301 | -- file: utils.yue | ||
| 302 | export macro map = (items, action) -> "[#{action} for _ in *#{items}]" | ||
| 303 | export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" | ||
| 304 | export macro foreach = (items, action) -> "for _ in *#{items} | ||
| 305 | #{action}" | ||
| 306 | |||
| 307 | -- file main.yue | ||
| 308 | -- fungsi import tidak tersedia di browser, coba di lingkungan nyata | ||
| 309 | --[[ | ||
| 310 | import "utils" as { | ||
| 311 | $, -- simbol untuk mengimpor semua macro | ||
| 312 | $foreach: $each -- ganti nama macro $foreach menjadi $each | ||
| 313 | } | ||
| 314 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | ||
| 315 | ]] | ||
| 316 | ``` | ||
| 317 | |||
| 318 | </YueDisplay> | ||
| 319 | |||
| 320 | ## Macro Bawaan | 153 | ## Macro Bawaan |
| 321 | 154 | ||
| 322 | Ada beberapa macro bawaan tetapi Anda bisa menimpanya dengan mendeklarasikan macro dengan nama yang sama. | 155 | Ada beberapa macro bawaan tetapi Anda bisa menimpanya dengan mendeklarasikan macro dengan nama yang sama. |
| @@ -326,15 +159,6 @@ print $FILE -- mendapatkan string nama modul saat ini | |||
| 326 | print $LINE -- mendapatkan angka 2 | 159 | print $LINE -- mendapatkan angka 2 |
| 327 | ``` | 160 | ``` |
| 328 | 161 | ||
| 329 | <YueDisplay> | ||
| 330 | |||
| 331 | ```yue | ||
| 332 | print $FILE -- mendapatkan string nama modul saat ini | ||
| 333 | print $LINE -- mendapatkan angka 2 | ||
| 334 | ``` | ||
| 335 | |||
| 336 | </YueDisplay> | ||
| 337 | |||
| 338 | ## Menghasilkan Macro dengan Macro | 162 | ## Menghasilkan Macro dengan Macro |
| 339 | 163 | ||
| 340 | Di YueScript, fungsi macro memungkinkan Anda menghasilkan kode pada waktu kompilasi. Dengan menumpuk fungsi macro, Anda dapat membuat pola generasi yang lebih kompleks. Fitur ini memungkinkan Anda mendefinisikan fungsi macro yang menghasilkan fungsi macro lain, sehingga menghasilkan kode yang lebih dinamis. | 164 | Di YueScript, fungsi macro memungkinkan Anda menghasilkan kode pada waktu kompilasi. Dengan menumpuk fungsi macro, Anda dapat membuat pola generasi yang lebih kompleks. Fitur ini memungkinkan Anda mendefinisikan fungsi macro yang menghasilkan fungsi macro lain, sehingga menghasilkan kode yang lebih dinamis. |
| @@ -357,28 +181,6 @@ print "Valid enum type:", $BodyType Static | |||
| 357 | -- print "Compilation error with enum type:", $BodyType Unknown | 181 | -- print "Compilation error with enum type:", $BodyType Unknown |
| 358 | ``` | 182 | ``` |
| 359 | 183 | ||
| 360 | <YueDisplay> | ||
| 361 | |||
| 362 | ```yue | ||
| 363 | macro Enum = (...) -> | ||
| 364 | items = {...} | ||
| 365 | itemSet = {item, true for item in *items} | ||
| 366 | (item) -> | ||
| 367 | error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] | ||
| 368 | "\"#{item}\"" | ||
| 369 | |||
| 370 | macro BodyType = $Enum( | ||
| 371 | Static | ||
| 372 | Dynamic | ||
| 373 | Kinematic | ||
| 374 | ) | ||
| 375 | |||
| 376 | print "Valid enum type:", $BodyType Static | ||
| 377 | -- print "Compilation error with enum type:", $BodyType Unknown | ||
| 378 | ``` | ||
| 379 | |||
| 380 | </YueDisplay> | ||
| 381 | |||
| 382 | ## Validasi Argumen | 184 | ## Validasi Argumen |
| 383 | 185 | ||
| 384 | Anda dapat mendeklarasikan tipe node AST yang diharapkan dalam daftar argumen, dan memeriksa apakah argumen macro yang masuk memenuhi harapan pada waktu kompilasi. | 186 | Anda dapat mendeklarasikan tipe node AST yang diharapkan dalam daftar argumen, dan memeriksa apakah argumen macro yang masuk memenuhi harapan pada waktu kompilasi. |
| @@ -393,20 +195,6 @@ macro printNumAndStr = (num `Num, str `String) -> | | |||
| 393 | $printNumAndStr 123, "hello" | 195 | $printNumAndStr 123, "hello" |
| 394 | ``` | 196 | ``` |
| 395 | 197 | ||
| 396 | <YueDisplay> | ||
| 397 | |||
| 398 | ```yue | ||
| 399 | macro printNumAndStr = (num `Num, str `String) -> | | ||
| 400 | print( | ||
| 401 | #{num} | ||
| 402 | #{str} | ||
| 403 | ) | ||
| 404 | |||
| 405 | $printNumAndStr 123, "hello" | ||
| 406 | ``` | ||
| 407 | |||
| 408 | </YueDisplay> | ||
| 409 | |||
| 410 | Jika Anda membutuhkan pengecekan argumen yang lebih fleksibel, Anda dapat menggunakan fungsi macro bawaan `$is_ast` untuk memeriksa secara manual pada tempat yang tepat. | 198 | Jika Anda membutuhkan pengecekan argumen yang lebih fleksibel, Anda dapat menggunakan fungsi macro bawaan `$is_ast` untuk memeriksa secara manual pada tempat yang tepat. |
| 411 | 199 | ||
| 412 | ```yuescript | 200 | ```yuescript |
| @@ -418,19 +206,6 @@ macro printNumAndStr = (num, str) -> | |||
| 418 | $printNumAndStr 123, "hello" | 206 | $printNumAndStr 123, "hello" |
| 419 | ``` | 207 | ``` |
| 420 | 208 | ||
| 421 | <YueDisplay> | ||
| 422 | |||
| 423 | ```yue | ||
| 424 | macro printNumAndStr = (num, str) -> | ||
| 425 | error "expected Num as first argument" unless $is_ast Num, num | ||
| 426 | error "expected String as second argument" unless $is_ast String, str | ||
| 427 | "print(#{num}, #{str})" | ||
| 428 | |||
| 429 | $printNumAndStr 123, "hello" | ||
| 430 | ``` | ||
| 431 | |||
| 432 | </YueDisplay> | ||
| 433 | |||
| 434 | Untuk detail lebih lanjut tentang node AST yang tersedia, silakan lihat definisi huruf besar di [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). | 209 | Untuk detail lebih lanjut tentang node AST yang tersedia, silakan lihat definisi huruf besar di [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). |
| 435 | 210 | ||
| 436 | # Try | 211 | # Try |
| @@ -465,38 +240,6 @@ catch err | |||
| 465 | print result | 240 | print result |
| 466 | ``` | 241 | ``` |
| 467 | 242 | ||
| 468 | <YueDisplay> | ||
| 469 | |||
| 470 | ```yue | ||
| 471 | try | ||
| 472 | func 1, 2, 3 | ||
| 473 | catch err | ||
| 474 | print yue.traceback err | ||
| 475 | |||
| 476 | success, result = try | ||
| 477 | func 1, 2, 3 | ||
| 478 | catch err | ||
| 479 | yue.traceback err | ||
| 480 | |||
| 481 | try func 1, 2, 3 | ||
| 482 | catch err | ||
| 483 | print yue.traceback err | ||
| 484 | |||
| 485 | success, result = try func 1, 2, 3 | ||
| 486 | |||
| 487 | try | ||
| 488 | print "trying" | ||
| 489 | func 1, 2, 3 | ||
| 490 | |||
| 491 | -- bekerja dengan pola if assignment | ||
| 492 | if success, result := try func 1, 2, 3 | ||
| 493 | catch err | ||
| 494 | print yue.traceback err | ||
| 495 | print result | ||
| 496 | ``` | ||
| 497 | |||
| 498 | </YueDisplay> | ||
| 499 | |||
| 500 | ## Try? | 243 | ## Try? |
| 501 | 244 | ||
| 502 | `try?` adalah bentuk sederhana untuk penanganan error yang menghilangkan status boolean dari pernyataan `try`, dan akan mengembalikan hasil dari blok try ketika berhasil, atau mengembalikan nil alih-alih objek error bila gagal. | 245 | `try?` adalah bentuk sederhana untuk penanganan error yang menghilangkan status boolean dari pernyataan `try`, dan akan mengembalikan hasil dari blok try ketika berhasil, atau mengembalikan nil alih-alih objek error bila gagal. |
| @@ -519,44 +262,14 @@ catch e | |||
| 519 | e | 262 | e |
| 520 | ``` | 263 | ``` |
| 521 | 264 | ||
| 522 | <YueDisplay> | ||
| 523 | |||
| 524 | ```yue | ||
| 525 | a, b, c = try? func! | ||
| 526 | |||
| 527 | -- dengan operator nil coalescing | ||
| 528 | a = (try? func!) ?? "default" | ||
| 529 | |||
| 530 | -- sebagai argumen fungsi | ||
| 531 | f try? func! | ||
| 532 | |||
| 533 | -- dengan blok catch | ||
| 534 | f try? | ||
| 535 | print 123 | ||
| 536 | func! | ||
| 537 | catch e | ||
| 538 | print e | ||
| 539 | e | ||
| 540 | ``` | ||
| 541 | |||
| 542 | </YueDisplay> | ||
| 543 | |||
| 544 | # Literal Tabel | 265 | # Literal Tabel |
| 545 | 266 | ||
| 546 | Seperti di Lua, tabel dibatasi dengan kurung kurawal. | 267 | Seperti di Lua, tabel dibatasi dengan kurung kurawal. |
| 547 | 268 | ||
| 548 | ```yuescript | 269 | ```yuescript |
| 549 | some_values = [1, 2, 3, 4] | 270 | some_values = {1, 2, 3, 4} |
| 550 | ``` | ||
| 551 | |||
| 552 | <YueDisplay> | ||
| 553 | |||
| 554 | ```yue | ||
| 555 | some_values = [1, 2, 3, 4] | ||
| 556 | ``` | 271 | ``` |
| 557 | 272 | ||
| 558 | </YueDisplay> | ||
| 559 | |||
| 560 | Berbeda dengan Lua, assignment nilai ke sebuah kunci di tabel dilakukan dengan **:** (bukan **=**). | 273 | Berbeda dengan Lua, assignment nilai ke sebuah kunci di tabel dilakukan dengan **:** (bukan **=**). |
| 561 | 274 | ||
| 562 | ```yuescript | 275 | ```yuescript |
| @@ -567,18 +280,6 @@ some_values = { | |||
| 567 | } | 280 | } |
| 568 | ``` | 281 | ``` |
| 569 | 282 | ||
| 570 | <YueDisplay> | ||
| 571 | |||
| 572 | ```yue | ||
| 573 | some_values = { | ||
| 574 | name: "Bill", | ||
| 575 | age: 200, | ||
| 576 | ["favorite food"]: "rice" | ||
| 577 | } | ||
| 578 | ``` | ||
| 579 | |||
| 580 | </YueDisplay> | ||
| 581 | |||
| 582 | Kurung kurawal dapat dihilangkan jika hanya satu tabel pasangan key-value yang di-assign. | 283 | Kurung kurawal dapat dihilangkan jika hanya satu tabel pasangan key-value yang di-assign. |
| 583 | 284 | ||
| 584 | ```yuescript | 285 | ```yuescript |
| @@ -588,17 +289,6 @@ profile = | |||
| 588 | favorite_foods: ["ice cream", "donuts"] | 289 | favorite_foods: ["ice cream", "donuts"] |
| 589 | ``` | 290 | ``` |
| 590 | 291 | ||
| 591 | <YueDisplay> | ||
| 592 | |||
| 593 | ```yue | ||
| 594 | profile = | ||
| 595 | height: "4 feet", | ||
| 596 | shoe_size: 13, | ||
| 597 | favorite_foods: ["ice cream", "donuts"] | ||
| 598 | ``` | ||
| 599 | |||
| 600 | </YueDisplay> | ||
| 601 | |||
| 602 | Baris baru dapat digunakan untuk memisahkan nilai sebagai ganti koma (atau keduanya): | 292 | Baris baru dapat digunakan untuk memisahkan nilai sebagai ganti koma (atau keduanya): |
| 603 | 293 | ||
| 604 | ```yuescript | 294 | ```yuescript |
| @@ -610,19 +300,6 @@ values = { | |||
| 610 | } | 300 | } |
| 611 | ``` | 301 | ``` |
| 612 | 302 | ||
| 613 | <YueDisplay> | ||
| 614 | |||
| 615 | ```yue | ||
| 616 | values = { | ||
| 617 | 1, 2, 3, 4 | ||
| 618 | 5, 6, 7, 8 | ||
| 619 | name: "superman" | ||
| 620 | occupation: "crime fighting" | ||
| 621 | } | ||
| 622 | ``` | ||
| 623 | |||
| 624 | </YueDisplay> | ||
| 625 | |||
| 626 | Saat membuat literal tabel satu baris, kurung kurawal juga bisa dihilangkan: | 303 | Saat membuat literal tabel satu baris, kurung kurawal juga bisa dihilangkan: |
| 627 | 304 | ||
| 628 | ```yuescript | 305 | ```yuescript |
| @@ -631,16 +308,6 @@ my_function dance: "Tango", partner: "none" | |||
| 631 | y = type: "dog", legs: 4, tails: 1 | 308 | y = type: "dog", legs: 4, tails: 1 |
| 632 | ``` | 309 | ``` |
| 633 | 310 | ||
| 634 | <YueDisplay> | ||
| 635 | |||
| 636 | ```yue | ||
| 637 | my_function dance: "Tango", partner: "none" | ||
| 638 | |||
| 639 | y = type: "dog", legs: 4, tails: 1 | ||
| 640 | ``` | ||
| 641 | |||
| 642 | </YueDisplay> | ||
| 643 | |||
| 644 | Kunci literal tabel dapat berupa kata kunci bahasa tanpa perlu di-escape: | 311 | Kunci literal tabel dapat berupa kata kunci bahasa tanpa perlu di-escape: |
| 645 | 312 | ||
| 646 | ```yuescript | 313 | ```yuescript |
| @@ -650,17 +317,6 @@ tbl = { | |||
| 650 | } | 317 | } |
| 651 | ``` | 318 | ``` |
| 652 | 319 | ||
| 653 | <YueDisplay> | ||
| 654 | |||
| 655 | ```yue | ||
| 656 | tbl = { | ||
| 657 | do: "something" | ||
| 658 | end: "hunger" | ||
| 659 | } | ||
| 660 | ``` | ||
| 661 | |||
| 662 | </YueDisplay> | ||
| 663 | |||
| 664 | Jika Anda membangun tabel dari variabel dan ingin kunci sama dengan nama variabel, maka operator prefiks **:** dapat digunakan: | 320 | Jika Anda membangun tabel dari variabel dan ingin kunci sama dengan nama variabel, maka operator prefiks **:** dapat digunakan: |
| 665 | 321 | ||
| 666 | ```yuescript | 322 | ```yuescript |
| @@ -671,18 +327,6 @@ person = { :hair, :height, shoe_size: 40 } | |||
| 671 | print_table :hair, :height | 327 | print_table :hair, :height |
| 672 | ``` | 328 | ``` |
| 673 | 329 | ||
| 674 | <YueDisplay> | ||
| 675 | |||
| 676 | ```yue | ||
| 677 | hair = "golden" | ||
| 678 | height = 200 | ||
| 679 | person = { :hair, :height, shoe_size: 40 } | ||
| 680 | |||
| 681 | print_table :hair, :height | ||
| 682 | ``` | ||
| 683 | |||
| 684 | </YueDisplay> | ||
| 685 | |||
| 686 | Jika Anda ingin kunci field dalam tabel menjadi hasil suatu ekspresi, Anda dapat membungkusnya dengan **[ ]**, seperti di Lua. Anda juga bisa menggunakan literal string langsung sebagai kunci tanpa tanda kurung siku. Ini berguna jika kunci memiliki karakter khusus. | 330 | Jika Anda ingin kunci field dalam tabel menjadi hasil suatu ekspresi, Anda dapat membungkusnya dengan **[ ]**, seperti di Lua. Anda juga bisa menggunakan literal string langsung sebagai kunci tanpa tanda kurung siku. Ini berguna jika kunci memiliki karakter khusus. |
| 687 | 331 | ||
| 688 | ```yuescript | 332 | ```yuescript |
| @@ -692,33 +336,13 @@ t = { | |||
| 692 | } | 336 | } |
| 693 | ``` | 337 | ``` |
| 694 | 338 | ||
| 695 | <YueDisplay> | 339 | Tabel Lua memiliki bagian array dan bagian hash, tetapi kadang-kadang berguna untuk membuat perbedaan semantik di antara keduanya. Anda dapat menggunakan **[ ]** sebagai ganti **{ }** untuk mendeklarasikan tabel secara eksplisit sebagai array, dengan begitu akan mencegah pasangan key-value dituliskan di dalamnya. |
| 696 | |||
| 697 | ```yue | ||
| 698 | t = { | ||
| 699 | [1 + 2]: "hello" | ||
| 700 | "hello world": true | ||
| 701 | } | ||
| 702 | ``` | ||
| 703 | |||
| 704 | </YueDisplay> | ||
| 705 | |||
| 706 | Tabel Lua memiliki bagian array dan bagian hash, tetapi terkadang Anda ingin membedakan penggunaan array dan hash secara semantik saat menulis tabel Lua. Maka Anda bisa menulis tabel Lua dengan **[ ]** alih-alih **{ }** untuk merepresentasikan tabel array, dan menuliskan pasangan key-value di tabel list tidak akan diizinkan. | ||
| 707 | 340 | ||
| 708 | ```yuescript | 341 | ```yuescript |
| 709 | some_values = [1, 2, 3, 4] | 342 | some_values = [1, 2, 3, 4] |
| 710 | list_with_one_element = [1, ] | 343 | list_with_one_element = [1, ] |
| 711 | ``` | 344 | ``` |
| 712 | 345 | ||
| 713 | <YueDisplay> | ||
| 714 | |||
| 715 | ```yue | ||
| 716 | some_values = [1, 2, 3, 4] | ||
| 717 | list_with_one_element = [1, ] | ||
| 718 | ``` | ||
| 719 | |||
| 720 | </YueDisplay> | ||
| 721 | |||
| 722 | # Komprehensi | 346 | # Komprehensi |
| 723 | 347 | ||
| 724 | Komprehensi menyediakan sintaks yang nyaman untuk membangun tabel baru dengan mengiterasi objek yang ada dan menerapkan ekspresi pada nilainya. Ada dua jenis komprehensi: komprehensi list dan komprehensi tabel. Keduanya menghasilkan tabel Lua; komprehensi list mengakumulasi nilai ke tabel mirip array, dan komprehensi tabel memungkinkan Anda menetapkan kunci dan nilai pada setiap iterasi. | 348 | Komprehensi menyediakan sintaks yang nyaman untuk membangun tabel baru dengan mengiterasi objek yang ada dan menerapkan ekspresi pada nilainya. Ada dua jenis komprehensi: komprehensi list dan komprehensi tabel. Keduanya menghasilkan tabel Lua; komprehensi list mengakumulasi nilai ke tabel mirip array, dan komprehensi tabel memungkinkan Anda menetapkan kunci dan nilai pada setiap iterasi. |
| @@ -732,43 +356,18 @@ items = [ 1, 2, 3, 4 ] | |||
| 732 | doubled = [item * 2 for i, item in ipairs items] | 356 | doubled = [item * 2 for i, item in ipairs items] |
| 733 | ``` | 357 | ``` |
| 734 | 358 | ||
| 735 | <YueDisplay> | ||
| 736 | |||
| 737 | ```yue | ||
| 738 | items = [ 1, 2, 3, 4 ] | ||
| 739 | doubled = [item * 2 for i, item in ipairs items] | ||
| 740 | ``` | ||
| 741 | |||
| 742 | </YueDisplay> | ||
| 743 | |||
| 744 | Item yang disertakan dalam tabel baru bisa dibatasi dengan klausa `when`: | 359 | Item yang disertakan dalam tabel baru bisa dibatasi dengan klausa `when`: |
| 745 | 360 | ||
| 746 | ```yuescript | 361 | ```yuescript |
| 747 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | 362 | slice = [item for i, item in ipairs items when i > 1 and i < 3] |
| 748 | ``` | 363 | ``` |
| 749 | 364 | ||
| 750 | <YueDisplay> | ||
| 751 | |||
| 752 | ```yue | ||
| 753 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | ||
| 754 | ``` | ||
| 755 | |||
| 756 | </YueDisplay> | ||
| 757 | |||
| 758 | Karena umum untuk mengiterasi nilai dari tabel berindeks numerik, operator **\*** diperkenalkan. Contoh `doubled` bisa ditulis ulang sebagai: | 365 | Karena umum untuk mengiterasi nilai dari tabel berindeks numerik, operator **\*** diperkenalkan. Contoh `doubled` bisa ditulis ulang sebagai: |
| 759 | 366 | ||
| 760 | ```yuescript | 367 | ```yuescript |
| 761 | doubled = [item * 2 for item in *items] | 368 | doubled = [item * 2 for item in *items] |
| 762 | ``` | 369 | ``` |
| 763 | 370 | ||
| 764 | <YueDisplay> | ||
| 765 | |||
| 766 | ```yue | ||
| 767 | doubled = [item * 2 for item in *items] | ||
| 768 | ``` | ||
| 769 | |||
| 770 | </YueDisplay> | ||
| 771 | |||
| 772 | Dalam komprehensi list, Anda juga bisa menggunakan operator spread `...` untuk meratakan list bertingkat, menghasilkan efek flat map: | 371 | Dalam komprehensi list, Anda juga bisa menggunakan operator spread `...` untuk meratakan list bertingkat, menghasilkan efek flat map: |
| 773 | 372 | ||
| 774 | ```yuescript | 373 | ```yuescript |
| @@ -780,19 +379,6 @@ flat = [...v for k,v in pairs data] | |||
| 780 | -- flat sekarang [1, 2, 3, 4, 5, 6] | 379 | -- flat sekarang [1, 2, 3, 4, 5, 6] |
| 781 | ``` | 380 | ``` |
| 782 | 381 | ||
| 783 | <YueDisplay> | ||
| 784 | |||
| 785 | ```yue | ||
| 786 | data = | ||
| 787 | a: [1, 2, 3] | ||
| 788 | b: [4, 5, 6] | ||
| 789 | |||
| 790 | flat = [...v for k,v in pairs data] | ||
| 791 | -- flat sekarang [1, 2, 3, 4, 5, 6] | ||
| 792 | ``` | ||
| 793 | |||
| 794 | </YueDisplay> | ||
| 795 | |||
| 796 | Klausa `for` dan `when` dapat dirantai sebanyak yang diinginkan. Satu-satunya syarat adalah komprehensi memiliki setidaknya satu klausa `for`. | 382 | Klausa `for` dan `when` dapat dirantai sebanyak yang diinginkan. Satu-satunya syarat adalah komprehensi memiliki setidaknya satu klausa `for`. |
| 797 | 383 | ||
| 798 | Menggunakan beberapa klausa `for` sama seperti menggunakan loop bertingkat: | 384 | Menggunakan beberapa klausa `for` sama seperti menggunakan loop bertingkat: |
| @@ -805,32 +391,12 @@ points = [ [x, y] for x in *x_coords \ | |||
| 805 | for y in *y_coords] | 391 | for y in *y_coords] |
| 806 | ``` | 392 | ``` |
| 807 | 393 | ||
| 808 | <YueDisplay> | ||
| 809 | |||
| 810 | ```yue | ||
| 811 | x_coords = [4, 5, 6, 7] | ||
| 812 | y_coords = [9, 2, 3] | ||
| 813 | |||
| 814 | points = [ [x, y] for x in *x_coords \ | ||
| 815 | for y in *y_coords] | ||
| 816 | ``` | ||
| 817 | |||
| 818 | </YueDisplay> | ||
| 819 | |||
| 820 | Perulangan for numerik juga bisa digunakan dalam komprehensi: | 394 | Perulangan for numerik juga bisa digunakan dalam komprehensi: |
| 821 | 395 | ||
| 822 | ```yuescript | 396 | ```yuescript |
| 823 | evens = [i for i = 1, 100 when i % 2 == 0] | 397 | evens = [i for i = 1, 100 when i % 2 == 0] |
| 824 | ``` | 398 | ``` |
| 825 | 399 | ||
| 826 | <YueDisplay> | ||
| 827 | |||
| 828 | ```yue | ||
| 829 | evens = [i for i = 1, 100 when i % 2 == 0] | ||
| 830 | ``` | ||
| 831 | |||
| 832 | </YueDisplay> | ||
| 833 | |||
| 834 | ## Komprehensi Tabel | 400 | ## Komprehensi Tabel |
| 835 | 401 | ||
| 836 | Sintaks untuk komprehensi tabel sangat mirip, hanya berbeda dengan penggunaan **{** dan **}** serta mengambil dua nilai dari setiap iterasi. | 402 | Sintaks untuk komprehensi tabel sangat mirip, hanya berbeda dengan penggunaan **{** dan **}** serta mengambil dua nilai dari setiap iterasi. |
| @@ -847,32 +413,10 @@ thing = { | |||
| 847 | thing_copy = {k, v for k, v in pairs thing} | 413 | thing_copy = {k, v for k, v in pairs thing} |
| 848 | ``` | 414 | ``` |
| 849 | 415 | ||
| 850 | <YueDisplay> | ||
| 851 | |||
| 852 | ```yue | ||
| 853 | thing = { | ||
| 854 | color: "red" | ||
| 855 | name: "fast" | ||
| 856 | width: 123 | ||
| 857 | } | ||
| 858 | |||
| 859 | thing_copy = {k, v for k, v in pairs thing} | ||
| 860 | ``` | ||
| 861 | |||
| 862 | </YueDisplay> | ||
| 863 | |||
| 864 | ```yuescript | 416 | ```yuescript |
| 865 | no_color = {k, v for k, v in pairs thing when k != "color"} | 417 | no_color = {k, v for k, v in pairs thing when k != "color"} |
| 866 | ``` | 418 | ``` |
| 867 | 419 | ||
| 868 | <YueDisplay> | ||
| 869 | |||
| 870 | ```yue | ||
| 871 | no_color = {k, v for k, v in pairs thing when k != "color"} | ||
| 872 | ``` | ||
| 873 | |||
| 874 | </YueDisplay> | ||
| 875 | |||
| 876 | Operator **\*** juga didukung. Di sini kita membuat tabel lookup akar kuadrat untuk beberapa angka. | 420 | Operator **\*** juga didukung. Di sini kita membuat tabel lookup akar kuadrat untuk beberapa angka. |
| 877 | 421 | ||
| 878 | ```yuescript | 422 | ```yuescript |
| @@ -880,15 +424,6 @@ numbers = [1, 2, 3, 4] | |||
| 880 | sqrts = {i, math.sqrt i for i in *numbers} | 424 | sqrts = {i, math.sqrt i for i in *numbers} |
| 881 | ``` | 425 | ``` |
| 882 | 426 | ||
| 883 | <YueDisplay> | ||
| 884 | |||
| 885 | ```yue | ||
| 886 | numbers = [1, 2, 3, 4] | ||
| 887 | sqrts = {i, math.sqrt i for i in *numbers} | ||
| 888 | ``` | ||
| 889 | |||
| 890 | </YueDisplay> | ||
| 891 | |||
| 892 | Tuple key-value dalam komprehensi tabel juga bisa berasal dari satu ekspresi, yang berarti ekspresi tersebut harus mengembalikan dua nilai. Nilai pertama digunakan sebagai kunci dan nilai kedua digunakan sebagai nilai: | 427 | Tuple key-value dalam komprehensi tabel juga bisa berasal dari satu ekspresi, yang berarti ekspresi tersebut harus mengembalikan dua nilai. Nilai pertama digunakan sebagai kunci dan nilai kedua digunakan sebagai nilai: |
| 893 | 428 | ||
| 894 | Dalam contoh ini kita mengonversi array pasangan menjadi tabel di mana item pertama dalam pasangan menjadi kunci dan item kedua menjadi nilai. | 429 | Dalam contoh ini kita mengonversi array pasangan menjadi tabel di mana item pertama dalam pasangan menjadi kunci dan item kedua menjadi nilai. |
| @@ -898,15 +433,6 @@ tuples = [ ["hello", "world"], ["foo", "bar"]] | |||
| 898 | tbl = {unpack tuple for tuple in *tuples} | 433 | tbl = {unpack tuple for tuple in *tuples} |
| 899 | ``` | 434 | ``` |
| 900 | 435 | ||
| 901 | <YueDisplay> | ||
| 902 | |||
| 903 | ```yue | ||
| 904 | tuples = [ ["hello", "world"], ["foo", "bar"]] | ||
| 905 | tbl = {unpack tuple for tuple in *tuples} | ||
| 906 | ``` | ||
| 907 | |||
| 908 | </YueDisplay> | ||
| 909 | |||
| 910 | ## Slicing | 436 | ## Slicing |
| 911 | 437 | ||
| 912 | Sintaks khusus disediakan untuk membatasi item yang diiterasi saat menggunakan operator **\***. Ini setara dengan mengatur batas iterasi dan ukuran langkah pada loop for. | 438 | Sintaks khusus disediakan untuk membatasi item yang diiterasi saat menggunakan operator **\***. Ini setara dengan mengatur batas iterasi dan ukuran langkah pada loop for. |
| @@ -917,42 +443,18 @@ Di sini kita bisa menetapkan batas minimum dan maksimum, mengambil semua item de | |||
| 917 | slice = [item for item in *items[1, 5]] | 443 | slice = [item for item in *items[1, 5]] |
| 918 | ``` | 444 | ``` |
| 919 | 445 | ||
| 920 | <YueDisplay> | ||
| 921 | |||
| 922 | ```yue | ||
| 923 | slice = [item for item in *items[1, 5]] | ||
| 924 | ``` | ||
| 925 | |||
| 926 | </YueDisplay> | ||
| 927 | |||
| 928 | Salah satu argumen slice boleh dikosongkan untuk menggunakan default yang masuk akal. Pada contoh ini, jika indeks maksimum dikosongkan, defaultnya adalah panjang tabel. Ini akan mengambil semua item kecuali elemen pertama: | 446 | Salah satu argumen slice boleh dikosongkan untuk menggunakan default yang masuk akal. Pada contoh ini, jika indeks maksimum dikosongkan, defaultnya adalah panjang tabel. Ini akan mengambil semua item kecuali elemen pertama: |
| 929 | 447 | ||
| 930 | ```yuescript | 448 | ```yuescript |
| 931 | slice = [item for item in *items[2,]] | 449 | slice = [item for item in *items[2,]] |
| 932 | ``` | 450 | ``` |
| 933 | 451 | ||
| 934 | <YueDisplay> | ||
| 935 | |||
| 936 | ```yue | ||
| 937 | slice = [item for item in *items[2,]] | ||
| 938 | ``` | ||
| 939 | |||
| 940 | </YueDisplay> | ||
| 941 | |||
| 942 | Jika batas minimum dikosongkan, defaultnya adalah 1. Di sini kita hanya memberikan ukuran langkah dan membiarkan batas lainnya kosong. Ini akan mengambil semua item berindeks ganjil: (1, 3, 5, …) | 452 | Jika batas minimum dikosongkan, defaultnya adalah 1. Di sini kita hanya memberikan ukuran langkah dan membiarkan batas lainnya kosong. Ini akan mengambil semua item berindeks ganjil: (1, 3, 5, …) |
| 943 | 453 | ||
| 944 | ```yuescript | 454 | ```yuescript |
| 945 | slice = [item for item in *items[,,2]] | 455 | slice = [item for item in *items[,,2]] |
| 946 | ``` | 456 | ``` |
| 947 | 457 | ||
| 948 | <YueDisplay> | ||
| 949 | |||
| 950 | ```yue | ||
| 951 | slice = [item for item in *items[,,2]] | ||
| 952 | ``` | ||
| 953 | |||
| 954 | </YueDisplay> | ||
| 955 | |||
| 956 | Batas minimum dan maksimum bisa bernilai negatif, yang berarti batas dihitung dari akhir tabel. | 458 | Batas minimum dan maksimum bisa bernilai negatif, yang berarti batas dihitung dari akhir tabel. |
| 957 | 459 | ||
| 958 | ```yuescript | 460 | ```yuescript |
| @@ -960,29 +462,12 @@ Batas minimum dan maksimum bisa bernilai negatif, yang berarti batas dihitung da | |||
| 960 | slice = [item for item in *items[-4,-1]] | 462 | slice = [item for item in *items[-4,-1]] |
| 961 | ``` | 463 | ``` |
| 962 | 464 | ||
| 963 | <YueDisplay> | ||
| 964 | |||
| 965 | ```yue | ||
| 966 | -- ambil 4 item terakhir | ||
| 967 | slice = [item for item in *items[-4,-1]] | ||
| 968 | ``` | ||
| 969 | |||
| 970 | </YueDisplay> | ||
| 971 | |||
| 972 | Ukuran langkah juga bisa negatif, yang berarti item diambil dalam urutan terbalik. | 465 | Ukuran langkah juga bisa negatif, yang berarti item diambil dalam urutan terbalik. |
| 973 | 466 | ||
| 974 | ```yuescript | 467 | ```yuescript |
| 975 | reverse_slice = [item for item in *items[-1,1,-1]] | 468 | reverse_slice = [item for item in *items[-1,1,-1]] |
| 976 | ``` | 469 | ``` |
| 977 | 470 | ||
| 978 | <YueDisplay> | ||
| 979 | |||
| 980 | ```yue | ||
| 981 | reverse_slice = [item for item in *items[-1,1,-1]] | ||
| 982 | ``` | ||
| 983 | |||
| 984 | </YueDisplay> | ||
| 985 | |||
| 986 | ### Ekspresi Slicing | 471 | ### Ekspresi Slicing |
| 987 | 472 | ||
| 988 | Slicing juga bisa digunakan sebagai ekspresi. Ini berguna untuk mendapatkan sub-list dari sebuah tabel. | 473 | Slicing juga bisa digunakan sebagai ekspresi. Ini berguna untuk mendapatkan sub-list dari sebuah tabel. |
| @@ -995,18 +480,6 @@ sub_list = items[2, 4] | |||
| 995 | last_four_items = items[-4, -1] | 480 | last_four_items = items[-4, -1] |
| 996 | ``` | 481 | ``` |
| 997 | 482 | ||
| 998 | <YueDisplay> | ||
| 999 | |||
| 1000 | ```yue | ||
| 1001 | -- ambil item ke-2 dan ke-4 sebagai list baru | ||
| 1002 | sub_list = items[2, 4] | ||
| 1003 | |||
| 1004 | -- ambil 4 item terakhir | ||
| 1005 | last_four_items = items[-4, -1] | ||
| 1006 | ``` | ||
| 1007 | |||
| 1008 | </YueDisplay> | ||
| 1009 | |||
| 1010 | # Pemrograman Berorientasi Objek | 483 | # Pemrograman Berorientasi Objek |
| 1011 | 484 | ||
| 1012 | Dalam contoh-contoh ini, kode Lua yang dihasilkan mungkin tampak berat. Sebaiknya fokus dulu pada makna kode YueScript, lalu lihat kode Lua jika Anda ingin mengetahui detail implementasinya. | 485 | Dalam contoh-contoh ini, kode Lua yang dihasilkan mungkin tampak berat. Sebaiknya fokus dulu pada makna kode YueScript, lalu lihat kode Lua jika Anda ingin mengetahui detail implementasinya. |
| @@ -1025,22 +498,6 @@ class Inventory | |||
| 1025 | @items[name] = 1 | 498 | @items[name] = 1 |
| 1026 | ``` | 499 | ``` |
| 1027 | 500 | ||
| 1028 | <YueDisplay> | ||
| 1029 | |||
| 1030 | ```yue | ||
| 1031 | class Inventory | ||
| 1032 | new: => | ||
| 1033 | @items = {} | ||
| 1034 | |||
| 1035 | add_item: (name) => | ||
| 1036 | if @items[name] | ||
| 1037 | @items[name] += 1 | ||
| 1038 | else | ||
| 1039 | @items[name] = 1 | ||
| 1040 | ``` | ||
| 1041 | |||
| 1042 | </YueDisplay> | ||
| 1043 | |||
| 1044 | Kelas dideklarasikan dengan pernyataan `class` diikuti deklarasi mirip tabel di mana semua method dan properti dicantumkan. | 501 | Kelas dideklarasikan dengan pernyataan `class` diikuti deklarasi mirip tabel di mana semua method dan properti dicantumkan. |
| 1045 | 502 | ||
| 1046 | Properti `new` bersifat khusus karena akan menjadi konstruktor. | 503 | Properti `new` bersifat khusus karena akan menjadi konstruktor. |
| @@ -1057,16 +514,6 @@ inv\add_item "t-shirt" | |||
| 1057 | inv\add_item "pants" | 514 | inv\add_item "pants" |
| 1058 | ``` | 515 | ``` |
| 1059 | 516 | ||
| 1060 | <YueDisplay> | ||
| 1061 | |||
| 1062 | ```yue | ||
| 1063 | inv = Inventory! | ||
| 1064 | inv\add_item "t-shirt" | ||
| 1065 | inv\add_item "pants" | ||
| 1066 | ``` | ||
| 1067 | |||
| 1068 | </YueDisplay> | ||
| 1069 | |||
| 1070 | Karena instance kelas perlu dikirim ke method saat dipanggil, operator `\` digunakan. | 517 | Karena instance kelas perlu dikirim ke method saat dipanggil, operator `\` digunakan. |
| 1071 | 518 | ||
| 1072 | Semua properti kelas dibagikan di antara instance. Ini baik untuk fungsi, tetapi untuk jenis objek lain dapat menimbulkan hasil yang tidak diinginkan. | 519 | Semua properti kelas dibagikan di antara instance. Ini baik untuk fungsi, tetapi untuk jenis objek lain dapat menimbulkan hasil yang tidak diinginkan. |
| @@ -1089,26 +536,6 @@ b\give_item "shirt" | |||
| 1089 | print item for item in *a.clothes | 536 | print item for item in *a.clothes |
| 1090 | ``` | 537 | ``` |
| 1091 | 538 | ||
| 1092 | <YueDisplay> | ||
| 1093 | |||
| 1094 | ```yue | ||
| 1095 | class Person | ||
| 1096 | clothes: [] | ||
| 1097 | give_item: (name) => | ||
| 1098 | table.insert @clothes, name | ||
| 1099 | |||
| 1100 | a = Person! | ||
| 1101 | b = Person! | ||
| 1102 | |||
| 1103 | a\give_item "pants" | ||
| 1104 | b\give_item "shirt" | ||
| 1105 | |||
| 1106 | -- akan mencetak pants dan shirt | ||
| 1107 | print item for item in *a.clothes | ||
| 1108 | ``` | ||
| 1109 | |||
| 1110 | </YueDisplay> | ||
| 1111 | |||
| 1112 | Cara yang benar untuk menghindari masalah ini adalah membuat state yang dapat berubah di konstruktor: | 539 | Cara yang benar untuk menghindari masalah ini adalah membuat state yang dapat berubah di konstruktor: |
| 1113 | 540 | ||
| 1114 | ```yuescript | 541 | ```yuescript |
| @@ -1117,16 +544,6 @@ class Person | |||
| 1117 | @clothes = [] | 544 | @clothes = [] |
| 1118 | ``` | 545 | ``` |
| 1119 | 546 | ||
| 1120 | <YueDisplay> | ||
| 1121 | |||
| 1122 | ```yue | ||
| 1123 | class Person | ||
| 1124 | new: => | ||
| 1125 | @clothes = [] | ||
| 1126 | ``` | ||
| 1127 | |||
| 1128 | </YueDisplay> | ||
| 1129 | |||
| 1130 | ## Pewarisan | 547 | ## Pewarisan |
| 1131 | 548 | ||
| 1132 | Kata kunci `extends` dapat digunakan dalam deklarasi kelas untuk mewarisi properti dan method dari kelas lain. | 549 | Kata kunci `extends` dapat digunakan dalam deklarasi kelas untuk mewarisi properti dan method dari kelas lain. |
| @@ -1139,18 +556,6 @@ class BackPack extends Inventory | |||
| 1139 | super name | 556 | super name |
| 1140 | ``` | 557 | ``` |
| 1141 | 558 | ||
| 1142 | <YueDisplay> | ||
| 1143 | |||
| 1144 | ```yue | ||
| 1145 | class BackPack extends Inventory | ||
| 1146 | size: 10 | ||
| 1147 | add_item: (name) => | ||
| 1148 | if #@items > size then error "backpack is full" | ||
| 1149 | super name | ||
| 1150 | ``` | ||
| 1151 | |||
| 1152 | </YueDisplay> | ||
| 1153 | |||
| 1154 | Di sini kita memperluas kelas Inventory, dan membatasi jumlah item yang bisa dibawa. | 559 | Di sini kita memperluas kelas Inventory, dan membatasi jumlah item yang bisa dibawa. |
| 1155 | 560 | ||
| 1156 | Dalam contoh ini, kita tidak mendefinisikan konstruktor pada subclass, sehingga konstruktor kelas induk dipanggil ketika membuat instance baru. Jika kita mendefinisikan konstruktor, kita bisa menggunakan method `super` untuk memanggil konstruktor induk. | 561 | Dalam contoh ini, kita tidak mendefinisikan konstruktor pada subclass, sehingga konstruktor kelas induk dipanggil ketika membuat instance baru. Jika kita mendefinisikan konstruktor, kita bisa menggunakan method `super` untuk memanggil konstruktor induk. |
| @@ -1166,19 +571,6 @@ class Shelf | |||
| 1166 | class Cupboard extends Shelf | 571 | class Cupboard extends Shelf |
| 1167 | ``` | 572 | ``` |
| 1168 | 573 | ||
| 1169 | <YueDisplay> | ||
| 1170 | |||
| 1171 | ```yue | ||
| 1172 | class Shelf | ||
| 1173 | @__inherited: (child) => | ||
| 1174 | print @__name, "was inherited by", child.__name | ||
| 1175 | |||
| 1176 | -- akan mencetak: Shelf was inherited by Cupboard | ||
| 1177 | class Cupboard extends Shelf | ||
| 1178 | ``` | ||
| 1179 | |||
| 1180 | </YueDisplay> | ||
| 1181 | |||
| 1182 | ## Super | 574 | ## Super |
| 1183 | 575 | ||
| 1184 | **super** adalah kata kunci khusus yang dapat digunakan dengan dua cara: sebagai objek, atau dipanggil seperti fungsi. Ia hanya memiliki fungsi khusus ketika berada di dalam kelas. | 576 | **super** adalah kata kunci khusus yang dapat digunakan dengan dua cara: sebagai objek, atau dipanggil seperti fungsi. Ia hanya memiliki fungsi khusus ketika berada di dalam kelas. |
| @@ -1205,22 +597,6 @@ class MyClass extends ParentClass | |||
| 1205 | assert super == ParentClass | 597 | assert super == ParentClass |
| 1206 | ``` | 598 | ``` |
| 1207 | 599 | ||
| 1208 | <YueDisplay> | ||
| 1209 | |||
| 1210 | ```yue | ||
| 1211 | class MyClass extends ParentClass | ||
| 1212 | a_method: => | ||
| 1213 | -- berikut memiliki efek yang sama: | ||
| 1214 | super "hello", "world" | ||
| 1215 | super\a_method "hello", "world" | ||
| 1216 | super.a_method self, "hello", "world" | ||
| 1217 | |||
| 1218 | -- super sebagai nilai sama dengan kelas induk: | ||
| 1219 | assert super == ParentClass | ||
| 1220 | ``` | ||
| 1221 | |||
| 1222 | </YueDisplay> | ||
| 1223 | |||
| 1224 | **super** juga dapat digunakan di sisi kiri Function Stub. Perbedaan utamanya adalah, alih-alih fungsi hasil terikat pada nilai `super`, fungsi terikat pada `self`. | 600 | **super** juga dapat digunakan di sisi kiri Function Stub. Perbedaan utamanya adalah, alih-alih fungsi hasil terikat pada nilai `super`, fungsi terikat pada `self`. |
| 1225 | 601 | ||
| 1226 | ## Tipe | 602 | ## Tipe |
| @@ -1234,17 +610,6 @@ assert b.__class == BackPack | |||
| 1234 | print BackPack.size -- mencetak 10 | 610 | print BackPack.size -- mencetak 10 |
| 1235 | ``` | 611 | ``` |
| 1236 | 612 | ||
| 1237 | <YueDisplay> | ||
| 1238 | |||
| 1239 | ```yue | ||
| 1240 | b = BackPack! | ||
| 1241 | assert b.__class == BackPack | ||
| 1242 | |||
| 1243 | print BackPack.size -- mencetak 10 | ||
| 1244 | ``` | ||
| 1245 | |||
| 1246 | </YueDisplay> | ||
| 1247 | |||
| 1248 | ## Objek Kelas | 613 | ## Objek Kelas |
| 1249 | 614 | ||
| 1250 | Objek kelas adalah yang kita buat saat menggunakan pernyataan `class`. Objek kelas disimpan dalam variabel dengan nama yang sama dengan kelas. | 615 | Objek kelas adalah yang kita buat saat menggunakan pernyataan `class`. Objek kelas disimpan dalam variabel dengan nama yang sama dengan kelas. |
| @@ -1265,14 +630,6 @@ Nama kelas saat dideklarasikan disimpan sebagai string di field `__name` pada ob | |||
| 1265 | print BackPack.__name -- mencetak Backpack | 630 | print BackPack.__name -- mencetak Backpack |
| 1266 | ``` | 631 | ``` |
| 1267 | 632 | ||
| 1268 | <YueDisplay> | ||
| 1269 | |||
| 1270 | ```yue | ||
| 1271 | print BackPack.__name -- mencetak Backpack | ||
| 1272 | ``` | ||
| 1273 | |||
| 1274 | </YueDisplay> | ||
| 1275 | |||
| 1276 | Objek base disimpan di `__base`. Kita dapat memodifikasi tabel ini untuk menambahkan fungsionalitas ke instance yang sudah dibuat maupun yang akan dibuat. | 633 | Objek base disimpan di `__base`. Kita dapat memodifikasi tabel ini untuk menambahkan fungsionalitas ke instance yang sudah dibuat maupun yang akan dibuat. |
| 1277 | 634 | ||
| 1278 | Jika kelas memperluas kelas lain, objek kelas induk disimpan di `__parent`. | 635 | Jika kelas memperluas kelas lain, objek kelas induk disimpan di `__parent`. |
| @@ -1291,20 +648,6 @@ Things\some_func! | |||
| 1291 | assert Things().some_func == nil | 648 | assert Things().some_func == nil |
| 1292 | ``` | 649 | ``` |
| 1293 | 650 | ||
| 1294 | <YueDisplay> | ||
| 1295 | |||
| 1296 | ```yue | ||
| 1297 | class Things | ||
| 1298 | @some_func: => print "Hello from", @__name | ||
| 1299 | |||
| 1300 | Things\some_func! | ||
| 1301 | |||
| 1302 | -- variabel kelas tidak terlihat pada instance | ||
| 1303 | assert Things().some_func == nil | ||
| 1304 | ``` | ||
| 1305 | |||
| 1306 | </YueDisplay> | ||
| 1307 | |||
| 1308 | Dalam ekspresi, kita dapat menggunakan `@@` untuk mengakses nilai yang disimpan di `__class` milik `self`. Jadi, `@@hello` adalah singkatan dari `self.__class.hello`. | 651 | Dalam ekspresi, kita dapat menggunakan `@@` untuk mengakses nilai yang disimpan di `__class` milik `self`. Jadi, `@@hello` adalah singkatan dari `self.__class.hello`. |
| 1309 | 652 | ||
| 1310 | ```yuescript | 653 | ```yuescript |
| @@ -1320,37 +663,12 @@ Counter! | |||
| 1320 | print Counter.count -- mencetak 2 | 663 | print Counter.count -- mencetak 2 |
| 1321 | ``` | 664 | ``` |
| 1322 | 665 | ||
| 1323 | <YueDisplay> | ||
| 1324 | |||
| 1325 | ```yue | ||
| 1326 | class Counter | ||
| 1327 | @count: 0 | ||
| 1328 | |||
| 1329 | new: => | ||
| 1330 | @@count += 1 | ||
| 1331 | |||
| 1332 | Counter! | ||
| 1333 | Counter! | ||
| 1334 | |||
| 1335 | print Counter.count -- mencetak 2 | ||
| 1336 | ``` | ||
| 1337 | |||
| 1338 | </YueDisplay> | ||
| 1339 | |||
| 1340 | Semantik pemanggilan `@@` mirip dengan `@`. Memanggil nama `@@` akan meneruskan kelas sebagai argumen pertama menggunakan sintaks kolon Lua. | 666 | Semantik pemanggilan `@@` mirip dengan `@`. Memanggil nama `@@` akan meneruskan kelas sebagai argumen pertama menggunakan sintaks kolon Lua. |
| 1341 | 667 | ||
| 1342 | ```yuescript | 668 | ```yuescript |
| 1343 | @@hello 1,2,3,4 | 669 | @@hello 1,2,3,4 |
| 1344 | ``` | 670 | ``` |
| 1345 | 671 | ||
| 1346 | <YueDisplay> | ||
| 1347 | |||
| 1348 | ```yue | ||
| 1349 | @@hello 1,2,3,4 | ||
| 1350 | ``` | ||
| 1351 | |||
| 1352 | </YueDisplay> | ||
| 1353 | |||
| 1354 | ## Pernyataan Deklarasi Kelas | 672 | ## Pernyataan Deklarasi Kelas |
| 1355 | 673 | ||
| 1356 | Di dalam badan deklarasi kelas, kita bisa memiliki ekspresi normal selain pasangan key/value. Dalam konteks ini, `self` sama dengan objek kelas. | 674 | Di dalam badan deklarasi kelas, kita bisa memiliki ekspresi normal selain pasangan key/value. Dalam konteks ini, `self` sama dengan objek kelas. |
| @@ -1362,15 +680,6 @@ class Things | |||
| 1362 | @class_var = "hello world" | 680 | @class_var = "hello world" |
| 1363 | ``` | 681 | ``` |
| 1364 | 682 | ||
| 1365 | <YueDisplay> | ||
| 1366 | |||
| 1367 | ```yue | ||
| 1368 | class Things | ||
| 1369 | @class_var = "hello world" | ||
| 1370 | ``` | ||
| 1371 | |||
| 1372 | </YueDisplay> | ||
| 1373 | |||
| 1374 | Ekspresi ini dieksekusi setelah semua properti ditambahkan ke base. | 683 | Ekspresi ini dieksekusi setelah semua properti ditambahkan ke base. |
| 1375 | 684 | ||
| 1376 | Semua variabel yang dideklarasikan di badan kelas bersifat lokal terhadap properti kelas. Ini berguna untuk menempatkan nilai privat atau fungsi pembantu yang hanya dapat diakses oleh method kelas: | 685 | Semua variabel yang dideklarasikan di badan kelas bersifat lokal terhadap properti kelas. Ini berguna untuk menempatkan nilai privat atau fungsi pembantu yang hanya dapat diakses oleh method kelas: |
| @@ -1384,19 +693,6 @@ class MoreThings | |||
| 1384 | log "hello world: " .. secret | 693 | log "hello world: " .. secret |
| 1385 | ``` | 694 | ``` |
| 1386 | 695 | ||
| 1387 | <YueDisplay> | ||
| 1388 | |||
| 1389 | ```yue | ||
| 1390 | class MoreThings | ||
| 1391 | secret = 123 | ||
| 1392 | log = (msg) -> print "LOG:", msg | ||
| 1393 | |||
| 1394 | some_method: => | ||
| 1395 | log "hello world: " .. secret | ||
| 1396 | ``` | ||
| 1397 | |||
| 1398 | </YueDisplay> | ||
| 1399 | |||
| 1400 | ## Nilai @ dan @@ | 696 | ## Nilai @ dan @@ |
| 1401 | 697 | ||
| 1402 | Ketika `@` dan `@@` diprefiks di depan sebuah nama, masing-masing merepresentasikan nama tersebut yang diakses di `self` dan `self.__class`. | 698 | Ketika `@` dan `@@` diprefiks di depan sebuah nama, masing-masing merepresentasikan nama tersebut yang diakses di `self` dan `self.__class`. |
| @@ -1408,29 +704,12 @@ assert @ == self | |||
| 1408 | assert @@ == self.__class | 704 | assert @@ == self.__class |
| 1409 | ``` | 705 | ``` |
| 1410 | 706 | ||
| 1411 | <YueDisplay> | ||
| 1412 | |||
| 1413 | ```yue | ||
| 1414 | assert @ == self | ||
| 1415 | assert @@ == self.__class | ||
| 1416 | ``` | ||
| 1417 | |||
| 1418 | </YueDisplay> | ||
| 1419 | |||
| 1420 | Contohnya, cara cepat untuk membuat instance baru dari kelas yang sama dari method instance menggunakan `@@`: | 707 | Contohnya, cara cepat untuk membuat instance baru dari kelas yang sama dari method instance menggunakan `@@`: |
| 1421 | 708 | ||
| 1422 | ```yuescript | 709 | ```yuescript |
| 1423 | some_instance_method = (...) => @@ ... | 710 | some_instance_method = (...) => @@ ... |
| 1424 | ``` | 711 | ``` |
| 1425 | 712 | ||
| 1426 | <YueDisplay> | ||
| 1427 | |||
| 1428 | ```yue | ||
| 1429 | some_instance_method = (...) => @@ ... | ||
| 1430 | ``` | ||
| 1431 | |||
| 1432 | </YueDisplay> | ||
| 1433 | |||
| 1434 | ## Promosi Properti Konstruktor | 713 | ## Promosi Properti Konstruktor |
| 1435 | 714 | ||
| 1436 | Untuk mengurangi boilerplate saat mendefinisikan objek nilai sederhana, Anda dapat menulis kelas sederhana seperti: | 715 | Untuk mengurangi boilerplate saat mendefinisikan objek nilai sederhana, Anda dapat menulis kelas sederhana seperti: |
| @@ -1449,24 +728,6 @@ class Something | |||
| 1449 | @@baz = baz | 728 | @@baz = baz |
| 1450 | ``` | 729 | ``` |
| 1451 | 730 | ||
| 1452 | <YueDisplay> | ||
| 1453 | |||
| 1454 | ```yue | ||
| 1455 | class Something | ||
| 1456 | new: (@foo, @bar, @@biz, @@baz) => | ||
| 1457 | |||
| 1458 | -- Yang merupakan singkatan dari | ||
| 1459 | |||
| 1460 | class Something | ||
| 1461 | new: (foo, bar, biz, baz) => | ||
| 1462 | @foo = foo | ||
| 1463 | @bar = bar | ||
| 1464 | @@biz = biz | ||
| 1465 | @@baz = baz | ||
| 1466 | ``` | ||
| 1467 | |||
| 1468 | </YueDisplay> | ||
| 1469 | |||
| 1470 | Anda juga bisa menggunakan sintaks ini untuk fungsi umum guna menginisialisasi field objek. | 731 | Anda juga bisa menggunakan sintaks ini untuk fungsi umum guna menginisialisasi field objek. |
| 1471 | 732 | ||
| 1472 | ```yuescript | 733 | ```yuescript |
| @@ -1475,16 +736,6 @@ obj = new {}, 123, "abc" | |||
| 1475 | print obj | 736 | print obj |
| 1476 | ``` | 737 | ``` |
| 1477 | 738 | ||
| 1478 | <YueDisplay> | ||
| 1479 | |||
| 1480 | ```yue | ||
| 1481 | new = (@fieldA, @fieldB) => @ | ||
| 1482 | obj = new {}, 123, "abc" | ||
| 1483 | print obj | ||
| 1484 | ``` | ||
| 1485 | |||
| 1486 | </YueDisplay> | ||
| 1487 | |||
| 1488 | ## Ekspresi Kelas | 739 | ## Ekspresi Kelas |
| 1489 | 740 | ||
| 1490 | Sintaks kelas juga bisa digunakan sebagai ekspresi yang dapat di-assign ke variabel atau di-return secara eksplisit. | 741 | Sintaks kelas juga bisa digunakan sebagai ekspresi yang dapat di-assign ke variabel atau di-return secara eksplisit. |
| @@ -1495,16 +746,6 @@ x = class Bucket | |||
| 1495 | add_drop: => @drops += 1 | 746 | add_drop: => @drops += 1 |
| 1496 | ``` | 747 | ``` |
| 1497 | 748 | ||
| 1498 | <YueDisplay> | ||
| 1499 | |||
| 1500 | ```yue | ||
| 1501 | x = class Bucket | ||
| 1502 | drops: 0 | ||
| 1503 | add_drop: => @drops += 1 | ||
| 1504 | ``` | ||
| 1505 | |||
| 1506 | </YueDisplay> | ||
| 1507 | |||
| 1508 | ## Kelas Anonim | 749 | ## Kelas Anonim |
| 1509 | 750 | ||
| 1510 | Nama bisa dihilangkan saat mendeklarasikan kelas. Atribut `__name` akan bernilai nil, kecuali ekspresi kelas berada dalam assignment. Nama di sisi kiri assignment digunakan sebagai ganti nil. | 751 | Nama bisa dihilangkan saat mendeklarasikan kelas. Atribut `__name` akan bernilai nil, kecuali ekspresi kelas berada dalam assignment. Nama di sisi kiri assignment digunakan sebagai ganti nil. |
| @@ -1516,31 +757,12 @@ BigBucket = class extends Bucket | |||
| 1516 | assert Bucket.__name == "BigBucket" | 757 | assert Bucket.__name == "BigBucket" |
| 1517 | ``` | 758 | ``` |
| 1518 | 759 | ||
| 1519 | <YueDisplay> | ||
| 1520 | |||
| 1521 | ```yue | ||
| 1522 | BigBucket = class extends Bucket | ||
| 1523 | add_drop: => @drops += 10 | ||
| 1524 | |||
| 1525 | assert Bucket.__name == "BigBucket" | ||
| 1526 | ``` | ||
| 1527 | |||
| 1528 | </YueDisplay> | ||
| 1529 | |||
| 1530 | Anda bahkan bisa menghilangkan badan kelas, artinya Anda bisa menulis kelas anonim kosong seperti ini: | 760 | Anda bahkan bisa menghilangkan badan kelas, artinya Anda bisa menulis kelas anonim kosong seperti ini: |
| 1531 | 761 | ||
| 1532 | ```yuescript | 762 | ```yuescript |
| 1533 | x = class | 763 | x = class |
| 1534 | ``` | 764 | ``` |
| 1535 | 765 | ||
| 1536 | <YueDisplay> | ||
| 1537 | |||
| 1538 | ```yue | ||
| 1539 | x = class | ||
| 1540 | ``` | ||
| 1541 | |||
| 1542 | </YueDisplay> | ||
| 1543 | |||
| 1544 | ## Pencampuran Kelas | 766 | ## Pencampuran Kelas |
| 1545 | 767 | ||
| 1546 | Anda bisa melakukan mixing dengan kata kunci `using` untuk menyalin fungsi dari tabel biasa atau objek kelas yang sudah didefinisikan ke kelas baru Anda. Saat mixing dengan tabel biasa, Anda dapat mengganti fungsi pengindeksan kelas (metamethod `__index`) dengan implementasi kustom. Saat mixing dengan objek kelas yang sudah ada, metamethod objek kelas tidak akan disalin. | 768 | Anda bisa melakukan mixing dengan kata kunci `using` untuk menyalin fungsi dari tabel biasa atau objek kelas yang sudah didefinisikan ke kelas baru Anda. Saat mixing dengan tabel biasa, Anda dapat mengganti fungsi pengindeksan kelas (metamethod `__index`) dengan implementasi kustom. Saat mixing dengan objek kelas yang sudah ada, metamethod objek kelas tidak akan disalin. |
| @@ -1563,28 +785,6 @@ y\func! | |||
| 1563 | assert y.__class.__parent ~= X -- X bukan parent dari Y | 785 | assert y.__class.__parent ~= X -- X bukan parent dari Y |
| 1564 | ``` | 786 | ``` |
| 1565 | 787 | ||
| 1566 | <YueDisplay> | ||
| 1567 | |||
| 1568 | ```yue | ||
| 1569 | MyIndex = __index: var: 1 | ||
| 1570 | |||
| 1571 | class X using MyIndex | ||
| 1572 | func: => | ||
| 1573 | print 123 | ||
| 1574 | |||
| 1575 | x = X! | ||
| 1576 | print x.var | ||
| 1577 | |||
| 1578 | class Y using X | ||
| 1579 | |||
| 1580 | y = Y! | ||
| 1581 | y\func! | ||
| 1582 | |||
| 1583 | assert y.__class.__parent ~= X -- X bukan parent dari Y | ||
| 1584 | ``` | ||
| 1585 | |||
| 1586 | </YueDisplay> | ||
| 1587 | |||
| 1588 | # Pernyataan With | 788 | # Pernyataan With |
| 1589 | 789 | ||
| 1590 | Pola umum saat membuat objek adalah memanggil serangkaian fungsi dan mengatur serangkaian properti segera setelah objek dibuat. | 790 | Pola umum saat membuat objek adalah memanggil serangkaian fungsi dan mengatur serangkaian properti segera setelah objek dibuat. |
| @@ -1603,18 +803,6 @@ with Person! | |||
| 1603 | print .name | 803 | print .name |
| 1604 | ``` | 804 | ``` |
| 1605 | 805 | ||
| 1606 | <YueDisplay> | ||
| 1607 | |||
| 1608 | ```yue | ||
| 1609 | with Person! | ||
| 1610 | .name = "Oswald" | ||
| 1611 | \add_relative my_dad | ||
| 1612 | \save! | ||
| 1613 | print .name | ||
| 1614 | ``` | ||
| 1615 | |||
| 1616 | </YueDisplay> | ||
| 1617 | |||
| 1618 | Pernyataan `with` juga bisa digunakan sebagai ekspresi yang mengembalikan nilai yang diberi akses. | 806 | Pernyataan `with` juga bisa digunakan sebagai ekspresi yang mengembalikan nilai yang diberi akses. |
| 1619 | 807 | ||
| 1620 | ```yuescript | 808 | ```yuescript |
| @@ -1622,15 +810,6 @@ file = with File "favorite_foods.txt" | |||
| 1622 | \set_encoding "utf8" | 810 | \set_encoding "utf8" |
| 1623 | ``` | 811 | ``` |
| 1624 | 812 | ||
| 1625 | <YueDisplay> | ||
| 1626 | |||
| 1627 | ```yue | ||
| 1628 | file = with File "favorite_foods.txt" | ||
| 1629 | \set_encoding "utf8" | ||
| 1630 | ``` | ||
| 1631 | |||
| 1632 | </YueDisplay> | ||
| 1633 | |||
| 1634 | Ekspresi `with` mendukung `break` dengan satu nilai: | 813 | Ekspresi `with` mendukung `break` dengan satu nilai: |
| 1635 | 814 | ||
| 1636 | ```yuescript | 815 | ```yuescript |
| @@ -1638,15 +817,6 @@ result = with obj | |||
| 1638 | break .value | 817 | break .value |
| 1639 | ``` | 818 | ``` |
| 1640 | 819 | ||
| 1641 | <YueDisplay> | ||
| 1642 | |||
| 1643 | ```yue | ||
| 1644 | result = with obj | ||
| 1645 | break .value | ||
| 1646 | ``` | ||
| 1647 | |||
| 1648 | </YueDisplay> | ||
| 1649 | |||
| 1650 | Setelah `break value` digunakan di dalam `with`, ekspresi `with` tidak lagi mengembalikan objek targetnya, melainkan mengembalikan nilai dari `break`. | 820 | Setelah `break value` digunakan di dalam `with`, ekspresi `with` tidak lagi mengembalikan objek targetnya, melainkan mengembalikan nilai dari `break`. |
| 1651 | 821 | ||
| 1652 | ```yuescript | 822 | ```yuescript |
| @@ -1659,20 +829,6 @@ b = with obj | |||
| 1659 | -- b adalah .x, bukan obj | 829 | -- b adalah .x, bukan obj |
| 1660 | ``` | 830 | ``` |
| 1661 | 831 | ||
| 1662 | <YueDisplay> | ||
| 1663 | |||
| 1664 | ```yue | ||
| 1665 | a = with obj | ||
| 1666 | .x = 1 | ||
| 1667 | -- a adalah obj | ||
| 1668 | |||
| 1669 | b = with obj | ||
| 1670 | break .x | ||
| 1671 | -- b adalah .x, bukan obj | ||
| 1672 | ``` | ||
| 1673 | |||
| 1674 | </YueDisplay> | ||
| 1675 | |||
| 1676 | Berbeda dari `for` / `while` / `repeat` / `do`, `with` hanya mendukung satu nilai `break`. | 832 | Berbeda dari `for` / `while` / `repeat` / `do`, `with` hanya mendukung satu nilai `break`. |
| 1677 | 833 | ||
| 1678 | Atau… | 834 | Atau… |
| @@ -1686,19 +842,6 @@ create_person = (name, relatives) -> | |||
| 1686 | me = create_person "Leaf", [dad, mother, sister] | 842 | me = create_person "Leaf", [dad, mother, sister] |
| 1687 | ``` | 843 | ``` |
| 1688 | 844 | ||
| 1689 | <YueDisplay> | ||
| 1690 | |||
| 1691 | ```yue | ||
| 1692 | create_person = (name, relatives) -> | ||
| 1693 | with Person! | ||
| 1694 | .name = name | ||
| 1695 | \add_relative relative for relative in *relatives | ||
| 1696 | |||
| 1697 | me = create_person "Leaf", [dad, mother, sister] | ||
| 1698 | ``` | ||
| 1699 | |||
| 1700 | </YueDisplay> | ||
| 1701 | |||
| 1702 | Dalam penggunaan ini, `with` dapat dilihat sebagai bentuk khusus dari kombinator K. | 845 | Dalam penggunaan ini, `with` dapat dilihat sebagai bentuk khusus dari kombinator K. |
| 1703 | 846 | ||
| 1704 | Ekspresi pada pernyataan `with` juga bisa berupa assignment jika Anda ingin memberi nama pada ekspresi tersebut. | 847 | Ekspresi pada pernyataan `with` juga bisa berupa assignment jika Anda ingin memberi nama pada ekspresi tersebut. |
| @@ -1709,16 +852,6 @@ with str := "Hello" | |||
| 1709 | print "upper:", \upper! | 852 | print "upper:", \upper! |
| 1710 | ``` | 853 | ``` |
| 1711 | 854 | ||
| 1712 | <YueDisplay> | ||
| 1713 | |||
| 1714 | ```yue | ||
| 1715 | with str := "Hello" | ||
| 1716 | print "original:", str | ||
| 1717 | print "upper:", \upper! | ||
| 1718 | ``` | ||
| 1719 | |||
| 1720 | </YueDisplay> | ||
| 1721 | |||
| 1722 | Anda bisa mengakses kunci khusus dengan `[]` di dalam pernyataan `with`. | 855 | Anda bisa mengakses kunci khusus dengan `[]` di dalam pernyataan `with`. |
| 1723 | 856 | ||
| 1724 | ```yuescript | 857 | ```yuescript |
| @@ -1731,20 +864,6 @@ with tb | |||
| 1731 | [] = "abc" -- menambahkan ke "tb" | 864 | [] = "abc" -- menambahkan ke "tb" |
| 1732 | ``` | 865 | ``` |
| 1733 | 866 | ||
| 1734 | <YueDisplay> | ||
| 1735 | |||
| 1736 | ```yue | ||
| 1737 | with tb | ||
| 1738 | [1] = 1 | ||
| 1739 | print [2] | ||
| 1740 | with [abc] | ||
| 1741 | [3] = [2]\func! | ||
| 1742 | ["key-name"] = value | ||
| 1743 | [] = "abc" -- menambahkan ke "tb" | ||
| 1744 | ``` | ||
| 1745 | |||
| 1746 | </YueDisplay> | ||
| 1747 | |||
| 1748 | `with?` adalah versi yang ditingkatkan dari sintaks `with`, yang memperkenalkan pengecekan keberadaan untuk mengakses objek yang mungkin nil secara aman tanpa pemeriksaan null eksplisit. | 867 | `with?` adalah versi yang ditingkatkan dari sintaks `with`, yang memperkenalkan pengecekan keberadaan untuk mengakses objek yang mungkin nil secara aman tanpa pemeriksaan null eksplisit. |
| 1749 | 868 | ||
| 1750 | ```yuescript | 869 | ```yuescript |
| @@ -1752,15 +871,6 @@ with? obj | |||
| 1752 | print obj.name | 871 | print obj.name |
| 1753 | ``` | 872 | ``` |
| 1754 | 873 | ||
| 1755 | <YueDisplay> | ||
| 1756 | |||
| 1757 | ```yue | ||
| 1758 | with? obj | ||
| 1759 | print obj.name | ||
| 1760 | ``` | ||
| 1761 | |||
| 1762 | </YueDisplay> | ||
| 1763 | |||
| 1764 | # Penugasan | 874 | # Penugasan |
| 1765 | 875 | ||
| 1766 | Variabel bersifat bertipe dinamis dan secara default dideklarasikan sebagai local. Namun Anda dapat mengubah cakupan deklarasi dengan pernyataan **local** dan **global**. | 876 | Variabel bersifat bertipe dinamis dan secara default dideklarasikan sebagai local. Namun Anda dapat mengubah cakupan deklarasi dengan pernyataan **local** dan **global**. |
| @@ -1771,16 +881,6 @@ a, b, c = 1, 2, 3 | |||
| 1771 | hello = 123 -- menggunakan variabel yang sudah ada | 881 | hello = 123 -- menggunakan variabel yang sudah ada |
| 1772 | ``` | 882 | ``` |
| 1773 | 883 | ||
| 1774 | <YueDisplay> | ||
| 1775 | |||
| 1776 | ```yue | ||
| 1777 | hello = "world" | ||
| 1778 | a, b, c = 1, 2, 3 | ||
| 1779 | hello = 123 -- menggunakan variabel yang sudah ada | ||
| 1780 | ``` | ||
| 1781 | |||
| 1782 | </YueDisplay> | ||
| 1783 | |||
| 1784 | ## Pembaruan Nilai | 884 | ## Pembaruan Nilai |
| 1785 | 885 | ||
| 1786 | Anda dapat melakukan assignment pembaruan dengan banyak operator biner. | 886 | Anda dapat melakukan assignment pembaruan dengan banyak operator biner. |
| @@ -1796,21 +896,6 @@ s ..= "world" -- akan menambah local baru jika variabel local belum ada | |||
| 1796 | arg or= "default value" | 896 | arg or= "default value" |
| 1797 | ``` | 897 | ``` |
| 1798 | 898 | ||
| 1799 | <YueDisplay> | ||
| 1800 | |||
| 1801 | ```yue | ||
| 1802 | x = 1 | ||
| 1803 | x += 1 | ||
| 1804 | x -= 1 | ||
| 1805 | x *= 10 | ||
| 1806 | x /= 10 | ||
| 1807 | x %= 10 | ||
| 1808 | s ..= "world" -- akan menambah local baru jika variabel local belum ada | ||
| 1809 | arg or= "default value" | ||
| 1810 | ``` | ||
| 1811 | |||
| 1812 | </YueDisplay> | ||
| 1813 | |||
| 1814 | ## Assignment Berantai | 899 | ## Assignment Berantai |
| 1815 | 900 | ||
| 1816 | Anda bisa melakukan assignment berantai untuk menetapkan beberapa item ke nilai yang sama. | 901 | Anda bisa melakukan assignment berantai untuk menetapkan beberapa item ke nilai yang sama. |
| @@ -1820,15 +905,6 @@ a = b = c = d = e = 0 | |||
| 1820 | x = y = z = f! | 905 | x = y = z = f! |
| 1821 | ``` | 906 | ``` |
| 1822 | 907 | ||
| 1823 | <YueDisplay> | ||
| 1824 | |||
| 1825 | ```yue | ||
| 1826 | a = b = c = d = e = 0 | ||
| 1827 | x = y = z = f! | ||
| 1828 | ``` | ||
| 1829 | |||
| 1830 | </YueDisplay> | ||
| 1831 | |||
| 1832 | ## Local Eksplisit | 908 | ## Local Eksplisit |
| 1833 | 909 | ||
| 1834 | ```yuescript | 910 | ```yuescript |
| @@ -1848,27 +924,6 @@ do | |||
| 1848 | B = 2 | 924 | B = 2 |
| 1849 | ``` | 925 | ``` |
| 1850 | 926 | ||
| 1851 | <YueDisplay> | ||
| 1852 | |||
| 1853 | ```yue | ||
| 1854 | do | ||
| 1855 | local a = 1 | ||
| 1856 | local * | ||
| 1857 | print "deklarasikan semua variabel sebagai local di awal" | ||
| 1858 | x = -> 1 + y + z | ||
| 1859 | y, z = 2, 3 | ||
| 1860 | global instance = Item\new! | ||
| 1861 | |||
| 1862 | do | ||
| 1863 | local X = 1 | ||
| 1864 | local ^ | ||
| 1865 | print "hanya deklarasikan variabel huruf besar sebagai local di awal" | ||
| 1866 | a = 1 | ||
| 1867 | B = 2 | ||
| 1868 | ``` | ||
| 1869 | |||
| 1870 | </YueDisplay> | ||
| 1871 | |||
| 1872 | ## Global Eksplisit | 927 | ## Global Eksplisit |
| 1873 | 928 | ||
| 1874 | ```yuescript | 929 | ```yuescript |
| @@ -1888,27 +943,6 @@ do | |||
| 1888 | local Temp = "a local value" | 943 | local Temp = "a local value" |
| 1889 | ``` | 944 | ``` |
| 1890 | 945 | ||
| 1891 | <YueDisplay> | ||
| 1892 | |||
| 1893 | ```yue | ||
| 1894 | do | ||
| 1895 | global a = 1 | ||
| 1896 | global * | ||
| 1897 | print "deklarasikan semua variabel sebagai global" | ||
| 1898 | x = -> 1 + y + z | ||
| 1899 | y, z = 2, 3 | ||
| 1900 | |||
| 1901 | do | ||
| 1902 | global X = 1 | ||
| 1903 | global ^ | ||
| 1904 | print "hanya deklarasikan variabel huruf besar sebagai global" | ||
| 1905 | a = 1 | ||
| 1906 | B = 2 | ||
| 1907 | local Temp = "a local value" | ||
| 1908 | ``` | ||
| 1909 | |||
| 1910 | </YueDisplay> | ||
| 1911 | |||
| 1912 | # Penugasan Varargs | 946 | # Penugasan Varargs |
| 1913 | 947 | ||
| 1914 | Anda dapat meng-assign hasil yang dikembalikan dari sebuah fungsi ke simbol varargs `...`. Lalu akses isinya menggunakan cara Lua. | 948 | Anda dapat meng-assign hasil yang dikembalikan dari sebuah fungsi ke simbol varargs `...`. Lalu akses isinya menggunakan cara Lua. |
| @@ -1922,19 +956,6 @@ first = select 1, ... | |||
| 1922 | print ok, count, first | 956 | print ok, count, first |
| 1923 | ``` | 957 | ``` |
| 1924 | 958 | ||
| 1925 | <YueDisplay> | ||
| 1926 | |||
| 1927 | ```yue | ||
| 1928 | list = [1, 2, 3, 4, 5] | ||
| 1929 | fn = (ok) -> ok, table.unpack list | ||
| 1930 | ok, ... = fn true | ||
| 1931 | count = select '#', ... | ||
| 1932 | first = select 1, ... | ||
| 1933 | print ok, count, first | ||
| 1934 | ``` | ||
| 1935 | |||
| 1936 | </YueDisplay> | ||
| 1937 | |||
| 1938 | # Penugasan pada If | 959 | # Penugasan pada If |
| 1939 | 960 | ||
| 1940 | Blok `if` dan `elseif` dapat menerima assignment sebagai ganti ekspresi kondisional. Saat kondisi dievaluasi, assignment akan dilakukan dan nilai yang di-assign akan digunakan sebagai ekspresi kondisional. Variabel yang di-assign hanya berada dalam scope badan kondisional, artinya tidak pernah tersedia jika nilai tidak truthy. Dan Anda harus menggunakan "walrus operator" `:=` sebagai ganti `=` untuk melakukan assignment. | 961 | Blok `if` dan `elseif` dapat menerima assignment sebagai ganti ekspresi kondisional. Saat kondisi dievaluasi, assignment akan dilakukan dan nilai yang di-assign akan digunakan sebagai ekspresi kondisional. Variabel yang di-assign hanya berada dalam scope badan kondisional, artinya tidak pernah tersedia jika nilai tidak truthy. Dan Anda harus menggunakan "walrus operator" `:=` sebagai ganti `=` untuk melakukan assignment. |
| @@ -1944,15 +965,6 @@ if user := database.find_user "moon" | |||
| 1944 | print user.name | 965 | print user.name |
| 1945 | ``` | 966 | ``` |
| 1946 | 967 | ||
| 1947 | <YueDisplay> | ||
| 1948 | |||
| 1949 | ```yue | ||
| 1950 | if user := database.find_user "moon" | ||
| 1951 | print user.name | ||
| 1952 | ``` | ||
| 1953 | |||
| 1954 | </YueDisplay> | ||
| 1955 | |||
| 1956 | ```yuescript | 968 | ```yuescript |
| 1957 | if hello := os.getenv "hello" | 969 | if hello := os.getenv "hello" |
| 1958 | print "You have hello", hello | 970 | print "You have hello", hello |
| @@ -1962,19 +974,6 @@ else | |||
| 1962 | print "nothing :(" | 974 | print "nothing :(" |
| 1963 | ``` | 975 | ``` |
| 1964 | 976 | ||
| 1965 | <YueDisplay> | ||
| 1966 | |||
| 1967 | ```yue | ||
| 1968 | if hello := os.getenv "hello" | ||
| 1969 | print "You have hello", hello | ||
| 1970 | elseif world := os.getenv "world" | ||
| 1971 | print "you have world", world | ||
| 1972 | else | ||
| 1973 | print "nothing :(" | ||
| 1974 | ``` | ||
| 1975 | |||
| 1976 | </YueDisplay> | ||
| 1977 | |||
| 1978 | Assignment if dengan beberapa nilai return. Hanya nilai pertama yang dicek, nilai lainnya tetap berada dalam scope. | 977 | Assignment if dengan beberapa nilai return. Hanya nilai pertama yang dicek, nilai lainnya tetap berada dalam scope. |
| 1979 | 978 | ||
| 1980 | ```yuescript | 979 | ```yuescript |
| @@ -1983,16 +982,6 @@ if success, result := pcall -> "get result without problems" | |||
| 1983 | print "OK" | 982 | print "OK" |
| 1984 | ``` | 983 | ``` |
| 1985 | 984 | ||
| 1986 | <YueDisplay> | ||
| 1987 | |||
| 1988 | ```yue | ||
| 1989 | if success, result := pcall -> "get result without problems" | ||
| 1990 | print result -- variabel result berada dalam scope | ||
| 1991 | print "OK" | ||
| 1992 | ``` | ||
| 1993 | |||
| 1994 | </YueDisplay> | ||
| 1995 | |||
| 1996 | ## Assignment pada While | 985 | ## Assignment pada While |
| 1997 | 986 | ||
| 1998 | Anda juga bisa menggunakan assignment if di loop while untuk mendapatkan nilai sebagai kondisi loop. | 987 | Anda juga bisa menggunakan assignment if di loop while untuk mendapatkan nilai sebagai kondisi loop. |
| @@ -2003,16 +992,6 @@ while byte := stream\read_one! | |||
| 2003 | print byte | 992 | print byte |
| 2004 | ``` | 993 | ``` |
| 2005 | 994 | ||
| 2006 | <YueDisplay> | ||
| 2007 | |||
| 2008 | ```yue | ||
| 2009 | while byte := stream\read_one! | ||
| 2010 | -- lakukan sesuatu dengan byte | ||
| 2011 | print byte | ||
| 2012 | ``` | ||
| 2013 | |||
| 2014 | </YueDisplay> | ||
| 2015 | |||
| 2016 | # Penugasan Destrukturisasi | 995 | # Penugasan Destrukturisasi |
| 2017 | 996 | ||
| 2018 | Assignment destrukturisasi adalah cara cepat untuk mengekstrak nilai dari sebuah tabel berdasarkan nama kunci atau posisinya pada tabel berbasis array. | 997 | Assignment destrukturisasi adalah cara cepat untuk mengekstrak nilai dari sebuah tabel berdasarkan nama kunci atau posisinya pada tabel berbasis array. |
| @@ -2028,17 +1007,6 @@ thing = [1, 2] | |||
| 2028 | print a, b | 1007 | print a, b |
| 2029 | ``` | 1008 | ``` |
| 2030 | 1009 | ||
| 2031 | <YueDisplay> | ||
| 2032 | |||
| 2033 | ```yue | ||
| 2034 | thing = [1, 2] | ||
| 2035 | |||
| 2036 | [a, b] = thing | ||
| 2037 | print a, b | ||
| 2038 | ``` | ||
| 2039 | |||
| 2040 | </YueDisplay> | ||
| 2041 | |||
| 2042 | Di literal tabel destrukturisasi, kunci mewakili kunci yang dibaca dari sisi kanan, dan nilai mewakili nama yang akan menerima nilai tersebut. | 1010 | Di literal tabel destrukturisasi, kunci mewakili kunci yang dibaca dari sisi kanan, dan nilai mewakili nama yang akan menerima nilai tersebut. |
| 2043 | 1011 | ||
| 2044 | ```yuescript | 1012 | ```yuescript |
| @@ -2054,23 +1022,6 @@ print hello, the_day | |||
| 2054 | :day = obj -- OK untuk destrukturisasi sederhana tanpa kurung | 1022 | :day = obj -- OK untuk destrukturisasi sederhana tanpa kurung |
| 2055 | ``` | 1023 | ``` |
| 2056 | 1024 | ||
| 2057 | <YueDisplay> | ||
| 2058 | |||
| 2059 | ```yue | ||
| 2060 | obj = { | ||
| 2061 | hello: "world" | ||
| 2062 | day: "tuesday" | ||
| 2063 | length: 20 | ||
| 2064 | } | ||
| 2065 | |||
| 2066 | {hello: hello, day: the_day} = obj | ||
| 2067 | print hello, the_day | ||
| 2068 | |||
| 2069 | :day = obj -- OK untuk destrukturisasi sederhana tanpa kurung | ||
| 2070 | ``` | ||
| 2071 | |||
| 2072 | </YueDisplay> | ||
| 2073 | |||
| 2074 | Ini juga bekerja pada struktur data bertingkat: | 1025 | Ini juga bekerja pada struktur data bertingkat: |
| 2075 | 1026 | ||
| 2076 | ```yuescript | 1027 | ```yuescript |
| @@ -2086,23 +1037,6 @@ obj2 = { | |||
| 2086 | print first, second, color | 1037 | print first, second, color |
| 2087 | ``` | 1038 | ``` |
| 2088 | 1039 | ||
| 2089 | <YueDisplay> | ||
| 2090 | |||
| 2091 | ```yue | ||
| 2092 | obj2 = { | ||
| 2093 | numbers: [1, 2, 3, 4] | ||
| 2094 | properties: { | ||
| 2095 | color: "green" | ||
| 2096 | height: 13.5 | ||
| 2097 | } | ||
| 2098 | } | ||
| 2099 | |||
| 2100 | {numbers: [first, second], properties: {color: color}} = obj2 | ||
| 2101 | print first, second, color | ||
| 2102 | ``` | ||
| 2103 | |||
| 2104 | </YueDisplay> | ||
| 2105 | |||
| 2106 | Jika pernyataan destrukturisasi kompleks, Anda bisa memecahnya ke beberapa baris. Contoh yang sedikit lebih rumit: | 1040 | Jika pernyataan destrukturisasi kompleks, Anda bisa memecahnya ke beberapa baris. Contoh yang sedikit lebih rumit: |
| 2107 | 1041 | ||
| 2108 | ```yuescript | 1042 | ```yuescript |
| @@ -2114,75 +1048,30 @@ Jika pernyataan destrukturisasi kompleks, Anda bisa memecahnya ke beberapa baris | |||
| 2114 | } = obj2 | 1048 | } = obj2 |
| 2115 | ``` | 1049 | ``` |
| 2116 | 1050 | ||
| 2117 | <YueDisplay> | ||
| 2118 | |||
| 2119 | ```yue | ||
| 2120 | { | ||
| 2121 | numbers: [first, second] | ||
| 2122 | properties: { | ||
| 2123 | color: color | ||
| 2124 | } | ||
| 2125 | } = obj2 | ||
| 2126 | ``` | ||
| 2127 | |||
| 2128 | </YueDisplay> | ||
| 2129 | |||
| 2130 | Umumnya mengekstrak nilai dari tabel lalu menugaskannya ke variabel local dengan nama yang sama dengan kuncinya. Untuk menghindari pengulangan, kita bisa menggunakan operator prefiks **:**: | 1051 | Umumnya mengekstrak nilai dari tabel lalu menugaskannya ke variabel local dengan nama yang sama dengan kuncinya. Untuk menghindari pengulangan, kita bisa menggunakan operator prefiks **:**: |
| 2131 | 1052 | ||
| 2132 | ```yuescript | 1053 | ```yuescript |
| 2133 | {:concat, :insert} = table | 1054 | {:concat, :insert} = table |
| 2134 | ``` | 1055 | ``` |
| 2135 | 1056 | ||
| 2136 | <YueDisplay> | ||
| 2137 | |||
| 2138 | ```yue | ||
| 2139 | {:concat, :insert} = table | ||
| 2140 | ``` | ||
| 2141 | |||
| 2142 | </YueDisplay> | ||
| 2143 | |||
| 2144 | Ini secara efektif sama seperti import, tetapi kita dapat mengganti nama field yang ingin diekstrak dengan menggabungkan sintaks: | 1057 | Ini secara efektif sama seperti import, tetapi kita dapat mengganti nama field yang ingin diekstrak dengan menggabungkan sintaks: |
| 2145 | 1058 | ||
| 2146 | ```yuescript | 1059 | ```yuescript |
| 2147 | {:mix, :max, random: rand} = math | 1060 | {:mix, :max, random: rand} = math |
| 2148 | ``` | 1061 | ``` |
| 2149 | 1062 | ||
| 2150 | <YueDisplay> | ||
| 2151 | |||
| 2152 | ```yue | ||
| 2153 | {:mix, :max, random: rand} = math | ||
| 2154 | ``` | ||
| 2155 | |||
| 2156 | </YueDisplay> | ||
| 2157 | |||
| 2158 | Anda bisa menulis nilai default saat destrukturisasi seperti: | 1063 | Anda bisa menulis nilai default saat destrukturisasi seperti: |
| 2159 | 1064 | ||
| 2160 | ```yuescript | 1065 | ```yuescript |
| 2161 | {:name = "nameless", :job = "jobless"} = person | 1066 | {:name = "nameless", :job = "jobless"} = person |
| 2162 | ``` | 1067 | ``` |
| 2163 | 1068 | ||
| 2164 | <YueDisplay> | ||
| 2165 | |||
| 2166 | ```yue | ||
| 2167 | {:name = "nameless", :job = "jobless"} = person | ||
| 2168 | ``` | ||
| 2169 | |||
| 2170 | </YueDisplay> | ||
| 2171 | |||
| 2172 | Anda dapat menggunakan `_` sebagai placeholder saat destrukturisasi list: | 1069 | Anda dapat menggunakan `_` sebagai placeholder saat destrukturisasi list: |
| 2173 | 1070 | ||
| 2174 | ```yuescript | 1071 | ```yuescript |
| 2175 | [_, two, _, four] = items | 1072 | [_, two, _, four] = items |
| 2176 | ``` | 1073 | ``` |
| 2177 | 1074 | ||
| 2178 | <YueDisplay> | ||
| 2179 | |||
| 2180 | ```yue | ||
| 2181 | [_, two, _, four] = items | ||
| 2182 | ``` | ||
| 2183 | |||
| 2184 | </YueDisplay> | ||
| 2185 | |||
| 2186 | ## Destrukturisasi Rentang | 1075 | ## Destrukturisasi Rentang |
| 2187 | 1076 | ||
| 2188 | Anda dapat menggunakan operator spread `...` pada destrukturisasi list untuk menangkap rentang nilai. Ini berguna ketika Anda ingin mengekstrak elemen tertentu dari awal dan akhir list sambil mengumpulkan sisanya di tengah. | 1077 | Anda dapat menggunakan operator spread `...` pada destrukturisasi list untuk menangkap rentang nilai. Ini berguna ketika Anda ingin mengekstrak elemen tertentu dari awal dan akhir list sambil mengumpulkan sisanya di tengah. |
| @@ -2195,18 +1084,6 @@ print bulk -- prints: {"second", "third", "fourth"} | |||
| 2195 | print last -- prints: last | 1084 | print last -- prints: last |
| 2196 | ``` | 1085 | ``` |
| 2197 | 1086 | ||
| 2198 | <YueDisplay> | ||
| 2199 | |||
| 2200 | ```yue | ||
| 2201 | orders = ["first", "second", "third", "fourth", "last"] | ||
| 2202 | [first, ...bulk, last] = orders | ||
| 2203 | print first -- prints: first | ||
| 2204 | print bulk -- prints: {"second", "third", "fourth"} | ||
| 2205 | print last -- prints: last | ||
| 2206 | ``` | ||
| 2207 | |||
| 2208 | </YueDisplay> | ||
| 2209 | |||
| 2210 | Operator spread dapat digunakan pada posisi berbeda untuk menangkap rentang yang berbeda, dan Anda bisa memakai `_` sebagai placeholder untuk nilai yang tidak ingin ditangkap: | 1087 | Operator spread dapat digunakan pada posisi berbeda untuk menangkap rentang yang berbeda, dan Anda bisa memakai `_` sebagai placeholder untuk nilai yang tidak ingin ditangkap: |
| 2211 | 1088 | ||
| 2212 | ```yuescript | 1089 | ```yuescript |
| @@ -2220,21 +1097,6 @@ Operator spread dapat digunakan pada posisi berbeda untuk menangkap rentang yang | |||
| 2220 | [first, ..._, last] = orders | 1097 | [first, ..._, last] = orders |
| 2221 | ``` | 1098 | ``` |
| 2222 | 1099 | ||
| 2223 | <YueDisplay> | ||
| 2224 | |||
| 2225 | ```yue | ||
| 2226 | -- Tangkap semuanya setelah elemen pertama | ||
| 2227 | [first, ...rest] = orders | ||
| 2228 | |||
| 2229 | -- Tangkap semuanya sebelum elemen terakhir | ||
| 2230 | [...start, last] = orders | ||
| 2231 | |||
| 2232 | -- Tangkap semuanya kecuali elemen tengah | ||
| 2233 | [first, ..._, last] = orders | ||
| 2234 | ``` | ||
| 2235 | |||
| 2236 | </YueDisplay> | ||
| 2237 | |||
| 2238 | ## Destrukturisasi di Tempat Lain | 1100 | ## Destrukturisasi di Tempat Lain |
| 2239 | 1101 | ||
| 2240 | Destrukturisasi juga dapat muncul di tempat-tempat di mana assignment terjadi secara implisit. Contohnya adalah perulangan for: | 1102 | Destrukturisasi juga dapat muncul di tempat-tempat di mana assignment terjadi secara implisit. Contohnya adalah perulangan for: |
| @@ -2249,20 +1111,6 @@ for [left, right] in *tuples | |||
| 2249 | print left, right | 1111 | print left, right |
| 2250 | ``` | 1112 | ``` |
| 2251 | 1113 | ||
| 2252 | <YueDisplay> | ||
| 2253 | |||
| 2254 | ```yue | ||
| 2255 | tuples = [ | ||
| 2256 | ["hello", "world"] | ||
| 2257 | ["egg", "head"] | ||
| 2258 | ] | ||
| 2259 | |||
| 2260 | for [left, right] in *tuples | ||
| 2261 | print left, right | ||
| 2262 | ``` | ||
| 2263 | |||
| 2264 | </YueDisplay> | ||
| 2265 | |||
| 2266 | Kita tahu setiap elemen pada tabel array adalah tuple dua item, sehingga kita dapat membongkarnya langsung di klausa nama pada pernyataan for menggunakan destrukturisasi. | 1114 | Kita tahu setiap elemen pada tabel array adalah tuple dua item, sehingga kita dapat membongkarnya langsung di klausa nama pada pernyataan for menggunakan destrukturisasi. |
| 2267 | 1115 | ||
| 2268 | # Klausa Using; Mengendalikan Penugasan Destruktif | 1116 | # Klausa Using; Mengendalikan Penugasan Destruktif |
| @@ -2285,26 +1133,6 @@ my_func! | |||
| 2285 | print i -- akan mencetak 0 | 1133 | print i -- akan mencetak 0 |
| 2286 | ``` | 1134 | ``` |
| 2287 | 1135 | ||
| 2288 | <YueDisplay> | ||
| 2289 | |||
| 2290 | ```yue | ||
| 2291 | i = 100 | ||
| 2292 | |||
| 2293 | -- banyak baris kode... | ||
| 2294 | |||
| 2295 | my_func = -> | ||
| 2296 | i = 10 | ||
| 2297 | while i > 0 | ||
| 2298 | print i | ||
| 2299 | i -= 1 | ||
| 2300 | |||
| 2301 | my_func! | ||
| 2302 | |||
| 2303 | print i -- akan mencetak 0 | ||
| 2304 | ``` | ||
| 2305 | |||
| 2306 | </YueDisplay> | ||
| 2307 | |||
| 2308 | Di `my_func`, kita tanpa sengaja menimpa nilai `i`. Dalam contoh ini halnya cukup jelas, tetapi bayangkan kode besar atau basis kode asing di mana tidak jelas nama apa saja yang sudah dideklarasikan. | 1136 | Di `my_func`, kita tanpa sengaja menimpa nilai `i`. Dalam contoh ini halnya cukup jelas, tetapi bayangkan kode besar atau basis kode asing di mana tidak jelas nama apa saja yang sudah dideklarasikan. |
| 2309 | 1137 | ||
| 2310 | Akan sangat membantu jika kita dapat menyatakan variabel mana dari scope luar yang memang ingin kita ubah, agar mencegah mengubah yang lain secara tidak sengaja. | 1138 | Akan sangat membantu jika kita dapat menyatakan variabel mana dari scope luar yang memang ingin kita ubah, agar mencegah mengubah yang lain secara tidak sengaja. |
| @@ -2321,20 +1149,6 @@ my_func! | |||
| 2321 | print i -- mencetak 100, i tidak terpengaruh | 1149 | print i -- mencetak 100, i tidak terpengaruh |
| 2322 | ``` | 1150 | ``` |
| 2323 | 1151 | ||
| 2324 | <YueDisplay> | ||
| 2325 | |||
| 2326 | ```yue | ||
| 2327 | i = 100 | ||
| 2328 | |||
| 2329 | my_func = (using nil) -> | ||
| 2330 | i = "hello" -- variabel local baru dibuat di sini | ||
| 2331 | |||
| 2332 | my_func! | ||
| 2333 | print i -- mencetak 100, i tidak terpengaruh | ||
| 2334 | ``` | ||
| 2335 | |||
| 2336 | </YueDisplay> | ||
| 2337 | |||
| 2338 | Beberapa nama dapat dipisahkan dengan koma. Nilai closure tetap bisa diakses, hanya saja tidak dapat dimodifikasi: | 1152 | Beberapa nama dapat dipisahkan dengan koma. Nilai closure tetap bisa diakses, hanya saja tidak dapat dimodifikasi: |
| 2339 | 1153 | ||
| 2340 | ```yuescript | 1154 | ```yuescript |
| @@ -2350,23 +1164,6 @@ my_func(22) | |||
| 2350 | print i, k -- ini telah diperbarui | 1164 | print i, k -- ini telah diperbarui |
| 2351 | ``` | 1165 | ``` |
| 2352 | 1166 | ||
| 2353 | <YueDisplay> | ||
| 2354 | |||
| 2355 | ```yue | ||
| 2356 | tmp = 1213 | ||
| 2357 | i, k = 100, 50 | ||
| 2358 | |||
| 2359 | my_func = (add using k, i) -> | ||
| 2360 | tmp = tmp + add -- tmp local baru dibuat | ||
| 2361 | i += tmp | ||
| 2362 | k += tmp | ||
| 2363 | |||
| 2364 | my_func(22) | ||
| 2365 | print i, k -- ini telah diperbarui | ||
| 2366 | ``` | ||
| 2367 | |||
| 2368 | </YueDisplay> | ||
| 2369 | |||
| 2370 | # Penggunaan | 1167 | # Penggunaan |
| 2371 | 1168 | ||
| 2372 | ## Modul Lua | 1169 | ## Modul Lua |
| @@ -2535,55 +1332,6 @@ with apple | |||
| 2535 | export 🌛 = "Skrip Bulan" | 1332 | export 🌛 = "Skrip Bulan" |
| 2536 | ``` | 1333 | ``` |
| 2537 | 1334 | ||
| 2538 | <YueDisplay> | ||
| 2539 | |||
| 2540 | ```yue | ||
| 2541 | -- import syntax | ||
| 2542 | import p, to_lua from "yue" | ||
| 2543 | |||
| 2544 | -- object literals | ||
| 2545 | inventory = | ||
| 2546 | equipment: | ||
| 2547 | - "sword" | ||
| 2548 | - "shield" | ||
| 2549 | items: | ||
| 2550 | - name: "potion" | ||
| 2551 | count: 10 | ||
| 2552 | - name: "bread" | ||
| 2553 | count: 3 | ||
| 2554 | |||
| 2555 | -- list comprehension | ||
| 2556 | map = (arr, action) -> | ||
| 2557 | [action item for item in *arr] | ||
| 2558 | |||
| 2559 | filter = (arr, cond) -> | ||
| 2560 | [item for item in *arr when cond item] | ||
| 2561 | |||
| 2562 | reduce = (arr, init, action): init -> | ||
| 2563 | init = action init, item for item in *arr | ||
| 2564 | |||
| 2565 | -- pipe operator | ||
| 2566 | [1, 2, 3] | ||
| 2567 | |> map (x) -> x * 2 | ||
| 2568 | |> filter (x) -> x > 4 | ||
| 2569 | |> reduce 0, (a, b) -> a + b | ||
| 2570 | |||
| 2571 | |||
| 2572 | -- metatable manipulation | ||
| 2573 | apple = | ||
| 2574 | size: 15 | ||
| 2575 | <index>: | ||
| 2576 | color: 0x00ffff | ||
| 2577 | |||
| 2578 | with apple | ||
| 2579 | p .size, .color, .<index> if .<>? | ||
| 2580 | |||
| 2581 | -- js-like export syntax | ||
| 2582 | export 🌛 = "Skrip Bulan" | ||
| 2583 | ``` | ||
| 2584 | |||
| 2585 | </YueDisplay> | ||
| 2586 | |||
| 2587 | ## Tentang Dora SSR | 1335 | ## Tentang Dora SSR |
| 2588 | 1336 | ||
| 2589 | YueScript dikembangkan dan dipelihara bersama mesin game open-source [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). YueScript telah digunakan untuk membuat alat mesin, demo game, dan prototipe, membuktikan kemampuannya dalam skenario dunia nyata sekaligus meningkatkan pengalaman pengembangan Dora SSR. | 1337 | YueScript dikembangkan dan dipelihara bersama mesin game open-source [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). YueScript telah digunakan untuk membuat alat mesin, demo game, dan prototipe, membuktikan kemampuannya dalam skenario dunia nyata sekaligus meningkatkan pengalaman pengembangan Dora SSR. |
| @@ -2642,18 +1390,6 @@ else | |||
| 2642 | print "Tidak ada koin" | 1390 | print "Tidak ada koin" |
| 2643 | ``` | 1391 | ``` |
| 2644 | 1392 | ||
| 2645 | <YueDisplay> | ||
| 2646 | |||
| 2647 | ```yue | ||
| 2648 | have_coins = false | ||
| 2649 | if have_coins | ||
| 2650 | print "Dapat koin" | ||
| 2651 | else | ||
| 2652 | print "Tidak ada koin" | ||
| 2653 | ``` | ||
| 2654 | |||
| 2655 | </YueDisplay> | ||
| 2656 | |||
| 2657 | Sintaks pendek untuk pernyataan tunggal juga bisa digunakan: | 1393 | Sintaks pendek untuk pernyataan tunggal juga bisa digunakan: |
| 2658 | 1394 | ||
| 2659 | ```yuescript | 1395 | ```yuescript |
| @@ -2661,15 +1397,6 @@ have_coins = false | |||
| 2661 | if have_coins then print "Dapat koin" else print "Tidak ada koin" | 1397 | if have_coins then print "Dapat koin" else print "Tidak ada koin" |
| 2662 | ``` | 1398 | ``` |
| 2663 | 1399 | ||
| 2664 | <YueDisplay> | ||
| 2665 | |||
| 2666 | ```yue | ||
| 2667 | have_coins = false | ||
| 2668 | if have_coins then print "Dapat koin" else print "Tidak ada koin" | ||
| 2669 | ``` | ||
| 2670 | |||
| 2671 | </YueDisplay> | ||
| 2672 | |||
| 2673 | Karena pernyataan if dapat digunakan sebagai ekspresi, ini juga bisa ditulis sebagai: | 1400 | Karena pernyataan if dapat digunakan sebagai ekspresi, ini juga bisa ditulis sebagai: |
| 2674 | 1401 | ||
| 2675 | ```yuescript | 1402 | ```yuescript |
| @@ -2677,15 +1404,6 @@ have_coins = false | |||
| 2677 | print if have_coins then "Dapat koin" else "Tidak ada koin" | 1404 | print if have_coins then "Dapat koin" else "Tidak ada koin" |
| 2678 | ``` | 1405 | ``` |
| 2679 | 1406 | ||
| 2680 | <YueDisplay> | ||
| 2681 | |||
| 2682 | ```yue | ||
| 2683 | have_coins = false | ||
| 2684 | print if have_coins then "Dapat koin" else "Tidak ada koin" | ||
| 2685 | ``` | ||
| 2686 | |||
| 2687 | </YueDisplay> | ||
| 2688 | |||
| 2689 | Kondisional juga bisa digunakan di pernyataan return dan assignment: | 1407 | Kondisional juga bisa digunakan di pernyataan return dan assignment: |
| 2690 | 1408 | ||
| 2691 | ```yuescript | 1409 | ```yuescript |
| @@ -2703,25 +1421,6 @@ else | |||
| 2703 | print message -- prints: Saya sangat tinggi | 1421 | print message -- prints: Saya sangat tinggi |
| 2704 | ``` | 1422 | ``` |
| 2705 | 1423 | ||
| 2706 | <YueDisplay> | ||
| 2707 | |||
| 2708 | ```yue | ||
| 2709 | is_tall = (name) -> | ||
| 2710 | if name == "Rob" | ||
| 2711 | true | ||
| 2712 | else | ||
| 2713 | false | ||
| 2714 | |||
| 2715 | message = if is_tall "Rob" | ||
| 2716 | "Saya sangat tinggi" | ||
| 2717 | else | ||
| 2718 | "Saya tidak terlalu tinggi" | ||
| 2719 | |||
| 2720 | print message -- prints: Saya sangat tinggi | ||
| 2721 | ``` | ||
| 2722 | |||
| 2723 | </YueDisplay> | ||
| 2724 | |||
| 2725 | Kebalikan dari if adalah unless: | 1424 | Kebalikan dari if adalah unless: |
| 2726 | 1425 | ||
| 2727 | ```yuescript | 1426 | ```yuescript |
| @@ -2729,27 +1428,10 @@ unless os.date("%A") == "Monday" | |||
| 2729 | print "hari ini bukan Senin!" | 1428 | print "hari ini bukan Senin!" |
| 2730 | ``` | 1429 | ``` |
| 2731 | 1430 | ||
| 2732 | <YueDisplay> | ||
| 2733 | |||
| 2734 | ```yue | ||
| 2735 | unless os.date("%A") == "Monday" | ||
| 2736 | print "hari ini bukan Senin!" | ||
| 2737 | ``` | ||
| 2738 | |||
| 2739 | </YueDisplay> | ||
| 2740 | |||
| 2741 | ```yuescript | 1431 | ```yuescript |
| 2742 | print "Kamu beruntung!" unless math.random! > 0.1 | 1432 | print "Kamu beruntung!" unless math.random! > 0.1 |
| 2743 | ``` | 1433 | ``` |
| 2744 | 1434 | ||
| 2745 | <YueDisplay> | ||
| 2746 | |||
| 2747 | ```yue | ||
| 2748 | print "Kamu beruntung!" unless math.random! > 0.1 | ||
| 2749 | ``` | ||
| 2750 | |||
| 2751 | </YueDisplay> | ||
| 2752 | |||
| 2753 | ## Ekspresi In | 1435 | ## Ekspresi In |
| 2754 | 1436 | ||
| 2755 | Anda dapat menulis kode pengecekan rentang dengan `ekspresi in`. | 1437 | Anda dapat menulis kode pengecekan rentang dengan `ekspresi in`. |
| @@ -2764,20 +1446,6 @@ if a in list | |||
| 2764 | print "memeriksa apakah `a` ada di dalam daftar" | 1446 | print "memeriksa apakah `a` ada di dalam daftar" |
| 2765 | ``` | 1447 | ``` |
| 2766 | 1448 | ||
| 2767 | <YueDisplay> | ||
| 2768 | |||
| 2769 | ```yue | ||
| 2770 | a = 5 | ||
| 2771 | |||
| 2772 | if a in [1, 3, 5, 7] | ||
| 2773 | print "memeriksa kesamaan dengan nilai-nilai diskrit" | ||
| 2774 | |||
| 2775 | if a in list | ||
| 2776 | print "memeriksa apakah `a` ada di dalam daftar" | ||
| 2777 | ``` | ||
| 2778 | |||
| 2779 | </YueDisplay> | ||
| 2780 | |||
| 2781 | Operator `in` juga dapat digunakan dengan tabel dan mendukung varian `not in` untuk negasi: | 1449 | Operator `in` juga dapat digunakan dengan tabel dan mendukung varian `not in` untuk negasi: |
| 2782 | 1450 | ||
| 2783 | ```yuescript | 1451 | ```yuescript |
| @@ -2791,21 +1459,6 @@ not_exist = item not in list | |||
| 2791 | check = -> value not in table | 1459 | check = -> value not in table |
| 2792 | ``` | 1460 | ``` |
| 2793 | 1461 | ||
| 2794 | <YueDisplay> | ||
| 2795 | |||
| 2796 | ```yue | ||
| 2797 | has = "foo" in {"bar", "foo"} | ||
| 2798 | |||
| 2799 | if a in {1, 2, 3} | ||
| 2800 | print "a ada di dalam tabel" | ||
| 2801 | |||
| 2802 | not_exist = item not in list | ||
| 2803 | |||
| 2804 | check = -> value not in table | ||
| 2805 | ``` | ||
| 2806 | |||
| 2807 | </YueDisplay> | ||
| 2808 | |||
| 2809 | Daftar atau tabel dengan satu elemen memeriksa kesamaan dengan elemen tersebut: | 1462 | Daftar atau tabel dengan satu elemen memeriksa kesamaan dengan elemen tersebut: |
| 2810 | 1463 | ||
| 2811 | ```yuescript | 1464 | ```yuescript |
| @@ -2820,22 +1473,6 @@ with tb | |||
| 2820 | c = a in [1] | 1473 | c = a in [1] |
| 2821 | ``` | 1474 | ``` |
| 2822 | 1475 | ||
| 2823 | <YueDisplay> | ||
| 2824 | |||
| 2825 | ```yue | ||
| 2826 | -- [1,] memeriksa apakah nilai == 1 | ||
| 2827 | c = a in [1,] | ||
| 2828 | |||
| 2829 | -- {1} juga memeriksa apakah nilai == 1 | ||
| 2830 | c = a in {1} | ||
| 2831 | |||
| 2832 | -- Tanpa koma, [1] adalah akses indeks (tb[1]) | ||
| 2833 | with tb | ||
| 2834 | c = a in [1] | ||
| 2835 | ``` | ||
| 2836 | |||
| 2837 | </YueDisplay> | ||
| 2838 | |||
| 2839 | # Perulangan For | 1476 | # Perulangan For |
| 2840 | 1477 | ||
| 2841 | Ada dua bentuk perulangan for, seperti di Lua. Satu numerik dan satu generik: | 1478 | Ada dua bentuk perulangan for, seperti di Lua. Satu numerik dan satu generik: |
| @@ -2851,21 +1488,6 @@ for key, value in pairs object | |||
| 2851 | print key, value | 1488 | print key, value |
| 2852 | ``` | 1489 | ``` |
| 2853 | 1490 | ||
| 2854 | <YueDisplay> | ||
| 2855 | |||
| 2856 | ```yue | ||
| 2857 | for i = 10, 20 | ||
| 2858 | print i | ||
| 2859 | |||
| 2860 | for k = 1, 15, 2 -- an optional step provided | ||
| 2861 | print k | ||
| 2862 | |||
| 2863 | for key, value in pairs object | ||
| 2864 | print key, value | ||
| 2865 | ``` | ||
| 2866 | |||
| 2867 | </YueDisplay> | ||
| 2868 | |||
| 2869 | Operator slicing dan **\*** dapat digunakan, seperti pada comprehension: | 1491 | Operator slicing dan **\*** dapat digunakan, seperti pada comprehension: |
| 2870 | 1492 | ||
| 2871 | ```yuescript | 1493 | ```yuescript |
| @@ -2873,15 +1495,6 @@ for item in *items[2, 4] | |||
| 2873 | print item | 1495 | print item |
| 2874 | ``` | 1496 | ``` |
| 2875 | 1497 | ||
| 2876 | <YueDisplay> | ||
| 2877 | |||
| 2878 | ```yue | ||
| 2879 | for item in *items[2, 4] | ||
| 2880 | print item | ||
| 2881 | ``` | ||
| 2882 | |||
| 2883 | </YueDisplay> | ||
| 2884 | |||
| 2885 | Sintaks yang lebih singkat juga tersedia untuk semua variasi ketika badan hanya satu baris: | 1498 | Sintaks yang lebih singkat juga tersedia untuk semua variasi ketika badan hanya satu baris: |
| 2886 | 1499 | ||
| 2887 | ```yuescript | 1500 | ```yuescript |
| @@ -2890,16 +1503,6 @@ for item in *items do print item | |||
| 2890 | for j = 1, 10, 3 do print j | 1503 | for j = 1, 10, 3 do print j |
| 2891 | ``` | 1504 | ``` |
| 2892 | 1505 | ||
| 2893 | <YueDisplay> | ||
| 2894 | |||
| 2895 | ```yue | ||
| 2896 | for item in *items do print item | ||
| 2897 | |||
| 2898 | for j = 1, 10, 3 do print j | ||
| 2899 | ``` | ||
| 2900 | |||
| 2901 | </YueDisplay> | ||
| 2902 | |||
| 2903 | Perulangan for juga bisa digunakan sebagai ekspresi. Pernyataan terakhir di badan for dipaksa menjadi ekspresi dan ditambahkan ke tabel array yang terakumulasi. | 1506 | Perulangan for juga bisa digunakan sebagai ekspresi. Pernyataan terakhir di badan for dipaksa menjadi ekspresi dan ditambahkan ke tabel array yang terakumulasi. |
| 2904 | 1507 | ||
| 2905 | Menggandakan setiap bilangan genap: | 1508 | Menggandakan setiap bilangan genap: |
| @@ -2912,18 +1515,6 @@ doubled_evens = for i = 1, 20 | |||
| 2912 | i | 1515 | i |
| 2913 | ``` | 1516 | ``` |
| 2914 | 1517 | ||
| 2915 | <YueDisplay> | ||
| 2916 | |||
| 2917 | ```yue | ||
| 2918 | doubled_evens = for i = 1, 20 | ||
| 2919 | if i % 2 == 0 | ||
| 2920 | i * 2 | ||
| 2921 | else | ||
| 2922 | i | ||
| 2923 | ``` | ||
| 2924 | |||
| 2925 | </YueDisplay> | ||
| 2926 | |||
| 2927 | Selain itu, loop for mendukung break dengan nilai kembalian, sehingga loop itu sendiri bisa dipakai sebagai ekspresi yang keluar lebih awal dengan hasil bermakna. Ekspresi `for` mendukung `break` dengan banyak nilai. | 1518 | Selain itu, loop for mendukung break dengan nilai kembalian, sehingga loop itu sendiri bisa dipakai sebagai ekspresi yang keluar lebih awal dengan hasil bermakna. Ekspresi `for` mendukung `break` dengan banyak nilai. |
| 2928 | 1519 | ||
| 2929 | Contohnya, untuk menemukan angka pertama yang lebih besar dari 10: | 1520 | Contohnya, untuk menemukan angka pertama yang lebih besar dari 10: |
| @@ -2933,15 +1524,6 @@ first_large = for n in *numbers | |||
| 2933 | break n if n > 10 | 1524 | break n if n > 10 |
| 2934 | ``` | 1525 | ``` |
| 2935 | 1526 | ||
| 2936 | <YueDisplay> | ||
| 2937 | |||
| 2938 | ```yue | ||
| 2939 | first_large = for n in *numbers | ||
| 2940 | break n if n > 10 | ||
| 2941 | ``` | ||
| 2942 | |||
| 2943 | </YueDisplay> | ||
| 2944 | |||
| 2945 | Sintaks break-dengan-nilai ini memungkinkan pola pencarian atau keluar-lebih-awal yang ringkas langsung di dalam ekspresi loop. | 1527 | Sintaks break-dengan-nilai ini memungkinkan pola pencarian atau keluar-lebih-awal yang ringkas langsung di dalam ekspresi loop. |
| 2946 | 1528 | ||
| 2947 | ```yuescript | 1529 | ```yuescript |
| @@ -2949,15 +1531,6 @@ key, score = for k, v in pairs data | |||
| 2949 | break k, v * 10 if k == "target" | 1531 | break k, v * 10 if k == "target" |
| 2950 | ``` | 1532 | ``` |
| 2951 | 1533 | ||
| 2952 | <YueDisplay> | ||
| 2953 | |||
| 2954 | ```yue | ||
| 2955 | key, score = for k, v in pairs data | ||
| 2956 | break k, v * 10 if k == "target" | ||
| 2957 | ``` | ||
| 2958 | |||
| 2959 | </YueDisplay> | ||
| 2960 | |||
| 2961 | Anda juga bisa memfilter nilai dengan menggabungkan ekspresi for dengan pernyataan continue. | 1534 | Anda juga bisa memfilter nilai dengan menggabungkan ekspresi for dengan pernyataan continue. |
| 2962 | 1535 | ||
| 2963 | Loop for di akhir badan fungsi tidak diakumulasikan menjadi tabel untuk nilai kembalian (sebaliknya fungsi akan mengembalikan nil). Gunakan pernyataan return eksplisit, atau ubah loop menjadi list comprehension. | 1536 | Loop for di akhir badan fungsi tidak diakumulasikan menjadi tabel untuk nilai kembalian (sebaliknya fungsi akan mengembalikan nil). Gunakan pernyataan return eksplisit, atau ubah loop menjadi list comprehension. |
| @@ -2970,18 +1543,6 @@ print func_a! -- prints nil | |||
| 2970 | print func_b! -- prints table object | 1543 | print func_b! -- prints table object |
| 2971 | ``` | 1544 | ``` |
| 2972 | 1545 | ||
| 2973 | <YueDisplay> | ||
| 2974 | |||
| 2975 | ```yue | ||
| 2976 | func_a = -> for i = 1, 10 do print i | ||
| 2977 | func_b = -> return for i = 1, 10 do i | ||
| 2978 | |||
| 2979 | print func_a! -- prints nil | ||
| 2980 | print func_b! -- prints table object | ||
| 2981 | ``` | ||
| 2982 | |||
| 2983 | </YueDisplay> | ||
| 2984 | |||
| 2985 | # Pernyataan Continue | 1546 | # Pernyataan Continue |
| 2986 | 1547 | ||
| 2987 | Pernyataan continue dapat digunakan untuk melewati iterasi saat ini di dalam loop. | 1548 | Pernyataan continue dapat digunakan untuk melewati iterasi saat ini di dalam loop. |
| @@ -2994,18 +1555,6 @@ while i < 10 | |||
| 2994 | print i | 1555 | print i |
| 2995 | ``` | 1556 | ``` |
| 2996 | 1557 | ||
| 2997 | <YueDisplay> | ||
| 2998 | |||
| 2999 | ```yue | ||
| 3000 | i = 0 | ||
| 3001 | while i < 10 | ||
| 3002 | i += 1 | ||
| 3003 | continue if i % 2 == 0 | ||
| 3004 | print i | ||
| 3005 | ``` | ||
| 3006 | |||
| 3007 | </YueDisplay> | ||
| 3008 | |||
| 3009 | continue juga bisa digunakan bersama ekspresi loop untuk mencegah iterasi tersebut diakumulasikan ke hasil. Contoh ini memfilter tabel array menjadi hanya angka genap: | 1558 | continue juga bisa digunakan bersama ekspresi loop untuk mencegah iterasi tersebut diakumulasikan ke hasil. Contoh ini memfilter tabel array menjadi hanya angka genap: |
| 3010 | 1559 | ||
| 3011 | ```yuescript | 1560 | ```yuescript |
| @@ -3015,17 +1564,6 @@ odds = for x in *my_numbers | |||
| 3015 | x | 1564 | x |
| 3016 | ``` | 1565 | ``` |
| 3017 | 1566 | ||
| 3018 | <YueDisplay> | ||
| 3019 | |||
| 3020 | ```yue | ||
| 3021 | my_numbers = [1, 2, 3, 4, 5, 6] | ||
| 3022 | odds = for x in *my_numbers | ||
| 3023 | continue if x % 2 == 1 | ||
| 3024 | x | ||
| 3025 | ``` | ||
| 3026 | |||
| 3027 | </YueDisplay> | ||
| 3028 | |||
| 3029 | # Pernyataan Switch | 1567 | # Pernyataan Switch |
| 3030 | 1568 | ||
| 3031 | Pernyataan switch adalah bentuk singkat untuk menulis serangkaian if yang membandingkan nilai yang sama. Perhatikan bahwa nilainya hanya dievaluasi sekali. Seperti if, switch bisa memiliki blok else untuk menangani tidak ada yang cocok. Perbandingan dilakukan dengan operator `==`. Di dalam switch, Anda juga bisa memakai ekspresi assignment untuk menyimpan nilai variabel sementara. | 1569 | Pernyataan switch adalah bentuk singkat untuk menulis serangkaian if yang membandingkan nilai yang sama. Perhatikan bahwa nilainya hanya dievaluasi sekali. Seperti if, switch bisa memiliki blok else untuk menangani tidak ada yang cocok. Perbandingan dilakukan dengan operator `==`. Di dalam switch, Anda juga bisa memakai ekspresi assignment untuk menyimpan nilai variabel sementara. |
| @@ -3040,20 +1578,6 @@ switch name := "Dan" | |||
| 3040 | print "I don't know about you with name #{name}" | 1578 | print "I don't know about you with name #{name}" |
| 3041 | ``` | 1579 | ``` |
| 3042 | 1580 | ||
| 3043 | <YueDisplay> | ||
| 3044 | |||
| 3045 | ```yue | ||
| 3046 | switch name := "Dan" | ||
| 3047 | when "Robert" | ||
| 3048 | print "You are Robert" | ||
| 3049 | when "Dan", "Daniel" | ||
| 3050 | print "Your name, it's Dan" | ||
| 3051 | else | ||
| 3052 | print "I don't know about you with name #{name}" | ||
| 3053 | ``` | ||
| 3054 | |||
| 3055 | </YueDisplay> | ||
| 3056 | |||
| 3057 | Klausa when pada switch bisa mencocokkan beberapa nilai dengan menuliskannya dipisah koma. | 1581 | Klausa when pada switch bisa mencocokkan beberapa nilai dengan menuliskannya dipisah koma. |
| 3058 | 1582 | ||
| 3059 | Switch juga bisa dipakai sebagai ekspresi; di sini kita dapat menetapkan hasil switch ke sebuah variabel: | 1583 | Switch juga bisa dipakai sebagai ekspresi; di sini kita dapat menetapkan hasil switch ke sebuah variabel: |
| @@ -3069,21 +1593,6 @@ next_number = switch b | |||
| 3069 | error "can't count that high!" | 1593 | error "can't count that high!" |
| 3070 | ``` | 1594 | ``` |
| 3071 | 1595 | ||
| 3072 | <YueDisplay> | ||
| 3073 | |||
| 3074 | ```yue | ||
| 3075 | b = 1 | ||
| 3076 | next_number = switch b | ||
| 3077 | when 1 | ||
| 3078 | 2 | ||
| 3079 | when 2 | ||
| 3080 | 3 | ||
| 3081 | else | ||
| 3082 | error "can't count that high!" | ||
| 3083 | ``` | ||
| 3084 | |||
| 3085 | </YueDisplay> | ||
| 3086 | |||
| 3087 | Kita bisa memakai kata kunci `then` untuk menulis blok when switch pada satu baris. Tidak ada kata kunci tambahan yang dibutuhkan untuk menulis blok else pada satu baris. | 1596 | Kita bisa memakai kata kunci `then` untuk menulis blok when switch pada satu baris. Tidak ada kata kunci tambahan yang dibutuhkan untuk menulis blok else pada satu baris. |
| 3088 | 1597 | ||
| 3089 | ```yuescript | 1598 | ```yuescript |
| @@ -3093,17 +1602,6 @@ msg = switch math.random(1, 5) | |||
| 3093 | else "not so lucky" | 1602 | else "not so lucky" |
| 3094 | ``` | 1603 | ``` |
| 3095 | 1604 | ||
| 3096 | <YueDisplay> | ||
| 3097 | |||
| 3098 | ```yue | ||
| 3099 | msg = switch math.random(1, 5) | ||
| 3100 | when 1 then "you are lucky" | ||
| 3101 | when 2 then "you are almost lucky" | ||
| 3102 | else "not so lucky" | ||
| 3103 | ``` | ||
| 3104 | |||
| 3105 | </YueDisplay> | ||
| 3106 | |||
| 3107 | Jika Anda ingin menulis kode dengan satu indentasi lebih sedikit saat menulis switch, Anda bisa menaruh klausa when pertama pada baris awal pernyataan, lalu semua klausa lain dapat ditulis dengan satu indentasi lebih sedikit. | 1605 | Jika Anda ingin menulis kode dengan satu indentasi lebih sedikit saat menulis switch, Anda bisa menaruh klausa when pertama pada baris awal pernyataan, lalu semua klausa lain dapat ditulis dengan satu indentasi lebih sedikit. |
| 3108 | 1606 | ||
| 3109 | ```yuescript | 1607 | ```yuescript |
| @@ -3119,23 +1617,6 @@ else | |||
| 3119 | print "not so lucky" | 1617 | print "not so lucky" |
| 3120 | ``` | 1618 | ``` |
| 3121 | 1619 | ||
| 3122 | <YueDisplay> | ||
| 3123 | |||
| 3124 | ```yue | ||
| 3125 | switch math.random(1, 5) | ||
| 3126 | when 1 | ||
| 3127 | print "you are lucky" -- two indents | ||
| 3128 | else | ||
| 3129 | print "not so lucky" | ||
| 3130 | |||
| 3131 | switch math.random(1, 5) when 1 | ||
| 3132 | print "you are lucky" -- one indent | ||
| 3133 | else | ||
| 3134 | print "not so lucky" | ||
| 3135 | ``` | ||
| 3136 | |||
| 3137 | </YueDisplay> | ||
| 3138 | |||
| 3139 | Perlu dicatat urutan ekspresi perbandingan kasus. Ekspresi kasus berada di sisi kiri. Ini bisa berguna jika ekspresi kasus ingin mengganti cara perbandingan dengan mendefinisikan metamethod `eq`. | 1620 | Perlu dicatat urutan ekspresi perbandingan kasus. Ekspresi kasus berada di sisi kiri. Ini bisa berguna jika ekspresi kasus ingin mengganti cara perbandingan dengan mendefinisikan metamethod `eq`. |
| 3140 | 1621 | ||
| 3141 | ## Pencocokan Tabel | 1622 | ## Pencocokan Tabel |
| @@ -3157,25 +1638,6 @@ for item in *items | |||
| 3157 | print "size #{width}, #{height}" | 1638 | print "size #{width}, #{height}" |
| 3158 | ``` | 1639 | ``` |
| 3159 | 1640 | ||
| 3160 | <YueDisplay> | ||
| 3161 | |||
| 3162 | ```yue | ||
| 3163 | items = | ||
| 3164 | * x: 100 | ||
| 3165 | y: 200 | ||
| 3166 | * width: 300 | ||
| 3167 | height: 400 | ||
| 3168 | |||
| 3169 | for item in *items | ||
| 3170 | switch item | ||
| 3171 | when :x, :y | ||
| 3172 | print "Vec2 #{x}, #{y}" | ||
| 3173 | when :width, :height | ||
| 3174 | print "size #{width}, #{height}" | ||
| 3175 | ``` | ||
| 3176 | |||
| 3177 | </YueDisplay> | ||
| 3178 | |||
| 3179 | Anda dapat menggunakan nilai default untuk mendestrukturisasi tabel secara opsional pada beberapa field. | 1641 | Anda dapat menggunakan nilai default untuk mendestrukturisasi tabel secara opsional pada beberapa field. |
| 3180 | 1642 | ||
| 3181 | ```yuescript | 1643 | ```yuescript |
| @@ -3188,20 +1650,6 @@ switch item | |||
| 3188 | print "Vec2 #{x}, #{y}" -- table destructuring will still pass | 1650 | print "Vec2 #{x}, #{y}" -- table destructuring will still pass |
| 3189 | ``` | 1651 | ``` |
| 3190 | 1652 | ||
| 3191 | <YueDisplay> | ||
| 3192 | |||
| 3193 | ```yue | ||
| 3194 | item = {} | ||
| 3195 | |||
| 3196 | {pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') | ||
| 3197 | |||
| 3198 | switch item | ||
| 3199 | when {pos: {:x = 50, :y = 200}} | ||
| 3200 | print "Vec2 #{x}, #{y}" -- table destructuring will still pass | ||
| 3201 | ``` | ||
| 3202 | |||
| 3203 | </YueDisplay> | ||
| 3204 | |||
| 3205 | Anda juga bisa mencocokkan elemen array, field tabel, dan bahkan struktur bertingkat dengan literal array atau tabel. | 1653 | Anda juga bisa mencocokkan elemen array, field tabel, dan bahkan struktur bertingkat dengan literal array atau tabel. |
| 3206 | 1654 | ||
| 3207 | Cocokkan terhadap elemen array. | 1655 | Cocokkan terhadap elemen array. |
| @@ -3216,20 +1664,6 @@ switch tb | |||
| 3216 | print "1, 2, #{b}" | 1664 | print "1, 2, #{b}" |
| 3217 | ``` | 1665 | ``` |
| 3218 | 1666 | ||
| 3219 | <YueDisplay> | ||
| 3220 | |||
| 3221 | ```yue | ||
| 3222 | switch tb | ||
| 3223 | when [1, 2, 3] | ||
| 3224 | print "1, 2, 3" | ||
| 3225 | when [1, b, 3] | ||
| 3226 | print "1, #{b}, 3" | ||
| 3227 | when [1, 2, b = 3] -- b has a default value | ||
| 3228 | print "1, 2, #{b}" | ||
| 3229 | ``` | ||
| 3230 | |||
| 3231 | </YueDisplay> | ||
| 3232 | |||
| 3233 | Cocokkan terhadap field tabel dengan destrukturisasi. | 1667 | Cocokkan terhadap field tabel dengan destrukturisasi. |
| 3234 | 1668 | ||
| 3235 | ```yuescript | 1669 | ```yuescript |
| @@ -3242,20 +1676,6 @@ switch tb | |||
| 3242 | print "invalid" | 1676 | print "invalid" |
| 3243 | ``` | 1677 | ``` |
| 3244 | 1678 | ||
| 3245 | <YueDisplay> | ||
| 3246 | |||
| 3247 | ```yue | ||
| 3248 | switch tb | ||
| 3249 | when success: true, :result | ||
| 3250 | print "success", result | ||
| 3251 | when success: false | ||
| 3252 | print "failed", result | ||
| 3253 | else | ||
| 3254 | print "invalid" | ||
| 3255 | ``` | ||
| 3256 | |||
| 3257 | </YueDisplay> | ||
| 3258 | |||
| 3259 | Cocokkan terhadap struktur tabel bertingkat. | 1679 | Cocokkan terhadap struktur tabel bertingkat. |
| 3260 | 1680 | ||
| 3261 | ```yuescript | 1681 | ```yuescript |
| @@ -3268,20 +1688,6 @@ switch tb | |||
| 3268 | print "invalid" | 1688 | print "invalid" |
| 3269 | ``` | 1689 | ``` |
| 3270 | 1690 | ||
| 3271 | <YueDisplay> | ||
| 3272 | |||
| 3273 | ```yue | ||
| 3274 | switch tb | ||
| 3275 | when data: {type: "success", :content} | ||
| 3276 | print "success", content | ||
| 3277 | when data: {type: "error", :content} | ||
| 3278 | print "failed", content | ||
| 3279 | else | ||
| 3280 | print "invalid" | ||
| 3281 | ``` | ||
| 3282 | |||
| 3283 | </YueDisplay> | ||
| 3284 | |||
| 3285 | Cocokkan terhadap array dari tabel. | 1691 | Cocokkan terhadap array dari tabel. |
| 3286 | 1692 | ||
| 3287 | ```yuescript | 1693 | ```yuescript |
| @@ -3295,21 +1701,6 @@ switch tb | |||
| 3295 | print "matched", fourth | 1701 | print "matched", fourth |
| 3296 | ``` | 1702 | ``` |
| 3297 | 1703 | ||
| 3298 | <YueDisplay> | ||
| 3299 | |||
| 3300 | ```yue | ||
| 3301 | switch tb | ||
| 3302 | when [ | ||
| 3303 | {a: 1, b: 2} | ||
| 3304 | {a: 3, b: 4} | ||
| 3305 | {a: 5, b: 6} | ||
| 3306 | fourth | ||
| 3307 | ] | ||
| 3308 | print "matched", fourth | ||
| 3309 | ``` | ||
| 3310 | |||
| 3311 | </YueDisplay> | ||
| 3312 | |||
| 3313 | Cocokkan terhadap daftar dan tangkap rentang elemen. | 1704 | Cocokkan terhadap daftar dan tangkap rentang elemen. |
| 3314 | 1705 | ||
| 3315 | ```yuescript | 1706 | ```yuescript |
| @@ -3321,19 +1712,6 @@ switch segments | |||
| 3321 | print "Action:", action -- prints: "view" | 1712 | print "Action:", action -- prints: "view" |
| 3322 | ``` | 1713 | ``` |
| 3323 | 1714 | ||
| 3324 | <YueDisplay> | ||
| 3325 | |||
| 3326 | ```yue | ||
| 3327 | segments = ["admin", "users", "logs", "view"] | ||
| 3328 | switch segments | ||
| 3329 | when [...groups, resource, action] | ||
| 3330 | print "Group:", groups -- prints: {"admin", "users"} | ||
| 3331 | print "Resource:", resource -- prints: "logs" | ||
| 3332 | print "Action:", action -- prints: "view" | ||
| 3333 | ``` | ||
| 3334 | |||
| 3335 | </YueDisplay> | ||
| 3336 | |||
| 3337 | # Perulangan While | 1715 | # Perulangan While |
| 3338 | 1716 | ||
| 3339 | Perulangan while juga memiliki empat variasi: | 1717 | Perulangan while juga memiliki empat variasi: |
| @@ -3347,19 +1725,6 @@ while i > 0 | |||
| 3347 | while running == true do my_function! | 1725 | while running == true do my_function! |
| 3348 | ``` | 1726 | ``` |
| 3349 | 1727 | ||
| 3350 | <YueDisplay> | ||
| 3351 | |||
| 3352 | ```yue | ||
| 3353 | i = 10 | ||
| 3354 | while i > 0 | ||
| 3355 | print i | ||
| 3356 | i -= 1 | ||
| 3357 | |||
| 3358 | while running == true do my_function! | ||
| 3359 | ``` | ||
| 3360 | |||
| 3361 | </YueDisplay> | ||
| 3362 | |||
| 3363 | ```yuescript | 1728 | ```yuescript |
| 3364 | i = 10 | 1729 | i = 10 |
| 3365 | until i == 0 | 1730 | until i == 0 |
| @@ -3369,18 +1734,6 @@ until i == 0 | |||
| 3369 | until running == false do my_function! | 1734 | until running == false do my_function! |
| 3370 | ``` | 1735 | ``` |
| 3371 | 1736 | ||
| 3372 | <YueDisplay> | ||
| 3373 | |||
| 3374 | ```yue | ||
| 3375 | i = 10 | ||
| 3376 | until i == 0 | ||
| 3377 | print i | ||
| 3378 | i -= 1 | ||
| 3379 | until running == false do my_function! | ||
| 3380 | ``` | ||
| 3381 | |||
| 3382 | </YueDisplay> | ||
| 3383 | |||
| 3384 | Seperti loop for, loop while juga bisa digunakan sebagai ekspresi. Ekspresi `while` dan `until` mendukung `break` dengan banyak nilai. | 1737 | Seperti loop for, loop while juga bisa digunakan sebagai ekspresi. Ekspresi `while` dan `until` mendukung `break` dengan banyak nilai. |
| 3385 | 1738 | ||
| 3386 | ```yuescript | 1739 | ```yuescript |
| @@ -3389,16 +1742,6 @@ value, doubled = while true | |||
| 3389 | break n, n * 2 if n > 10 | 1742 | break n, n * 2 if n > 10 |
| 3390 | ``` | 1743 | ``` |
| 3391 | 1744 | ||
| 3392 | <YueDisplay> | ||
| 3393 | |||
| 3394 | ```yue | ||
| 3395 | value, doubled = while true | ||
| 3396 | n = get_next! | ||
| 3397 | break n, n * 2 if n > 10 | ||
| 3398 | ``` | ||
| 3399 | |||
| 3400 | </YueDisplay> | ||
| 3401 | |||
| 3402 | Selain itu, agar sebuah fungsi mengembalikan nilai akumulasi dari loop while, pernyataannya harus di-return secara eksplisit. | 1745 | Selain itu, agar sebuah fungsi mengembalikan nilai akumulasi dari loop while, pernyataannya harus di-return secara eksplisit. |
| 3403 | 1746 | ||
| 3404 | ## Repeat Loop | 1747 | ## Repeat Loop |
| @@ -3413,18 +1756,6 @@ repeat | |||
| 3413 | until i == 0 | 1756 | until i == 0 |
| 3414 | ``` | 1757 | ``` |
| 3415 | 1758 | ||
| 3416 | <YueDisplay> | ||
| 3417 | |||
| 3418 | ```yue | ||
| 3419 | i = 10 | ||
| 3420 | repeat | ||
| 3421 | print i | ||
| 3422 | i -= 1 | ||
| 3423 | until i == 0 | ||
| 3424 | ``` | ||
| 3425 | |||
| 3426 | </YueDisplay> | ||
| 3427 | |||
| 3428 | Ekspresi `repeat` juga mendukung `break` dengan banyak nilai: | 1759 | Ekspresi `repeat` juga mendukung `break` dengan banyak nilai: |
| 3429 | 1760 | ||
| 3430 | ```yuescript | 1761 | ```yuescript |
| @@ -3435,18 +1766,6 @@ value, scaled = repeat | |||
| 3435 | until false | 1766 | until false |
| 3436 | ``` | 1767 | ``` |
| 3437 | 1768 | ||
| 3438 | <YueDisplay> | ||
| 3439 | |||
| 3440 | ```yue | ||
| 3441 | i = 1 | ||
| 3442 | value, scaled = repeat | ||
| 3443 | break i, i * 100 if i > 3 | ||
| 3444 | i += 1 | ||
| 3445 | until false | ||
| 3446 | ``` | ||
| 3447 | |||
| 3448 | </YueDisplay> | ||
| 3449 | |||
| 3450 | # Stub Fungsi | 1769 | # Stub Fungsi |
| 3451 | 1770 | ||
| 3452 | Sering kali fungsi dari sebuah objek diteruskan sebagai nilai, misalnya meneruskan method instance ke fungsi lain sebagai callback. Jika fungsi mengharapkan objek yang dioperasikan sebagai argumen pertama, maka Anda harus menggabungkan objek tersebut dengan fungsi agar dapat dipanggil dengan benar. | 1771 | Sering kali fungsi dari sebuah objek diteruskan sebagai nilai, misalnya meneruskan method instance ke fungsi lain sebagai callback. Jika fungsi mengharapkan objek yang dioperasikan sebagai argumen pertama, maka Anda harus menggabungkan objek tersebut dengan fungsi agar dapat dipanggil dengan benar. |
| @@ -3474,29 +1793,6 @@ run_callback my_object.write | |||
| 3474 | run_callback my_object\write | 1793 | run_callback my_object\write |
| 3475 | ``` | 1794 | ``` |
| 3476 | 1795 | ||
| 3477 | <YueDisplay> | ||
| 3478 | |||
| 3479 | ```yue | ||
| 3480 | my_object = { | ||
| 3481 | value: 1000 | ||
| 3482 | write: => print "the value:", @value | ||
| 3483 | } | ||
| 3484 | |||
| 3485 | run_callback = (func) -> | ||
| 3486 | print "running callback..." | ||
| 3487 | func! | ||
| 3488 | |||
| 3489 | -- ini tidak akan berfungsi: | ||
| 3490 | -- fungsi tidak memiliki referensi ke my_object | ||
| 3491 | run_callback my_object.write | ||
| 3492 | |||
| 3493 | -- sintaks stub fungsi | ||
| 3494 | -- memungkinkan kita membundel objek ke fungsi baru | ||
| 3495 | run_callback my_object\write | ||
| 3496 | ``` | ||
| 3497 | |||
| 3498 | </YueDisplay> | ||
| 3499 | |||
| 3500 | # Backcall | 1796 | # Backcall |
| 3501 | 1797 | ||
| 3502 | Backcall digunakan untuk meratakan callback yang bersarang. Backcall didefinisikan menggunakan panah yang mengarah ke kiri sebagai parameter terakhir secara default yang akan mengisi pemanggilan fungsi. Semua sintaks pada dasarnya sama seperti fungsi panah biasa, kecuali arahnya berlawanan dan badan fungsi tidak memerlukan indentasi. | 1798 | Backcall digunakan untuk meratakan callback yang bersarang. Backcall didefinisikan menggunakan panah yang mengarah ke kiri sebagai parameter terakhir secara default yang akan mengisi pemanggilan fungsi. Semua sintaks pada dasarnya sama seperti fungsi panah biasa, kecuali arahnya berlawanan dan badan fungsi tidak memerlukan indentasi. |
| @@ -3506,15 +1802,6 @@ x <- f | |||
| 3506 | print "hello" .. x | 1802 | print "hello" .. x |
| 3507 | ``` | 1803 | ``` |
| 3508 | 1804 | ||
| 3509 | <YueDisplay> | ||
| 3510 | |||
| 3511 | ```yue | ||
| 3512 | x <- f | ||
| 3513 | print "hello" .. x | ||
| 3514 | ``` | ||
| 3515 | |||
| 3516 | </YueDisplay> | ||
| 3517 | |||
| 3518 | Fungsi panah tebal juga tersedia. | 1805 | Fungsi panah tebal juga tersedia. |
| 3519 | 1806 | ||
| 3520 | ```yuescript | 1807 | ```yuescript |
| @@ -3522,15 +1809,6 @@ Fungsi panah tebal juga tersedia. | |||
| 3522 | print @value | 1809 | print @value |
| 3523 | ``` | 1810 | ``` |
| 3524 | 1811 | ||
| 3525 | <YueDisplay> | ||
| 3526 | |||
| 3527 | ```yue | ||
| 3528 | <= f | ||
| 3529 | print @value | ||
| 3530 | ``` | ||
| 3531 | |||
| 3532 | </YueDisplay> | ||
| 3533 | |||
| 3534 | Anda dapat menentukan placeholder untuk posisi fungsi backcall sebagai parameter. | 1812 | Anda dapat menentukan placeholder untuk posisi fungsi backcall sebagai parameter. |
| 3535 | 1813 | ||
| 3536 | ```yuescript | 1814 | ```yuescript |
| @@ -3538,15 +1816,6 @@ Anda dapat menentukan placeholder untuk posisi fungsi backcall sebagai parameter | |||
| 3538 | x * 2 | 1816 | x * 2 |
| 3539 | ``` | 1817 | ``` |
| 3540 | 1818 | ||
| 3541 | <YueDisplay> | ||
| 3542 | |||
| 3543 | ```yue | ||
| 3544 | (x) <- map _, [1, 2, 3] | ||
| 3545 | x * 2 | ||
| 3546 | ``` | ||
| 3547 | |||
| 3548 | </YueDisplay> | ||
| 3549 | |||
| 3550 | Jika Anda ingin menulis kode lanjutan setelah backcall, Anda dapat memisahkannya dengan pernyataan `do`. Tanda kurung dapat dihilangkan untuk fungsi panah non-tebal. | 1819 | Jika Anda ingin menulis kode lanjutan setelah backcall, Anda dapat memisahkannya dengan pernyataan `do`. Tanda kurung dapat dihilangkan untuk fungsi panah non-tebal. |
| 3551 | 1820 | ||
| 3552 | ```yuescript | 1821 | ```yuescript |
| @@ -3558,19 +1827,6 @@ result, msg = do | |||
| 3558 | print result, msg | 1827 | print result, msg |
| 3559 | ``` | 1828 | ``` |
| 3560 | 1829 | ||
| 3561 | <YueDisplay> | ||
| 3562 | |||
| 3563 | ```yue | ||
| 3564 | result, msg = do | ||
| 3565 | data <- readAsync "filename.txt" | ||
| 3566 | print data | ||
| 3567 | info <- processAsync data | ||
| 3568 | check info | ||
| 3569 | print result, msg | ||
| 3570 | ``` | ||
| 3571 | |||
| 3572 | </YueDisplay> | ||
| 3573 | |||
| 3574 | # Literal Fungsi | 1830 | # Literal Fungsi |
| 3575 | 1831 | ||
| 3576 | Semua fungsi dibuat menggunakan ekspresi fungsi. Fungsi sederhana ditandai dengan panah: **->**. | 1832 | Semua fungsi dibuat menggunakan ekspresi fungsi. Fungsi sederhana ditandai dengan panah: **->**. |
| @@ -3580,15 +1836,6 @@ my_function = -> | |||
| 3580 | my_function() -- memanggil fungsi kosong | 1836 | my_function() -- memanggil fungsi kosong |
| 3581 | ``` | 1837 | ``` |
| 3582 | 1838 | ||
| 3583 | <YueDisplay> | ||
| 3584 | |||
| 3585 | ```yue | ||
| 3586 | my_function = -> | ||
| 3587 | my_function() -- memanggil fungsi kosong | ||
| 3588 | ``` | ||
| 3589 | |||
| 3590 | </YueDisplay> | ||
| 3591 | |||
| 3592 | Badan fungsi bisa berupa satu pernyataan yang ditulis langsung setelah panah, atau berupa serangkaian pernyataan yang diindentasi di baris berikutnya: | 1839 | Badan fungsi bisa berupa satu pernyataan yang ditulis langsung setelah panah, atau berupa serangkaian pernyataan yang diindentasi di baris berikutnya: |
| 3593 | 1840 | ||
| 3594 | ```yuescript | 1841 | ```yuescript |
| @@ -3599,18 +1846,6 @@ func_b = -> | |||
| 3599 | print "The value:", value | 1846 | print "The value:", value |
| 3600 | ``` | 1847 | ``` |
| 3601 | 1848 | ||
| 3602 | <YueDisplay> | ||
| 3603 | |||
| 3604 | ```yue | ||
| 3605 | func_a = -> print "hello world" | ||
| 3606 | |||
| 3607 | func_b = -> | ||
| 3608 | value = 100 | ||
| 3609 | print "The value:", value | ||
| 3610 | ``` | ||
| 3611 | |||
| 3612 | </YueDisplay> | ||
| 3613 | |||
| 3614 | Jika fungsi tidak memiliki argumen, ia dapat dipanggil menggunakan operator `!`, sebagai ganti tanda kurung kosong. Pemanggilan `!` adalah cara yang disarankan untuk memanggil fungsi tanpa argumen. | 1849 | Jika fungsi tidak memiliki argumen, ia dapat dipanggil menggunakan operator `!`, sebagai ganti tanda kurung kosong. Pemanggilan `!` adalah cara yang disarankan untuk memanggil fungsi tanpa argumen. |
| 3615 | 1850 | ||
| 3616 | ```yuescript | 1851 | ```yuescript |
| @@ -3618,29 +1853,12 @@ func_a! | |||
| 3618 | func_b() | 1853 | func_b() |
| 3619 | ``` | 1854 | ``` |
| 3620 | 1855 | ||
| 3621 | <YueDisplay> | ||
| 3622 | |||
| 3623 | ```yue | ||
| 3624 | func_a! | ||
| 3625 | func_b() | ||
| 3626 | ``` | ||
| 3627 | |||
| 3628 | </YueDisplay> | ||
| 3629 | |||
| 3630 | Fungsi dengan argumen dapat dibuat dengan menaruh daftar nama argumen dalam tanda kurung sebelum panah: | 1856 | Fungsi dengan argumen dapat dibuat dengan menaruh daftar nama argumen dalam tanda kurung sebelum panah: |
| 3631 | 1857 | ||
| 3632 | ```yuescript | 1858 | ```yuescript |
| 3633 | sum = (x, y) -> print "sum", x + y | 1859 | sum = (x, y) -> print "sum", x + y |
| 3634 | ``` | 1860 | ``` |
| 3635 | 1861 | ||
| 3636 | <YueDisplay> | ||
| 3637 | |||
| 3638 | ```yue | ||
| 3639 | sum = (x, y) -> print "sum", x + y | ||
| 3640 | ``` | ||
| 3641 | |||
| 3642 | </YueDisplay> | ||
| 3643 | |||
| 3644 | Fungsi dapat dipanggil dengan menuliskan argumen setelah nama ekspresi yang mengevaluasi ke fungsi. Saat merangkai pemanggilan fungsi, argumen diterapkan ke fungsi terdekat di sebelah kiri. | 1862 | Fungsi dapat dipanggil dengan menuliskan argumen setelah nama ekspresi yang mengevaluasi ke fungsi. Saat merangkai pemanggilan fungsi, argumen diterapkan ke fungsi terdekat di sebelah kiri. |
| 3645 | 1863 | ||
| 3646 | ```yuescript | 1864 | ```yuescript |
| @@ -3650,31 +1868,12 @@ print sum 10, 20 | |||
| 3650 | a b c "a", "b", "c" | 1868 | a b c "a", "b", "c" |
| 3651 | ``` | 1869 | ``` |
| 3652 | 1870 | ||
| 3653 | <YueDisplay> | ||
| 3654 | |||
| 3655 | ```yue | ||
| 3656 | sum 10, 20 | ||
| 3657 | print sum 10, 20 | ||
| 3658 | |||
| 3659 | a b c "a", "b", "c" | ||
| 3660 | ``` | ||
| 3661 | |||
| 3662 | </YueDisplay> | ||
| 3663 | |||
| 3664 | Untuk menghindari ambiguitas saat memanggil fungsi, tanda kurung juga bisa digunakan untuk mengelilingi argumen. Ini diperlukan di sini agar argumen yang tepat dikirim ke fungsi yang tepat. | 1871 | Untuk menghindari ambiguitas saat memanggil fungsi, tanda kurung juga bisa digunakan untuk mengelilingi argumen. Ini diperlukan di sini agar argumen yang tepat dikirim ke fungsi yang tepat. |
| 3665 | 1872 | ||
| 3666 | ```yuescript | 1873 | ```yuescript |
| 3667 | print "x:", sum(10, 20), "y:", sum(30, 40) | 1874 | print "x:", sum(10, 20), "y:", sum(30, 40) |
| 3668 | ``` | 1875 | ``` |
| 3669 | 1876 | ||
| 3670 | <YueDisplay> | ||
| 3671 | |||
| 3672 | ```yue | ||
| 3673 | print "x:", sum(10, 20), "y:", sum(30, 40) | ||
| 3674 | ``` | ||
| 3675 | |||
| 3676 | </YueDisplay> | ||
| 3677 | |||
| 3678 | Tidak boleh ada spasi antara tanda kurung buka dan nama fungsi. | 1877 | Tidak boleh ada spasi antara tanda kurung buka dan nama fungsi. |
| 3679 | 1878 | ||
| 3680 | Fungsi akan memaksa pernyataan terakhir di badannya menjadi pernyataan return, ini disebut return implisit: | 1879 | Fungsi akan memaksa pernyataan terakhir di badannya menjadi pernyataan return, ini disebut return implisit: |
| @@ -3684,29 +1883,12 @@ sum = (x, y) -> x + y | |||
| 3684 | print "The sum is ", sum 10, 20 | 1883 | print "The sum is ", sum 10, 20 |
| 3685 | ``` | 1884 | ``` |
| 3686 | 1885 | ||
| 3687 | <YueDisplay> | ||
| 3688 | |||
| 3689 | ```yue | ||
| 3690 | sum = (x, y) -> x + y | ||
| 3691 | print "The sum is ", sum 10, 20 | ||
| 3692 | ``` | ||
| 3693 | |||
| 3694 | </YueDisplay> | ||
| 3695 | |||
| 3696 | Dan jika Anda perlu return secara eksplisit, Anda bisa menggunakan kata kunci `return`: | 1886 | Dan jika Anda perlu return secara eksplisit, Anda bisa menggunakan kata kunci `return`: |
| 3697 | 1887 | ||
| 3698 | ```yuescript | 1888 | ```yuescript |
| 3699 | sum = (x, y) -> return x + y | 1889 | sum = (x, y) -> return x + y |
| 3700 | ``` | 1890 | ``` |
| 3701 | 1891 | ||
| 3702 | <YueDisplay> | ||
| 3703 | |||
| 3704 | ```yue | ||
| 3705 | sum = (x, y) -> return x + y | ||
| 3706 | ``` | ||
| 3707 | |||
| 3708 | </YueDisplay> | ||
| 3709 | |||
| 3710 | Seperti di Lua, fungsi dapat mengembalikan beberapa nilai. Pernyataan terakhir harus berupa daftar nilai yang dipisahkan koma: | 1892 | Seperti di Lua, fungsi dapat mengembalikan beberapa nilai. Pernyataan terakhir harus berupa daftar nilai yang dipisahkan koma: |
| 3711 | 1893 | ||
| 3712 | ```yuescript | 1894 | ```yuescript |
| @@ -3714,15 +1896,6 @@ mystery = (x, y) -> x + y, x - y | |||
| 3714 | a, b = mystery 10, 20 | 1896 | a, b = mystery 10, 20 |
| 3715 | ``` | 1897 | ``` |
| 3716 | 1898 | ||
| 3717 | <YueDisplay> | ||
| 3718 | |||
| 3719 | ```yue | ||
| 3720 | mystery = (x, y) -> x + y, x - y | ||
| 3721 | a, b = mystery 10, 20 | ||
| 3722 | ``` | ||
| 3723 | |||
| 3724 | </YueDisplay> | ||
| 3725 | |||
| 3726 | ## Panah Tebal | 1899 | ## Panah Tebal |
| 3727 | 1900 | ||
| 3728 | Karena sudah menjadi idiom di Lua untuk mengirim objek sebagai argumen pertama saat memanggil method, disediakan sintaks khusus untuk membuat fungsi yang otomatis menyertakan argumen `self`. | 1901 | Karena sudah menjadi idiom di Lua untuk mengirim objek sebagai argumen pertama saat memanggil method, disediakan sintaks khusus untuk membuat fungsi yang otomatis menyertakan argumen `self`. |
| @@ -3731,14 +1904,6 @@ Karena sudah menjadi idiom di Lua untuk mengirim objek sebagai argumen pertama s | |||
| 3731 | func = (num) => @value + num | 1904 | func = (num) => @value + num |
| 3732 | ``` | 1905 | ``` |
| 3733 | 1906 | ||
| 3734 | <YueDisplay> | ||
| 3735 | |||
| 3736 | ```yue | ||
| 3737 | func = (num) => @value + num | ||
| 3738 | ``` | ||
| 3739 | |||
| 3740 | </YueDisplay> | ||
| 3741 | |||
| 3742 | ## Nilai Default Argumen | 1907 | ## Nilai Default Argumen |
| 3743 | 1908 | ||
| 3744 | Dimungkinkan untuk menyediakan nilai default bagi argumen fungsi. Argumen dianggap kosong jika nilainya nil. Argumen nil yang memiliki nilai default akan diganti sebelum badan fungsi dijalankan. | 1909 | Dimungkinkan untuk menyediakan nilai default bagi argumen fungsi. Argumen dianggap kosong jika nilainya nil. Argumen nil yang memiliki nilai default akan diganti sebelum badan fungsi dijalankan. |
| @@ -3749,16 +1914,6 @@ my_function = (name = "something", height = 100) -> | |||
| 3749 | print "My height is", height | 1914 | print "My height is", height |
| 3750 | ``` | 1915 | ``` |
| 3751 | 1916 | ||
| 3752 | <YueDisplay> | ||
| 3753 | |||
| 3754 | ```yue | ||
| 3755 | my_function = (name = "something", height = 100) -> | ||
| 3756 | print "Hello I am", name | ||
| 3757 | print "My height is", height | ||
| 3758 | ``` | ||
| 3759 | |||
| 3760 | </YueDisplay> | ||
| 3761 | |||
| 3762 | Ekspresi nilai default argumen dievaluasi di dalam badan fungsi sesuai urutan deklarasi argumen. Karena itu, nilai default dapat mengakses argumen yang dideklarasikan sebelumnya. | 1917 | Ekspresi nilai default argumen dievaluasi di dalam badan fungsi sesuai urutan deklarasi argumen. Karena itu, nilai default dapat mengakses argumen yang dideklarasikan sebelumnya. |
| 3763 | 1918 | ||
| 3764 | ```yuescript | 1919 | ```yuescript |
| @@ -3766,15 +1921,6 @@ some_args = (x = 100, y = x + 1000) -> | |||
| 3766 | print x + y | 1921 | print x + y |
| 3767 | ``` | 1922 | ``` |
| 3768 | 1923 | ||
| 3769 | <YueDisplay> | ||
| 3770 | |||
| 3771 | ```yue | ||
| 3772 | some_args = (x = 100, y = x + 1000) -> | ||
| 3773 | print x + y | ||
| 3774 | ``` | ||
| 3775 | |||
| 3776 | </YueDisplay> | ||
| 3777 | |||
| 3778 | ## Pertimbangan | 1924 | ## Pertimbangan |
| 3779 | 1925 | ||
| 3780 | Karena cara pemanggilan fungsi tanpa tanda kurung yang ekspresif, beberapa pembatasan harus diterapkan untuk menghindari ambiguitas parsing yang melibatkan spasi. | 1926 | Karena cara pemanggilan fungsi tanpa tanda kurung yang ekspresif, beberapa pembatasan harus diterapkan untuk menghindari ambiguitas parsing yang melibatkan spasi. |
| @@ -3788,17 +1934,6 @@ c = x -y | |||
| 3788 | d = x- z | 1934 | d = x- z |
| 3789 | ``` | 1935 | ``` |
| 3790 | 1936 | ||
| 3791 | <YueDisplay> | ||
| 3792 | |||
| 3793 | ```yue | ||
| 3794 | a = x - 10 | ||
| 3795 | b = x-10 | ||
| 3796 | c = x -y | ||
| 3797 | d = x- z | ||
| 3798 | ``` | ||
| 3799 | |||
| 3800 | </YueDisplay> | ||
| 3801 | |||
| 3802 | Prioritas argumen pertama pada pemanggilan fungsi dapat dikendalikan menggunakan spasi jika argumennya adalah literal string. Di Lua, sudah umum untuk menghilangkan tanda kurung saat memanggil fungsi dengan satu literal string atau tabel. | 1937 | Prioritas argumen pertama pada pemanggilan fungsi dapat dikendalikan menggunakan spasi jika argumennya adalah literal string. Di Lua, sudah umum untuk menghilangkan tanda kurung saat memanggil fungsi dengan satu literal string atau tabel. |
| 3803 | 1938 | ||
| 3804 | Ketika tidak ada spasi antara variabel dan literal string, pemanggilan fungsi akan memiliki prioritas atas ekspresi yang mengikuti. Tidak ada argumen lain yang dapat diberikan pada fungsi ketika dipanggil dengan cara ini. | 1939 | Ketika tidak ada spasi antara variabel dan literal string, pemanggilan fungsi akan memiliki prioritas atas ekspresi yang mengikuti. Tidak ada argumen lain yang dapat diberikan pada fungsi ketika dipanggil dengan cara ini. |
| @@ -3810,15 +1945,6 @@ x = func"hello" + 100 | |||
| 3810 | y = func "hello" + 100 | 1945 | y = func "hello" + 100 |
| 3811 | ``` | 1946 | ``` |
| 3812 | 1947 | ||
| 3813 | <YueDisplay> | ||
| 3814 | |||
| 3815 | ```yue | ||
| 3816 | x = func"hello" + 100 | ||
| 3817 | y = func "hello" + 100 | ||
| 3818 | ``` | ||
| 3819 | |||
| 3820 | </YueDisplay> | ||
| 3821 | |||
| 3822 | ## Argumen Multi-baris | 1948 | ## Argumen Multi-baris |
| 3823 | 1949 | ||
| 3824 | Saat memanggil fungsi yang menerima banyak argumen, akan lebih nyaman untuk memecah daftar argumen menjadi beberapa baris. Karena sifat bahasa yang peka terhadap spasi, perlu hati-hati saat memecah daftar argumen. | 1950 | Saat memanggil fungsi yang menerima banyak argumen, akan lebih nyaman untuk memecah daftar argumen menjadi beberapa baris. Karena sifat bahasa yang peka terhadap spasi, perlu hati-hati saat memecah daftar argumen. |
| @@ -3835,20 +1961,6 @@ cool_func 1, 2, | |||
| 3835 | 7, 8 | 1961 | 7, 8 |
| 3836 | ``` | 1962 | ``` |
| 3837 | 1963 | ||
| 3838 | <YueDisplay> | ||
| 3839 | |||
| 3840 | ```yue | ||
| 3841 | my_func 5, 4, 3, | ||
| 3842 | 8, 9, 10 | ||
| 3843 | |||
| 3844 | cool_func 1, 2, | ||
| 3845 | 3, 4, | ||
| 3846 | 5, 6, | ||
| 3847 | 7, 8 | ||
| 3848 | ``` | ||
| 3849 | |||
| 3850 | </YueDisplay> | ||
| 3851 | |||
| 3852 | Jenis pemanggilan ini dapat dinest. Tingkat indentasi digunakan untuk menentukan argumen milik fungsi yang mana. | 1964 | Jenis pemanggilan ini dapat dinest. Tingkat indentasi digunakan untuk menentukan argumen milik fungsi yang mana. |
| 3853 | 1965 | ||
| 3854 | ```yuescript | 1966 | ```yuescript |
| @@ -3858,17 +1970,6 @@ my_func 5, 6, 7, | |||
| 3858 | 5, 4 | 1970 | 5, 4 |
| 3859 | ``` | 1971 | ``` |
| 3860 | 1972 | ||
| 3861 | <YueDisplay> | ||
| 3862 | |||
| 3863 | ```yue | ||
| 3864 | my_func 5, 6, 7, | ||
| 3865 | 6, another_func 6, 7, 8, | ||
| 3866 | 9, 1, 2, | ||
| 3867 | 5, 4 | ||
| 3868 | ``` | ||
| 3869 | |||
| 3870 | </YueDisplay> | ||
| 3871 | |||
| 3872 | Karena tabel juga menggunakan koma sebagai pemisah, sintaks indentasi ini membantu agar nilai menjadi bagian dari daftar argumen, bukan bagian dari tabel. | 1973 | Karena tabel juga menggunakan koma sebagai pemisah, sintaks indentasi ini membantu agar nilai menjadi bagian dari daftar argumen, bukan bagian dari tabel. |
| 3873 | 1974 | ||
| 3874 | ```yuescript | 1975 | ```yuescript |
| @@ -3879,18 +1980,6 @@ x = [ | |||
| 3879 | ] | 1980 | ] |
| 3880 | ``` | 1981 | ``` |
| 3881 | 1982 | ||
| 3882 | <YueDisplay> | ||
| 3883 | |||
| 3884 | ```yue | ||
| 3885 | x = [ | ||
| 3886 | 1, 2, 3, 4, a_func 4, 5, | ||
| 3887 | 5, 6, | ||
| 3888 | 8, 9, 10 | ||
| 3889 | ] | ||
| 3890 | ``` | ||
| 3891 | |||
| 3892 | </YueDisplay> | ||
| 3893 | |||
| 3894 | Meskipun jarang, perhatikan bahwa kita bisa memberikan indentasi yang lebih dalam untuk argumen fungsi jika kita tahu akan menggunakan indentasi yang lebih dangkal di bagian selanjutnya. | 1983 | Meskipun jarang, perhatikan bahwa kita bisa memberikan indentasi yang lebih dalam untuk argumen fungsi jika kita tahu akan menggunakan indentasi yang lebih dangkal di bagian selanjutnya. |
| 3895 | 1984 | ||
| 3896 | ```yuescript | 1985 | ```yuescript |
| @@ -3900,17 +1989,6 @@ y = [ my_func 1, 2, 3, | |||
| 3900 | ] | 1989 | ] |
| 3901 | ``` | 1990 | ``` |
| 3902 | 1991 | ||
| 3903 | <YueDisplay> | ||
| 3904 | |||
| 3905 | ```yue | ||
| 3906 | y = [ my_func 1, 2, 3, | ||
| 3907 | 4, 5, | ||
| 3908 | 5, 6, 7 | ||
| 3909 | ] | ||
| 3910 | ``` | ||
| 3911 | |||
| 3912 | </YueDisplay> | ||
| 3913 | |||
| 3914 | Hal yang sama juga dapat dilakukan pada pernyataan tingkat blok lainnya seperti kondisional. Kita bisa menggunakan tingkat indentasi untuk menentukan nilai milik pernyataan apa: | 1992 | Hal yang sama juga dapat dilakukan pada pernyataan tingkat blok lainnya seperti kondisional. Kita bisa menggunakan tingkat indentasi untuk menentukan nilai milik pernyataan apa: |
| 3915 | 1993 | ||
| 3916 | ```yuescript | 1994 | ```yuescript |
| @@ -3927,24 +2005,6 @@ if func 1, 2, 3, | |||
| 3927 | print "I am inside if" | 2005 | print "I am inside if" |
| 3928 | ``` | 2006 | ``` |
| 3929 | 2007 | ||
| 3930 | <YueDisplay> | ||
| 3931 | |||
| 3932 | ```yue | ||
| 3933 | if func 1, 2, 3, | ||
| 3934 | "hello", | ||
| 3935 | "world" | ||
| 3936 | print "hello" | ||
| 3937 | print "I am inside if" | ||
| 3938 | |||
| 3939 | if func 1, 2, 3, | ||
| 3940 | "hello", | ||
| 3941 | "world" | ||
| 3942 | print "hello" | ||
| 3943 | print "I am inside if" | ||
| 3944 | ``` | ||
| 3945 | |||
| 3946 | </YueDisplay> | ||
| 3947 | |||
| 3948 | ## Destrukturisasi Parameter | 2008 | ## Destrukturisasi Parameter |
| 3949 | 2009 | ||
| 3950 | YueScript kini mendukung destrukturisasi parameter fungsi ketika argumen berupa objek. Dua bentuk destrukturisasi literal tabel tersedia: | 2010 | YueScript kini mendukung destrukturisasi parameter fungsi ketika argumen berupa objek. Dua bentuk destrukturisasi literal tabel tersedia: |
| @@ -3966,23 +2026,6 @@ arg1 = {a: 0} | |||
| 3966 | f2 arg1, arg2 | 2026 | f2 arg1, arg2 |
| 3967 | ``` | 2027 | ``` |
| 3968 | 2028 | ||
| 3969 | <YueDisplay> | ||
| 3970 | |||
| 3971 | ```yue | ||
| 3972 | f1 = (:a, :b, :c) -> | ||
| 3973 | print a, b, c | ||
| 3974 | |||
| 3975 | f1 a: 1, b: "2", c: {} | ||
| 3976 | |||
| 3977 | f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) -> | ||
| 3978 | print a1, b, c | ||
| 3979 | |||
| 3980 | arg1 = {a: 0} | ||
| 3981 | f2 arg1, arg2 | ||
| 3982 | ``` | ||
| 3983 | |||
| 3984 | </YueDisplay> | ||
| 3985 | |||
| 3986 | ## Ekspresi Return Berawalan | 2029 | ## Ekspresi Return Berawalan |
| 3987 | 2030 | ||
| 3988 | Saat bekerja dengan badan fungsi yang sangat bertingkat, menjaga keterbacaan dan konsistensi nilai return bisa terasa melelahkan. Untuk mengatasinya, YueScript memperkenalkan sintaks **Ekspresi Return Berawalan**. Bentuknya sebagai berikut: | 2031 | Saat bekerja dengan badan fungsi yang sangat bertingkat, menjaga keterbacaan dan konsistensi nilai return bisa terasa melelahkan. Untuk mengatasinya, YueScript memperkenalkan sintaks **Ekspresi Return Berawalan**. Bentuknya sebagai berikut: |
| @@ -3996,19 +2039,6 @@ findFirstEven = (list): nil -> | |||
| 3996 | return sub | 2039 | return sub |
| 3997 | ``` | 2040 | ``` |
| 3998 | 2041 | ||
| 3999 | <YueDisplay> | ||
| 4000 | |||
| 4001 | ```yue | ||
| 4002 | findFirstEven = (list): nil -> | ||
| 4003 | for item in *list | ||
| 4004 | if type(item) == "table" | ||
| 4005 | for sub in *item | ||
| 4006 | if sub % 2 == 0 | ||
| 4007 | return sub | ||
| 4008 | ``` | ||
| 4009 | |||
| 4010 | </YueDisplay> | ||
| 4011 | |||
| 4012 | Ini setara dengan: | 2042 | Ini setara dengan: |
| 4013 | 2043 | ||
| 4014 | ```yuescript | 2044 | ```yuescript |
| @@ -4021,20 +2051,6 @@ findFirstEven = (list) -> | |||
| 4021 | nil | 2051 | nil |
| 4022 | ``` | 2052 | ``` |
| 4023 | 2053 | ||
| 4024 | <YueDisplay> | ||
| 4025 | |||
| 4026 | ```yue | ||
| 4027 | findFirstEven = (list) -> | ||
| 4028 | for item in *list | ||
| 4029 | if type(item) == "table" | ||
| 4030 | for sub in *item | ||
| 4031 | if sub % 2 == 0 | ||
| 4032 | return sub | ||
| 4033 | nil | ||
| 4034 | ``` | ||
| 4035 | |||
| 4036 | </YueDisplay> | ||
| 4037 | |||
| 4038 | Satu-satunya perbedaan adalah Anda dapat memindahkan ekspresi return terakhir sebelum token `->` atau `=>` untuk menunjukkan nilai return implisit fungsi sebagai pernyataan terakhir. Dengan cara ini, bahkan pada fungsi dengan banyak loop bertingkat atau cabang kondisional, Anda tidak lagi perlu menulis ekspresi return di akhir badan fungsi, sehingga struktur logika menjadi lebih lurus dan mudah diikuti. | 2054 | Satu-satunya perbedaan adalah Anda dapat memindahkan ekspresi return terakhir sebelum token `->` atau `=>` untuk menunjukkan nilai return implisit fungsi sebagai pernyataan terakhir. Dengan cara ini, bahkan pada fungsi dengan banyak loop bertingkat atau cabang kondisional, Anda tidak lagi perlu menulis ekspresi return di akhir badan fungsi, sehingga struktur logika menjadi lebih lurus dan mudah diikuti. |
| 4039 | 2055 | ||
| 4040 | ## Varargs Bernama | 2056 | ## Varargs Bernama |
| @@ -4063,32 +2079,6 @@ process = (...args) -> | |||
| 4063 | process 1, nil, 3, nil, 5 | 2079 | process 1, nil, 3, nil, 5 |
| 4064 | ``` | 2080 | ``` |
| 4065 | 2081 | ||
| 4066 | <YueDisplay> | ||
| 4067 | |||
| 4068 | ```yue | ||
| 4069 | f = (...t) -> | ||
| 4070 | print "argument count:", t.n | ||
| 4071 | print "table length:", #t | ||
| 4072 | for i = 1, t.n | ||
| 4073 | print t[i] | ||
| 4074 | |||
| 4075 | f 1, 2, 3 | ||
| 4076 | f "a", "b", "c", "d" | ||
| 4077 | f! | ||
| 4078 | |||
| 4079 | -- Menangani kasus dengan nilai nil | ||
| 4080 | process = (...args) -> | ||
| 4081 | sum = 0 | ||
| 4082 | for i = 1, args.n | ||
| 4083 | if args[i] != nil and type(args[i]) == "number" | ||
| 4084 | sum += args[i] | ||
| 4085 | sum | ||
| 4086 | |||
| 4087 | process 1, nil, 3, nil, 5 | ||
| 4088 | ``` | ||
| 4089 | |||
| 4090 | </YueDisplay> | ||
| 4091 | |||
| 4092 | # Spasi Kosong | 2082 | # Spasi Kosong |
| 4093 | 2083 | ||
| 4094 | YueScript adalah bahasa yang peka terhadap spasi. Anda harus menulis beberapa blok kode dengan indentasi yang sama menggunakan spasi **' '** atau tab **'\t'** seperti badan fungsi, daftar nilai, dan beberapa blok kontrol. Ekspresi yang mengandung spasi berbeda dapat bermakna berbeda. Tab diperlakukan seperti 4 spasi, tetapi sebaiknya jangan mencampur penggunaan spasi dan tab. | 2084 | YueScript adalah bahasa yang peka terhadap spasi. Anda harus menulis beberapa blok kode dengan indentasi yang sama menggunakan spasi **' '** atau tab **'\t'** seperti badan fungsi, daftar nilai, dan beberapa blok kontrol. Ekspresi yang mengandung spasi berbeda dapat bermakna berbeda. Tab diperlakukan seperti 4 spasi, tetapi sebaiknya jangan mencampur penggunaan spasi dan tab. |
| @@ -4101,14 +2091,6 @@ Sebuah pernyataan biasanya berakhir pada pergantian baris. Anda juga bisa memaka | |||
| 4101 | a = 1; b = 2; print a + b | 2091 | a = 1; b = 2; print a + b |
| 4102 | ``` | 2092 | ``` |
| 4103 | 2093 | ||
| 4104 | <YueDisplay> | ||
| 4105 | |||
| 4106 | ```yue | ||
| 4107 | a = 1; b = 2; print a + b | ||
| 4108 | ``` | ||
| 4109 | |||
| 4110 | </YueDisplay> | ||
| 4111 | |||
| 4112 | ## Rantai Multibaris | 2094 | ## Rantai Multibaris |
| 4113 | 2095 | ||
| 4114 | Anda bisa menulis pemanggilan fungsi berantai multi-baris dengan indentasi yang sama. | 2096 | Anda bisa menulis pemanggilan fungsi berantai multi-baris dengan indentasi yang sama. |
| @@ -4122,19 +2104,6 @@ Rx.Observable | |||
| 4122 | \subscribe print | 2104 | \subscribe print |
| 4123 | ``` | 2105 | ``` |
| 4124 | 2106 | ||
| 4125 | <YueDisplay> | ||
| 4126 | |||
| 4127 | ```yue | ||
| 4128 | Rx.Observable | ||
| 4129 | .fromRange 1, 8 | ||
| 4130 | \filter (x) -> x % 2 == 0 | ||
| 4131 | \concat Rx.Observable.of 'who do we appreciate' | ||
| 4132 | \map (value) -> value .. '!' | ||
| 4133 | \subscribe print | ||
| 4134 | ``` | ||
| 4135 | |||
| 4136 | </YueDisplay> | ||
| 4137 | |||
| 4138 | # Komentar | 2107 | # Komentar |
| 4139 | 2108 | ||
| 4140 | ```yuescript | 2109 | ```yuescript |
| @@ -4150,23 +2119,6 @@ Tidak masalah. | |||
| 4150 | func --[[port]] 3000, --[[ip]] "192.168.1.1" | 2119 | func --[[port]] 3000, --[[ip]] "192.168.1.1" |
| 4151 | ``` | 2120 | ``` |
| 4152 | 2121 | ||
| 4153 | <YueDisplay> | ||
| 4154 | |||
| 4155 | ```yue | ||
| 4156 | -- Saya adalah komentar | ||
| 4157 | |||
| 4158 | str = --[[ | ||
| 4159 | Ini komentar multi-baris. | ||
| 4160 | Tidak masalah. | ||
| 4161 | ]] strA \ -- komentar 1 | ||
| 4162 | .. strB \ -- komentar 2 | ||
| 4163 | .. strC | ||
| 4164 | |||
| 4165 | func --[[port]] 3000, --[[ip]] "192.168.1.1" | ||
| 4166 | ``` | ||
| 4167 | |||
| 4168 | </YueDisplay> | ||
| 4169 | |||
| 4170 | # Atribut | 2122 | # Atribut |
| 4171 | 2123 | ||
| 4172 | Dukungan sintaks untuk atribut Lua 5.4. Anda juga masih bisa menggunakan deklarasi `const` dan `close` dan mendapatkan pemeriksaan konstanta serta callback berbatas-scope ketika menargetkan versi Lua di bawah 5.4. | 2124 | Dukungan sintaks untuk atribut Lua 5.4. Anda juga masih bisa menggunakan deklarasi `const` dan `close` dan mendapatkan pemeriksaan konstanta serta callback berbatas-scope ketika menargetkan versi Lua di bawah 5.4. |
| @@ -4176,15 +2128,6 @@ const a = 123 | |||
| 4176 | close _ = <close>: -> print "Out of scope." | 2128 | close _ = <close>: -> print "Out of scope." |
| 4177 | ``` | 2129 | ``` |
| 4178 | 2130 | ||
| 4179 | <YueDisplay> | ||
| 4180 | |||
| 4181 | ```yue | ||
| 4182 | const a = 123 | ||
| 4183 | close _ = <close>: -> print "Out of scope." | ||
| 4184 | ``` | ||
| 4185 | |||
| 4186 | </YueDisplay> | ||
| 4187 | |||
| 4188 | Anda dapat melakukan destrukturisasi dengan variabel yang diberi atribut sebagai konstanta. | 2131 | Anda dapat melakukan destrukturisasi dengan variabel yang diberi atribut sebagai konstanta. |
| 4189 | 2132 | ||
| 4190 | ```yuescript | 2133 | ```yuescript |
| @@ -4192,15 +2135,6 @@ const {:a, :b, c, d} = tb | |||
| 4192 | -- a = 1 | 2135 | -- a = 1 |
| 4193 | ``` | 2136 | ``` |
| 4194 | 2137 | ||
| 4195 | <YueDisplay> | ||
| 4196 | |||
| 4197 | ```yue | ||
| 4198 | const {:a, :b, c, d} = tb | ||
| 4199 | -- a = 1 | ||
| 4200 | ``` | ||
| 4201 | |||
| 4202 | </YueDisplay> | ||
| 4203 | |||
| 4204 | Anda juga bisa mendeklarasikan variabel global sebagai `const`. | 2138 | Anda juga bisa mendeklarasikan variabel global sebagai `const`. |
| 4205 | 2139 | ||
| 4206 | ```yuescript | 2140 | ```yuescript |
| @@ -4208,15 +2142,6 @@ global const Constant = 123 | |||
| 4208 | -- Constant = 1 | 2142 | -- Constant = 1 |
| 4209 | ``` | 2143 | ``` |
| 4210 | 2144 | ||
| 4211 | <YueDisplay> | ||
| 4212 | |||
| 4213 | ```yue | ||
| 4214 | global const Constant = 123 | ||
| 4215 | -- Constant = 1 | ||
| 4216 | ``` | ||
| 4217 | |||
| 4218 | </YueDisplay> | ||
| 4219 | |||
| 4220 | # Operator | 2145 | # Operator |
| 4221 | 2146 | ||
| 4222 | Semua operator biner dan unari Lua tersedia. Selain itu **!=** adalah alias untuk **~=**, dan **\\** atau **::** bisa digunakan untuk menulis pemanggilan fungsi berantai seperti `tb\func!` atau `tb::func!`. YueScript juga menawarkan beberapa operator khusus lain untuk menulis kode yang lebih ekspresif. | 2147 | Semua operator biner dan unari Lua tersedia. Selain itu **!=** adalah alias untuk **~=**, dan **\\** atau **::** bisa digunakan untuk menulis pemanggilan fungsi berantai seperti `tb\func!` atau `tb::func!`. YueScript juga menawarkan beberapa operator khusus lain untuk menulis kode yang lebih ekspresif. |
| @@ -4226,15 +2151,6 @@ tb\func! if tb ~= nil | |||
| 4226 | tb::func! if tb != nil | 2151 | tb::func! if tb != nil |
| 4227 | ``` | 2152 | ``` |
| 4228 | 2153 | ||
| 4229 | <YueDisplay> | ||
| 4230 | |||
| 4231 | ```yue | ||
| 4232 | tb\func! if tb ~= nil | ||
| 4233 | tb::func! if tb != nil | ||
| 4234 | ``` | ||
| 4235 | |||
| 4236 | </YueDisplay> | ||
| 4237 | |||
| 4238 | ## Perbandingan Berantai | 2154 | ## Perbandingan Berantai |
| 4239 | 2155 | ||
| 4240 | Perbandingan bisa dirantai secara bebas: | 2156 | Perbandingan bisa dirantai secara bebas: |
| @@ -4248,19 +2164,6 @@ print 1 <= a <= 10 | |||
| 4248 | -- output: true | 2164 | -- output: true |
| 4249 | ``` | 2165 | ``` |
| 4250 | 2166 | ||
| 4251 | <YueDisplay> | ||
| 4252 | |||
| 4253 | ```yue | ||
| 4254 | print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 | ||
| 4255 | -- output: true | ||
| 4256 | |||
| 4257 | a = 5 | ||
| 4258 | print 1 <= a <= 10 | ||
| 4259 | -- output: true | ||
| 4260 | ``` | ||
| 4261 | |||
| 4262 | </YueDisplay> | ||
| 4263 | |||
| 4264 | Perhatikan perilaku evaluasi perbandingan berantai: | 2167 | Perhatikan perilaku evaluasi perbandingan berantai: |
| 4265 | 2168 | ||
| 4266 | ```yuescript | 2169 | ```yuescript |
| @@ -4286,33 +2189,6 @@ print v(1) > v(2) <= v(3) | |||
| 4286 | ]] | 2189 | ]] |
| 4287 | ``` | 2190 | ``` |
| 4288 | 2191 | ||
| 4289 | <YueDisplay> | ||
| 4290 | |||
| 4291 | ```yue | ||
| 4292 | v = (x) -> | ||
| 4293 | print x | ||
| 4294 | x | ||
| 4295 | |||
| 4296 | print v(1) < v(2) <= v(3) | ||
| 4297 | --[[ | ||
| 4298 | output: | ||
| 4299 | 2 | ||
| 4300 | 1 | ||
| 4301 | 3 | ||
| 4302 | true | ||
| 4303 | ]] | ||
| 4304 | |||
| 4305 | print v(1) > v(2) <= v(3) | ||
| 4306 | --[[ | ||
| 4307 | output: | ||
| 4308 | 2 | ||
| 4309 | 1 | ||
| 4310 | false | ||
| 4311 | ]] | ||
| 4312 | ``` | ||
| 4313 | |||
| 4314 | </YueDisplay> | ||
| 4315 | |||
| 4316 | Ekspresi tengah hanya dievaluasi sekali, bukan dua kali seperti jika ekspresi ditulis sebagai `v(1) < v(2) and v(2) <= v(3)`. Namun, urutan evaluasi pada perbandingan berantai tidak didefinisikan. Sangat disarankan untuk tidak menggunakan ekspresi dengan efek samping (seperti `print`) di perbandingan berantai. Jika efek samping diperlukan, operator short-circuit `and` sebaiknya digunakan secara eksplisit. | 2192 | Ekspresi tengah hanya dievaluasi sekali, bukan dua kali seperti jika ekspresi ditulis sebagai `v(1) < v(2) and v(2) <= v(3)`. Namun, urutan evaluasi pada perbandingan berantai tidak didefinisikan. Sangat disarankan untuk tidak menggunakan ekspresi dengan efek samping (seperti `print`) di perbandingan berantai. Jika efek samping diperlukan, operator short-circuit `and` sebaiknya digunakan secara eksplisit. |
| 4317 | 2193 | ||
| 4318 | ## Menambahkan ke Tabel | 2194 | ## Menambahkan ke Tabel |
| @@ -4324,15 +2200,6 @@ tab = [] | |||
| 4324 | tab[] = "Value" | 2200 | tab[] = "Value" |
| 4325 | ``` | 2201 | ``` |
| 4326 | 2202 | ||
| 4327 | <YueDisplay> | ||
| 4328 | |||
| 4329 | ```yue | ||
| 4330 | tab = [] | ||
| 4331 | tab[] = "Value" | ||
| 4332 | ``` | ||
| 4333 | |||
| 4334 | </YueDisplay> | ||
| 4335 | |||
| 4336 | Anda juga bisa memakai operator spread `...` untuk menambahkan semua elemen dari satu list ke list lain: | 2203 | Anda juga bisa memakai operator spread `...` untuk menambahkan semua elemen dari satu list ke list lain: |
| 4337 | 2204 | ||
| 4338 | ```yuescript | 2205 | ```yuescript |
| @@ -4342,17 +2209,6 @@ tbA[] = ...tbB | |||
| 4342 | -- tbA sekarang [1, 2, 3, 4, 5, 6] | 2209 | -- tbA sekarang [1, 2, 3, 4, 5, 6] |
| 4343 | ``` | 2210 | ``` |
| 4344 | 2211 | ||
| 4345 | <YueDisplay> | ||
| 4346 | |||
| 4347 | ```yue | ||
| 4348 | tbA = [1, 2, 3] | ||
| 4349 | tbB = [4, 5, 6] | ||
| 4350 | tbA[] = ...tbB | ||
| 4351 | -- tbA sekarang [1, 2, 3, 4, 5, 6] | ||
| 4352 | ``` | ||
| 4353 | |||
| 4354 | </YueDisplay> | ||
| 4355 | |||
| 4356 | ## Penyebaran Tabel | 2212 | ## Penyebaran Tabel |
| 4357 | 2213 | ||
| 4358 | Anda bisa menggabungkan tabel array atau tabel hash menggunakan operator spread `...` sebelum ekspresi di literal tabel. | 2214 | Anda bisa menggabungkan tabel array atau tabel hash menggunakan operator spread `...` sebelum ekspresi di literal tabel. |
| @@ -4374,27 +2230,6 @@ b = {4, 5, y: 1} | |||
| 4374 | merge = {...a, ...b} | 2230 | merge = {...a, ...b} |
| 4375 | ``` | 2231 | ``` |
| 4376 | 2232 | ||
| 4377 | <YueDisplay> | ||
| 4378 | |||
| 4379 | ```yue | ||
| 4380 | parts = | ||
| 4381 | * "shoulders" | ||
| 4382 | * "knees" | ||
| 4383 | lyrics = | ||
| 4384 | * "head" | ||
| 4385 | * ...parts | ||
| 4386 | * "and" | ||
| 4387 | * "toes" | ||
| 4388 | |||
| 4389 | copy = {...other} | ||
| 4390 | |||
| 4391 | a = {1, 2, 3, x: 1} | ||
| 4392 | b = {4, 5, y: 1} | ||
| 4393 | merge = {...a, ...b} | ||
| 4394 | ``` | ||
| 4395 | |||
| 4396 | </YueDisplay> | ||
| 4397 | |||
| 4398 | ## Indeks Balik Tabel | 2233 | ## Indeks Balik Tabel |
| 4399 | 2234 | ||
| 4400 | Anda dapat menggunakan operator **#** untuk mendapatkan elemen terakhir dari tabel. | 2235 | Anda dapat menggunakan operator **#** untuk mendapatkan elemen terakhir dari tabel. |
| @@ -4405,16 +2240,6 @@ second_last = data.items[#-1] | |||
| 4405 | data.items[#] = 1 | 2240 | data.items[#] = 1 |
| 4406 | ``` | 2241 | ``` |
| 4407 | 2242 | ||
| 4408 | <YueDisplay> | ||
| 4409 | |||
| 4410 | ```yue | ||
| 4411 | last = data.items[#] | ||
| 4412 | second_last = data.items[#-1] | ||
| 4413 | data.items[#] = 1 | ||
| 4414 | ``` | ||
| 4415 | |||
| 4416 | </YueDisplay> | ||
| 4417 | |||
| 4418 | ## Metatable | 2243 | ## Metatable |
| 4419 | 2244 | ||
| 4420 | Operator **<>** dapat digunakan sebagai pintasan untuk manipulasi metatable. | 2245 | Operator **<>** dapat digunakan sebagai pintasan untuk manipulasi metatable. |
| @@ -4439,26 +2264,6 @@ print d.value | |||
| 4439 | close _ = <close>: -> print "out of scope" | 2264 | close _ = <close>: -> print "out of scope" |
| 4440 | ``` | 2265 | ``` |
| 4441 | 2266 | ||
| 4442 | <YueDisplay> | ||
| 4443 | |||
| 4444 | ```yue | ||
| 4445 | mt = {} | ||
| 4446 | add = (right) => <>: mt, value: @value + right.value | ||
| 4447 | mt.__add = add | ||
| 4448 | |||
| 4449 | a = <>: mt, value: 1 | ||
| 4450 | -- set field dengan variabel bernama sama | ||
| 4451 | b = :<add>, value: 2 | ||
| 4452 | c = <add>: mt.__add, value: 3 | ||
| 4453 | |||
| 4454 | d = a + b + c | ||
| 4455 | print d.value | ||
| 4456 | |||
| 4457 | close _ = <close>: -> print "out of scope" | ||
| 4458 | ``` | ||
| 4459 | |||
| 4460 | </YueDisplay> | ||
| 4461 | |||
| 4462 | ### Mengakses Metatable | 2267 | ### Mengakses Metatable |
| 4463 | 2268 | ||
| 4464 | Akses metatable dengan **<>**, nama metamethod yang dikelilingi **<>**, atau menulis ekspresi di dalam **<>**. | 2269 | Akses metatable dengan **<>**, nama metamethod yang dikelilingi **<>**, atau menulis ekspresi di dalam **<>**. |
| @@ -4473,19 +2278,6 @@ tb.<> = __index: {item: "hello"} | |||
| 4473 | print tb.item | 2278 | print tb.item |
| 4474 | ``` | 2279 | ``` |
| 4475 | 2280 | ||
| 4476 | <YueDisplay> | ||
| 4477 | |||
| 4478 | ```yue | ||
| 4479 | -- dibuat dengan metatable yang berisi field "value" | ||
| 4480 | tb = <"value">: 123 | ||
| 4481 | tb.<index> = tb.<> | ||
| 4482 | print tb.value | ||
| 4483 | tb.<> = __index: {item: "hello"} | ||
| 4484 | print tb.item | ||
| 4485 | ``` | ||
| 4486 | |||
| 4487 | </YueDisplay> | ||
| 4488 | |||
| 4489 | ### Destrukturisasi Metatable | 2281 | ### Destrukturisasi Metatable |
| 4490 | 2282 | ||
| 4491 | Destrukturisasi metatable dengan kunci metamethod yang dikelilingi **<>**. | 2283 | Destrukturisasi metatable dengan kunci metamethod yang dikelilingi **<>**. |
| @@ -4495,15 +2287,6 @@ Destrukturisasi metatable dengan kunci metamethod yang dikelilingi **<>**. | |||
| 4495 | print item, new, close, getter | 2287 | print item, new, close, getter |
| 4496 | ``` | 2288 | ``` |
| 4497 | 2289 | ||
| 4498 | <YueDisplay> | ||
| 4499 | |||
| 4500 | ```yue | ||
| 4501 | {item, :new, :<close>, <index>: getter} = tb | ||
| 4502 | print item, new, close, getter | ||
| 4503 | ``` | ||
| 4504 | |||
| 4505 | </YueDisplay> | ||
| 4506 | |||
| 4507 | ## Keberadaan | 2290 | ## Keberadaan |
| 4508 | 2291 | ||
| 4509 | Operator **?** dapat digunakan dalam berbagai konteks untuk memeriksa keberadaan. | 2292 | Operator **?** dapat digunakan dalam berbagai konteks untuk memeriksa keberadaan. |
| @@ -4523,25 +2306,6 @@ with? io.open "test.txt", "w" | |||
| 4523 | \close! | 2306 | \close! |
| 4524 | ``` | 2307 | ``` |
| 4525 | 2308 | ||
| 4526 | <YueDisplay> | ||
| 4527 | |||
| 4528 | ```yue | ||
| 4529 | func?! | ||
| 4530 | print abc?["hello world"]?.xyz | ||
| 4531 | |||
| 4532 | x = tab?.value | ||
| 4533 | len = utf8?.len or string?.len or (o) -> #o | ||
| 4534 | |||
| 4535 | if print and x? | ||
| 4536 | print x | ||
| 4537 | |||
| 4538 | with? io.open "test.txt", "w" | ||
| 4539 | \write "hello" | ||
| 4540 | \close! | ||
| 4541 | ``` | ||
| 4542 | |||
| 4543 | </YueDisplay> | ||
| 4544 | |||
| 4545 | ## Piping | 2309 | ## Piping |
| 4546 | 2310 | ||
| 4547 | Sebagai ganti serangkaian pemanggilan fungsi bersarang, Anda bisa mengalirkan nilai dengan operator **|>**. | 2311 | Sebagai ganti serangkaian pemanggilan fungsi bersarang, Anda bisa mengalirkan nilai dengan operator **|>**. |
| @@ -4560,24 +2324,6 @@ readFile "example.txt" | |||
| 4560 | 2324 | ||
| 4561 | ``` | 2325 | ``` |
| 4562 | 2326 | ||
| 4563 | <YueDisplay> | ||
| 4564 | |||
| 4565 | ```yue | ||
| 4566 | "hello" |> print | ||
| 4567 | 1 |> print 2 -- sisipkan nilai pipe sebagai argumen pertama | ||
| 4568 | 2 |> print 1, _, 3 -- pipe dengan placeholder | ||
| 4569 | |||
| 4570 | -- ekspresi pipe multi-baris | ||
| 4571 | readFile "example.txt" | ||
| 4572 | |> extract language, {} | ||
| 4573 | |> parse language | ||
| 4574 | |> emit | ||
| 4575 | |> render | ||
| 4576 | |||
| 4577 | ``` | ||
| 4578 | |||
| 4579 | </YueDisplay> | ||
| 4580 | |||
| 4581 | ## Nil Coalescing | 2327 | ## Nil Coalescing |
| 4582 | 2328 | ||
| 4583 | Operator nil-coalescing **??** mengembalikan nilai dari operan kiri jika bukan **nil**; jika tidak, operator mengevaluasi operan kanan dan mengembalikan hasilnya. Operator **??** tidak mengevaluasi operan kanan jika operan kiri bernilai non-nil. | 2329 | Operator nil-coalescing **??** mengembalikan nilai dari operan kiri jika bukan **nil**; jika tidak, operator mengevaluasi operan kanan dan mengembalikan hasilnya. Operator **??** tidak mengevaluasi operan kanan jika operan kiri bernilai non-nil. |
| @@ -4590,17 +2336,6 @@ func a ?? {} | |||
| 4590 | a ??= false | 2336 | a ??= false |
| 4591 | ``` | 2337 | ``` |
| 4592 | 2338 | ||
| 4593 | <YueDisplay> | ||
| 4594 | |||
| 4595 | ```yue | ||
| 4596 | local a, b, c, d | ||
| 4597 | a = b ?? c ?? d | ||
| 4598 | func a ?? {} | ||
| 4599 | a ??= false | ||
| 4600 | ``` | ||
| 4601 | |||
| 4602 | </YueDisplay> | ||
| 4603 | |||
| 4604 | ## Objek Implisit | 2339 | ## Objek Implisit |
| 4605 | 2340 | ||
| 4606 | Anda dapat menulis daftar struktur implisit yang diawali simbol **\*** atau **-** di dalam blok tabel. Jika Anda membuat objek implisit, field objek harus berada pada indentasi yang sama. | 2341 | Anda dapat menulis daftar struktur implisit yang diawali simbol **\*** atau **-** di dalam blok tabel. Jika Anda membuat objek implisit, field objek harus berada pada indentasi yang sama. |
| @@ -4648,52 +2383,6 @@ tb = | |||
| 4648 | 2383 | ||
| 4649 | ``` | 2384 | ``` |
| 4650 | 2385 | ||
| 4651 | <YueDisplay> | ||
| 4652 | |||
| 4653 | ```yue | ||
| 4654 | -- assignment dengan objek implisit | ||
| 4655 | list = | ||
| 4656 | * 1 | ||
| 4657 | * 2 | ||
| 4658 | * 3 | ||
| 4659 | |||
| 4660 | -- pemanggilan fungsi dengan objek implisit | ||
| 4661 | func | ||
| 4662 | * 1 | ||
| 4663 | * 2 | ||
| 4664 | * 3 | ||
| 4665 | |||
| 4666 | -- return dengan objek implisit | ||
| 4667 | f = -> | ||
| 4668 | return | ||
| 4669 | * 1 | ||
| 4670 | * 2 | ||
| 4671 | * 3 | ||
| 4672 | |||
| 4673 | -- tabel dengan objek implisit | ||
| 4674 | tb = | ||
| 4675 | name: "abc" | ||
| 4676 | |||
| 4677 | values: | ||
| 4678 | - "a" | ||
| 4679 | - "b" | ||
| 4680 | - "c" | ||
| 4681 | |||
| 4682 | objects: | ||
| 4683 | - name: "a" | ||
| 4684 | value: 1 | ||
| 4685 | func: => @value + 1 | ||
| 4686 | tb: | ||
| 4687 | fieldA: 1 | ||
| 4688 | |||
| 4689 | - name: "b" | ||
| 4690 | value: 2 | ||
| 4691 | func: => @value + 2 | ||
| 4692 | tb: { } | ||
| 4693 | ``` | ||
| 4694 | |||
| 4695 | </YueDisplay> | ||
| 4696 | |||
| 4697 | # Literal | 2386 | # Literal |
| 4698 | 2387 | ||
| 4699 | Semua literal primitif di Lua dapat digunakan. Ini berlaku untuk angka, string, boolean, dan **nil**. | 2388 | Semua literal primitif di Lua dapat digunakan. Ini berlaku untuk angka, string, boolean, dan **nil**. |
| @@ -4709,19 +2398,6 @@ some_string = "Here is a string | |||
| 4709 | print "I am #{math.random! * 100}% sure." | 2398 | print "I am #{math.random! * 100}% sure." |
| 4710 | ``` | 2399 | ``` |
| 4711 | 2400 | ||
| 4712 | <YueDisplay> | ||
| 4713 | |||
| 4714 | ```yue | ||
| 4715 | some_string = "Here is a string | ||
| 4716 | that has a line break in it." | ||
| 4717 | |||
| 4718 | -- Anda dapat mencampur ekspresi ke dalam literal string dengan sintaks #{}. | ||
| 4719 | -- Interpolasi string hanya tersedia pada string dengan tanda kutip ganda. | ||
| 4720 | print "I am #{math.random! * 100}% sure." | ||
| 4721 | ``` | ||
| 4722 | |||
| 4723 | </YueDisplay> | ||
| 4724 | |||
| 4725 | ## Literal Angka | 2401 | ## Literal Angka |
| 4726 | 2402 | ||
| 4727 | Anda bisa menggunakan garis bawah pada literal angka untuk meningkatkan keterbacaan. | 2403 | Anda bisa menggunakan garis bawah pada literal angka untuk meningkatkan keterbacaan. |
| @@ -4732,16 +2408,6 @@ hex = 0xEF_BB_BF | |||
| 4732 | binary = 0B10011 | 2408 | binary = 0B10011 |
| 4733 | ``` | 2409 | ``` |
| 4734 | 2410 | ||
| 4735 | <YueDisplay> | ||
| 4736 | |||
| 4737 | ```yue | ||
| 4738 | integer = 1_000_000 | ||
| 4739 | hex = 0xEF_BB_BF | ||
| 4740 | binary = 0B10011 | ||
| 4741 | ``` | ||
| 4742 | |||
| 4743 | </YueDisplay> | ||
| 4744 | |||
| 4745 | ## String Multibaris YAML | 2411 | ## String Multibaris YAML |
| 4746 | 2412 | ||
| 4747 | Prefiks `|` memperkenalkan literal string multibaris bergaya YAML: | 2413 | Prefiks `|` memperkenalkan literal string multibaris bergaya YAML: |
| @@ -4754,18 +2420,6 @@ str = | | |||
| 4754 | - #{expr} | 2420 | - #{expr} |
| 4755 | ``` | 2421 | ``` |
| 4756 | 2422 | ||
| 4757 | <YueDisplay> | ||
| 4758 | |||
| 4759 | ```yue | ||
| 4760 | str = | | ||
| 4761 | key: value | ||
| 4762 | list: | ||
| 4763 | - item1 | ||
| 4764 | - #{expr} | ||
| 4765 | ``` | ||
| 4766 | |||
| 4767 | </YueDisplay> | ||
| 4768 | |||
| 4769 | Ini memungkinkan penulisan teks multibaris terstruktur dengan mudah. Semua pemisah baris dan indentasi dipertahankan relatif terhadap baris non-kosong pertama, dan ekspresi di dalam `#{...}` diinterpolasi otomatis sebagai `tostring(expr)`. | 2423 | Ini memungkinkan penulisan teks multibaris terstruktur dengan mudah. Semua pemisah baris dan indentasi dipertahankan relatif terhadap baris non-kosong pertama, dan ekspresi di dalam `#{...}` diinterpolasi otomatis sebagai `tostring(expr)`. |
| 4770 | 2424 | ||
| 4771 | String Multibaris YAML secara otomatis mendeteksi prefiks spasi awal yang sama (indentasi minimum di seluruh baris non-kosong) dan menghapusnya dari semua baris. Ini memudahkan untuk mengindentasi kode secara visual tanpa memengaruhi isi string yang dihasilkan. | 2425 | String Multibaris YAML secara otomatis mendeteksi prefiks spasi awal yang sama (indentasi minimum di seluruh baris non-kosong) dan menghapusnya dari semua baris. Ini memudahkan untuk mengindentasi kode secara visual tanpa memengaruhi isi string yang dihasilkan. |
| @@ -4778,18 +2432,6 @@ fn = -> | |||
| 4778 | return str | 2432 | return str |
| 4779 | ``` | 2433 | ``` |
| 4780 | 2434 | ||
| 4781 | <YueDisplay> | ||
| 4782 | |||
| 4783 | ```yue | ||
| 4784 | fn = -> | ||
| 4785 | str = | | ||
| 4786 | foo: | ||
| 4787 | bar: baz | ||
| 4788 | return str | ||
| 4789 | ``` | ||
| 4790 | |||
| 4791 | </YueDisplay> | ||
| 4792 | |||
| 4793 | Indentasi internal dipertahankan relatif terhadap prefiks umum yang dihapus, sehingga struktur bertingkat tetap rapi. | 2435 | Indentasi internal dipertahankan relatif terhadap prefiks umum yang dihapus, sehingga struktur bertingkat tetap rapi. |
| 4794 | 2436 | ||
| 4795 | Semua karakter khusus seperti tanda kutip (`"`) dan backslash (`\`) di dalam blok YAMLMultiline di-escape secara otomatis agar string Lua yang dihasilkan valid secara sintaks dan berperilaku sebagaimana mestinya. | 2437 | Semua karakter khusus seperti tanda kutip (`"`) dan backslash (`\`) di dalam blok YAMLMultiline di-escape secara otomatis agar string Lua yang dihasilkan valid secara sintaks dan berperilaku sebagaimana mestinya. |
| @@ -4800,16 +2442,6 @@ str = | | |||
| 4800 | note: 'He said: "#{Hello}!"' | 2442 | note: 'He said: "#{Hello}!"' |
| 4801 | ``` | 2443 | ``` |
| 4802 | 2444 | ||
| 4803 | <YueDisplay> | ||
| 4804 | |||
| 4805 | ```yue | ||
| 4806 | str = | | ||
| 4807 | path: "C:\Program Files\App" | ||
| 4808 | note: 'He said: "#{Hello}!"' | ||
| 4809 | ``` | ||
| 4810 | |||
| 4811 | </YueDisplay> | ||
| 4812 | |||
| 4813 | # Modul | 2445 | # Modul |
| 4814 | 2446 | ||
| 4815 | ## Import | 2447 | ## Import |
| @@ -4841,35 +2473,6 @@ do | |||
| 4841 | import "export" as {one, two, Something:{umm:{ch}}} | 2473 | import "export" as {one, two, Something:{umm:{ch}}} |
| 4842 | ``` | 2474 | ``` |
| 4843 | 2475 | ||
| 4844 | <YueDisplay> | ||
| 4845 | |||
| 4846 | ```yue | ||
| 4847 | -- digunakan sebagai destrukturisasi tabel | ||
| 4848 | do | ||
| 4849 | import insert, concat from table | ||
| 4850 | -- akan error saat meng-assign ke insert, concat | ||
| 4851 | import C, Ct, Cmt from require "lpeg" | ||
| 4852 | -- shortcut untuk require implisit | ||
| 4853 | import x, y, z from 'mymodule' | ||
| 4854 | -- import gaya Python | ||
| 4855 | from 'module' import a, b, c | ||
| 4856 | |||
| 4857 | -- shortcut untuk require modul | ||
| 4858 | do | ||
| 4859 | import 'module' | ||
| 4860 | import 'module_x' | ||
| 4861 | import "d-a-s-h-e-s" | ||
| 4862 | import "module.part" | ||
| 4863 | |||
| 4864 | -- require modul dengan aliasing atau destrukturisasi tabel | ||
| 4865 | do | ||
| 4866 | import "player" as PlayerModule | ||
| 4867 | import "lpeg" as :C, :Ct, :Cmt | ||
| 4868 | import "export" as {one, two, Something:{umm:{ch}}} | ||
| 4869 | ``` | ||
| 4870 | |||
| 4871 | </YueDisplay> | ||
| 4872 | |||
| 4873 | ## Import Global | 2476 | ## Import Global |
| 4874 | 2477 | ||
| 4875 | Anda dapat mengimpor global tertentu ke variabel local dengan `import`. Saat mengimpor rangkaian akses variabel global, field terakhir akan di-assign ke variabel local. | 2478 | Anda dapat mengimpor global tertentu ke variabel local dengan `import`. Saat mengimpor rangkaian akses variabel global, field terakhir akan di-assign ke variabel local. |
| @@ -4881,17 +2484,6 @@ do | |||
| 4881 | print concat ["a", tostring 1] | 2484 | print concat ["a", tostring 1] |
| 4882 | ``` | 2485 | ``` |
| 4883 | 2486 | ||
| 4884 | <YueDisplay> | ||
| 4885 | |||
| 4886 | ```yue | ||
| 4887 | do | ||
| 4888 | import tostring | ||
| 4889 | import table.concat | ||
| 4890 | print concat ["a", tostring 1] | ||
| 4891 | ``` | ||
| 4892 | |||
| 4893 | </YueDisplay> | ||
| 4894 | |||
| 4895 | ### Import Variabel Global Otomatis | 2487 | ### Import Variabel Global Otomatis |
| 4896 | 2488 | ||
| 4897 | Anda dapat menempatkan `import global` di awal blok untuk mengimpor secara otomatis semua nama yang belum dideklarasikan atau di-assign secara eksplisit di scope saat ini sebagai global. Import implisit ini diperlakukan sebagai local const yang mereferensikan global terkait pada posisi pernyataan tersebut. | 2489 | Anda dapat menempatkan `import global` di awal blok untuk mengimpor secara otomatis semua nama yang belum dideklarasikan atau di-assign secara eksplisit di scope saat ini sebagai global. Import implisit ini diperlakukan sebagai local const yang mereferensikan global terkait pada posisi pernyataan tersebut. |
| @@ -4913,25 +2505,6 @@ do | |||
| 4913 | FLAG = 123 | 2505 | FLAG = 123 |
| 4914 | ``` | 2506 | ``` |
| 4915 | 2507 | ||
| 4916 | <YueDisplay> | ||
| 4917 | |||
| 4918 | ```yue | ||
| 4919 | do | ||
| 4920 | import global | ||
| 4921 | print "hello" | ||
| 4922 | math.random 3 | ||
| 4923 | -- print = nil -- error: imported globals are const | ||
| 4924 | |||
| 4925 | do | ||
| 4926 | -- variabel global eksplisit tidak akan diimpor | ||
| 4927 | import global | ||
| 4928 | global FLAG | ||
| 4929 | print FLAG | ||
| 4930 | FLAG = 123 | ||
| 4931 | ``` | ||
| 4932 | |||
| 4933 | </YueDisplay> | ||
| 4934 | |||
| 4935 | ## Export | 2508 | ## Export |
| 4936 | 2509 | ||
| 4937 | Pernyataan `export` menawarkan cara ringkas untuk mendefinisikan modul. | 2510 | Pernyataan `export` menawarkan cara ringkas untuk mendefinisikan modul. |
| @@ -4956,26 +2529,6 @@ export class Something | |||
| 4956 | umm: "cool" | 2529 | umm: "cool" |
| 4957 | ``` | 2530 | ``` |
| 4958 | 2531 | ||
| 4959 | <YueDisplay> | ||
| 4960 | |||
| 4961 | ```yue | ||
| 4962 | export a, b, c = 1, 2, 3 | ||
| 4963 | export cool = "cat" | ||
| 4964 | |||
| 4965 | export What = if this | ||
| 4966 | "abc" | ||
| 4967 | else | ||
| 4968 | "def" | ||
| 4969 | |||
| 4970 | export y = -> | ||
| 4971 | hallo = 3434 | ||
| 4972 | |||
| 4973 | export class Something | ||
| 4974 | umm: "cool" | ||
| 4975 | ``` | ||
| 4976 | |||
| 4977 | </YueDisplay> | ||
| 4978 | |||
| 4979 | Melakukan export bernama dengan destrukturisasi. | 2532 | Melakukan export bernama dengan destrukturisasi. |
| 4980 | 2533 | ||
| 4981 | ```yuescript | 2534 | ```yuescript |
| @@ -4983,15 +2536,6 @@ export :loadstring, to_lua: tolua = yue | |||
| 4983 | export {itemA: {:fieldA = 'default'}} = tb | 2536 | export {itemA: {:fieldA = 'default'}} = tb |
| 4984 | ``` | 2537 | ``` |
| 4985 | 2538 | ||
| 4986 | <YueDisplay> | ||
| 4987 | |||
| 4988 | ```yue | ||
| 4989 | export :loadstring, to_lua: tolua = yue | ||
| 4990 | export {itemA: {:fieldA = 'default'}} = tb | ||
| 4991 | ``` | ||
| 4992 | |||
| 4993 | </YueDisplay> | ||
| 4994 | |||
| 4995 | Export item bernama dari modul tanpa membuat variabel local. | 2539 | Export item bernama dari modul tanpa membuat variabel local. |
| 4996 | 2540 | ||
| 4997 | ```yuescript | 2541 | ```yuescript |
| @@ -5000,16 +2544,6 @@ export.<index> = items | |||
| 5000 | export["a-b-c"] = 123 | 2544 | export["a-b-c"] = 123 |
| 5001 | ``` | 2545 | ``` |
| 5002 | 2546 | ||
| 5003 | <YueDisplay> | ||
| 5004 | |||
| 5005 | ```yue | ||
| 5006 | export.itemA = tb | ||
| 5007 | export.<index> = items | ||
| 5008 | export["a-b-c"] = 123 | ||
| 5009 | ``` | ||
| 5010 | |||
| 5011 | </YueDisplay> | ||
| 5012 | |||
| 5013 | ### Export Tanpa Nama | 2547 | ### Export Tanpa Nama |
| 5014 | 2548 | ||
| 5015 | Export tanpa nama akan menambahkan item target ke bagian array dari tabel export. | 2549 | Export tanpa nama akan menambahkan item target ke bagian array dari tabel export. |
| @@ -5027,23 +2561,6 @@ export with tmp | |||
| 5027 | j = 2000 | 2561 | j = 2000 |
| 5028 | ``` | 2562 | ``` |
| 5029 | 2563 | ||
| 5030 | <YueDisplay> | ||
| 5031 | |||
| 5032 | ```yue | ||
| 5033 | d, e, f = 3, 2, 1 | ||
| 5034 | export d, e, f | ||
| 5035 | |||
| 5036 | export if this | ||
| 5037 | 123 | ||
| 5038 | else | ||
| 5039 | 456 | ||
| 5040 | |||
| 5041 | export with tmp | ||
| 5042 | j = 2000 | ||
| 5043 | ``` | ||
| 5044 | |||
| 5045 | </YueDisplay> | ||
| 5046 | |||
| 5047 | ### Export Default | 2564 | ### Export Default |
| 5048 | 2565 | ||
| 5049 | Gunakan kata kunci **default** dalam pernyataan export untuk mengganti tabel export dengan apa pun. | 2566 | Gunakan kata kunci **default** dalam pernyataan export untuk mengganti tabel export dengan apa pun. |
| @@ -5054,16 +2571,6 @@ export default -> | |||
| 5054 | 123 | 2571 | 123 |
| 5055 | ``` | 2572 | ``` |
| 5056 | 2573 | ||
| 5057 | <YueDisplay> | ||
| 5058 | |||
| 5059 | ```yue | ||
| 5060 | export default -> | ||
| 5061 | print "hello" | ||
| 5062 | 123 | ||
| 5063 | ``` | ||
| 5064 | |||
| 5065 | </YueDisplay> | ||
| 5066 | |||
| 5067 | # Lisensi: MIT | 2574 | # Lisensi: MIT |
| 5068 | 2575 | ||
| 5069 | Copyright (c) 2017-2026 Li Jin <dragon-fly@qq.com> | 2576 | Copyright (c) 2017-2026 Li Jin <dragon-fly@qq.com> |
diff --git a/doc/yue-pt-br.md b/doc/yue-pt-br.md index 7bab231..dac3aad 100644 --- a/doc/yue-pt-br.md +++ b/doc/yue-pt-br.md | |||
| @@ -1,11 +1,5 @@ | |||
| 1 | --- | ||
| 2 | title: Referência | ||
| 3 | --- | ||
| 4 | |||
| 5 | # Documentação do YueScript | 1 | # Documentação do YueScript |
| 6 | 2 | ||
| 7 | <img src="/image/yuescript.svg" width="250px" height="250px" alt="logo" style="padding-top: 3em; padding-bottom: 2em;"/> | ||
| 8 | |||
| 9 | Bem-vindo à documentação oficial do <b>YueScript</b>!<br/> | 3 | Bem-vindo à documentação oficial do <b>YueScript</b>!<br/> |
| 10 | Aqui você encontra recursos da linguagem, uso, exemplos de referência e materiais úteis.<br/> | 4 | Aqui você encontra recursos da linguagem, uso, exemplos de referência e materiais úteis.<br/> |
| 11 | Selecione um capítulo na barra lateral para começar a aprender YueScript. | 5 | Selecione um capítulo na barra lateral para começar a aprender YueScript. |
| @@ -21,17 +15,6 @@ do | |||
| 21 | print var -- nil aqui | 15 | print var -- nil aqui |
| 22 | ``` | 16 | ``` |
| 23 | 17 | ||
| 24 | <YueDisplay> | ||
| 25 | |||
| 26 | ```yue | ||
| 27 | do | ||
| 28 | var = "hello" | ||
| 29 | print var | ||
| 30 | print var -- nil aqui | ||
| 31 | ``` | ||
| 32 | |||
| 33 | </YueDisplay> | ||
| 34 | |||
| 35 | O **do** do YueScript também pode ser usado como expressão. Permitindo combinar múltiplas linhas em uma. O resultado da expressão do é a última instrução em seu corpo. Expressões `do` suportam usar `break` para interromper o fluxo de execução e retornar múltiplos valores antecipadamente. | 18 | O **do** do YueScript também pode ser usado como expressão. Permitindo combinar múltiplas linhas em uma. O resultado da expressão do é a última instrução em seu corpo. Expressões `do` suportam usar `break` para interromper o fluxo de execução e retornar múltiplos valores antecipadamente. |
| 36 | 19 | ||
| 37 | ```yuescript | 20 | ```yuescript |
| @@ -42,18 +25,6 @@ status, value = do | |||
| 42 | break "small", n | 25 | break "small", n |
| 43 | ``` | 26 | ``` |
| 44 | 27 | ||
| 45 | <YueDisplay> | ||
| 46 | |||
| 47 | ```yue | ||
| 48 | status, value = do | ||
| 49 | n = 12 | ||
| 50 | if n > 10 | ||
| 51 | break "large", n | ||
| 52 | break "small", n | ||
| 53 | ``` | ||
| 54 | |||
| 55 | </YueDisplay> | ||
| 56 | |||
| 57 | ```yuescript | 28 | ```yuescript |
| 58 | counter = do | 29 | counter = do |
| 59 | i = 0 | 30 | i = 0 |
| @@ -65,21 +36,6 @@ print counter! | |||
| 65 | print counter! | 36 | print counter! |
| 66 | ``` | 37 | ``` |
| 67 | 38 | ||
| 68 | <YueDisplay> | ||
| 69 | |||
| 70 | ```yue | ||
| 71 | counter = do | ||
| 72 | i = 0 | ||
| 73 | -> | ||
| 74 | i += 1 | ||
| 75 | i | ||
| 76 | |||
| 77 | print counter! | ||
| 78 | print counter! | ||
| 79 | ``` | ||
| 80 | |||
| 81 | </YueDisplay> | ||
| 82 | |||
| 83 | ```yuescript | 39 | ```yuescript |
| 84 | tbl = { | 40 | tbl = { |
| 85 | key: do | 41 | key: do |
| @@ -88,18 +44,6 @@ tbl = { | |||
| 88 | } | 44 | } |
| 89 | ``` | 45 | ``` |
| 90 | 46 | ||
| 91 | <YueDisplay> | ||
| 92 | |||
| 93 | ```yue | ||
| 94 | tbl = { | ||
| 95 | key: do | ||
| 96 | print "assigning key!" | ||
| 97 | 1234 | ||
| 98 | } | ||
| 99 | ``` | ||
| 100 | |||
| 101 | </YueDisplay> | ||
| 102 | |||
| 103 | # Decoradores de linha | 47 | # Decoradores de linha |
| 104 | 48 | ||
| 105 | Por conveniência, o loop for e a instrução if podem ser aplicados a instruções únicas no final da linha: | 49 | Por conveniência, o loop for e a instrução if podem ser aplicados a instruções únicas no final da linha: |
| @@ -108,28 +52,12 @@ Por conveniência, o loop for e a instrução if podem ser aplicados a instruç | |||
| 108 | print "hello world" if name == "Rob" | 52 | print "hello world" if name == "Rob" |
| 109 | ``` | 53 | ``` |
| 110 | 54 | ||
| 111 | <YueDisplay> | ||
| 112 | |||
| 113 | ```yue | ||
| 114 | print "hello world" if name == "Rob" | ||
| 115 | ``` | ||
| 116 | |||
| 117 | </YueDisplay> | ||
| 118 | |||
| 119 | E com loops básicos: | 55 | E com loops básicos: |
| 120 | 56 | ||
| 121 | ```yuescript | 57 | ```yuescript |
| 122 | print "item: ", item for item in *items | 58 | print "item: ", item for item in *items |
| 123 | ``` | 59 | ``` |
| 124 | 60 | ||
| 125 | <YueDisplay> | ||
| 126 | |||
| 127 | ```yue | ||
| 128 | print "item: ", item for item in *items | ||
| 129 | ``` | ||
| 130 | |||
| 131 | </YueDisplay> | ||
| 132 | |||
| 133 | E com loops while: | 61 | E com loops while: |
| 134 | 62 | ||
| 135 | ```yuescript | 63 | ```yuescript |
| @@ -138,16 +66,6 @@ game\update! while game\isRunning! | |||
| 138 | reader\parse_line! until reader\eof! | 66 | reader\parse_line! until reader\eof! |
| 139 | ``` | 67 | ``` |
| 140 | 68 | ||
| 141 | <YueDisplay> | ||
| 142 | |||
| 143 | ```yue | ||
| 144 | game\update! while game\isRunning! | ||
| 145 | |||
| 146 | reader\parse_line! until reader\eof! | ||
| 147 | ``` | ||
| 148 | |||
| 149 | </YueDisplay> | ||
| 150 | |||
| 151 | # Macro | 69 | # Macro |
| 152 | 70 | ||
| 153 | ## Uso comum | 71 | ## Uso comum |
| @@ -183,39 +101,6 @@ if $and f1!, f2!, f3! | |||
| 183 | print "OK" | 101 | print "OK" |
| 184 | ``` | 102 | ``` |
| 185 | 103 | ||
| 186 | <YueDisplay> | ||
| 187 | |||
| 188 | ```yue | ||
| 189 | macro PI2 = -> math.pi * 2 | ||
| 190 | area = $PI2 * 5 | ||
| 191 | |||
| 192 | macro HELLO = -> "'hello world'" | ||
| 193 | print $HELLO | ||
| 194 | |||
| 195 | macro config = (debugging) -> | ||
| 196 | global debugMode = debugging == "true" | ||
| 197 | "" | ||
| 198 | |||
| 199 | macro asserts = (cond) -> | ||
| 200 | debugMode and "assert #{cond}" or "" | ||
| 201 | |||
| 202 | macro assert = (cond) -> | ||
| 203 | debugMode and "assert #{cond}" or "#{cond}" | ||
| 204 | |||
| 205 | $config true | ||
| 206 | $asserts item ~= nil | ||
| 207 | |||
| 208 | $config false | ||
| 209 | value = $assert item | ||
| 210 | |||
| 211 | -- as expressões passadas são tratadas como strings | ||
| 212 | macro and = (...) -> "#{ table.concat {...}, ' and ' }" | ||
| 213 | if $and f1!, f2!, f3! | ||
| 214 | print "OK" | ||
| 215 | ``` | ||
| 216 | |||
| 217 | </YueDisplay> | ||
| 218 | |||
| 219 | ## Inserir códigos brutos | 104 | ## Inserir códigos brutos |
| 220 | 105 | ||
| 221 | Uma função macro pode retornar uma string YueScript ou uma tabela de configuração contendo códigos Lua. | 106 | Uma função macro pode retornar uma string YueScript ou uma tabela de configuração contendo códigos Lua. |
| @@ -246,36 +131,6 @@ end | |||
| 246 | ]==] | 131 | ]==] |
| 247 | ``` | 132 | ``` |
| 248 | 133 | ||
| 249 | <YueDisplay> | ||
| 250 | |||
| 251 | ```yue | ||
| 252 | macro yueFunc = (var) -> "local #{var} = ->" | ||
| 253 | $yueFunc funcA | ||
| 254 | funcA = -> "fail to assign to the Yue macro defined variable" | ||
| 255 | |||
| 256 | macro luaFunc = (var) -> { | ||
| 257 | code: "local function #{var}() end" | ||
| 258 | type: "lua" | ||
| 259 | } | ||
| 260 | $luaFunc funcB | ||
| 261 | funcB = -> "fail to assign to the Lua macro defined variable" | ||
| 262 | |||
| 263 | macro lua = (code) -> { | ||
| 264 | :code | ||
| 265 | type: "lua" | ||
| 266 | } | ||
| 267 | |||
| 268 | -- os símbolos inicial e final da string bruta são aparados automaticamente | ||
| 269 | $lua[==[ | ||
| 270 | -- inserção de códigos Lua brutos | ||
| 271 | if cond then | ||
| 272 | print("output") | ||
| 273 | end | ||
| 274 | ]==] | ||
| 275 | ``` | ||
| 276 | |||
| 277 | </YueDisplay> | ||
| 278 | |||
| 279 | ## Exportar macro | 134 | ## Exportar macro |
| 280 | 135 | ||
| 281 | Funções macro podem ser exportadas de um módulo e importadas em outro módulo. Você deve colocar funções export macro em um único arquivo para uso, e apenas definição de macro, importação de macro e expansão de macro inline podem ser colocadas no módulo exportador de macro. | 136 | Funções macro podem ser exportadas de um módulo e importadas em outro módulo. Você deve colocar funções export macro em um único arquivo para uso, e apenas definição de macro, importação de macro e expansão de macro inline podem ser colocadas no módulo exportador de macro. |
| @@ -295,27 +150,6 @@ import "utils" as { | |||
| 295 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | 150 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ |
| 296 | ``` | 151 | ``` |
| 297 | 152 | ||
| 298 | <YueDisplay> | ||
| 299 | |||
| 300 | ```yue | ||
| 301 | -- arquivo: utils.yue | ||
| 302 | export macro map = (items, action) -> "[#{action} for _ in *#{items}]" | ||
| 303 | export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" | ||
| 304 | export macro foreach = (items, action) -> "for _ in *#{items} | ||
| 305 | #{action}" | ||
| 306 | |||
| 307 | -- arquivo main.yue | ||
| 308 | --[[ | ||
| 309 | import "utils" as { | ||
| 310 | $, -- símbolo para importar todas as macros | ||
| 311 | $foreach: $each -- renomear macro $foreach para $each | ||
| 312 | } | ||
| 313 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | ||
| 314 | ]] | ||
| 315 | ``` | ||
| 316 | |||
| 317 | </YueDisplay> | ||
| 318 | |||
| 319 | ## Macro embutida | 153 | ## Macro embutida |
| 320 | 154 | ||
| 321 | Existem algumas macros embutidas, mas você pode sobrescrevê-las declarando macros com os mesmos nomes. | 155 | Existem algumas macros embutidas, mas você pode sobrescrevê-las declarando macros com os mesmos nomes. |
| @@ -325,15 +159,6 @@ print $FILE -- obtém string do nome do módulo atual | |||
| 325 | print $LINE -- obtém número 2 | 159 | print $LINE -- obtém número 2 |
| 326 | ``` | 160 | ``` |
| 327 | 161 | ||
| 328 | <YueDisplay> | ||
| 329 | |||
| 330 | ```yue | ||
| 331 | print $FILE -- obtém string do nome do módulo atual | ||
| 332 | print $LINE -- obtém número 2 | ||
| 333 | ``` | ||
| 334 | |||
| 335 | </YueDisplay> | ||
| 336 | |||
| 337 | ## Gerando macros com macros | 162 | ## Gerando macros com macros |
| 338 | 163 | ||
| 339 | No YueScript, as funções macro permitem que você gere código em tempo de compilação. Aninhando funções macro, você pode criar padrões de geração mais complexos. Este recurso permite que você defina uma função macro que gera outra função macro, permitindo geração de código mais dinâmica. | 164 | No YueScript, as funções macro permitem que você gere código em tempo de compilação. Aninhando funções macro, você pode criar padrões de geração mais complexos. Este recurso permite que você defina uma função macro que gera outra função macro, permitindo geração de código mais dinâmica. |
| @@ -356,28 +181,6 @@ print "Valid enum type:", $BodyType Static | |||
| 356 | -- print "Compilation error with enum type:", $BodyType Unknown | 181 | -- print "Compilation error with enum type:", $BodyType Unknown |
| 357 | ``` | 182 | ``` |
| 358 | 183 | ||
| 359 | <YueDisplay> | ||
| 360 | |||
| 361 | ```yue | ||
| 362 | macro Enum = (...) -> | ||
| 363 | items = {...} | ||
| 364 | itemSet = {item, true for item in *items} | ||
| 365 | (item) -> | ||
| 366 | error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] | ||
| 367 | "\"#{item}\"" | ||
| 368 | |||
| 369 | macro BodyType = $Enum( | ||
| 370 | Static | ||
| 371 | Dynamic | ||
| 372 | Kinematic | ||
| 373 | ) | ||
| 374 | |||
| 375 | print "Valid enum type:", $BodyType Static | ||
| 376 | -- print "Compilation error with enum type:", $BodyType Unknown | ||
| 377 | ``` | ||
| 378 | |||
| 379 | </YueDisplay> | ||
| 380 | |||
| 381 | ## Validação de argumentos | 184 | ## Validação de argumentos |
| 382 | 185 | ||
| 383 | Você pode declarar os tipos de nós AST esperados na lista de argumentos e verificar se os argumentos da macro recebidos atendem às expectativas em tempo de compilação. | 186 | Você pode declarar os tipos de nós AST esperados na lista de argumentos e verificar se os argumentos da macro recebidos atendem às expectativas em tempo de compilação. |
| @@ -392,20 +195,6 @@ macro printNumAndStr = (num `Num, str `String) -> | | |||
| 392 | $printNumAndStr 123, "hello" | 195 | $printNumAndStr 123, "hello" |
| 393 | ``` | 196 | ``` |
| 394 | 197 | ||
| 395 | <YueDisplay> | ||
| 396 | |||
| 397 | ```yue | ||
| 398 | macro printNumAndStr = (num `Num, str `String) -> | | ||
| 399 | print( | ||
| 400 | #{num} | ||
| 401 | #{str} | ||
| 402 | ) | ||
| 403 | |||
| 404 | $printNumAndStr 123, "hello" | ||
| 405 | ``` | ||
| 406 | |||
| 407 | </YueDisplay> | ||
| 408 | |||
| 409 | Se você precisar de verificação de argumentos mais flexível, pode usar a função macro embutida `$is_ast` para verificar manualmente no lugar apropriado. | 198 | Se você precisar de verificação de argumentos mais flexível, pode usar a função macro embutida `$is_ast` para verificar manualmente no lugar apropriado. |
| 410 | 199 | ||
| 411 | ```yuescript | 200 | ```yuescript |
| @@ -417,19 +206,6 @@ macro printNumAndStr = (num, str) -> | |||
| 417 | $printNumAndStr 123, "hello" | 206 | $printNumAndStr 123, "hello" |
| 418 | ``` | 207 | ``` |
| 419 | 208 | ||
| 420 | <YueDisplay> | ||
| 421 | |||
| 422 | ```yue | ||
| 423 | macro printNumAndStr = (num, str) -> | ||
| 424 | error "expected Num as first argument" unless $is_ast Num, num | ||
| 425 | error "expected String as second argument" unless $is_ast String, str | ||
| 426 | "print(#{num}, #{str})" | ||
| 427 | |||
| 428 | $printNumAndStr 123, "hello" | ||
| 429 | ``` | ||
| 430 | |||
| 431 | </YueDisplay> | ||
| 432 | |||
| 433 | Para mais detalhes sobre os nós AST disponíveis, consulte as definições em maiúsculas em [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). | 209 | Para mais detalhes sobre os nós AST disponíveis, consulte as definições em maiúsculas em [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). |
| 434 | 210 | ||
| 435 | # Try | 211 | # Try |
| @@ -464,38 +240,6 @@ catch err | |||
| 464 | print result | 240 | print result |
| 465 | ``` | 241 | ``` |
| 466 | 242 | ||
| 467 | <YueDisplay> | ||
| 468 | |||
| 469 | ```yue | ||
| 470 | try | ||
| 471 | func 1, 2, 3 | ||
| 472 | catch err | ||
| 473 | print yue.traceback err | ||
| 474 | |||
| 475 | success, result = try | ||
| 476 | func 1, 2, 3 | ||
| 477 | catch err | ||
| 478 | yue.traceback err | ||
| 479 | |||
| 480 | try func 1, 2, 3 | ||
| 481 | catch err | ||
| 482 | print yue.traceback err | ||
| 483 | |||
| 484 | success, result = try func 1, 2, 3 | ||
| 485 | |||
| 486 | try | ||
| 487 | print "trying" | ||
| 488 | func 1, 2, 3 | ||
| 489 | |||
| 490 | -- funcionando com padrão de atribuição em if | ||
| 491 | if success, result := try func 1, 2, 3 | ||
| 492 | catch err | ||
| 493 | print yue.traceback err | ||
| 494 | print result | ||
| 495 | ``` | ||
| 496 | |||
| 497 | </YueDisplay> | ||
| 498 | |||
| 499 | ## Try? | 243 | ## Try? |
| 500 | 244 | ||
| 501 | `try?` é um uso simplificado para sintaxe de tratamento de erros que omite o status booleano da instrução `try`, e retornará o resultado do bloco try quando tiver sucesso, retornando nil em vez do objeto de erro caso contrário. | 245 | `try?` é um uso simplificado para sintaxe de tratamento de erros que omite o status booleano da instrução `try`, e retornará o resultado do bloco try quando tiver sucesso, retornando nil em vez do objeto de erro caso contrário. |
| @@ -518,44 +262,14 @@ catch e | |||
| 518 | e | 262 | e |
| 519 | ``` | 263 | ``` |
| 520 | 264 | ||
| 521 | <YueDisplay> | ||
| 522 | |||
| 523 | ```yue | ||
| 524 | a, b, c = try? func! | ||
| 525 | |||
| 526 | -- com operador de coalescência de nil | ||
| 527 | a = (try? func!) ?? "default" | ||
| 528 | |||
| 529 | -- como argumento de função | ||
| 530 | f try? func! | ||
| 531 | |||
| 532 | -- com bloco catch | ||
| 533 | f try? | ||
| 534 | print 123 | ||
| 535 | func! | ||
| 536 | catch e | ||
| 537 | print e | ||
| 538 | e | ||
| 539 | ``` | ||
| 540 | |||
| 541 | </YueDisplay> | ||
| 542 | |||
| 543 | # Literais de tabela | 265 | # Literais de tabela |
| 544 | 266 | ||
| 545 | Como no Lua, as tabelas são delimitadas por chaves. | 267 | Como no Lua, as tabelas são delimitadas por chaves. |
| 546 | 268 | ||
| 547 | ```yuescript | 269 | ```yuescript |
| 548 | some_values = [1, 2, 3, 4] | 270 | some_values = {1, 2, 3, 4} |
| 549 | ``` | ||
| 550 | |||
| 551 | <YueDisplay> | ||
| 552 | |||
| 553 | ```yue | ||
| 554 | some_values = [1, 2, 3, 4] | ||
| 555 | ``` | 271 | ``` |
| 556 | 272 | ||
| 557 | </YueDisplay> | ||
| 558 | |||
| 559 | Diferente do Lua, atribuir um valor a uma chave em uma tabela é feito com **:** (em vez de **=**). | 273 | Diferente do Lua, atribuir um valor a uma chave em uma tabela é feito com **:** (em vez de **=**). |
| 560 | 274 | ||
| 561 | ```yuescript | 275 | ```yuescript |
| @@ -566,18 +280,6 @@ some_values = { | |||
| 566 | } | 280 | } |
| 567 | ``` | 281 | ``` |
| 568 | 282 | ||
| 569 | <YueDisplay> | ||
| 570 | |||
| 571 | ```yue | ||
| 572 | some_values = { | ||
| 573 | name: "Bill", | ||
| 574 | age: 200, | ||
| 575 | ["favorite food"]: "rice" | ||
| 576 | } | ||
| 577 | ``` | ||
| 578 | |||
| 579 | </YueDisplay> | ||
| 580 | |||
| 581 | As chaves podem ser omitidas se uma única tabela de pares chave-valor está sendo atribuída. | 283 | As chaves podem ser omitidas se uma única tabela de pares chave-valor está sendo atribuída. |
| 582 | 284 | ||
| 583 | ```yuescript | 285 | ```yuescript |
| @@ -587,17 +289,6 @@ profile = | |||
| 587 | favorite_foods: ["ice cream", "donuts"] | 289 | favorite_foods: ["ice cream", "donuts"] |
| 588 | ``` | 290 | ``` |
| 589 | 291 | ||
| 590 | <YueDisplay> | ||
| 591 | |||
| 592 | ```yue | ||
| 593 | profile = | ||
| 594 | height: "4 feet", | ||
| 595 | shoe_size: 13, | ||
| 596 | favorite_foods: ["ice cream", "donuts"] | ||
| 597 | ``` | ||
| 598 | |||
| 599 | </YueDisplay> | ||
| 600 | |||
| 601 | Quebras de linha podem ser usadas para delimitar valores em vez de vírgula (ou ambos): | 292 | Quebras de linha podem ser usadas para delimitar valores em vez de vírgula (ou ambos): |
| 602 | 293 | ||
| 603 | ```yuescript | 294 | ```yuescript |
| @@ -609,19 +300,6 @@ values = { | |||
| 609 | } | 300 | } |
| 610 | ``` | 301 | ``` |
| 611 | 302 | ||
| 612 | <YueDisplay> | ||
| 613 | |||
| 614 | ```yue | ||
| 615 | values = { | ||
| 616 | 1, 2, 3, 4 | ||
| 617 | 5, 6, 7, 8 | ||
| 618 | name: "superman" | ||
| 619 | occupation: "crime fighting" | ||
| 620 | } | ||
| 621 | ``` | ||
| 622 | |||
| 623 | </YueDisplay> | ||
| 624 | |||
| 625 | Ao criar um literal de tabela em uma única linha, as chaves também podem ser omitidas: | 303 | Ao criar um literal de tabela em uma única linha, as chaves também podem ser omitidas: |
| 626 | 304 | ||
| 627 | ```yuescript | 305 | ```yuescript |
| @@ -630,16 +308,6 @@ my_function dance: "Tango", partner: "none" | |||
| 630 | y = type: "dog", legs: 4, tails: 1 | 308 | y = type: "dog", legs: 4, tails: 1 |
| 631 | ``` | 309 | ``` |
| 632 | 310 | ||
| 633 | <YueDisplay> | ||
| 634 | |||
| 635 | ```yue | ||
| 636 | my_function dance: "Tango", partner: "none" | ||
| 637 | |||
| 638 | y = type: "dog", legs: 4, tails: 1 | ||
| 639 | ``` | ||
| 640 | |||
| 641 | </YueDisplay> | ||
| 642 | |||
| 643 | As chaves de um literal de tabela podem ser palavras-chave da linguagem sem precisar escapar: | 311 | As chaves de um literal de tabela podem ser palavras-chave da linguagem sem precisar escapar: |
| 644 | 312 | ||
| 645 | ```yuescript | 313 | ```yuescript |
| @@ -649,17 +317,6 @@ tbl = { | |||
| 649 | } | 317 | } |
| 650 | ``` | 318 | ``` |
| 651 | 319 | ||
| 652 | <YueDisplay> | ||
| 653 | |||
| 654 | ```yue | ||
| 655 | tbl = { | ||
| 656 | do: "something" | ||
| 657 | end: "hunger" | ||
| 658 | } | ||
| 659 | ``` | ||
| 660 | |||
| 661 | </YueDisplay> | ||
| 662 | |||
| 663 | Se você está construindo uma tabela a partir de variáveis e deseja que as chaves sejam iguais aos nomes das variáveis, então o operador de prefixo **:** pode ser usado: | 320 | Se você está construindo uma tabela a partir de variáveis e deseja que as chaves sejam iguais aos nomes das variáveis, então o operador de prefixo **:** pode ser usado: |
| 664 | 321 | ||
| 665 | ```yuescript | 322 | ```yuescript |
| @@ -670,18 +327,6 @@ person = { :hair, :height, shoe_size: 40 } | |||
| 670 | print_table :hair, :height | 327 | print_table :hair, :height |
| 671 | ``` | 328 | ``` |
| 672 | 329 | ||
| 673 | <YueDisplay> | ||
| 674 | |||
| 675 | ```yue | ||
| 676 | hair = "golden" | ||
| 677 | height = 200 | ||
| 678 | person = { :hair, :height, shoe_size: 40 } | ||
| 679 | |||
| 680 | print_table :hair, :height | ||
| 681 | ``` | ||
| 682 | |||
| 683 | </YueDisplay> | ||
| 684 | |||
| 685 | Se você quiser que a chave de um campo na tabela seja o resultado de uma expressão, então pode envolvê-la em **[ ]**, assim como no Lua. Você também pode usar um literal de string diretamente como chave, omitindo os colchetes. Isso é útil se sua chave tiver caracteres especiais. | 330 | Se você quiser que a chave de um campo na tabela seja o resultado de uma expressão, então pode envolvê-la em **[ ]**, assim como no Lua. Você também pode usar um literal de string diretamente como chave, omitindo os colchetes. Isso é útil se sua chave tiver caracteres especiais. |
| 686 | 331 | ||
| 687 | ```yuescript | 332 | ```yuescript |
| @@ -691,33 +336,13 @@ t = { | |||
| 691 | } | 336 | } |
| 692 | ``` | 337 | ``` |
| 693 | 338 | ||
| 694 | <YueDisplay> | 339 | As tabelas Lua têm tanto uma parte array quanto uma parte hash, mas às vezes é útil fazer uma distinção semântica entre as duas. Você pode usar **[ ]** em vez de **{ }** para declarar explicitamente uma tabela como um array, fazer isso impedirá que quaisquer pares chave-valor sejam escritos dentro dela. |
| 695 | |||
| 696 | ```yue | ||
| 697 | t = { | ||
| 698 | [1 + 2]: "hello" | ||
| 699 | "hello world": true | ||
| 700 | } | ||
| 701 | ``` | ||
| 702 | |||
| 703 | </YueDisplay> | ||
| 704 | |||
| 705 | As tabelas Lua têm tanto uma parte array quanto uma parte hash, mas às vezes você quer fazer uma distinção semântica entre uso de array e hash ao escrever tabelas Lua. Então você pode escrever tabela Lua com **[ ]** em vez de **{ }** para representar uma tabela array, e escrever qualquer par chave-valor em uma tabela lista não será permitido. | ||
| 706 | 340 | ||
| 707 | ```yuescript | 341 | ```yuescript |
| 708 | some_values = [1, 2, 3, 4] | 342 | some_values = [1, 2, 3, 4] |
| 709 | list_with_one_element = [1, ] | 343 | list_with_one_element = [1, ] |
| 710 | ``` | 344 | ``` |
| 711 | 345 | ||
| 712 | <YueDisplay> | ||
| 713 | |||
| 714 | ```yue | ||
| 715 | some_values = [1, 2, 3, 4] | ||
| 716 | list_with_one_element = [1, ] | ||
| 717 | ``` | ||
| 718 | |||
| 719 | </YueDisplay> | ||
| 720 | |||
| 721 | # Compreensões | 346 | # Compreensões |
| 722 | 347 | ||
| 723 | As compreensões fornecem uma sintaxe conveniente para construir uma nova tabela iterando sobre algum objeto existente e aplicando uma expressão a seus valores. Existem dois tipos de compreensões: compreensões de lista e compreensões de tabela. Ambas produzem tabelas Lua; as compreensões de lista acumulam valores em uma tabela semelhante a array, e as compreensões de tabela permitem definir tanto a chave quanto o valor em cada iteração. | 348 | As compreensões fornecem uma sintaxe conveniente para construir uma nova tabela iterando sobre algum objeto existente e aplicando uma expressão a seus valores. Existem dois tipos de compreensões: compreensões de lista e compreensões de tabela. Ambas produzem tabelas Lua; as compreensões de lista acumulam valores em uma tabela semelhante a array, e as compreensões de tabela permitem definir tanto a chave quanto o valor em cada iteração. |
| @@ -731,43 +356,18 @@ items = [ 1, 2, 3, 4 ] | |||
| 731 | doubled = [item * 2 for i, item in ipairs items] | 356 | doubled = [item * 2 for i, item in ipairs items] |
| 732 | ``` | 357 | ``` |
| 733 | 358 | ||
| 734 | <YueDisplay> | ||
| 735 | |||
| 736 | ```yue | ||
| 737 | items = [ 1, 2, 3, 4 ] | ||
| 738 | doubled = [item * 2 for i, item in ipairs items] | ||
| 739 | ``` | ||
| 740 | |||
| 741 | </YueDisplay> | ||
| 742 | |||
| 743 | Os itens incluídos na nova tabela podem ser restringidos com uma cláusula when: | 359 | Os itens incluídos na nova tabela podem ser restringidos com uma cláusula when: |
| 744 | 360 | ||
| 745 | ```yuescript | 361 | ```yuescript |
| 746 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | 362 | slice = [item for i, item in ipairs items when i > 1 and i < 3] |
| 747 | ``` | 363 | ``` |
| 748 | 364 | ||
| 749 | <YueDisplay> | ||
| 750 | |||
| 751 | ```yue | ||
| 752 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | ||
| 753 | ``` | ||
| 754 | |||
| 755 | </YueDisplay> | ||
| 756 | |||
| 757 | Como é comum iterar sobre os valores de uma tabela indexada numericamente, um operador **\*** é introduzido. O exemplo doubled pode ser reescrito como: | 365 | Como é comum iterar sobre os valores de uma tabela indexada numericamente, um operador **\*** é introduzido. O exemplo doubled pode ser reescrito como: |
| 758 | 366 | ||
| 759 | ```yuescript | 367 | ```yuescript |
| 760 | doubled = [item * 2 for item in *items] | 368 | doubled = [item * 2 for item in *items] |
| 761 | ``` | 369 | ``` |
| 762 | 370 | ||
| 763 | <YueDisplay> | ||
| 764 | |||
| 765 | ```yue | ||
| 766 | doubled = [item * 2 for item in *items] | ||
| 767 | ``` | ||
| 768 | |||
| 769 | </YueDisplay> | ||
| 770 | |||
| 771 | Nas compreensões de lista, você também pode usar o operador spread `...` para achatar listas aninhadas, alcançando um efeito de flat map: | 371 | Nas compreensões de lista, você também pode usar o operador spread `...` para achatar listas aninhadas, alcançando um efeito de flat map: |
| 772 | 372 | ||
| 773 | ```yuescript | 373 | ```yuescript |
| @@ -779,19 +379,6 @@ flat = [...v for k,v in pairs data] | |||
| 779 | -- flat agora é [1, 2, 3, 4, 5, 6] | 379 | -- flat agora é [1, 2, 3, 4, 5, 6] |
| 780 | ``` | 380 | ``` |
| 781 | 381 | ||
| 782 | <YueDisplay> | ||
| 783 | |||
| 784 | ```yue | ||
| 785 | data = | ||
| 786 | a: [1, 2, 3] | ||
| 787 | b: [4, 5, 6] | ||
| 788 | |||
| 789 | flat = [...v for k,v in pairs data] | ||
| 790 | -- flat agora é [1, 2, 3, 4, 5, 6] | ||
| 791 | ``` | ||
| 792 | |||
| 793 | </YueDisplay> | ||
| 794 | |||
| 795 | As cláusulas for e when podem ser encadeadas tanto quanto desejado. O único requisito é que uma compreensão tenha pelo menos uma cláusula for. | 382 | As cláusulas for e when podem ser encadeadas tanto quanto desejado. O único requisito é que uma compreensão tenha pelo menos uma cláusula for. |
| 796 | 383 | ||
| 797 | Usar múltiplas cláusulas for é o mesmo que usar loops aninhados: | 384 | Usar múltiplas cláusulas for é o mesmo que usar loops aninhados: |
| @@ -804,32 +391,12 @@ points = [ [x, y] for x in *x_coords \ | |||
| 804 | for y in *y_coords] | 391 | for y in *y_coords] |
| 805 | ``` | 392 | ``` |
| 806 | 393 | ||
| 807 | <YueDisplay> | ||
| 808 | |||
| 809 | ```yue | ||
| 810 | x_coords = [4, 5, 6, 7] | ||
| 811 | y_coords = [9, 2, 3] | ||
| 812 | |||
| 813 | points = [ [x, y] for x in *x_coords \ | ||
| 814 | for y in *y_coords] | ||
| 815 | ``` | ||
| 816 | |||
| 817 | </YueDisplay> | ||
| 818 | |||
| 819 | Loops for numéricos também podem ser usados em compreensões: | 394 | Loops for numéricos também podem ser usados em compreensões: |
| 820 | 395 | ||
| 821 | ```yuescript | 396 | ```yuescript |
| 822 | evens = [i for i = 1, 100 when i % 2 == 0] | 397 | evens = [i for i = 1, 100 when i % 2 == 0] |
| 823 | ``` | 398 | ``` |
| 824 | 399 | ||
| 825 | <YueDisplay> | ||
| 826 | |||
| 827 | ```yue | ||
| 828 | evens = [i for i = 1, 100 when i % 2 == 0] | ||
| 829 | ``` | ||
| 830 | |||
| 831 | </YueDisplay> | ||
| 832 | |||
| 833 | ## Compreensões de tabela | 400 | ## Compreensões de tabela |
| 834 | 401 | ||
| 835 | A sintaxe para compreensões de tabela é muito semelhante, diferindo apenas por usar **{** e **}** e receber dois valores de cada iteração. | 402 | A sintaxe para compreensões de tabela é muito semelhante, diferindo apenas por usar **{** e **}** e receber dois valores de cada iteração. |
| @@ -846,32 +413,10 @@ thing = { | |||
| 846 | thing_copy = {k, v for k, v in pairs thing} | 413 | thing_copy = {k, v for k, v in pairs thing} |
| 847 | ``` | 414 | ``` |
| 848 | 415 | ||
| 849 | <YueDisplay> | ||
| 850 | |||
| 851 | ```yue | ||
| 852 | thing = { | ||
| 853 | color: "red" | ||
| 854 | name: "fast" | ||
| 855 | width: 123 | ||
| 856 | } | ||
| 857 | |||
| 858 | thing_copy = {k, v for k, v in pairs thing} | ||
| 859 | ``` | ||
| 860 | |||
| 861 | </YueDisplay> | ||
| 862 | |||
| 863 | ```yuescript | 416 | ```yuescript |
| 864 | no_color = {k, v for k, v in pairs thing when k != "color"} | 417 | no_color = {k, v for k, v in pairs thing when k != "color"} |
| 865 | ``` | 418 | ``` |
| 866 | 419 | ||
| 867 | <YueDisplay> | ||
| 868 | |||
| 869 | ```yue | ||
| 870 | no_color = {k, v for k, v in pairs thing when k != "color"} | ||
| 871 | ``` | ||
| 872 | |||
| 873 | </YueDisplay> | ||
| 874 | |||
| 875 | O operador **\*** também é suportado. Aqui criamos uma tabela de consulta de raiz quadrada para alguns números. | 420 | O operador **\*** também é suportado. Aqui criamos uma tabela de consulta de raiz quadrada para alguns números. |
| 876 | 421 | ||
| 877 | ```yuescript | 422 | ```yuescript |
| @@ -879,15 +424,6 @@ numbers = [1, 2, 3, 4] | |||
| 879 | sqrts = {i, math.sqrt i for i in *numbers} | 424 | sqrts = {i, math.sqrt i for i in *numbers} |
| 880 | ``` | 425 | ``` |
| 881 | 426 | ||
| 882 | <YueDisplay> | ||
| 883 | |||
| 884 | ```yue | ||
| 885 | numbers = [1, 2, 3, 4] | ||
| 886 | sqrts = {i, math.sqrt i for i in *numbers} | ||
| 887 | ``` | ||
| 888 | |||
| 889 | </YueDisplay> | ||
| 890 | |||
| 891 | A tupla chave-valor em uma compreensão de tabela também pode vir de uma única expressão, caso em que a expressão deve retornar dois valores. O primeiro é usado como chave e o segundo é usado como valor: | 427 | A tupla chave-valor em uma compreensão de tabela também pode vir de uma única expressão, caso em que a expressão deve retornar dois valores. O primeiro é usado como chave e o segundo é usado como valor: |
| 892 | 428 | ||
| 893 | Neste exemplo convertemos um array de pares em uma tabela onde o primeiro item do par é a chave e o segundo é o valor. | 429 | Neste exemplo convertemos um array de pares em uma tabela onde o primeiro item do par é a chave e o segundo é o valor. |
| @@ -897,15 +433,6 @@ tuples = [ ["hello", "world"], ["foo", "bar"]] | |||
| 897 | tbl = {unpack tuple for tuple in *tuples} | 433 | tbl = {unpack tuple for tuple in *tuples} |
| 898 | ``` | 434 | ``` |
| 899 | 435 | ||
| 900 | <YueDisplay> | ||
| 901 | |||
| 902 | ```yue | ||
| 903 | tuples = [ ["hello", "world"], ["foo", "bar"]] | ||
| 904 | tbl = {unpack tuple for tuple in *tuples} | ||
| 905 | ``` | ||
| 906 | |||
| 907 | </YueDisplay> | ||
| 908 | |||
| 909 | ## Slicing | 436 | ## Slicing |
| 910 | 437 | ||
| 911 | Uma sintaxe especial é fornecida para restringir os itens sobre os quais se itera ao usar o operador **\***. Isso é equivalente a definir os limites de iteração e um tamanho de passo em um loop for. | 438 | Uma sintaxe especial é fornecida para restringir os itens sobre os quais se itera ao usar o operador **\***. Isso é equivalente a definir os limites de iteração e um tamanho de passo em um loop for. |
| @@ -916,42 +443,18 @@ Aqui podemos definir os limites mínimo e máximo, pegando todos os itens com í | |||
| 916 | slice = [item for item in *items[1, 5]] | 443 | slice = [item for item in *items[1, 5]] |
| 917 | ``` | 444 | ``` |
| 918 | 445 | ||
| 919 | <YueDisplay> | ||
| 920 | |||
| 921 | ```yue | ||
| 922 | slice = [item for item in *items[1, 5]] | ||
| 923 | ``` | ||
| 924 | |||
| 925 | </YueDisplay> | ||
| 926 | |||
| 927 | Qualquer um dos argumentos do slice pode ser omitido para usar um padrão sensato. Neste exemplo, se o índice máximo for omitido, ele usa como padrão o comprimento da tabela. Isso pegará tudo exceto o primeiro elemento: | 446 | Qualquer um dos argumentos do slice pode ser omitido para usar um padrão sensato. Neste exemplo, se o índice máximo for omitido, ele usa como padrão o comprimento da tabela. Isso pegará tudo exceto o primeiro elemento: |
| 928 | 447 | ||
| 929 | ```yuescript | 448 | ```yuescript |
| 930 | slice = [item for item in *items[2,]] | 449 | slice = [item for item in *items[2,]] |
| 931 | ``` | 450 | ``` |
| 932 | 451 | ||
| 933 | <YueDisplay> | ||
| 934 | |||
| 935 | ```yue | ||
| 936 | slice = [item for item in *items[2,]] | ||
| 937 | ``` | ||
| 938 | |||
| 939 | </YueDisplay> | ||
| 940 | |||
| 941 | Se o limite mínimo for omitido, ele usa como padrão 1. Aqui fornecemos apenas um tamanho de passo e deixamos os outros limites em branco. Isso pega todos os itens com índice ímpar: (1, 3, 5, …) | 452 | Se o limite mínimo for omitido, ele usa como padrão 1. Aqui fornecemos apenas um tamanho de passo e deixamos os outros limites em branco. Isso pega todos os itens com índice ímpar: (1, 3, 5, …) |
| 942 | 453 | ||
| 943 | ```yuescript | 454 | ```yuescript |
| 944 | slice = [item for item in *items[,,2]] | 455 | slice = [item for item in *items[,,2]] |
| 945 | ``` | 456 | ``` |
| 946 | 457 | ||
| 947 | <YueDisplay> | ||
| 948 | |||
| 949 | ```yue | ||
| 950 | slice = [item for item in *items[,,2]] | ||
| 951 | ``` | ||
| 952 | |||
| 953 | </YueDisplay> | ||
| 954 | |||
| 955 | Tanto o limite mínimo quanto o máximo podem ser negativos, o que significa que os limites são contados a partir do fim da tabela. | 458 | Tanto o limite mínimo quanto o máximo podem ser negativos, o que significa que os limites são contados a partir do fim da tabela. |
| 956 | 459 | ||
| 957 | ```yuescript | 460 | ```yuescript |
| @@ -959,29 +462,12 @@ Tanto o limite mínimo quanto o máximo podem ser negativos, o que significa que | |||
| 959 | slice = [item for item in *items[-4,-1]] | 462 | slice = [item for item in *items[-4,-1]] |
| 960 | ``` | 463 | ``` |
| 961 | 464 | ||
| 962 | <YueDisplay> | ||
| 963 | |||
| 964 | ```yue | ||
| 965 | -- pegar os últimos 4 itens | ||
| 966 | slice = [item for item in *items[-4,-1]] | ||
| 967 | ``` | ||
| 968 | |||
| 969 | </YueDisplay> | ||
| 970 | |||
| 971 | O tamanho do passo também pode ser negativo, o que significa que os itens são tomados em ordem reversa. | 465 | O tamanho do passo também pode ser negativo, o que significa que os itens são tomados em ordem reversa. |
| 972 | 466 | ||
| 973 | ```yuescript | 467 | ```yuescript |
| 974 | reverse_slice = [item for item in *items[-1,1,-1]] | 468 | reverse_slice = [item for item in *items[-1,1,-1]] |
| 975 | ``` | 469 | ``` |
| 976 | 470 | ||
| 977 | <YueDisplay> | ||
| 978 | |||
| 979 | ```yue | ||
| 980 | reverse_slice = [item for item in *items[-1,1,-1]] | ||
| 981 | ``` | ||
| 982 | |||
| 983 | </YueDisplay> | ||
| 984 | |||
| 985 | ### Expressão de slicing | 471 | ### Expressão de slicing |
| 986 | 472 | ||
| 987 | O slicing também pode ser usado como expressão. Isso é útil para obter uma sublista de uma tabela. | 473 | O slicing também pode ser usado como expressão. Isso é útil para obter uma sublista de uma tabela. |
| @@ -994,18 +480,6 @@ sub_list = items[2, 4] | |||
| 994 | last_four_items = items[-4, -1] | 480 | last_four_items = items[-4, -1] |
| 995 | ``` | 481 | ``` |
| 996 | 482 | ||
| 997 | <YueDisplay> | ||
| 998 | |||
| 999 | ```yue | ||
| 1000 | -- pegar o 2º e 4º itens como nova lista | ||
| 1001 | sub_list = items[2, 4] | ||
| 1002 | |||
| 1003 | -- pegar os últimos 4 itens | ||
| 1004 | last_four_items = items[-4, -1] | ||
| 1005 | ``` | ||
| 1006 | |||
| 1007 | </YueDisplay> | ||
| 1008 | |||
| 1009 | # Programação orientada a objetos | 483 | # Programação orientada a objetos |
| 1010 | 484 | ||
| 1011 | Nestes exemplos, o código Lua gerado pode parecer avassalador. É melhor focar primeiro no significado do código YueScript e depois olhar o código Lua se desejar conhecer os detalhes da implementação. | 485 | Nestes exemplos, o código Lua gerado pode parecer avassalador. É melhor focar primeiro no significado do código YueScript e depois olhar o código Lua se desejar conhecer os detalhes da implementação. |
| @@ -1024,22 +498,6 @@ class Inventory | |||
| 1024 | @items[name] = 1 | 498 | @items[name] = 1 |
| 1025 | ``` | 499 | ``` |
| 1026 | 500 | ||
| 1027 | <YueDisplay> | ||
| 1028 | |||
| 1029 | ```yue | ||
| 1030 | class Inventory | ||
| 1031 | new: => | ||
| 1032 | @items = {} | ||
| 1033 | |||
| 1034 | add_item: (name) => | ||
| 1035 | if @items[name] | ||
| 1036 | @items[name] += 1 | ||
| 1037 | else | ||
| 1038 | @items[name] = 1 | ||
| 1039 | ``` | ||
| 1040 | |||
| 1041 | </YueDisplay> | ||
| 1042 | |||
| 1043 | Uma classe é declarada com uma instrução class seguida de uma declaração semelhante a tabela onde todos os métodos e propriedades são listados. | 501 | Uma classe é declarada com uma instrução class seguida de uma declaração semelhante a tabela onde todos os métodos e propriedades são listados. |
| 1044 | 502 | ||
| 1045 | A propriedade new é especial pois se tornará o construtor. | 503 | A propriedade new é especial pois se tornará o construtor. |
| @@ -1056,16 +514,6 @@ inv\add_item "t-shirt" | |||
| 1056 | inv\add_item "pants" | 514 | inv\add_item "pants" |
| 1057 | ``` | 515 | ``` |
| 1058 | 516 | ||
| 1059 | <YueDisplay> | ||
| 1060 | |||
| 1061 | ```yue | ||
| 1062 | inv = Inventory! | ||
| 1063 | inv\add_item "t-shirt" | ||
| 1064 | inv\add_item "pants" | ||
| 1065 | ``` | ||
| 1066 | |||
| 1067 | </YueDisplay> | ||
| 1068 | |||
| 1069 | Como a instância da classe precisa ser enviada aos métodos quando são chamados, o operador \ é usado. | 517 | Como a instância da classe precisa ser enviada aos métodos quando são chamados, o operador \ é usado. |
| 1070 | 518 | ||
| 1071 | Todas as propriedades de uma classe são compartilhadas entre as instâncias. Isso é bom para funções, mas para outros tipos de objetos, resultados indesejados podem ocorrer. | 519 | Todas as propriedades de uma classe são compartilhadas entre as instâncias. Isso é bom para funções, mas para outros tipos de objetos, resultados indesejados podem ocorrer. |
| @@ -1088,26 +536,6 @@ b\give_item "shirt" | |||
| 1088 | print item for item in *a.clothes | 536 | print item for item in *a.clothes |
| 1089 | ``` | 537 | ``` |
| 1090 | 538 | ||
| 1091 | <YueDisplay> | ||
| 1092 | |||
| 1093 | ```yue | ||
| 1094 | class Person | ||
| 1095 | clothes: [] | ||
| 1096 | give_item: (name) => | ||
| 1097 | table.insert @clothes, name | ||
| 1098 | |||
| 1099 | a = Person! | ||
| 1100 | b = Person! | ||
| 1101 | |||
| 1102 | a\give_item "pants" | ||
| 1103 | b\give_item "shirt" | ||
| 1104 | |||
| 1105 | -- vai imprimir tanto pants quanto shirt | ||
| 1106 | print item for item in *a.clothes | ||
| 1107 | ``` | ||
| 1108 | |||
| 1109 | </YueDisplay> | ||
| 1110 | |||
| 1111 | A forma correta de evitar esse problema é criar o estado mutável do objeto no construtor: | 539 | A forma correta de evitar esse problema é criar o estado mutável do objeto no construtor: |
| 1112 | 540 | ||
| 1113 | ```yuescript | 541 | ```yuescript |
| @@ -1116,16 +544,6 @@ class Person | |||
| 1116 | @clothes = [] | 544 | @clothes = [] |
| 1117 | ``` | 545 | ``` |
| 1118 | 546 | ||
| 1119 | <YueDisplay> | ||
| 1120 | |||
| 1121 | ```yue | ||
| 1122 | class Person | ||
| 1123 | new: => | ||
| 1124 | @clothes = [] | ||
| 1125 | ``` | ||
| 1126 | |||
| 1127 | </YueDisplay> | ||
| 1128 | |||
| 1129 | ## Herança | 547 | ## Herança |
| 1130 | 548 | ||
| 1131 | A palavra-chave extends pode ser usada em uma declaração de classe para herdar as propriedades e métodos de outra classe. | 549 | A palavra-chave extends pode ser usada em uma declaração de classe para herdar as propriedades e métodos de outra classe. |
| @@ -1138,18 +556,6 @@ class BackPack extends Inventory | |||
| 1138 | super name | 556 | super name |
| 1139 | ``` | 557 | ``` |
| 1140 | 558 | ||
| 1141 | <YueDisplay> | ||
| 1142 | |||
| 1143 | ```yue | ||
| 1144 | class BackPack extends Inventory | ||
| 1145 | size: 10 | ||
| 1146 | add_item: (name) => | ||
| 1147 | if #@items > size then error "backpack is full" | ||
| 1148 | super name | ||
| 1149 | ``` | ||
| 1150 | |||
| 1151 | </YueDisplay> | ||
| 1152 | |||
| 1153 | Aqui estendemos nossa classe Inventory e limitamos a quantidade de itens que ela pode carregar. | 559 | Aqui estendemos nossa classe Inventory e limitamos a quantidade de itens que ela pode carregar. |
| 1154 | 560 | ||
| 1155 | Neste exemplo, não definimos um construtor na subclasse, então o construtor da classe pai é chamado quando criamos uma nova instância. Se definirmos um construtor, podemos usar o método super para chamar o construtor pai. | 561 | Neste exemplo, não definimos um construtor na subclasse, então o construtor da classe pai é chamado quando criamos uma nova instância. Se definirmos um construtor, podemos usar o método super para chamar o construtor pai. |
| @@ -1165,19 +571,6 @@ class Shelf | |||
| 1165 | class Cupboard extends Shelf | 571 | class Cupboard extends Shelf |
| 1166 | ``` | 572 | ``` |
| 1167 | 573 | ||
| 1168 | <YueDisplay> | ||
| 1169 | |||
| 1170 | ```yue | ||
| 1171 | class Shelf | ||
| 1172 | @__inherited: (child) => | ||
| 1173 | print @__name, "was inherited by", child.__name | ||
| 1174 | |||
| 1175 | -- vai imprimir: Shelf was inherited by Cupboard | ||
| 1176 | class Cupboard extends Shelf | ||
| 1177 | ``` | ||
| 1178 | |||
| 1179 | </YueDisplay> | ||
| 1180 | |||
| 1181 | ## Super | 574 | ## Super |
| 1182 | 575 | ||
| 1183 | **super** é uma palavra-chave especial que pode ser usada de duas formas diferentes: pode ser tratado como um objeto, ou pode ser chamado como uma função. Só tem funcionalidade especial quando está dentro de uma classe. | 576 | **super** é uma palavra-chave especial que pode ser usada de duas formas diferentes: pode ser tratado como um objeto, ou pode ser chamado como uma função. Só tem funcionalidade especial quando está dentro de uma classe. |
| @@ -1204,22 +597,6 @@ class MyClass extends ParentClass | |||
| 1204 | assert super == ParentClass | 597 | assert super == ParentClass |
| 1205 | ``` | 598 | ``` |
| 1206 | 599 | ||
| 1207 | <YueDisplay> | ||
| 1208 | |||
| 1209 | ```yue | ||
| 1210 | class MyClass extends ParentClass | ||
| 1211 | a_method: => | ||
| 1212 | -- os seguintes têm o mesmo efeito: | ||
| 1213 | super "hello", "world" | ||
| 1214 | super\a_method "hello", "world" | ||
| 1215 | super.a_method self, "hello", "world" | ||
| 1216 | |||
| 1217 | -- super como valor é igual à classe pai: | ||
| 1218 | assert super == ParentClass | ||
| 1219 | ``` | ||
| 1220 | |||
| 1221 | </YueDisplay> | ||
| 1222 | |||
| 1223 | **super** também pode ser usado no lado esquerdo de um Function Stub. A única diferença principal é que, em vez da função resultante estar vinculada ao valor de super, ela está vinculada a self. | 600 | **super** também pode ser usado no lado esquerdo de um Function Stub. A única diferença principal é que, em vez da função resultante estar vinculada ao valor de super, ela está vinculada a self. |
| 1224 | 601 | ||
| 1225 | ## Tipos | 602 | ## Tipos |
| @@ -1233,17 +610,6 @@ assert b.__class == BackPack | |||
| 1233 | print BackPack.size -- imprime 10 | 610 | print BackPack.size -- imprime 10 |
| 1234 | ``` | 611 | ``` |
| 1235 | 612 | ||
| 1236 | <YueDisplay> | ||
| 1237 | |||
| 1238 | ```yue | ||
| 1239 | b = BackPack! | ||
| 1240 | assert b.__class == BackPack | ||
| 1241 | |||
| 1242 | print BackPack.size -- imprime 10 | ||
| 1243 | ``` | ||
| 1244 | |||
| 1245 | </YueDisplay> | ||
| 1246 | |||
| 1247 | ## Objetos de classe | 613 | ## Objetos de classe |
| 1248 | 614 | ||
| 1249 | O objeto da classe é o que criamos quando usamos uma instrução class. O objeto da classe é armazenado em uma variável com o mesmo nome da classe. | 615 | O objeto da classe é o que criamos quando usamos uma instrução class. O objeto da classe é armazenado em uma variável com o mesmo nome da classe. |
| @@ -1264,14 +630,6 @@ O nome da classe quando foi declarada é armazenado como string no campo \_\_nam | |||
| 1264 | print BackPack.__name -- imprime Backpack | 630 | print BackPack.__name -- imprime Backpack |
| 1265 | ``` | 631 | ``` |
| 1266 | 632 | ||
| 1267 | <YueDisplay> | ||
| 1268 | |||
| 1269 | ```yue | ||
| 1270 | print BackPack.__name -- imprime Backpack | ||
| 1271 | ``` | ||
| 1272 | |||
| 1273 | </YueDisplay> | ||
| 1274 | |||
| 1275 | O objeto base é armazenado em \_\_base. Podemos modificar esta tabela para adicionar funcionalidade a instâncias que já foram criadas e às que ainda serão criadas. | 633 | O objeto base é armazenado em \_\_base. Podemos modificar esta tabela para adicionar funcionalidade a instâncias que já foram criadas e às que ainda serão criadas. |
| 1276 | 634 | ||
| 1277 | Se a classe estende de algo, o objeto da classe pai é armazenado em \_\_parent. | 635 | Se a classe estende de algo, o objeto da classe pai é armazenado em \_\_parent. |
| @@ -1290,20 +648,6 @@ Things\some_func! | |||
| 1290 | assert Things().some_func == nil | 648 | assert Things().some_func == nil |
| 1291 | ``` | 649 | ``` |
| 1292 | 650 | ||
| 1293 | <YueDisplay> | ||
| 1294 | |||
| 1295 | ```yue | ||
| 1296 | class Things | ||
| 1297 | @some_func: => print "Hello from", @__name | ||
| 1298 | |||
| 1299 | Things\some_func! | ||
| 1300 | |||
| 1301 | -- variáveis de classe não visíveis em instâncias | ||
| 1302 | assert Things().some_func == nil | ||
| 1303 | ``` | ||
| 1304 | |||
| 1305 | </YueDisplay> | ||
| 1306 | |||
| 1307 | Em expressões, podemos usar @@ para acessar um valor armazenado no **class de self. Assim, @@hello é abreviação para self.**class.hello. | 651 | Em expressões, podemos usar @@ para acessar um valor armazenado no **class de self. Assim, @@hello é abreviação para self.**class.hello. |
| 1308 | 652 | ||
| 1309 | ```yuescript | 653 | ```yuescript |
| @@ -1319,37 +663,12 @@ Counter! | |||
| 1319 | print Counter.count -- imprime 2 | 663 | print Counter.count -- imprime 2 |
| 1320 | ``` | 664 | ``` |
| 1321 | 665 | ||
| 1322 | <YueDisplay> | ||
| 1323 | |||
| 1324 | ```yue | ||
| 1325 | class Counter | ||
| 1326 | @count: 0 | ||
| 1327 | |||
| 1328 | new: => | ||
| 1329 | @@count += 1 | ||
| 1330 | |||
| 1331 | Counter! | ||
| 1332 | Counter! | ||
| 1333 | |||
| 1334 | print Counter.count -- imprime 2 | ||
| 1335 | ``` | ||
| 1336 | |||
| 1337 | </YueDisplay> | ||
| 1338 | |||
| 1339 | A semântica de chamada de @@ é semelhante a @. Chamar um nome @@ passará a classe como primeiro argumento usando a sintaxe de dois pontos do Lua. | 666 | A semântica de chamada de @@ é semelhante a @. Chamar um nome @@ passará a classe como primeiro argumento usando a sintaxe de dois pontos do Lua. |
| 1340 | 667 | ||
| 1341 | ```yuescript | 668 | ```yuescript |
| 1342 | @@hello 1,2,3,4 | 669 | @@hello 1,2,3,4 |
| 1343 | ``` | 670 | ``` |
| 1344 | 671 | ||
| 1345 | <YueDisplay> | ||
| 1346 | |||
| 1347 | ```yue | ||
| 1348 | @@hello 1,2,3,4 | ||
| 1349 | ``` | ||
| 1350 | |||
| 1351 | </YueDisplay> | ||
| 1352 | |||
| 1353 | ## Instruções de declaração de classe | 672 | ## Instruções de declaração de classe |
| 1354 | 673 | ||
| 1355 | No corpo de uma declaração de classe, podemos ter expressões normais além de pares chave/valor. Neste contexto, self é igual ao objeto da classe. | 674 | No corpo de uma declaração de classe, podemos ter expressões normais além de pares chave/valor. Neste contexto, self é igual ao objeto da classe. |
| @@ -1361,15 +680,6 @@ class Things | |||
| 1361 | @class_var = "hello world" | 680 | @class_var = "hello world" |
| 1362 | ``` | 681 | ``` |
| 1363 | 682 | ||
| 1364 | <YueDisplay> | ||
| 1365 | |||
| 1366 | ```yue | ||
| 1367 | class Things | ||
| 1368 | @class_var = "hello world" | ||
| 1369 | ``` | ||
| 1370 | |||
| 1371 | </YueDisplay> | ||
| 1372 | |||
| 1373 | Estas expressões são executadas após todas as propriedades terem sido adicionadas à base. | 683 | Estas expressões são executadas após todas as propriedades terem sido adicionadas à base. |
| 1374 | 684 | ||
| 1375 | Todas as variáveis declaradas no corpo da classe são locais às propriedades da classe. Isso é conveniente para colocar valores privados ou funções auxiliares que apenas os métodos da classe podem acessar: | 685 | Todas as variáveis declaradas no corpo da classe são locais às propriedades da classe. Isso é conveniente para colocar valores privados ou funções auxiliares que apenas os métodos da classe podem acessar: |
| @@ -1383,19 +693,6 @@ class MoreThings | |||
| 1383 | log "hello world: " .. secret | 693 | log "hello world: " .. secret |
| 1384 | ``` | 694 | ``` |
| 1385 | 695 | ||
| 1386 | <YueDisplay> | ||
| 1387 | |||
| 1388 | ```yue | ||
| 1389 | class MoreThings | ||
| 1390 | secret = 123 | ||
| 1391 | log = (msg) -> print "LOG:", msg | ||
| 1392 | |||
| 1393 | some_method: => | ||
| 1394 | log "hello world: " .. secret | ||
| 1395 | ``` | ||
| 1396 | |||
| 1397 | </YueDisplay> | ||
| 1398 | |||
| 1399 | ## Valores @ e @@ | 696 | ## Valores @ e @@ |
| 1400 | 697 | ||
| 1401 | Quando @ e @@ são prefixados na frente de um nome, eles representam, respectivamente, esse nome acessado em self e self.\_\_class. | 698 | Quando @ e @@ são prefixados na frente de um nome, eles representam, respectivamente, esse nome acessado em self e self.\_\_class. |
| @@ -1407,29 +704,12 @@ assert @ == self | |||
| 1407 | assert @@ == self.__class | 704 | assert @@ == self.__class |
| 1408 | ``` | 705 | ``` |
| 1409 | 706 | ||
| 1410 | <YueDisplay> | ||
| 1411 | |||
| 1412 | ```yue | ||
| 1413 | assert @ == self | ||
| 1414 | assert @@ == self.__class | ||
| 1415 | ``` | ||
| 1416 | |||
| 1417 | </YueDisplay> | ||
| 1418 | |||
| 1419 | Por exemplo, uma forma rápida de criar uma nova instância da mesma classe a partir de um método de instância usando @@: | 707 | Por exemplo, uma forma rápida de criar uma nova instância da mesma classe a partir de um método de instância usando @@: |
| 1420 | 708 | ||
| 1421 | ```yuescript | 709 | ```yuescript |
| 1422 | some_instance_method = (...) => @@ ... | 710 | some_instance_method = (...) => @@ ... |
| 1423 | ``` | 711 | ``` |
| 1424 | 712 | ||
| 1425 | <YueDisplay> | ||
| 1426 | |||
| 1427 | ```yue | ||
| 1428 | some_instance_method = (...) => @@ ... | ||
| 1429 | ``` | ||
| 1430 | |||
| 1431 | </YueDisplay> | ||
| 1432 | |||
| 1433 | ## Promoção de propriedade no construtor | 713 | ## Promoção de propriedade no construtor |
| 1434 | 714 | ||
| 1435 | Para reduzir o código repetitivo na definição de objetos de valor simples. Você pode escrever uma classe simples como: | 715 | Para reduzir o código repetitivo na definição de objetos de valor simples. Você pode escrever uma classe simples como: |
| @@ -1448,24 +728,6 @@ class Something | |||
| 1448 | @@baz = baz | 728 | @@baz = baz |
| 1449 | ``` | 729 | ``` |
| 1450 | 730 | ||
| 1451 | <YueDisplay> | ||
| 1452 | |||
| 1453 | ```yue | ||
| 1454 | class Something | ||
| 1455 | new: (@foo, @bar, @@biz, @@baz) => | ||
| 1456 | |||
| 1457 | -- O que é abreviação para | ||
| 1458 | |||
| 1459 | class Something | ||
| 1460 | new: (foo, bar, biz, baz) => | ||
| 1461 | @foo = foo | ||
| 1462 | @bar = bar | ||
| 1463 | @@biz = biz | ||
| 1464 | @@baz = baz | ||
| 1465 | ``` | ||
| 1466 | |||
| 1467 | </YueDisplay> | ||
| 1468 | |||
| 1469 | Você também pode usar esta sintaxe para uma função comum para inicializar os campos de um objeto. | 731 | Você também pode usar esta sintaxe para uma função comum para inicializar os campos de um objeto. |
| 1470 | 732 | ||
| 1471 | ```yuescript | 733 | ```yuescript |
| @@ -1474,16 +736,6 @@ obj = new {}, 123, "abc" | |||
| 1474 | print obj | 736 | print obj |
| 1475 | ``` | 737 | ``` |
| 1476 | 738 | ||
| 1477 | <YueDisplay> | ||
| 1478 | |||
| 1479 | ```yue | ||
| 1480 | new = (@fieldA, @fieldB) => @ | ||
| 1481 | obj = new {}, 123, "abc" | ||
| 1482 | print obj | ||
| 1483 | ``` | ||
| 1484 | |||
| 1485 | </YueDisplay> | ||
| 1486 | |||
| 1487 | ## Expressões de classe | 739 | ## Expressões de classe |
| 1488 | 740 | ||
| 1489 | A sintaxe de classe também pode ser usada como expressão que pode ser atribuída a uma variável ou retornada explicitamente. | 741 | A sintaxe de classe também pode ser usada como expressão que pode ser atribuída a uma variável ou retornada explicitamente. |
| @@ -1494,16 +746,6 @@ x = class Bucket | |||
| 1494 | add_drop: => @drops += 1 | 746 | add_drop: => @drops += 1 |
| 1495 | ``` | 747 | ``` |
| 1496 | 748 | ||
| 1497 | <YueDisplay> | ||
| 1498 | |||
| 1499 | ```yue | ||
| 1500 | x = class Bucket | ||
| 1501 | drops: 0 | ||
| 1502 | add_drop: => @drops += 1 | ||
| 1503 | ``` | ||
| 1504 | |||
| 1505 | </YueDisplay> | ||
| 1506 | |||
| 1507 | ## Classes anônimas | 749 | ## Classes anônimas |
| 1508 | 750 | ||
| 1509 | O nome pode ser omitido ao declarar uma classe. O atributo \_\_name será nil, a menos que a expressão da classe esteja em uma atribuição. O nome no lado esquerdo da atribuição é usado em vez de nil. | 751 | O nome pode ser omitido ao declarar uma classe. O atributo \_\_name será nil, a menos que a expressão da classe esteja em uma atribuição. O nome no lado esquerdo da atribuição é usado em vez de nil. |
| @@ -1515,31 +757,12 @@ BigBucket = class extends Bucket | |||
| 1515 | assert Bucket.__name == "BigBucket" | 757 | assert Bucket.__name == "BigBucket" |
| 1516 | ``` | 758 | ``` |
| 1517 | 759 | ||
| 1518 | <YueDisplay> | ||
| 1519 | |||
| 1520 | ```yue | ||
| 1521 | BigBucket = class extends Bucket | ||
| 1522 | add_drop: => @drops += 10 | ||
| 1523 | |||
| 1524 | assert Bucket.__name == "BigBucket" | ||
| 1525 | ``` | ||
| 1526 | |||
| 1527 | </YueDisplay> | ||
| 1528 | |||
| 1529 | Você pode até omitir o corpo, significando que pode escrever uma classe anônima em branco assim: | 760 | Você pode até omitir o corpo, significando que pode escrever uma classe anônima em branco assim: |
| 1530 | 761 | ||
| 1531 | ```yuescript | 762 | ```yuescript |
| 1532 | x = class | 763 | x = class |
| 1533 | ``` | 764 | ``` |
| 1534 | 765 | ||
| 1535 | <YueDisplay> | ||
| 1536 | |||
| 1537 | ```yue | ||
| 1538 | x = class | ||
| 1539 | ``` | ||
| 1540 | |||
| 1541 | </YueDisplay> | ||
| 1542 | |||
| 1543 | ## Mistura de classes | 766 | ## Mistura de classes |
| 1544 | 767 | ||
| 1545 | Você pode fazer mistura com a palavra-chave `using` para copiar funções de uma tabela simples ou de um objeto de classe predefinido para sua nova classe. Ao fazer mistura com uma tabela simples, você pode sobrescrever a função de indexação da classe (metamétodo `__index`) para sua implementação personalizada. Ao fazer mistura com um objeto de classe existente, os metamétodos do objeto da classe não serão copiados. | 768 | Você pode fazer mistura com a palavra-chave `using` para copiar funções de uma tabela simples ou de um objeto de classe predefinido para sua nova classe. Ao fazer mistura com uma tabela simples, você pode sobrescrever a função de indexação da classe (metamétodo `__index`) para sua implementação personalizada. Ao fazer mistura com um objeto de classe existente, os metamétodos do objeto da classe não serão copiados. |
| @@ -1562,28 +785,6 @@ y\func! | |||
| 1562 | assert y.__class.__parent ~= X -- X não é pai de Y | 785 | assert y.__class.__parent ~= X -- X não é pai de Y |
| 1563 | ``` | 786 | ``` |
| 1564 | 787 | ||
| 1565 | <YueDisplay> | ||
| 1566 | |||
| 1567 | ```yue | ||
| 1568 | MyIndex = __index: var: 1 | ||
| 1569 | |||
| 1570 | class X using MyIndex | ||
| 1571 | func: => | ||
| 1572 | print 123 | ||
| 1573 | |||
| 1574 | x = X! | ||
| 1575 | print x.var | ||
| 1576 | |||
| 1577 | class Y using X | ||
| 1578 | |||
| 1579 | y = Y! | ||
| 1580 | y\func! | ||
| 1581 | |||
| 1582 | assert y.__class.__parent ~= X -- X não é pai de Y | ||
| 1583 | ``` | ||
| 1584 | |||
| 1585 | </YueDisplay> | ||
| 1586 | |||
| 1587 | # Instrução With | 788 | # Instrução With |
| 1588 | 789 | ||
| 1589 | Um padrão comum envolvendo a criação de um objeto é chamar uma série de funções e definir uma série de propriedades imediatamente após criá-lo. | 790 | Um padrão comum envolvendo a criação de um objeto é chamar uma série de funções e definir uma série de propriedades imediatamente após criá-lo. |
| @@ -1602,18 +803,6 @@ with Person! | |||
| 1602 | print .name | 803 | print .name |
| 1603 | ``` | 804 | ``` |
| 1604 | 805 | ||
| 1605 | <YueDisplay> | ||
| 1606 | |||
| 1607 | ```yue | ||
| 1608 | with Person! | ||
| 1609 | .name = "Oswald" | ||
| 1610 | \add_relative my_dad | ||
| 1611 | \save! | ||
| 1612 | print .name | ||
| 1613 | ``` | ||
| 1614 | |||
| 1615 | </YueDisplay> | ||
| 1616 | |||
| 1617 | A instrução with também pode ser usada como expressão que retorna o valor ao qual foi dado acesso. | 806 | A instrução with também pode ser usada como expressão que retorna o valor ao qual foi dado acesso. |
| 1618 | 807 | ||
| 1619 | ```yuescript | 808 | ```yuescript |
| @@ -1621,15 +810,6 @@ file = with File "favorite_foods.txt" | |||
| 1621 | \set_encoding "utf8" | 810 | \set_encoding "utf8" |
| 1622 | ``` | 811 | ``` |
| 1623 | 812 | ||
| 1624 | <YueDisplay> | ||
| 1625 | |||
| 1626 | ```yue | ||
| 1627 | file = with File "favorite_foods.txt" | ||
| 1628 | \set_encoding "utf8" | ||
| 1629 | ``` | ||
| 1630 | |||
| 1631 | </YueDisplay> | ||
| 1632 | |||
| 1633 | Expressões `with` suportam `break` com um valor: | 813 | Expressões `with` suportam `break` com um valor: |
| 1634 | 814 | ||
| 1635 | ```yuescript | 815 | ```yuescript |
| @@ -1637,15 +817,6 @@ result = with obj | |||
| 1637 | break .value | 817 | break .value |
| 1638 | ``` | 818 | ``` |
| 1639 | 819 | ||
| 1640 | <YueDisplay> | ||
| 1641 | |||
| 1642 | ```yue | ||
| 1643 | result = with obj | ||
| 1644 | break .value | ||
| 1645 | ``` | ||
| 1646 | |||
| 1647 | </YueDisplay> | ||
| 1648 | |||
| 1649 | Depois que `break value` é usado dentro de `with`, a expressão `with` deixa de retornar seu objeto-alvo e passa a retornar o valor de `break`. | 820 | Depois que `break value` é usado dentro de `with`, a expressão `with` deixa de retornar seu objeto-alvo e passa a retornar o valor de `break`. |
| 1650 | 821 | ||
| 1651 | ```yuescript | 822 | ```yuescript |
| @@ -1658,20 +829,6 @@ b = with obj | |||
| 1658 | -- b é .x, não obj | 829 | -- b é .x, não obj |
| 1659 | ``` | 830 | ``` |
| 1660 | 831 | ||
| 1661 | <YueDisplay> | ||
| 1662 | |||
| 1663 | ```yue | ||
| 1664 | a = with obj | ||
| 1665 | .x = 1 | ||
| 1666 | -- a é obj | ||
| 1667 | |||
| 1668 | b = with obj | ||
| 1669 | break .x | ||
| 1670 | -- b é .x, não obj | ||
| 1671 | ``` | ||
| 1672 | |||
| 1673 | </YueDisplay> | ||
| 1674 | |||
| 1675 | Diferente de `for` / `while` / `repeat` / `do`, `with` suporta apenas um valor de `break`. | 832 | Diferente de `for` / `while` / `repeat` / `do`, `with` suporta apenas um valor de `break`. |
| 1676 | 833 | ||
| 1677 | Ou… | 834 | Ou… |
| @@ -1685,19 +842,6 @@ create_person = (name, relatives) -> | |||
| 1685 | me = create_person "Leaf", [dad, mother, sister] | 842 | me = create_person "Leaf", [dad, mother, sister] |
| 1686 | ``` | 843 | ``` |
| 1687 | 844 | ||
| 1688 | <YueDisplay> | ||
| 1689 | |||
| 1690 | ```yue | ||
| 1691 | create_person = (name, relatives) -> | ||
| 1692 | with Person! | ||
| 1693 | .name = name | ||
| 1694 | \add_relative relative for relative in *relatives | ||
| 1695 | |||
| 1696 | me = create_person "Leaf", [dad, mother, sister] | ||
| 1697 | ``` | ||
| 1698 | |||
| 1699 | </YueDisplay> | ||
| 1700 | |||
| 1701 | Neste uso, with pode ser visto como uma forma especial do combinador K. | 845 | Neste uso, with pode ser visto como uma forma especial do combinador K. |
| 1702 | 846 | ||
| 1703 | A expressão na instrução with também pode ser uma atribuição, se você quiser dar um nome à expressão. | 847 | A expressão na instrução with também pode ser uma atribuição, se você quiser dar um nome à expressão. |
| @@ -1708,16 +852,6 @@ with str := "Hello" | |||
| 1708 | print "upper:", \upper! | 852 | print "upper:", \upper! |
| 1709 | ``` | 853 | ``` |
| 1710 | 854 | ||
| 1711 | <YueDisplay> | ||
| 1712 | |||
| 1713 | ```yue | ||
| 1714 | with str := "Hello" | ||
| 1715 | print "original:", str | ||
| 1716 | print "upper:", \upper! | ||
| 1717 | ``` | ||
| 1718 | |||
| 1719 | </YueDisplay> | ||
| 1720 | |||
| 1721 | Você pode acessar chaves especiais com `[]` em uma instrução `with`. | 855 | Você pode acessar chaves especiais com `[]` em uma instrução `with`. |
| 1722 | 856 | ||
| 1723 | ```yuescript | 857 | ```yuescript |
| @@ -1730,20 +864,6 @@ with tb | |||
| 1730 | [] = "abc" -- anexando a "tb" | 864 | [] = "abc" -- anexando a "tb" |
| 1731 | ``` | 865 | ``` |
| 1732 | 866 | ||
| 1733 | <YueDisplay> | ||
| 1734 | |||
| 1735 | ```yue | ||
| 1736 | with tb | ||
| 1737 | [1] = 1 | ||
| 1738 | print [2] | ||
| 1739 | with [abc] | ||
| 1740 | [3] = [2]\func! | ||
| 1741 | ["key-name"] = value | ||
| 1742 | [] = "abc" -- anexando a "tb" | ||
| 1743 | ``` | ||
| 1744 | |||
| 1745 | </YueDisplay> | ||
| 1746 | |||
| 1747 | `with?` é uma versão aprimorada da sintaxe `with`, que introduz uma verificação existencial para acessar com segurança objetos que podem ser nil sem verificações explícitas de null. | 867 | `with?` é uma versão aprimorada da sintaxe `with`, que introduz uma verificação existencial para acessar com segurança objetos que podem ser nil sem verificações explícitas de null. |
| 1748 | 868 | ||
| 1749 | ```yuescript | 869 | ```yuescript |
| @@ -1751,15 +871,6 @@ with? obj | |||
| 1751 | print obj.name | 871 | print obj.name |
| 1752 | ``` | 872 | ``` |
| 1753 | 873 | ||
| 1754 | <YueDisplay> | ||
| 1755 | |||
| 1756 | ```yue | ||
| 1757 | with? obj | ||
| 1758 | print obj.name | ||
| 1759 | ``` | ||
| 1760 | |||
| 1761 | </YueDisplay> | ||
| 1762 | |||
| 1763 | # Atribuição | 874 | # Atribuição |
| 1764 | 875 | ||
| 1765 | A variável é tipada dinamicamente e é definida como local por padrão. Mas você pode alterar o escopo da declaração pelas instruções **local** e **global**. | 876 | A variável é tipada dinamicamente e é definida como local por padrão. Mas você pode alterar o escopo da declaração pelas instruções **local** e **global**. |
| @@ -1770,16 +881,6 @@ a, b, c = 1, 2, 3 | |||
| 1770 | hello = 123 -- usa a variável existente | 881 | hello = 123 -- usa a variável existente |
| 1771 | ``` | 882 | ``` |
| 1772 | 883 | ||
| 1773 | <YueDisplay> | ||
| 1774 | |||
| 1775 | ```yue | ||
| 1776 | hello = "world" | ||
| 1777 | a, b, c = 1, 2, 3 | ||
| 1778 | hello = 123 -- usa a variável existente | ||
| 1779 | ``` | ||
| 1780 | |||
| 1781 | </YueDisplay> | ||
| 1782 | |||
| 1783 | ## Atualização | 884 | ## Atualização |
| 1784 | 885 | ||
| 1785 | Você pode realizar atribuição de atualização com muitos operadores binários. | 886 | Você pode realizar atribuição de atualização com muitos operadores binários. |
| @@ -1795,21 +896,6 @@ s ..= "world" -- adiciona um novo local se a variável local não existir | |||
| 1795 | arg or= "valor padrão" | 896 | arg or= "valor padrão" |
| 1796 | ``` | 897 | ``` |
| 1797 | 898 | ||
| 1798 | <YueDisplay> | ||
| 1799 | |||
| 1800 | ```yue | ||
| 1801 | x = 1 | ||
| 1802 | x += 1 | ||
| 1803 | x -= 1 | ||
| 1804 | x *= 10 | ||
| 1805 | x /= 10 | ||
| 1806 | x %= 10 | ||
| 1807 | s ..= "world" -- adiciona um novo local se a variável local não existir | ||
| 1808 | arg or= "valor padrão" | ||
| 1809 | ``` | ||
| 1810 | |||
| 1811 | </YueDisplay> | ||
| 1812 | |||
| 1813 | ## Atribuição encadeada | 899 | ## Atribuição encadeada |
| 1814 | 900 | ||
| 1815 | Você pode fazer atribuição encadeada para atribuir múltiplos itens ao mesmo valor. | 901 | Você pode fazer atribuição encadeada para atribuir múltiplos itens ao mesmo valor. |
| @@ -1819,15 +905,6 @@ a = b = c = d = e = 0 | |||
| 1819 | x = y = z = f! | 905 | x = y = z = f! |
| 1820 | ``` | 906 | ``` |
| 1821 | 907 | ||
| 1822 | <YueDisplay> | ||
| 1823 | |||
| 1824 | ```yue | ||
| 1825 | a = b = c = d = e = 0 | ||
| 1826 | x = y = z = f! | ||
| 1827 | ``` | ||
| 1828 | |||
| 1829 | </YueDisplay> | ||
| 1830 | |||
| 1831 | ## Locais explícitos | 908 | ## Locais explícitos |
| 1832 | 909 | ||
| 1833 | ```yuescript | 910 | ```yuescript |
| @@ -1847,27 +924,6 @@ do | |||
| 1847 | B = 2 | 924 | B = 2 |
| 1848 | ``` | 925 | ``` |
| 1849 | 926 | ||
| 1850 | <YueDisplay> | ||
| 1851 | |||
| 1852 | ```yue | ||
| 1853 | do | ||
| 1854 | local a = 1 | ||
| 1855 | local * | ||
| 1856 | print "declarar antecipadamente todas as variáveis como locais" | ||
| 1857 | x = -> 1 + y + z | ||
| 1858 | y, z = 2, 3 | ||
| 1859 | global instance = Item\new! | ||
| 1860 | |||
| 1861 | do | ||
| 1862 | local X = 1 | ||
| 1863 | local ^ | ||
| 1864 | print "declarar antecipadamente apenas variáveis em maiúsculas" | ||
| 1865 | a = 1 | ||
| 1866 | B = 2 | ||
| 1867 | ``` | ||
| 1868 | |||
| 1869 | </YueDisplay> | ||
| 1870 | |||
| 1871 | ## Globais explícitos | 927 | ## Globais explícitos |
| 1872 | 928 | ||
| 1873 | ```yuescript | 929 | ```yuescript |
| @@ -1887,27 +943,6 @@ do | |||
| 1887 | local Temp = "um valor local" | 943 | local Temp = "um valor local" |
| 1888 | ``` | 944 | ``` |
| 1889 | 945 | ||
| 1890 | <YueDisplay> | ||
| 1891 | |||
| 1892 | ```yue | ||
| 1893 | do | ||
| 1894 | global a = 1 | ||
| 1895 | global * | ||
| 1896 | print "declarar todas as variáveis como globais" | ||
| 1897 | x = -> 1 + y + z | ||
| 1898 | y, z = 2, 3 | ||
| 1899 | |||
| 1900 | do | ||
| 1901 | global X = 1 | ||
| 1902 | global ^ | ||
| 1903 | print "declarar apenas variáveis em maiúsculas como globais" | ||
| 1904 | a = 1 | ||
| 1905 | B = 2 | ||
| 1906 | local Temp = "um valor local" | ||
| 1907 | ``` | ||
| 1908 | |||
| 1909 | </YueDisplay> | ||
| 1910 | |||
| 1911 | # Atribuição de varargs | 946 | # Atribuição de varargs |
| 1912 | 947 | ||
| 1913 | Você pode atribuir os resultados retornados de uma função a um símbolo varargs `...`. E então acessar seu conteúdo da forma Lua. | 948 | Você pode atribuir os resultados retornados de uma função a um símbolo varargs `...`. E então acessar seu conteúdo da forma Lua. |
| @@ -1921,19 +956,6 @@ first = select 1, ... | |||
| 1921 | print ok, count, first | 956 | print ok, count, first |
| 1922 | ``` | 957 | ``` |
| 1923 | 958 | ||
| 1924 | <YueDisplay> | ||
| 1925 | |||
| 1926 | ```yue | ||
| 1927 | list = [1, 2, 3, 4, 5] | ||
| 1928 | fn = (ok) -> ok, table.unpack list | ||
| 1929 | ok, ... = fn true | ||
| 1930 | count = select '#', ... | ||
| 1931 | first = select 1, ... | ||
| 1932 | print ok, count, first | ||
| 1933 | ``` | ||
| 1934 | |||
| 1935 | </YueDisplay> | ||
| 1936 | |||
| 1937 | # Atribuição em if | 959 | # Atribuição em if |
| 1938 | 960 | ||
| 1939 | Os blocos `if` e `elseif` podem receber uma atribuição no lugar de uma expressão condicional. Ao avaliar o condicional, a atribuição será realizada e o valor que foi atribuído será usado como expressão condicional. A variável atribuída está no escopo apenas para o corpo do condicional, ou seja, nunca está disponível se o valor não for truthy. E você precisa usar o "operador walrus" `:=` em vez de `=` para fazer a atribuição. | 961 | Os blocos `if` e `elseif` podem receber uma atribuição no lugar de uma expressão condicional. Ao avaliar o condicional, a atribuição será realizada e o valor que foi atribuído será usado como expressão condicional. A variável atribuída está no escopo apenas para o corpo do condicional, ou seja, nunca está disponível se o valor não for truthy. E você precisa usar o "operador walrus" `:=` em vez de `=` para fazer a atribuição. |
| @@ -1943,15 +965,6 @@ if user := database.find_user "moon" | |||
| 1943 | print user.name | 965 | print user.name |
| 1944 | ``` | 966 | ``` |
| 1945 | 967 | ||
| 1946 | <YueDisplay> | ||
| 1947 | |||
| 1948 | ```yue | ||
| 1949 | if user := database.find_user "moon" | ||
| 1950 | print user.name | ||
| 1951 | ``` | ||
| 1952 | |||
| 1953 | </YueDisplay> | ||
| 1954 | |||
| 1955 | ```yuescript | 968 | ```yuescript |
| 1956 | if hello := os.getenv "hello" | 969 | if hello := os.getenv "hello" |
| 1957 | print "Você tem hello", hello | 970 | print "Você tem hello", hello |
| @@ -1961,19 +974,6 @@ else | |||
| 1961 | print "nada :(" | 974 | print "nada :(" |
| 1962 | ``` | 975 | ``` |
| 1963 | 976 | ||
| 1964 | <YueDisplay> | ||
| 1965 | |||
| 1966 | ```yue | ||
| 1967 | if hello := os.getenv "hello" | ||
| 1968 | print "Você tem hello", hello | ||
| 1969 | elseif world := os.getenv "world" | ||
| 1970 | print "você tem world", world | ||
| 1971 | else | ||
| 1972 | print "nada :(" | ||
| 1973 | ``` | ||
| 1974 | |||
| 1975 | </YueDisplay> | ||
| 1976 | |||
| 1977 | Atribuição em if com múltiplos valores de retorno. Apenas o primeiro valor é verificado, os outros valores estão no escopo. | 977 | Atribuição em if com múltiplos valores de retorno. Apenas o primeiro valor é verificado, os outros valores estão no escopo. |
| 1978 | 978 | ||
| 1979 | ```yuescript | 979 | ```yuescript |
| @@ -1982,16 +982,6 @@ if success, result := pcall -> "obter resultado sem problemas" | |||
| 1982 | print "OK" | 982 | print "OK" |
| 1983 | ``` | 983 | ``` |
| 1984 | 984 | ||
| 1985 | <YueDisplay> | ||
| 1986 | |||
| 1987 | ```yue | ||
| 1988 | if success, result := pcall -> "obter resultado sem problemas" | ||
| 1989 | print result -- variável result está no escopo | ||
| 1990 | print "OK" | ||
| 1991 | ``` | ||
| 1992 | |||
| 1993 | </YueDisplay> | ||
| 1994 | |||
| 1995 | ## Atribuição em while | 985 | ## Atribuição em while |
| 1996 | 986 | ||
| 1997 | Você também pode usar atribuição em if em um loop while para obter o valor como condição do loop. | 987 | Você também pode usar atribuição em if em um loop while para obter o valor como condição do loop. |
| @@ -2002,16 +992,6 @@ while byte := stream\read_one! | |||
| 2002 | print byte | 992 | print byte |
| 2003 | ``` | 993 | ``` |
| 2004 | 994 | ||
| 2005 | <YueDisplay> | ||
| 2006 | |||
| 2007 | ```yue | ||
| 2008 | while byte := stream\read_one! | ||
| 2009 | -- fazer algo com o byte | ||
| 2010 | print byte | ||
| 2011 | ``` | ||
| 2012 | |||
| 2013 | </YueDisplay> | ||
| 2014 | |||
| 2015 | # Atribuição por desestruturação | 995 | # Atribuição por desestruturação |
| 2016 | 996 | ||
| 2017 | A atribuição por desestruturação é uma forma de extrair rapidamente valores de uma tabela por seu nome ou posição em tabelas baseadas em array. | 997 | A atribuição por desestruturação é uma forma de extrair rapidamente valores de uma tabela por seu nome ou posição em tabelas baseadas em array. |
| @@ -2027,17 +1007,6 @@ thing = [1, 2] | |||
| 2027 | print a, b | 1007 | print a, b |
| 2028 | ``` | 1008 | ``` |
| 2029 | 1009 | ||
| 2030 | <YueDisplay> | ||
| 2031 | |||
| 2032 | ```yue | ||
| 2033 | thing = [1, 2] | ||
| 2034 | |||
| 2035 | [a, b] = thing | ||
| 2036 | print a, b | ||
| 2037 | ``` | ||
| 2038 | |||
| 2039 | </YueDisplay> | ||
| 2040 | |||
| 2041 | No literal de tabela de desestruturação, a chave representa a chave para ler do lado direito, e o valor representa o nome ao qual o valor lido será atribuído. | 1010 | No literal de tabela de desestruturação, a chave representa a chave para ler do lado direito, e o valor representa o nome ao qual o valor lido será atribuído. |
| 2042 | 1011 | ||
| 2043 | ```yuescript | 1012 | ```yuescript |
| @@ -2053,23 +1022,6 @@ print hello, the_day | |||
| 2053 | :day = obj -- OK fazer desestruturação simples sem chaves | 1022 | :day = obj -- OK fazer desestruturação simples sem chaves |
| 2054 | ``` | 1023 | ``` |
| 2055 | 1024 | ||
| 2056 | <YueDisplay> | ||
| 2057 | |||
| 2058 | ```yue | ||
| 2059 | obj = { | ||
| 2060 | hello: "world" | ||
| 2061 | day: "tuesday" | ||
| 2062 | length: 20 | ||
| 2063 | } | ||
| 2064 | |||
| 2065 | {hello: hello, day: the_day} = obj | ||
| 2066 | print hello, the_day | ||
| 2067 | |||
| 2068 | :day = obj -- OK fazer desestruturação simples sem chaves | ||
| 2069 | ``` | ||
| 2070 | |||
| 2071 | </YueDisplay> | ||
| 2072 | |||
| 2073 | Isso também funciona com estruturas de dados aninhadas: | 1025 | Isso também funciona com estruturas de dados aninhadas: |
| 2074 | 1026 | ||
| 2075 | ```yuescript | 1027 | ```yuescript |
| @@ -2085,23 +1037,6 @@ obj2 = { | |||
| 2085 | print first, second, color | 1037 | print first, second, color |
| 2086 | ``` | 1038 | ``` |
| 2087 | 1039 | ||
| 2088 | <YueDisplay> | ||
| 2089 | |||
| 2090 | ```yue | ||
| 2091 | obj2 = { | ||
| 2092 | numbers: [1, 2, 3, 4] | ||
| 2093 | properties: { | ||
| 2094 | color: "green" | ||
| 2095 | height: 13.5 | ||
| 2096 | } | ||
| 2097 | } | ||
| 2098 | |||
| 2099 | {numbers: [first, second], properties: {color: color}} = obj2 | ||
| 2100 | print first, second, color | ||
| 2101 | ``` | ||
| 2102 | |||
| 2103 | </YueDisplay> | ||
| 2104 | |||
| 2105 | Se a instrução de desestruturação for complicada, sinta-se à vontade para espalhá-la em várias linhas. Um exemplo um pouco mais complicado: | 1040 | Se a instrução de desestruturação for complicada, sinta-se à vontade para espalhá-la em várias linhas. Um exemplo um pouco mais complicado: |
| 2106 | 1041 | ||
| 2107 | ```yuescript | 1042 | ```yuescript |
| @@ -2113,75 +1048,30 @@ Se a instrução de desestruturação for complicada, sinta-se à vontade para e | |||
| 2113 | } = obj2 | 1048 | } = obj2 |
| 2114 | ``` | 1049 | ``` |
| 2115 | 1050 | ||
| 2116 | <YueDisplay> | ||
| 2117 | |||
| 2118 | ```yue | ||
| 2119 | { | ||
| 2120 | numbers: [first, second] | ||
| 2121 | properties: { | ||
| 2122 | color: color | ||
| 2123 | } | ||
| 2124 | } = obj2 | ||
| 2125 | ``` | ||
| 2126 | |||
| 2127 | </YueDisplay> | ||
| 2128 | |||
| 2129 | É comum extrair valores de uma tabela e atribuí-los a variáveis locais que têm o mesmo nome da chave. Para evitar repetição, podemos usar o operador de prefixo **:**: | 1051 | É comum extrair valores de uma tabela e atribuí-los a variáveis locais que têm o mesmo nome da chave. Para evitar repetição, podemos usar o operador de prefixo **:**: |
| 2130 | 1052 | ||
| 2131 | ```yuescript | 1053 | ```yuescript |
| 2132 | {:concat, :insert} = table | 1054 | {:concat, :insert} = table |
| 2133 | ``` | 1055 | ``` |
| 2134 | 1056 | ||
| 2135 | <YueDisplay> | ||
| 2136 | |||
| 2137 | ```yue | ||
| 2138 | {:concat, :insert} = table | ||
| 2139 | ``` | ||
| 2140 | |||
| 2141 | </YueDisplay> | ||
| 2142 | |||
| 2143 | Isso é efetivamente o mesmo que import, mas podemos renomear campos que queremos extrair misturando a sintaxe: | 1057 | Isso é efetivamente o mesmo que import, mas podemos renomear campos que queremos extrair misturando a sintaxe: |
| 2144 | 1058 | ||
| 2145 | ```yuescript | 1059 | ```yuescript |
| 2146 | {:mix, :max, random: rand} = math | 1060 | {:mix, :max, random: rand} = math |
| 2147 | ``` | 1061 | ``` |
| 2148 | 1062 | ||
| 2149 | <YueDisplay> | ||
| 2150 | |||
| 2151 | ```yue | ||
| 2152 | {:mix, :max, random: rand} = math | ||
| 2153 | ``` | ||
| 2154 | |||
| 2155 | </YueDisplay> | ||
| 2156 | |||
| 2157 | Você pode escrever valores padrão ao fazer desestruturação: | 1063 | Você pode escrever valores padrão ao fazer desestruturação: |
| 2158 | 1064 | ||
| 2159 | ```yuescript | 1065 | ```yuescript |
| 2160 | {:name = "sem nome", :job = "sem emprego"} = person | 1066 | {:name = "sem nome", :job = "sem emprego"} = person |
| 2161 | ``` | 1067 | ``` |
| 2162 | 1068 | ||
| 2163 | <YueDisplay> | ||
| 2164 | |||
| 2165 | ```yue | ||
| 2166 | {:name = "sem nome", :job = "sem emprego"} = person | ||
| 2167 | ``` | ||
| 2168 | |||
| 2169 | </YueDisplay> | ||
| 2170 | |||
| 2171 | Você pode usar `_` como placeholder ao fazer desestruturação de lista: | 1069 | Você pode usar `_` como placeholder ao fazer desestruturação de lista: |
| 2172 | 1070 | ||
| 2173 | ```yuescript | 1071 | ```yuescript |
| 2174 | [_, two, _, four] = items | 1072 | [_, two, _, four] = items |
| 2175 | ``` | 1073 | ``` |
| 2176 | 1074 | ||
| 2177 | <YueDisplay> | ||
| 2178 | |||
| 2179 | ```yue | ||
| 2180 | [_, two, _, four] = items | ||
| 2181 | ``` | ||
| 2182 | |||
| 2183 | </YueDisplay> | ||
| 2184 | |||
| 2185 | ## Desestruturação por intervalo | 1075 | ## Desestruturação por intervalo |
| 2186 | 1076 | ||
| 2187 | Você pode usar o operador spread `...` na desestruturação de lista para capturar um intervalo de valores. Isso é útil quando você quer extrair elementos específicos do início e do fim de uma lista enquanto coleta o restante entre eles. | 1077 | Você pode usar o operador spread `...` na desestruturação de lista para capturar um intervalo de valores. Isso é útil quando você quer extrair elementos específicos do início e do fim de uma lista enquanto coleta o restante entre eles. |
| @@ -2194,18 +1084,6 @@ print bulk -- imprime: {"second", "third", "fourth"} | |||
| 2194 | print last -- imprime: last | 1084 | print last -- imprime: last |
| 2195 | ``` | 1085 | ``` |
| 2196 | 1086 | ||
| 2197 | <YueDisplay> | ||
| 2198 | |||
| 2199 | ```yue | ||
| 2200 | orders = ["first", "second", "third", "fourth", "last"] | ||
| 2201 | [first, ...bulk, last] = orders | ||
| 2202 | print first -- imprime: first | ||
| 2203 | print bulk -- imprime: {"second", "third", "fourth"} | ||
| 2204 | print last -- imprime: last | ||
| 2205 | ``` | ||
| 2206 | |||
| 2207 | </YueDisplay> | ||
| 2208 | |||
| 2209 | O operador spread pode ser usado em diferentes posições para capturar diferentes intervalos, e você pode usar `_` como placeholder para os valores que não quer capturar: | 1087 | O operador spread pode ser usado em diferentes posições para capturar diferentes intervalos, e você pode usar `_` como placeholder para os valores que não quer capturar: |
| 2210 | 1088 | ||
| 2211 | ```yuescript | 1089 | ```yuescript |
| @@ -2219,21 +1097,6 @@ O operador spread pode ser usado em diferentes posições para capturar diferent | |||
| 2219 | [first, ..._, last] = orders | 1097 | [first, ..._, last] = orders |
| 2220 | ``` | 1098 | ``` |
| 2221 | 1099 | ||
| 2222 | <YueDisplay> | ||
| 2223 | |||
| 2224 | ```yue | ||
| 2225 | -- Capturar tudo após o primeiro elemento | ||
| 2226 | [first, ...rest] = orders | ||
| 2227 | |||
| 2228 | -- Capturar tudo antes do último elemento | ||
| 2229 | [...start, last] = orders | ||
| 2230 | |||
| 2231 | -- Capturar tudo exceto os elementos do meio | ||
| 2232 | [first, ..._, last] = orders | ||
| 2233 | ``` | ||
| 2234 | |||
| 2235 | </YueDisplay> | ||
| 2236 | |||
| 2237 | ## Desestruturação em outros lugares | 1100 | ## Desestruturação em outros lugares |
| 2238 | 1101 | ||
| 2239 | A desestruturação também pode aparecer em lugares onde uma atribuição ocorre implicitamente. Um exemplo disso é um loop for: | 1102 | A desestruturação também pode aparecer em lugares onde uma atribuição ocorre implicitamente. Um exemplo disso é um loop for: |
| @@ -2248,20 +1111,6 @@ for [left, right] in *tuples | |||
| 2248 | print left, right | 1111 | print left, right |
| 2249 | ``` | 1112 | ``` |
| 2250 | 1113 | ||
| 2251 | <YueDisplay> | ||
| 2252 | |||
| 2253 | ```yue | ||
| 2254 | tuples = [ | ||
| 2255 | ["hello", "world"] | ||
| 2256 | ["egg", "head"] | ||
| 2257 | ] | ||
| 2258 | |||
| 2259 | for [left, right] in *tuples | ||
| 2260 | print left, right | ||
| 2261 | ``` | ||
| 2262 | |||
| 2263 | </YueDisplay> | ||
| 2264 | |||
| 2265 | Sabemos que cada elemento na tabela array é uma tupla de dois itens, então podemos desempacotá-lo diretamente na cláusula de nomes da instrução for usando desestruturação. | 1114 | Sabemos que cada elemento na tabela array é uma tupla de dois itens, então podemos desempacotá-lo diretamente na cláusula de nomes da instrução for usando desestruturação. |
| 2266 | 1115 | ||
| 2267 | # A cláusula Using; controlando atribuição destrutiva | 1116 | # A cláusula Using; controlando atribuição destrutiva |
| @@ -2284,26 +1133,6 @@ my_func! | |||
| 2284 | print i -- vai imprimir 0 | 1133 | print i -- vai imprimir 0 |
| 2285 | ``` | 1134 | ``` |
| 2286 | 1135 | ||
| 2287 | <YueDisplay> | ||
| 2288 | |||
| 2289 | ```yue | ||
| 2290 | i = 100 | ||
| 2291 | |||
| 2292 | -- muitas linhas de código... | ||
| 2293 | |||
| 2294 | my_func = -> | ||
| 2295 | i = 10 | ||
| 2296 | while i > 0 | ||
| 2297 | print i | ||
| 2298 | i -= 1 | ||
| 2299 | |||
| 2300 | my_func! | ||
| 2301 | |||
| 2302 | print i -- vai imprimir 0 | ||
| 2303 | ``` | ||
| 2304 | |||
| 2305 | </YueDisplay> | ||
| 2306 | |||
| 2307 | Em my_func, sobrescrevemos o valor de i por engano. Neste exemplo é bem óbvio, mas considere uma base de código grande ou estrangeira onde não está claro quais nomes já foram declarados. | 1136 | Em my_func, sobrescrevemos o valor de i por engano. Neste exemplo é bem óbvio, mas considere uma base de código grande ou estrangeira onde não está claro quais nomes já foram declarados. |
| 2308 | 1137 | ||
| 2309 | Seria útil dizer quais variáveis do escopo envolvente pretendemos alterar, para evitar que alteremos outras por acidente. | 1138 | Seria útil dizer quais variáveis do escopo envolvente pretendemos alterar, para evitar que alteremos outras por acidente. |
| @@ -2320,20 +1149,6 @@ my_func! | |||
| 2320 | print i -- imprime 100, i não é afetado | 1149 | print i -- imprime 100, i não é afetado |
| 2321 | ``` | 1150 | ``` |
| 2322 | 1151 | ||
| 2323 | <YueDisplay> | ||
| 2324 | |||
| 2325 | ```yue | ||
| 2326 | i = 100 | ||
| 2327 | |||
| 2328 | my_func = (using nil) -> | ||
| 2329 | i = "hello" -- uma nova variável local é criada aqui | ||
| 2330 | |||
| 2331 | my_func! | ||
| 2332 | print i -- imprime 100, i não é afetado | ||
| 2333 | ``` | ||
| 2334 | |||
| 2335 | </YueDisplay> | ||
| 2336 | |||
| 2337 | Múltiplos nomes podem ser separados por vírgulas. Os valores do closure ainda podem ser acessados, apenas não podem ser modificados: | 1152 | Múltiplos nomes podem ser separados por vírgulas. Os valores do closure ainda podem ser acessados, apenas não podem ser modificados: |
| 2338 | 1153 | ||
| 2339 | ```yuescript | 1154 | ```yuescript |
| @@ -2349,23 +1164,6 @@ my_func(22) | |||
| 2349 | print i, k -- estes foram atualizados | 1164 | print i, k -- estes foram atualizados |
| 2350 | ``` | 1165 | ``` |
| 2351 | 1166 | ||
| 2352 | <YueDisplay> | ||
| 2353 | |||
| 2354 | ```yue | ||
| 2355 | tmp = 1213 | ||
| 2356 | i, k = 100, 50 | ||
| 2357 | |||
| 2358 | my_func = (add using k, i) -> | ||
| 2359 | tmp = tmp + add -- uma nova variável local tmp é criada | ||
| 2360 | i += tmp | ||
| 2361 | k += tmp | ||
| 2362 | |||
| 2363 | my_func(22) | ||
| 2364 | print i, k -- estes foram atualizados | ||
| 2365 | ``` | ||
| 2366 | |||
| 2367 | </YueDisplay> | ||
| 2368 | |||
| 2369 | # Uso | 1167 | # Uso |
| 2370 | 1168 | ||
| 2371 | ## Módulo Lua | 1169 | ## Módulo Lua |
| @@ -2534,55 +1332,6 @@ with apple | |||
| 2534 | export 🌛 = "Script da Lua" | 1332 | export 🌛 = "Script da Lua" |
| 2535 | ``` | 1333 | ``` |
| 2536 | 1334 | ||
| 2537 | <YueDisplay> | ||
| 2538 | |||
| 2539 | ```yue | ||
| 2540 | -- sintaxe de importação | ||
| 2541 | import p, to_lua from "yue" | ||
| 2542 | |||
| 2543 | -- literais de objeto | ||
| 2544 | inventory = | ||
| 2545 | equipment: | ||
| 2546 | - "sword" | ||
| 2547 | - "shield" | ||
| 2548 | items: | ||
| 2549 | - name: "potion" | ||
| 2550 | count: 10 | ||
| 2551 | - name: "bread" | ||
| 2552 | count: 3 | ||
| 2553 | |||
| 2554 | -- compreensão de lista | ||
| 2555 | map = (arr, action) -> | ||
| 2556 | [action item for item in *arr] | ||
| 2557 | |||
| 2558 | filter = (arr, cond) -> | ||
| 2559 | [item for item in *arr when cond item] | ||
| 2560 | |||
| 2561 | reduce = (arr, init, action): init -> | ||
| 2562 | init = action init, item for item in *arr | ||
| 2563 | |||
| 2564 | -- operador pipe | ||
| 2565 | [1, 2, 3] | ||
| 2566 | |> map (x) -> x * 2 | ||
| 2567 | |> filter (x) -> x > 4 | ||
| 2568 | |> reduce 0, (a, b) -> a + b | ||
| 2569 | |||
| 2570 | |||
| 2571 | -- manipulação de metatable | ||
| 2572 | apple = | ||
| 2573 | size: 15 | ||
| 2574 | <index>: | ||
| 2575 | color: 0x00ffff | ||
| 2576 | |||
| 2577 | with apple | ||
| 2578 | p .size, .color, .<index> if .<>? | ||
| 2579 | |||
| 2580 | -- sintaxe de exportação estilo js | ||
| 2581 | export 🌛 = "Script da Lua" | ||
| 2582 | ``` | ||
| 2583 | |||
| 2584 | </YueDisplay> | ||
| 2585 | |||
| 2586 | ## Sobre o Dora SSR | 1335 | ## Sobre o Dora SSR |
| 2587 | 1336 | ||
| 2588 | O YueScript está sendo desenvolvido e mantido em conjunto com o motor de jogo open-source [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). Tem sido usado para criar ferramentas do motor, demonstrações de jogos e protótipos, validando suas capacidades em cenários do mundo real e aprimorando a experiência de desenvolvimento do Dora SSR. | 1337 | O YueScript está sendo desenvolvido e mantido em conjunto com o motor de jogo open-source [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). Tem sido usado para criar ferramentas do motor, demonstrações de jogos e protótipos, validando suas capacidades em cenários do mundo real e aprimorando a experiência de desenvolvimento do Dora SSR. |
| @@ -2641,18 +1390,6 @@ else | |||
| 2641 | print "Sem moedas" | 1390 | print "Sem moedas" |
| 2642 | ``` | 1391 | ``` |
| 2643 | 1392 | ||
| 2644 | <YueDisplay> | ||
| 2645 | |||
| 2646 | ```yue | ||
| 2647 | have_coins = false | ||
| 2648 | if have_coins | ||
| 2649 | print "Tem moedas" | ||
| 2650 | else | ||
| 2651 | print "Sem moedas" | ||
| 2652 | ``` | ||
| 2653 | |||
| 2654 | </YueDisplay> | ||
| 2655 | |||
| 2656 | Uma sintaxe curta para instruções únicas também pode ser usada: | 1393 | Uma sintaxe curta para instruções únicas também pode ser usada: |
| 2657 | 1394 | ||
| 2658 | ```yuescript | 1395 | ```yuescript |
| @@ -2660,15 +1397,6 @@ have_coins = false | |||
| 2660 | if have_coins then print "Tem moedas" else print "Sem moedas" | 1397 | if have_coins then print "Tem moedas" else print "Sem moedas" |
| 2661 | ``` | 1398 | ``` |
| 2662 | 1399 | ||
| 2663 | <YueDisplay> | ||
| 2664 | |||
| 2665 | ```yue | ||
| 2666 | have_coins = false | ||
| 2667 | if have_coins then print "Tem moedas" else print "Sem moedas" | ||
| 2668 | ``` | ||
| 2669 | |||
| 2670 | </YueDisplay> | ||
| 2671 | |||
| 2672 | Como instruções if podem ser usadas como expressões, isso também pode ser escrito como: | 1400 | Como instruções if podem ser usadas como expressões, isso também pode ser escrito como: |
| 2673 | 1401 | ||
| 2674 | ```yuescript | 1402 | ```yuescript |
| @@ -2676,15 +1404,6 @@ have_coins = false | |||
| 2676 | print if have_coins then "Tem moedas" else "Sem moedas" | 1404 | print if have_coins then "Tem moedas" else "Sem moedas" |
| 2677 | ``` | 1405 | ``` |
| 2678 | 1406 | ||
| 2679 | <YueDisplay> | ||
| 2680 | |||
| 2681 | ```yue | ||
| 2682 | have_coins = false | ||
| 2683 | print if have_coins then "Tem moedas" else "Sem moedas" | ||
| 2684 | ``` | ||
| 2685 | |||
| 2686 | </YueDisplay> | ||
| 2687 | |||
| 2688 | Condicionais também podem ser usados em instruções de retorno e atribuições: | 1407 | Condicionais também podem ser usados em instruções de retorno e atribuições: |
| 2689 | 1408 | ||
| 2690 | ```yuescript | 1409 | ```yuescript |
| @@ -2702,25 +1421,6 @@ else | |||
| 2702 | print message -- imprime: Sou muito alto | 1421 | print message -- imprime: Sou muito alto |
| 2703 | ``` | 1422 | ``` |
| 2704 | 1423 | ||
| 2705 | <YueDisplay> | ||
| 2706 | |||
| 2707 | ```yue | ||
| 2708 | is_tall = (name) -> | ||
| 2709 | if name == "Rob" | ||
| 2710 | true | ||
| 2711 | else | ||
| 2712 | false | ||
| 2713 | |||
| 2714 | message = if is_tall "Rob" | ||
| 2715 | "Sou muito alto" | ||
| 2716 | else | ||
| 2717 | "Não sou tão alto" | ||
| 2718 | |||
| 2719 | print message -- imprime: Sou muito alto | ||
| 2720 | ``` | ||
| 2721 | |||
| 2722 | </YueDisplay> | ||
| 2723 | |||
| 2724 | O oposto de if é unless: | 1424 | O oposto de if é unless: |
| 2725 | 1425 | ||
| 2726 | ```yuescript | 1426 | ```yuescript |
| @@ -2728,27 +1428,10 @@ unless os.date("%A") == "Monday" | |||
| 2728 | print "não é segunda-feira!" | 1428 | print "não é segunda-feira!" |
| 2729 | ``` | 1429 | ``` |
| 2730 | 1430 | ||
| 2731 | <YueDisplay> | ||
| 2732 | |||
| 2733 | ```yue | ||
| 2734 | unless os.date("%A") == "Monday" | ||
| 2735 | print "não é segunda-feira!" | ||
| 2736 | ``` | ||
| 2737 | |||
| 2738 | </YueDisplay> | ||
| 2739 | |||
| 2740 | ```yuescript | 1431 | ```yuescript |
| 2741 | print "Você tem sorte!" unless math.random! > 0.1 | 1432 | print "Você tem sorte!" unless math.random! > 0.1 |
| 2742 | ``` | 1433 | ``` |
| 2743 | 1434 | ||
| 2744 | <YueDisplay> | ||
| 2745 | |||
| 2746 | ```yue | ||
| 2747 | print "Você tem sorte!" unless math.random! > 0.1 | ||
| 2748 | ``` | ||
| 2749 | |||
| 2750 | </YueDisplay> | ||
| 2751 | |||
| 2752 | ## Em expressão | 1435 | ## Em expressão |
| 2753 | 1436 | ||
| 2754 | Você pode escrever código de verificação de intervalo com uma `in-expression`. | 1437 | Você pode escrever código de verificação de intervalo com uma `in-expression`. |
| @@ -2763,20 +1446,6 @@ if a in list | |||
| 2763 | print "verificando se `a` está na lista" | 1446 | print "verificando se `a` está na lista" |
| 2764 | ``` | 1447 | ``` |
| 2765 | 1448 | ||
| 2766 | <YueDisplay> | ||
| 2767 | |||
| 2768 | ```yue | ||
| 2769 | a = 5 | ||
| 2770 | |||
| 2771 | if a in [1, 3, 5, 7] | ||
| 2772 | print "verificando igualdade com valores discretos" | ||
| 2773 | |||
| 2774 | if a in list | ||
| 2775 | print "verificando se `a` está na lista" | ||
| 2776 | ``` | ||
| 2777 | |||
| 2778 | </YueDisplay> | ||
| 2779 | |||
| 2780 | O operador `in` também pode ser usado com tabelas e suporta a variante `not in` para negação: | 1449 | O operador `in` também pode ser usado com tabelas e suporta a variante `not in` para negação: |
| 2781 | 1450 | ||
| 2782 | ```yuescript | 1451 | ```yuescript |
| @@ -2790,21 +1459,6 @@ not_exist = item not in list | |||
| 2790 | check = -> value not in table | 1459 | check = -> value not in table |
| 2791 | ``` | 1460 | ``` |
| 2792 | 1461 | ||
| 2793 | <YueDisplay> | ||
| 2794 | |||
| 2795 | ```yue | ||
| 2796 | has = "foo" in {"bar", "foo"} | ||
| 2797 | |||
| 2798 | if a in {1, 2, 3} | ||
| 2799 | print "a está na tabela" | ||
| 2800 | |||
| 2801 | not_exist = item not in list | ||
| 2802 | |||
| 2803 | check = -> value not in table | ||
| 2804 | ``` | ||
| 2805 | |||
| 2806 | </YueDisplay> | ||
| 2807 | |||
| 2808 | Uma lista ou tabela de único elemento verifica igualdade com esse elemento: | 1462 | Uma lista ou tabela de único elemento verifica igualdade com esse elemento: |
| 2809 | 1463 | ||
| 2810 | ```yuescript | 1464 | ```yuescript |
| @@ -2819,22 +1473,6 @@ with tb | |||
| 2819 | c = a in [1] | 1473 | c = a in [1] |
| 2820 | ``` | 1474 | ``` |
| 2821 | 1475 | ||
| 2822 | <YueDisplay> | ||
| 2823 | |||
| 2824 | ```yue | ||
| 2825 | -- [1,] verifica se valor == 1 | ||
| 2826 | c = a in [1,] | ||
| 2827 | |||
| 2828 | -- {1} também verifica se valor == 1 | ||
| 2829 | c = a in {1} | ||
| 2830 | |||
| 2831 | -- Sem vírgula, [1] é acesso por índice (tb[1]) | ||
| 2832 | with tb | ||
| 2833 | c = a in [1] | ||
| 2834 | ``` | ||
| 2835 | |||
| 2836 | </YueDisplay> | ||
| 2837 | |||
| 2838 | # Loop For | 1476 | # Loop For |
| 2839 | 1477 | ||
| 2840 | Existem duas formas de loop for, assim como no Lua. Uma numérica e uma genérica: | 1478 | Existem duas formas de loop for, assim como no Lua. Uma numérica e uma genérica: |
| @@ -2850,21 +1488,6 @@ for key, value in pairs object | |||
| 2850 | print key, value | 1488 | print key, value |
| 2851 | ``` | 1489 | ``` |
| 2852 | 1490 | ||
| 2853 | <YueDisplay> | ||
| 2854 | |||
| 2855 | ```yue | ||
| 2856 | for i = 10, 20 | ||
| 2857 | print i | ||
| 2858 | |||
| 2859 | for k = 1, 15, 2 -- um passo opcional fornecido | ||
| 2860 | print k | ||
| 2861 | |||
| 2862 | for key, value in pairs object | ||
| 2863 | print key, value | ||
| 2864 | ``` | ||
| 2865 | |||
| 2866 | </YueDisplay> | ||
| 2867 | |||
| 2868 | Os operadores de slicing e **\*** podem ser usados, assim como com compreensões: | 1491 | Os operadores de slicing e **\*** podem ser usados, assim como com compreensões: |
| 2869 | 1492 | ||
| 2870 | ```yuescript | 1493 | ```yuescript |
| @@ -2872,15 +1495,6 @@ for item in *items[2, 4] | |||
| 2872 | print item | 1495 | print item |
| 2873 | ``` | 1496 | ``` |
| 2874 | 1497 | ||
| 2875 | <YueDisplay> | ||
| 2876 | |||
| 2877 | ```yue | ||
| 2878 | for item in *items[2, 4] | ||
| 2879 | print item | ||
| 2880 | ``` | ||
| 2881 | |||
| 2882 | </YueDisplay> | ||
| 2883 | |||
| 2884 | Uma sintaxe mais curta também está disponível para todas as variações quando o corpo é apenas uma linha: | 1498 | Uma sintaxe mais curta também está disponível para todas as variações quando o corpo é apenas uma linha: |
| 2885 | 1499 | ||
| 2886 | ```yuescript | 1500 | ```yuescript |
| @@ -2889,16 +1503,6 @@ for item in *items do print item | |||
| 2889 | for j = 1, 10, 3 do print j | 1503 | for j = 1, 10, 3 do print j |
| 2890 | ``` | 1504 | ``` |
| 2891 | 1505 | ||
| 2892 | <YueDisplay> | ||
| 2893 | |||
| 2894 | ```yue | ||
| 2895 | for item in *items do print item | ||
| 2896 | |||
| 2897 | for j = 1, 10, 3 do print j | ||
| 2898 | ``` | ||
| 2899 | |||
| 2900 | </YueDisplay> | ||
| 2901 | |||
| 2902 | Um loop for também pode ser usado como expressão. A última instrução no corpo do loop for é convertida em expressão e anexada a uma tabela array acumuladora. | 1506 | Um loop for também pode ser usado como expressão. A última instrução no corpo do loop for é convertida em expressão e anexada a uma tabela array acumuladora. |
| 2903 | 1507 | ||
| 2904 | Dobrando cada número par: | 1508 | Dobrando cada número par: |
| @@ -2911,18 +1515,6 @@ doubled_evens = for i = 1, 20 | |||
| 2911 | i | 1515 | i |
| 2912 | ``` | 1516 | ``` |
| 2913 | 1517 | ||
| 2914 | <YueDisplay> | ||
| 2915 | |||
| 2916 | ```yue | ||
| 2917 | doubled_evens = for i = 1, 20 | ||
| 2918 | if i % 2 == 0 | ||
| 2919 | i * 2 | ||
| 2920 | else | ||
| 2921 | i | ||
| 2922 | ``` | ||
| 2923 | |||
| 2924 | </YueDisplay> | ||
| 2925 | |||
| 2926 | Além disso, os loops for suportam break com valores de retorno, permitindo que o próprio loop seja usado como expressão que sai antecipadamente com um resultado significativo. Expressões `for` suportam `break` com múltiplos valores. | 1518 | Além disso, os loops for suportam break com valores de retorno, permitindo que o próprio loop seja usado como expressão que sai antecipadamente com um resultado significativo. Expressões `for` suportam `break` com múltiplos valores. |
| 2927 | 1519 | ||
| 2928 | Por exemplo, para encontrar o primeiro número maior que 10: | 1520 | Por exemplo, para encontrar o primeiro número maior que 10: |
| @@ -2932,15 +1524,6 @@ first_large = for n in *numbers | |||
| 2932 | break n if n > 10 | 1524 | break n if n > 10 |
| 2933 | ``` | 1525 | ``` |
| 2934 | 1526 | ||
| 2935 | <YueDisplay> | ||
| 2936 | |||
| 2937 | ```yue | ||
| 2938 | first_large = for n in *numbers | ||
| 2939 | break n if n > 10 | ||
| 2940 | ``` | ||
| 2941 | |||
| 2942 | </YueDisplay> | ||
| 2943 | |||
| 2944 | Esta sintaxe de break-com-valor permite padrões concisos e expressivos de busca ou saída antecipada diretamente em expressões de loop. | 1527 | Esta sintaxe de break-com-valor permite padrões concisos e expressivos de busca ou saída antecipada diretamente em expressões de loop. |
| 2945 | 1528 | ||
| 2946 | ```yuescript | 1529 | ```yuescript |
| @@ -2948,15 +1531,6 @@ key, score = for k, v in pairs data | |||
| 2948 | break k, v * 10 if k == "target" | 1531 | break k, v * 10 if k == "target" |
| 2949 | ``` | 1532 | ``` |
| 2950 | 1533 | ||
| 2951 | <YueDisplay> | ||
| 2952 | |||
| 2953 | ```yue | ||
| 2954 | key, score = for k, v in pairs data | ||
| 2955 | break k, v * 10 if k == "target" | ||
| 2956 | ``` | ||
| 2957 | |||
| 2958 | </YueDisplay> | ||
| 2959 | |||
| 2960 | Você também pode filtrar valores combinando a expressão do loop for com a instrução continue. | 1534 | Você também pode filtrar valores combinando a expressão do loop for com a instrução continue. |
| 2961 | 1535 | ||
| 2962 | Loops for no final do corpo de uma função não são acumulados em uma tabela para valor de retorno (em vez disso, a função retornará nil). Uma instrução return explícita pode ser usada, ou o loop pode ser convertido em compreensão de lista. | 1536 | Loops for no final do corpo de uma função não são acumulados em uma tabela para valor de retorno (em vez disso, a função retornará nil). Uma instrução return explícita pode ser usada, ou o loop pode ser convertido em compreensão de lista. |
| @@ -2969,18 +1543,6 @@ print func_a! -- imprime nil | |||
| 2969 | print func_b! -- imprime objeto table | 1543 | print func_b! -- imprime objeto table |
| 2970 | ``` | 1544 | ``` |
| 2971 | 1545 | ||
| 2972 | <YueDisplay> | ||
| 2973 | |||
| 2974 | ```yue | ||
| 2975 | func_a = -> for i = 1, 10 do print i | ||
| 2976 | func_b = -> return for i = 1, 10 do i | ||
| 2977 | |||
| 2978 | print func_a! -- imprime nil | ||
| 2979 | print func_b! -- imprime objeto table | ||
| 2980 | ``` | ||
| 2981 | |||
| 2982 | </YueDisplay> | ||
| 2983 | |||
| 2984 | Isso é feito para evitar a criação desnecessária de tabelas para funções que não precisam retornar os resultados do loop. | 1546 | Isso é feito para evitar a criação desnecessária de tabelas para funções que não precisam retornar os resultados do loop. |
| 2985 | 1547 | ||
| 2986 | # Continue | 1548 | # Continue |
| @@ -2995,18 +1557,6 @@ while i < 10 | |||
| 2995 | print i | 1557 | print i |
| 2996 | ``` | 1558 | ``` |
| 2997 | 1559 | ||
| 2998 | <YueDisplay> | ||
| 2999 | |||
| 3000 | ```yue | ||
| 3001 | i = 0 | ||
| 3002 | while i < 10 | ||
| 3003 | i += 1 | ||
| 3004 | continue if i % 2 == 0 | ||
| 3005 | print i | ||
| 3006 | ``` | ||
| 3007 | |||
| 3008 | </YueDisplay> | ||
| 3009 | |||
| 3010 | continue também pode ser usado com expressões de loop para impedir que essa iteração seja acumulada no resultado. Este exemplo filtra a tabela array para apenas números pares: | 1560 | continue também pode ser usado com expressões de loop para impedir que essa iteração seja acumulada no resultado. Este exemplo filtra a tabela array para apenas números pares: |
| 3011 | 1561 | ||
| 3012 | ```yuescript | 1562 | ```yuescript |
| @@ -3016,17 +1566,6 @@ odds = for x in *my_numbers | |||
| 3016 | x | 1566 | x |
| 3017 | ``` | 1567 | ``` |
| 3018 | 1568 | ||
| 3019 | <YueDisplay> | ||
| 3020 | |||
| 3021 | ```yue | ||
| 3022 | my_numbers = [1, 2, 3, 4, 5, 6] | ||
| 3023 | odds = for x in *my_numbers | ||
| 3024 | continue if x % 2 == 1 | ||
| 3025 | x | ||
| 3026 | ``` | ||
| 3027 | |||
| 3028 | </YueDisplay> | ||
| 3029 | |||
| 3030 | # Switch | 1569 | # Switch |
| 3031 | 1570 | ||
| 3032 | A instrução switch é uma forma abreviada de escrever uma série de instruções if que verificam o mesmo valor. Observe que o valor é avaliado apenas uma vez. Como as instruções if, os switches podem ter um bloco else para tratar ausência de correspondências. A comparação é feita com o operador ==. Na instrução switch, você também pode usar expressão de atribuição para armazenar valor de variável temporária. | 1571 | A instrução switch é uma forma abreviada de escrever uma série de instruções if que verificam o mesmo valor. Observe que o valor é avaliado apenas uma vez. Como as instruções if, os switches podem ter um bloco else para tratar ausência de correspondências. A comparação é feita com o operador ==. Na instrução switch, você também pode usar expressão de atribuição para armazenar valor de variável temporária. |
| @@ -3041,20 +1580,6 @@ switch name := "Dan" | |||
| 3041 | print "Não sei quem você é com o nome #{name}" | 1580 | print "Não sei quem você é com o nome #{name}" |
| 3042 | ``` | 1581 | ``` |
| 3043 | 1582 | ||
| 3044 | <YueDisplay> | ||
| 3045 | |||
| 3046 | ```yue | ||
| 3047 | switch name := "Dan" | ||
| 3048 | when "Robert" | ||
| 3049 | print "Você é Robert" | ||
| 3050 | when "Dan", "Daniel" | ||
| 3051 | print "Seu nome é Dan" | ||
| 3052 | else | ||
| 3053 | print "Não sei quem você é com o nome #{name}" | ||
| 3054 | ``` | ||
| 3055 | |||
| 3056 | </YueDisplay> | ||
| 3057 | |||
| 3058 | Uma cláusula when de um switch pode corresponder a múltiplos valores listando-os separados por vírgula. | 1583 | Uma cláusula when de um switch pode corresponder a múltiplos valores listando-os separados por vírgula. |
| 3059 | 1584 | ||
| 3060 | Os switches também podem ser usados como expressões; aqui podemos atribuir o resultado do switch a uma variável: | 1585 | Os switches também podem ser usados como expressões; aqui podemos atribuir o resultado do switch a uma variável: |
| @@ -3070,21 +1595,6 @@ next_number = switch b | |||
| 3070 | error "não consigo contar tão alto!" | 1595 | error "não consigo contar tão alto!" |
| 3071 | ``` | 1596 | ``` |
| 3072 | 1597 | ||
| 3073 | <YueDisplay> | ||
| 3074 | |||
| 3075 | ```yue | ||
| 3076 | b = 1 | ||
| 3077 | next_number = switch b | ||
| 3078 | when 1 | ||
| 3079 | 2 | ||
| 3080 | when 2 | ||
| 3081 | 3 | ||
| 3082 | else | ||
| 3083 | error "não consigo contar tão alto!" | ||
| 3084 | ``` | ||
| 3085 | |||
| 3086 | </YueDisplay> | ||
| 3087 | |||
| 3088 | Podemos usar a palavra-chave then para escrever o bloco when de um switch em uma única linha. Nenhuma palavra-chave extra é necessária para escrever o bloco else em uma única linha. | 1598 | Podemos usar a palavra-chave then para escrever o bloco when de um switch em uma única linha. Nenhuma palavra-chave extra é necessária para escrever o bloco else em uma única linha. |
| 3089 | 1599 | ||
| 3090 | ```yuescript | 1600 | ```yuescript |
| @@ -3094,17 +1604,6 @@ msg = switch math.random(1, 5) | |||
| 3094 | else "não tão sortudo" | 1604 | else "não tão sortudo" |
| 3095 | ``` | 1605 | ``` |
| 3096 | 1606 | ||
| 3097 | <YueDisplay> | ||
| 3098 | |||
| 3099 | ```yue | ||
| 3100 | msg = switch math.random(1, 5) | ||
| 3101 | when 1 then "você tem sorte" | ||
| 3102 | when 2 then "você quase tem sorte" | ||
| 3103 | else "não tão sortudo" | ||
| 3104 | ``` | ||
| 3105 | |||
| 3106 | </YueDisplay> | ||
| 3107 | |||
| 3108 | Se você quiser escrever código com uma indentação a menos ao escrever uma instrução switch, pode colocar a primeira cláusula when na linha de início da instrução, e então todas as outras cláusulas podem ser escritas com uma indentação a menos. | 1607 | Se você quiser escrever código com uma indentação a menos ao escrever uma instrução switch, pode colocar a primeira cláusula when na linha de início da instrução, e então todas as outras cláusulas podem ser escritas com uma indentação a menos. |
| 3109 | 1608 | ||
| 3110 | ```yuescript | 1609 | ```yuescript |
| @@ -3120,23 +1619,6 @@ else | |||
| 3120 | print "não tão sortudo" | 1619 | print "não tão sortudo" |
| 3121 | ``` | 1620 | ``` |
| 3122 | 1621 | ||
| 3123 | <YueDisplay> | ||
| 3124 | |||
| 3125 | ```yue | ||
| 3126 | switch math.random(1, 5) | ||
| 3127 | when 1 | ||
| 3128 | print "você tem sorte" -- duas indentações | ||
| 3129 | else | ||
| 3130 | print "não tão sortudo" | ||
| 3131 | |||
| 3132 | switch math.random(1, 5) when 1 | ||
| 3133 | print "você tem sorte" -- uma indentação | ||
| 3134 | else | ||
| 3135 | print "não tão sortudo" | ||
| 3136 | ``` | ||
| 3137 | |||
| 3138 | </YueDisplay> | ||
| 3139 | |||
| 3140 | Vale notar a ordem da expressão de comparação do case. A expressão do case está no lado esquerdo. Isso pode ser útil se a expressão do case quiser sobrescrever como a comparação é feita definindo um metamétodo eq. | 1622 | Vale notar a ordem da expressão de comparação do case. A expressão do case está no lado esquerdo. Isso pode ser útil se a expressão do case quiser sobrescrever como a comparação é feita definindo um metamétodo eq. |
| 3141 | 1623 | ||
| 3142 | ## Correspondência de tabela | 1624 | ## Correspondência de tabela |
| @@ -3158,25 +1640,6 @@ for item in *items | |||
| 3158 | print "tamanho #{width}, #{height}" | 1640 | print "tamanho #{width}, #{height}" |
| 3159 | ``` | 1641 | ``` |
| 3160 | 1642 | ||
| 3161 | <YueDisplay> | ||
| 3162 | |||
| 3163 | ```yue | ||
| 3164 | items = | ||
| 3165 | * x: 100 | ||
| 3166 | y: 200 | ||
| 3167 | * width: 300 | ||
| 3168 | height: 400 | ||
| 3169 | |||
| 3170 | for item in *items | ||
| 3171 | switch item | ||
| 3172 | when :x, :y | ||
| 3173 | print "Vec2 #{x}, #{y}" | ||
| 3174 | when :width, :height | ||
| 3175 | print "tamanho #{width}, #{height}" | ||
| 3176 | ``` | ||
| 3177 | |||
| 3178 | </YueDisplay> | ||
| 3179 | |||
| 3180 | Você pode usar valores padrão para opcionalmente desestruturar a tabela para alguns campos. | 1643 | Você pode usar valores padrão para opcionalmente desestruturar a tabela para alguns campos. |
| 3181 | 1644 | ||
| 3182 | ```yuescript | 1645 | ```yuescript |
| @@ -3189,20 +1652,6 @@ switch item | |||
| 3189 | print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará | 1652 | print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará |
| 3190 | ``` | 1653 | ``` |
| 3191 | 1654 | ||
| 3192 | <YueDisplay> | ||
| 3193 | |||
| 3194 | ```yue | ||
| 3195 | item = {} | ||
| 3196 | |||
| 3197 | {pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos') | ||
| 3198 | |||
| 3199 | switch item | ||
| 3200 | when {pos: {:x = 50, :y = 200}} | ||
| 3201 | print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará | ||
| 3202 | ``` | ||
| 3203 | |||
| 3204 | </YueDisplay> | ||
| 3205 | |||
| 3206 | Você também pode corresponder contra elementos de array, campos de tabela, e até estruturas aninhadas com literais de array ou tabela. | 1655 | Você também pode corresponder contra elementos de array, campos de tabela, e até estruturas aninhadas com literais de array ou tabela. |
| 3207 | 1656 | ||
| 3208 | Corresponder contra elementos de array. | 1657 | Corresponder contra elementos de array. |
| @@ -3217,20 +1666,6 @@ switch tb | |||
| 3217 | print "1, 2, #{b}" | 1666 | print "1, 2, #{b}" |
| 3218 | ``` | 1667 | ``` |
| 3219 | 1668 | ||
| 3220 | <YueDisplay> | ||
| 3221 | |||
| 3222 | ```yue | ||
| 3223 | switch tb | ||
| 3224 | when [1, 2, 3] | ||
| 3225 | print "1, 2, 3" | ||
| 3226 | when [1, b, 3] | ||
| 3227 | print "1, #{b}, 3" | ||
| 3228 | when [1, 2, b = 3] -- b tem valor padrão | ||
| 3229 | print "1, 2, #{b}" | ||
| 3230 | ``` | ||
| 3231 | |||
| 3232 | </YueDisplay> | ||
| 3233 | |||
| 3234 | Corresponder contra campos de tabela com desestruturação. | 1669 | Corresponder contra campos de tabela com desestruturação. |
| 3235 | 1670 | ||
| 3236 | ```yuescript | 1671 | ```yuescript |
| @@ -3243,20 +1678,6 @@ switch tb | |||
| 3243 | print "inválido" | 1678 | print "inválido" |
| 3244 | ``` | 1679 | ``` |
| 3245 | 1680 | ||
| 3246 | <YueDisplay> | ||
| 3247 | |||
| 3248 | ```yue | ||
| 3249 | switch tb | ||
| 3250 | when success: true, :result | ||
| 3251 | print "sucesso", result | ||
| 3252 | when success: false | ||
| 3253 | print "falhou", result | ||
| 3254 | else | ||
| 3255 | print "inválido" | ||
| 3256 | ``` | ||
| 3257 | |||
| 3258 | </YueDisplay> | ||
| 3259 | |||
| 3260 | Corresponder contra estruturas de tabela aninhadas. | 1681 | Corresponder contra estruturas de tabela aninhadas. |
| 3261 | 1682 | ||
| 3262 | ```yuescript | 1683 | ```yuescript |
| @@ -3269,20 +1690,6 @@ switch tb | |||
| 3269 | print "inválido" | 1690 | print "inválido" |
| 3270 | ``` | 1691 | ``` |
| 3271 | 1692 | ||
| 3272 | <YueDisplay> | ||
| 3273 | |||
| 3274 | ```yue | ||
| 3275 | switch tb | ||
| 3276 | when data: {type: "success", :content} | ||
| 3277 | print "sucesso", content | ||
| 3278 | when data: {type: "error", :content} | ||
| 3279 | print "erro", content | ||
| 3280 | else | ||
| 3281 | print "inválido" | ||
| 3282 | ``` | ||
| 3283 | |||
| 3284 | </YueDisplay> | ||
| 3285 | |||
| 3286 | Corresponder contra array de tabelas. | 1693 | Corresponder contra array de tabelas. |
| 3287 | 1694 | ||
| 3288 | ```yuescript | 1695 | ```yuescript |
| @@ -3296,21 +1703,6 @@ switch tb | |||
| 3296 | print "correspondido", fourth | 1703 | print "correspondido", fourth |
| 3297 | ``` | 1704 | ``` |
| 3298 | 1705 | ||
| 3299 | <YueDisplay> | ||
| 3300 | |||
| 3301 | ```yue | ||
| 3302 | switch tb | ||
| 3303 | when [ | ||
| 3304 | {a: 1, b: 2} | ||
| 3305 | {a: 3, b: 4} | ||
| 3306 | {a: 5, b: 6} | ||
| 3307 | fourth | ||
| 3308 | ] | ||
| 3309 | print "correspondido", fourth | ||
| 3310 | ``` | ||
| 3311 | |||
| 3312 | </YueDisplay> | ||
| 3313 | |||
| 3314 | Corresponder contra uma lista e capturar um intervalo de elementos. | 1706 | Corresponder contra uma lista e capturar um intervalo de elementos. |
| 3315 | 1707 | ||
| 3316 | ```yuescript | 1708 | ```yuescript |
| @@ -3322,19 +1714,6 @@ switch segments | |||
| 3322 | print "Ação:", action -- imprime: "view" | 1714 | print "Ação:", action -- imprime: "view" |
| 3323 | ``` | 1715 | ``` |
| 3324 | 1716 | ||
| 3325 | <YueDisplay> | ||
| 3326 | |||
| 3327 | ```yue | ||
| 3328 | segments = ["admin", "users", "logs", "view"] | ||
| 3329 | switch segments | ||
| 3330 | when [...groups, resource, action] | ||
| 3331 | print "Grupo:", groups -- imprime: {"admin", "users"} | ||
| 3332 | print "Recurso:", resource -- imprime: "logs" | ||
| 3333 | print "Ação:", action -- imprime: "view" | ||
| 3334 | ``` | ||
| 3335 | |||
| 3336 | </YueDisplay> | ||
| 3337 | |||
| 3338 | # Loop While | 1717 | # Loop While |
| 3339 | 1718 | ||
| 3340 | O loop while também vem em quatro variações: | 1719 | O loop while também vem em quatro variações: |
| @@ -3348,19 +1727,6 @@ while i > 0 | |||
| 3348 | while running == true do my_function! | 1727 | while running == true do my_function! |
| 3349 | ``` | 1728 | ``` |
| 3350 | 1729 | ||
| 3351 | <YueDisplay> | ||
| 3352 | |||
| 3353 | ```yue | ||
| 3354 | i = 10 | ||
| 3355 | while i > 0 | ||
| 3356 | print i | ||
| 3357 | i -= 1 | ||
| 3358 | |||
| 3359 | while running == true do my_function! | ||
| 3360 | ``` | ||
| 3361 | |||
| 3362 | </YueDisplay> | ||
| 3363 | |||
| 3364 | ```yuescript | 1730 | ```yuescript |
| 3365 | i = 10 | 1731 | i = 10 |
| 3366 | until i == 0 | 1732 | until i == 0 |
| @@ -3370,18 +1736,6 @@ until i == 0 | |||
| 3370 | until running == false do my_function! | 1736 | until running == false do my_function! |
| 3371 | ``` | 1737 | ``` |
| 3372 | 1738 | ||
| 3373 | <YueDisplay> | ||
| 3374 | |||
| 3375 | ```yue | ||
| 3376 | i = 10 | ||
| 3377 | until i == 0 | ||
| 3378 | print i | ||
| 3379 | i -= 1 | ||
| 3380 | until running == false do my_function! | ||
| 3381 | ``` | ||
| 3382 | |||
| 3383 | </YueDisplay> | ||
| 3384 | |||
| 3385 | Como os loops for, o loop while também pode ser usado como expressão. Expressões `while` e `until` suportam `break` com múltiplos valores. | 1739 | Como os loops for, o loop while também pode ser usado como expressão. Expressões `while` e `until` suportam `break` com múltiplos valores. |
| 3386 | 1740 | ||
| 3387 | ```yuescript | 1741 | ```yuescript |
| @@ -3390,16 +1744,6 @@ value, doubled = while true | |||
| 3390 | break n, n * 2 if n > 10 | 1744 | break n, n * 2 if n > 10 |
| 3391 | ``` | 1745 | ``` |
| 3392 | 1746 | ||
| 3393 | <YueDisplay> | ||
| 3394 | |||
| 3395 | ```yue | ||
| 3396 | value, doubled = while true | ||
| 3397 | n = get_next! | ||
| 3398 | break n, n * 2 if n > 10 | ||
| 3399 | ``` | ||
| 3400 | |||
| 3401 | </YueDisplay> | ||
| 3402 | |||
| 3403 | Além disso, para uma função retornar o valor acumulado de um loop while, a instrução deve ser explicitamente retornada. | 1747 | Além disso, para uma função retornar o valor acumulado de um loop while, a instrução deve ser explicitamente retornada. |
| 3404 | 1748 | ||
| 3405 | ## Loop Repeat | 1749 | ## Loop Repeat |
| @@ -3414,18 +1758,6 @@ repeat | |||
| 3414 | until i == 0 | 1758 | until i == 0 |
| 3415 | ``` | 1759 | ``` |
| 3416 | 1760 | ||
| 3417 | <YueDisplay> | ||
| 3418 | |||
| 3419 | ```yue | ||
| 3420 | i = 10 | ||
| 3421 | repeat | ||
| 3422 | print i | ||
| 3423 | i -= 1 | ||
| 3424 | until i == 0 | ||
| 3425 | ``` | ||
| 3426 | |||
| 3427 | </YueDisplay> | ||
| 3428 | |||
| 3429 | Expressões `repeat` também suportam `break` com múltiplos valores: | 1761 | Expressões `repeat` também suportam `break` com múltiplos valores: |
| 3430 | 1762 | ||
| 3431 | ```yuescript | 1763 | ```yuescript |
| @@ -3436,18 +1768,6 @@ value, scaled = repeat | |||
| 3436 | until false | 1768 | until false |
| 3437 | ``` | 1769 | ``` |
| 3438 | 1770 | ||
| 3439 | <YueDisplay> | ||
| 3440 | |||
| 3441 | ```yue | ||
| 3442 | i = 1 | ||
| 3443 | value, scaled = repeat | ||
| 3444 | break i, i * 100 if i > 3 | ||
| 3445 | i += 1 | ||
| 3446 | until false | ||
| 3447 | ``` | ||
| 3448 | |||
| 3449 | </YueDisplay> | ||
| 3450 | |||
| 3451 | # Stubs de função | 1771 | # Stubs de função |
| 3452 | 1772 | ||
| 3453 | É comum passar uma função de um objeto como valor, por exemplo, passando um método de instância para uma função como callback. Se a função espera o objeto em que está operando como primeiro argumento, então você deve de alguma forma empacotar esse objeto com a função para que ela possa ser chamada corretamente. | 1773 | É comum passar uma função de um objeto como valor, por exemplo, passando um método de instância para uma função como callback. Se a função espera o objeto em que está operando como primeiro argumento, então você deve de alguma forma empacotar esse objeto com a função para que ela possa ser chamada corretamente. |
| @@ -3475,29 +1795,6 @@ run_callback my_object.write | |||
| 3475 | run_callback my_object\write | 1795 | run_callback my_object\write |
| 3476 | ``` | 1796 | ``` |
| 3477 | 1797 | ||
| 3478 | <YueDisplay> | ||
| 3479 | |||
| 3480 | ```yue | ||
| 3481 | my_object = { | ||
| 3482 | value: 1000 | ||
| 3483 | write: => print "the value:", @value | ||
| 3484 | } | ||
| 3485 | |||
| 3486 | run_callback = (func) -> | ||
| 3487 | print "running callback..." | ||
| 3488 | func! | ||
| 3489 | |||
| 3490 | -- isso não funcionará: | ||
| 3491 | -- a função não tem referência a my_object | ||
| 3492 | run_callback my_object.write | ||
| 3493 | |||
| 3494 | -- sintaxe de function stub | ||
| 3495 | -- nos permite empacotar o objeto em uma nova função | ||
| 3496 | run_callback my_object\write | ||
| 3497 | ``` | ||
| 3498 | |||
| 3499 | </YueDisplay> | ||
| 3500 | |||
| 3501 | # Backcalls | 1798 | # Backcalls |
| 3502 | 1799 | ||
| 3503 | Backcalls são usados para desaninhar callbacks. Eles são definidos usando setas apontando para a esquerda como o último parâmetro, preenchendo por padrão uma chamada de função. Toda a sintaxe é basicamente a mesma das funções seta regulares, exceto que apenas aponta para o outro lado e o corpo da função não requer indentação. | 1800 | Backcalls são usados para desaninhar callbacks. Eles são definidos usando setas apontando para a esquerda como o último parâmetro, preenchendo por padrão uma chamada de função. Toda a sintaxe é basicamente a mesma das funções seta regulares, exceto que apenas aponta para o outro lado e o corpo da função não requer indentação. |
| @@ -3507,15 +1804,6 @@ x <- f | |||
| 3507 | print "hello" .. x | 1804 | print "hello" .. x |
| 3508 | ``` | 1805 | ``` |
| 3509 | 1806 | ||
| 3510 | <YueDisplay> | ||
| 3511 | |||
| 3512 | ```yue | ||
| 3513 | x <- f | ||
| 3514 | print "hello" .. x | ||
| 3515 | ``` | ||
| 3516 | |||
| 3517 | </YueDisplay> | ||
| 3518 | |||
| 3519 | Funções seta "fat" também estão disponíveis. | 1807 | Funções seta "fat" também estão disponíveis. |
| 3520 | 1808 | ||
| 3521 | ```yuescript | 1809 | ```yuescript |
| @@ -3523,15 +1811,6 @@ Funções seta "fat" também estão disponíveis. | |||
| 3523 | print @value | 1811 | print @value |
| 3524 | ``` | 1812 | ``` |
| 3525 | 1813 | ||
| 3526 | <YueDisplay> | ||
| 3527 | |||
| 3528 | ```yue | ||
| 3529 | <= f | ||
| 3530 | print @value | ||
| 3531 | ``` | ||
| 3532 | |||
| 3533 | </YueDisplay> | ||
| 3534 | |||
| 3535 | Você pode especificar um placeholder para onde deseja que a função backcall vá como parâmetro. | 1814 | Você pode especificar um placeholder para onde deseja que a função backcall vá como parâmetro. |
| 3536 | 1815 | ||
| 3537 | ```yuescript | 1816 | ```yuescript |
| @@ -3539,15 +1818,6 @@ Você pode especificar um placeholder para onde deseja que a função backcall v | |||
| 3539 | x * 2 | 1818 | x * 2 |
| 3540 | ``` | 1819 | ``` |
| 3541 | 1820 | ||
| 3542 | <YueDisplay> | ||
| 3543 | |||
| 3544 | ```yue | ||
| 3545 | (x) <- map _, [1, 2, 3] | ||
| 3546 | x * 2 | ||
| 3547 | ``` | ||
| 3548 | |||
| 3549 | </YueDisplay> | ||
| 3550 | |||
| 3551 | Se você desejar ter mais código após seus backcalls, pode colocá-los em uma instrução do. E os parênteses podem ser omitidos com funções seta não-fat. | 1821 | Se você desejar ter mais código após seus backcalls, pode colocá-los em uma instrução do. E os parênteses podem ser omitidos com funções seta não-fat. |
| 3552 | 1822 | ||
| 3553 | ```yuescript | 1823 | ```yuescript |
| @@ -3559,19 +1829,6 @@ result, msg = do | |||
| 3559 | print result, msg | 1829 | print result, msg |
| 3560 | ``` | 1830 | ``` |
| 3561 | 1831 | ||
| 3562 | <YueDisplay> | ||
| 3563 | |||
| 3564 | ```yue | ||
| 3565 | result, msg = do | ||
| 3566 | data <- readAsync "filename.txt" | ||
| 3567 | print data | ||
| 3568 | info <- processAsync data | ||
| 3569 | check info | ||
| 3570 | print result, msg | ||
| 3571 | ``` | ||
| 3572 | |||
| 3573 | </YueDisplay> | ||
| 3574 | |||
| 3575 | # Literais de função | 1832 | # Literais de função |
| 3576 | 1833 | ||
| 3577 | Todas as funções são criadas usando uma expressão de função. Uma função simples é denotada usando a seta: **->**. | 1834 | Todas as funções são criadas usando uma expressão de função. Uma função simples é denotada usando a seta: **->**. |
| @@ -3581,15 +1838,6 @@ my_function = -> | |||
| 3581 | my_function() -- chama a função vazia | 1838 | my_function() -- chama a função vazia |
| 3582 | ``` | 1839 | ``` |
| 3583 | 1840 | ||
| 3584 | <YueDisplay> | ||
| 3585 | |||
| 3586 | ```yue | ||
| 3587 | my_function = -> | ||
| 3588 | my_function() -- chama a função vazia | ||
| 3589 | ``` | ||
| 3590 | |||
| 3591 | </YueDisplay> | ||
| 3592 | |||
| 3593 | O corpo da função pode ser uma instrução colocada diretamente após a seta, ou pode ser uma série de instruções indentadas nas linhas seguintes: | 1841 | O corpo da função pode ser uma instrução colocada diretamente após a seta, ou pode ser uma série de instruções indentadas nas linhas seguintes: |
| 3594 | 1842 | ||
| 3595 | ```yuescript | 1843 | ```yuescript |
| @@ -3600,18 +1848,6 @@ func_b = -> | |||
| 3600 | print "The value:", value | 1848 | print "The value:", value |
| 3601 | ``` | 1849 | ``` |
| 3602 | 1850 | ||
| 3603 | <YueDisplay> | ||
| 3604 | |||
| 3605 | ```yue | ||
| 3606 | func_a = -> print "hello world" | ||
| 3607 | |||
| 3608 | func_b = -> | ||
| 3609 | value = 100 | ||
| 3610 | print "The value:", value | ||
| 3611 | ``` | ||
| 3612 | |||
| 3613 | </YueDisplay> | ||
| 3614 | |||
| 3615 | Se uma função não tem argumentos, ela pode ser chamada usando o operador !, em vez de parênteses vazios. A invocação ! é a forma preferida de chamar funções sem argumentos. | 1851 | Se uma função não tem argumentos, ela pode ser chamada usando o operador !, em vez de parênteses vazios. A invocação ! é a forma preferida de chamar funções sem argumentos. |
| 3616 | 1852 | ||
| 3617 | ```yuescript | 1853 | ```yuescript |
| @@ -3619,29 +1855,12 @@ func_a! | |||
| 3619 | func_b() | 1855 | func_b() |
| 3620 | ``` | 1856 | ``` |
| 3621 | 1857 | ||
| 3622 | <YueDisplay> | ||
| 3623 | |||
| 3624 | ```yue | ||
| 3625 | func_a! | ||
| 3626 | func_b() | ||
| 3627 | ``` | ||
| 3628 | |||
| 3629 | </YueDisplay> | ||
| 3630 | |||
| 3631 | Funções com argumentos podem ser criadas precedendo a seta com uma lista de nomes de argumentos entre parênteses: | 1858 | Funções com argumentos podem ser criadas precedendo a seta com uma lista de nomes de argumentos entre parênteses: |
| 3632 | 1859 | ||
| 3633 | ```yuescript | 1860 | ```yuescript |
| 3634 | sum = (x, y) -> print "sum", x + y | 1861 | sum = (x, y) -> print "sum", x + y |
| 3635 | ``` | 1862 | ``` |
| 3636 | 1863 | ||
| 3637 | <YueDisplay> | ||
| 3638 | |||
| 3639 | ```yue | ||
| 3640 | sum = (x, y) -> print "sum", x + y | ||
| 3641 | ``` | ||
| 3642 | |||
| 3643 | </YueDisplay> | ||
| 3644 | |||
| 3645 | Funções podem ser chamadas listando os argumentos após o nome de uma expressão que avalia para uma função. Ao encadear chamadas de função, os argumentos são aplicados à função mais próxima à esquerda. | 1864 | Funções podem ser chamadas listando os argumentos após o nome de uma expressão que avalia para uma função. Ao encadear chamadas de função, os argumentos são aplicados à função mais próxima à esquerda. |
| 3646 | 1865 | ||
| 3647 | ```yuescript | 1866 | ```yuescript |
| @@ -3651,31 +1870,12 @@ print sum 10, 20 | |||
| 3651 | a b c "a", "b", "c" | 1870 | a b c "a", "b", "c" |
| 3652 | ``` | 1871 | ``` |
| 3653 | 1872 | ||
| 3654 | <YueDisplay> | ||
| 3655 | |||
| 3656 | ```yue | ||
| 3657 | sum 10, 20 | ||
| 3658 | print sum 10, 20 | ||
| 3659 | |||
| 3660 | a b c "a", "b", "c" | ||
| 3661 | ``` | ||
| 3662 | |||
| 3663 | </YueDisplay> | ||
| 3664 | |||
| 3665 | Para evitar ambiguidade ao chamar funções, parênteses também podem ser usados para envolver os argumentos. Isso é necessário aqui para garantir que os argumentos certos sejam enviados às funções certas. | 1873 | Para evitar ambiguidade ao chamar funções, parênteses também podem ser usados para envolver os argumentos. Isso é necessário aqui para garantir que os argumentos certos sejam enviados às funções certas. |
| 3666 | 1874 | ||
| 3667 | ```yuescript | 1875 | ```yuescript |
| 3668 | print "x:", sum(10, 20), "y:", sum(30, 40) | 1876 | print "x:", sum(10, 20), "y:", sum(30, 40) |
| 3669 | ``` | 1877 | ``` |
| 3670 | 1878 | ||
| 3671 | <YueDisplay> | ||
| 3672 | |||
| 3673 | ```yue | ||
| 3674 | print "x:", sum(10, 20), "y:", sum(30, 40) | ||
| 3675 | ``` | ||
| 3676 | |||
| 3677 | </YueDisplay> | ||
| 3678 | |||
| 3679 | Não deve haver espaço entre o parêntese de abertura e a função. | 1879 | Não deve haver espaço entre o parêntese de abertura e a função. |
| 3680 | 1880 | ||
| 3681 | As funções convertem a última instrução em seu corpo em uma instrução de retorno, isso é chamado de retorno implícito: | 1881 | As funções convertem a última instrução em seu corpo em uma instrução de retorno, isso é chamado de retorno implícito: |
| @@ -3685,29 +1885,12 @@ sum = (x, y) -> x + y | |||
| 3685 | print "The sum is ", sum 10, 20 | 1885 | print "The sum is ", sum 10, 20 |
| 3686 | ``` | 1886 | ``` |
| 3687 | 1887 | ||
| 3688 | <YueDisplay> | ||
| 3689 | |||
| 3690 | ```yue | ||
| 3691 | sum = (x, y) -> x + y | ||
| 3692 | print "The sum is ", sum 10, 20 | ||
| 3693 | ``` | ||
| 3694 | |||
| 3695 | </YueDisplay> | ||
| 3696 | |||
| 3697 | E se você precisar retornar explicitamente, pode usar a palavra-chave return: | 1888 | E se você precisar retornar explicitamente, pode usar a palavra-chave return: |
| 3698 | 1889 | ||
| 3699 | ```yuescript | 1890 | ```yuescript |
| 3700 | sum = (x, y) -> return x + y | 1891 | sum = (x, y) -> return x + y |
| 3701 | ``` | 1892 | ``` |
| 3702 | 1893 | ||
| 3703 | <YueDisplay> | ||
| 3704 | |||
| 3705 | ```yue | ||
| 3706 | sum = (x, y) -> return x + y | ||
| 3707 | ``` | ||
| 3708 | |||
| 3709 | </YueDisplay> | ||
| 3710 | |||
| 3711 | Assim como no Lua, as funções podem retornar múltiplos valores. A última instrução deve ser uma lista de valores separados por vírgulas: | 1894 | Assim como no Lua, as funções podem retornar múltiplos valores. A última instrução deve ser uma lista de valores separados por vírgulas: |
| 3712 | 1895 | ||
| 3713 | ```yuescript | 1896 | ```yuescript |
| @@ -3715,15 +1898,6 @@ mystery = (x, y) -> x + y, x - y | |||
| 3715 | a, b = mystery 10, 20 | 1898 | a, b = mystery 10, 20 |
| 3716 | ``` | 1899 | ``` |
| 3717 | 1900 | ||
| 3718 | <YueDisplay> | ||
| 3719 | |||
| 3720 | ```yue | ||
| 3721 | mystery = (x, y) -> x + y, x - y | ||
| 3722 | a, b = mystery 10, 20 | ||
| 3723 | ``` | ||
| 3724 | |||
| 3725 | </YueDisplay> | ||
| 3726 | |||
| 3727 | ## Setas fat | 1901 | ## Setas fat |
| 3728 | 1902 | ||
| 3729 | Como é um idioma em Lua enviar um objeto como primeiro argumento ao chamar um método, uma sintaxe especial é fornecida para criar funções que incluem automaticamente um argumento self. | 1903 | Como é um idioma em Lua enviar um objeto como primeiro argumento ao chamar um método, uma sintaxe especial é fornecida para criar funções que incluem automaticamente um argumento self. |
| @@ -3732,14 +1906,6 @@ Como é um idioma em Lua enviar um objeto como primeiro argumento ao chamar um m | |||
| 3732 | func = (num) => @value + num | 1906 | func = (num) => @value + num |
| 3733 | ``` | 1907 | ``` |
| 3734 | 1908 | ||
| 3735 | <YueDisplay> | ||
| 3736 | |||
| 3737 | ```yue | ||
| 3738 | func = (num) => @value + num | ||
| 3739 | ``` | ||
| 3740 | |||
| 3741 | </YueDisplay> | ||
| 3742 | |||
| 3743 | ## Valores padrão de argumentos | 1909 | ## Valores padrão de argumentos |
| 3744 | 1910 | ||
| 3745 | É possível fornecer valores padrão para os argumentos de uma função. Um argumento é determinado como vazio se seu valor for nil. Qualquer argumento nil que tenha valor padrão será substituído antes da execução do corpo da função. | 1911 | É possível fornecer valores padrão para os argumentos de uma função. Um argumento é determinado como vazio se seu valor for nil. Qualquer argumento nil que tenha valor padrão será substituído antes da execução do corpo da função. |
| @@ -3750,16 +1916,6 @@ my_function = (name = "something", height = 100) -> | |||
| 3750 | print "My height is", height | 1916 | print "My height is", height |
| 3751 | ``` | 1917 | ``` |
| 3752 | 1918 | ||
| 3753 | <YueDisplay> | ||
| 3754 | |||
| 3755 | ```yue | ||
| 3756 | my_function = (name = "something", height = 100) -> | ||
| 3757 | print "Hello I am", name | ||
| 3758 | print "My height is", height | ||
| 3759 | ``` | ||
| 3760 | |||
| 3761 | </YueDisplay> | ||
| 3762 | |||
| 3763 | Uma expressão de valor padrão de argumento é avaliada no corpo da função na ordem das declarações de argumentos. Por esse motivo, os valores padrão têm acesso aos argumentos declarados anteriormente. | 1919 | Uma expressão de valor padrão de argumento é avaliada no corpo da função na ordem das declarações de argumentos. Por esse motivo, os valores padrão têm acesso aos argumentos declarados anteriormente. |
| 3764 | 1920 | ||
| 3765 | ```yuescript | 1921 | ```yuescript |
| @@ -3767,15 +1923,6 @@ some_args = (x = 100, y = x + 1000) -> | |||
| 3767 | print x + y | 1923 | print x + y |
| 3768 | ``` | 1924 | ``` |
| 3769 | 1925 | ||
| 3770 | <YueDisplay> | ||
| 3771 | |||
| 3772 | ```yue | ||
| 3773 | some_args = (x = 100, y = x + 1000) -> | ||
| 3774 | print x + y | ||
| 3775 | ``` | ||
| 3776 | |||
| 3777 | </YueDisplay> | ||
| 3778 | |||
| 3779 | ## Considerações | 1926 | ## Considerações |
| 3780 | 1927 | ||
| 3781 | Devido à forma expressiva de chamar funções sem parênteses, algumas restrições devem ser colocadas para evitar ambiguidade de análise envolvendo espaço em branco. | 1928 | Devido à forma expressiva de chamar funções sem parênteses, algumas restrições devem ser colocadas para evitar ambiguidade de análise envolvendo espaço em branco. |
| @@ -3789,17 +1936,6 @@ c = x -y | |||
| 3789 | d = x- z | 1936 | d = x- z |
| 3790 | ``` | 1937 | ``` |
| 3791 | 1938 | ||
| 3792 | <YueDisplay> | ||
| 3793 | |||
| 3794 | ```yue | ||
| 3795 | a = x - 10 | ||
| 3796 | b = x-10 | ||
| 3797 | c = x -y | ||
| 3798 | d = x- z | ||
| 3799 | ``` | ||
| 3800 | |||
| 3801 | </YueDisplay> | ||
| 3802 | |||
| 3803 | A precedência do primeiro argumento de uma chamada de função pode ser controlada usando espaço em branco se o argumento for um literal de string. Em Lua, é comum omitir parênteses ao chamar uma função com uma única string ou literal de tabela. | 1939 | A precedência do primeiro argumento de uma chamada de função pode ser controlada usando espaço em branco se o argumento for um literal de string. Em Lua, é comum omitir parênteses ao chamar uma função com uma única string ou literal de tabela. |
| 3804 | 1940 | ||
| 3805 | Quando não há espaço entre uma variável e um literal de string, a chamada de função tem precedência sobre quaisquer expressões seguintes. Nenhum outro argumento pode ser passado para a função quando ela é chamada dessa forma. | 1941 | Quando não há espaço entre uma variável e um literal de string, a chamada de função tem precedência sobre quaisquer expressões seguintes. Nenhum outro argumento pode ser passado para a função quando ela é chamada dessa forma. |
| @@ -3811,15 +1947,6 @@ x = func"hello" + 100 | |||
| 3811 | y = func "hello" + 100 | 1947 | y = func "hello" + 100 |
| 3812 | ``` | 1948 | ``` |
| 3813 | 1949 | ||
| 3814 | <YueDisplay> | ||
| 3815 | |||
| 3816 | ```yue | ||
| 3817 | x = func"hello" + 100 | ||
| 3818 | y = func "hello" + 100 | ||
| 3819 | ``` | ||
| 3820 | |||
| 3821 | </YueDisplay> | ||
| 3822 | |||
| 3823 | ## Argumentos multilinha | 1950 | ## Argumentos multilinha |
| 3824 | 1951 | ||
| 3825 | Ao chamar funções que recebem um grande número de argumentos, é conveniente dividir a lista de argumentos em várias linhas. Devido à natureza sensível a espaço em branco da linguagem, deve-se ter cuidado ao dividir a lista de argumentos. | 1952 | Ao chamar funções que recebem um grande número de argumentos, é conveniente dividir a lista de argumentos em várias linhas. Devido à natureza sensível a espaço em branco da linguagem, deve-se ter cuidado ao dividir a lista de argumentos. |
| @@ -3836,20 +1963,6 @@ cool_func 1, 2, | |||
| 3836 | 7, 8 | 1963 | 7, 8 |
| 3837 | ``` | 1964 | ``` |
| 3838 | 1965 | ||
| 3839 | <YueDisplay> | ||
| 3840 | |||
| 3841 | ```yue | ||
| 3842 | my_func 5, 4, 3, | ||
| 3843 | 8, 9, 10 | ||
| 3844 | |||
| 3845 | cool_func 1, 2, | ||
| 3846 | 3, 4, | ||
| 3847 | 5, 6, | ||
| 3848 | 7, 8 | ||
| 3849 | ``` | ||
| 3850 | |||
| 3851 | </YueDisplay> | ||
| 3852 | |||
| 3853 | Este tipo de invocação pode ser aninhado. O nível de indentação é usado para determinar a qual função os argumentos pertencem. | 1966 | Este tipo de invocação pode ser aninhado. O nível de indentação é usado para determinar a qual função os argumentos pertencem. |
| 3854 | 1967 | ||
| 3855 | ```yuescript | 1968 | ```yuescript |
| @@ -3859,17 +1972,6 @@ my_func 5, 6, 7, | |||
| 3859 | 5, 4 | 1972 | 5, 4 |
| 3860 | ``` | 1973 | ``` |
| 3861 | 1974 | ||
| 3862 | <YueDisplay> | ||
| 3863 | |||
| 3864 | ```yue | ||
| 3865 | my_func 5, 6, 7, | ||
| 3866 | 6, another_func 6, 7, 8, | ||
| 3867 | 9, 1, 2, | ||
| 3868 | 5, 4 | ||
| 3869 | ``` | ||
| 3870 | |||
| 3871 | </YueDisplay> | ||
| 3872 | |||
| 3873 | Como as tabelas também usam vírgula como delimitador, esta sintaxe de indentação ajuda a deixar os valores fazerem parte da lista de argumentos em vez de fazerem parte da tabela. | 1975 | Como as tabelas também usam vírgula como delimitador, esta sintaxe de indentação ajuda a deixar os valores fazerem parte da lista de argumentos em vez de fazerem parte da tabela. |
| 3874 | 1976 | ||
| 3875 | ```yuescript | 1977 | ```yuescript |
| @@ -3880,18 +1982,6 @@ x = [ | |||
| 3880 | ] | 1982 | ] |
| 3881 | ``` | 1983 | ``` |
| 3882 | 1984 | ||
| 3883 | <YueDisplay> | ||
| 3884 | |||
| 3885 | ```yue | ||
| 3886 | x = [ | ||
| 3887 | 1, 2, 3, 4, a_func 4, 5, | ||
| 3888 | 5, 6, | ||
| 3889 | 8, 9, 10 | ||
| 3890 | ] | ||
| 3891 | ``` | ||
| 3892 | |||
| 3893 | </YueDisplay> | ||
| 3894 | |||
| 3895 | Embora incomum, observe como podemos dar uma indentação mais profunda para argumentos de função se soubermos que usaremos uma indentação menor mais adiante. | 1985 | Embora incomum, observe como podemos dar uma indentação mais profunda para argumentos de função se soubermos que usaremos uma indentação menor mais adiante. |
| 3896 | 1986 | ||
| 3897 | ```yuescript | 1987 | ```yuescript |
| @@ -3901,17 +1991,6 @@ y = [ my_func 1, 2, 3, | |||
| 3901 | ] | 1991 | ] |
| 3902 | ``` | 1992 | ``` |
| 3903 | 1993 | ||
| 3904 | <YueDisplay> | ||
| 3905 | |||
| 3906 | ```yue | ||
| 3907 | y = [ my_func 1, 2, 3, | ||
| 3908 | 4, 5, | ||
| 3909 | 5, 6, 7 | ||
| 3910 | ] | ||
| 3911 | ``` | ||
| 3912 | |||
| 3913 | </YueDisplay> | ||
| 3914 | |||
| 3915 | A mesma coisa pode ser feita com outras instruções em nível de bloco como condicionais. Podemos usar o nível de indentação para determinar a qual instrução um valor pertence: | 1994 | A mesma coisa pode ser feita com outras instruções em nível de bloco como condicionais. Podemos usar o nível de indentação para determinar a qual instrução um valor pertence: |
| 3916 | 1995 | ||
| 3917 | ```yuescript | 1996 | ```yuescript |
| @@ -3928,24 +2007,6 @@ if func 1, 2, 3, | |||
| 3928 | print "I am inside if" | 2007 | print "I am inside if" |
| 3929 | ``` | 2008 | ``` |
| 3930 | 2009 | ||
| 3931 | <YueDisplay> | ||
| 3932 | |||
| 3933 | ```yue | ||
| 3934 | if func 1, 2, 3, | ||
| 3935 | "hello", | ||
| 3936 | "world" | ||
| 3937 | print "hello" | ||
| 3938 | print "I am inside if" | ||
| 3939 | |||
| 3940 | if func 1, 2, 3, | ||
| 3941 | "hello", | ||
| 3942 | "world" | ||
| 3943 | print "hello" | ||
| 3944 | print "I am inside if" | ||
| 3945 | ``` | ||
| 3946 | |||
| 3947 | </YueDisplay> | ||
| 3948 | |||
| 3949 | ## Desestruturação de parâmetros | 2010 | ## Desestruturação de parâmetros |
| 3950 | 2011 | ||
| 3951 | YueScript agora suporta desestruturação de parâmetros de função quando o argumento é um objeto. Duas formas de literais de tabela de desestruturação estão disponíveis: | 2012 | YueScript agora suporta desestruturação de parâmetros de função quando o argumento é um objeto. Duas formas de literais de tabela de desestruturação estão disponíveis: |
| @@ -3967,23 +2028,6 @@ arg1 = {a: 0} | |||
| 3967 | f2 arg1, arg2 | 2028 | f2 arg1, arg2 |
| 3968 | ``` | 2029 | ``` |
| 3969 | 2030 | ||
| 3970 | <YueDisplay> | ||
| 3971 | |||
| 3972 | ```yue | ||
| 3973 | f1 = (:a, :b, :c) -> | ||
| 3974 | print a, b, c | ||
| 3975 | |||
| 3976 | f1 a: 1, b: "2", c: {} | ||
| 3977 | |||
| 3978 | f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) -> | ||
| 3979 | print a1, b, c | ||
| 3980 | |||
| 3981 | arg1 = {a: 0} | ||
| 3982 | f2 arg1, arg2 | ||
| 3983 | ``` | ||
| 3984 | |||
| 3985 | </YueDisplay> | ||
| 3986 | |||
| 3987 | ## Expressão de retorno prefixada | 2031 | ## Expressão de retorno prefixada |
| 3988 | 2032 | ||
| 3989 | Ao trabalhar com corpos de função profundamente aninhados, pode ser tedioso manter a legibilidade e consistência do valor de retorno. Para resolver isso, YueScript introduz a sintaxe **Expressão de Retorno Prefixada**. Sua forma é a seguinte: | 2033 | Ao trabalhar com corpos de função profundamente aninhados, pode ser tedioso manter a legibilidade e consistência do valor de retorno. Para resolver isso, YueScript introduz a sintaxe **Expressão de Retorno Prefixada**. Sua forma é a seguinte: |
| @@ -3997,19 +2041,6 @@ findFirstEven = (list): nil -> | |||
| 3997 | return sub | 2041 | return sub |
| 3998 | ``` | 2042 | ``` |
| 3999 | 2043 | ||
| 4000 | <YueDisplay> | ||
| 4001 | |||
| 4002 | ```yue | ||
| 4003 | findFirstEven = (list): nil -> | ||
| 4004 | for item in *list | ||
| 4005 | if type(item) == "table" | ||
| 4006 | for sub in *item | ||
| 4007 | if sub % 2 == 0 | ||
| 4008 | return sub | ||
| 4009 | ``` | ||
| 4010 | |||
| 4011 | </YueDisplay> | ||
| 4012 | |||
| 4013 | Isso é equivalente a: | 2044 | Isso é equivalente a: |
| 4014 | 2045 | ||
| 4015 | ```yuescript | 2046 | ```yuescript |
| @@ -4022,20 +2053,6 @@ findFirstEven = (list) -> | |||
| 4022 | nil | 2053 | nil |
| 4023 | ``` | 2054 | ``` |
| 4024 | 2055 | ||
| 4025 | <YueDisplay> | ||
| 4026 | |||
| 4027 | ```yue | ||
| 4028 | findFirstEven = (list) -> | ||
| 4029 | for item in *list | ||
| 4030 | if type(item) == "table" | ||
| 4031 | for sub in *item | ||
| 4032 | if sub % 2 == 0 | ||
| 4033 | return sub | ||
| 4034 | nil | ||
| 4035 | ``` | ||
| 4036 | |||
| 4037 | </YueDisplay> | ||
| 4038 | |||
| 4039 | A única diferença é que você pode mover a expressão de retorno final antes do token `->` ou `=>` para indicar o valor de retorno implícito da função como última instrução. Dessa forma, mesmo em funções com múltiplos loops aninhados ou ramificações condicionais, você não precisa mais escrever uma expressão de retorno no final do corpo da função, tornando a estrutura lógica mais direta e fácil de seguir. | 2056 | A única diferença é que você pode mover a expressão de retorno final antes do token `->` ou `=>` para indicar o valor de retorno implícito da função como última instrução. Dessa forma, mesmo em funções com múltiplos loops aninhados ou ramificações condicionais, você não precisa mais escrever uma expressão de retorno no final do corpo da função, tornando a estrutura lógica mais direta e fácil de seguir. |
| 4040 | 2057 | ||
| 4041 | ## Varargs nomeados | 2058 | ## Varargs nomeados |
| @@ -4064,32 +2081,6 @@ process = (...args) -> | |||
| 4064 | process 1, nil, 3, nil, 5 | 2081 | process 1, nil, 3, nil, 5 |
| 4065 | ``` | 2082 | ``` |
| 4066 | 2083 | ||
| 4067 | <YueDisplay> | ||
| 4068 | |||
| 4069 | ```yue | ||
| 4070 | f = (...t) -> | ||
| 4071 | print "contagem de argumentos:", t.n | ||
| 4072 | print "comprimento da tabela:", #t | ||
| 4073 | for i = 1, t.n | ||
| 4074 | print t[i] | ||
| 4075 | |||
| 4076 | f 1, 2, 3 | ||
| 4077 | f "a", "b", "c", "d" | ||
| 4078 | f! | ||
| 4079 | |||
| 4080 | -- Tratando casos com valores nil | ||
| 4081 | process = (...args) -> | ||
| 4082 | sum = 0 | ||
| 4083 | for i = 1, args.n | ||
| 4084 | if args[i] != nil and type(args[i]) == "number" | ||
| 4085 | sum += args[i] | ||
| 4086 | sum | ||
| 4087 | |||
| 4088 | process 1, nil, 3, nil, 5 | ||
| 4089 | ``` | ||
| 4090 | |||
| 4091 | </YueDisplay> | ||
| 4092 | |||
| 4093 | # Espaço em branco | 2084 | # Espaço em branco |
| 4094 | 2085 | ||
| 4095 | YueScript é uma linguagem sensível a espaço em branco. Você precisa escrever blocos de código na mesma indentação com espaço **' '** ou tabulação **'\t'**, como corpo de função, lista de valores e alguns blocos de controle. E expressões contendo diferentes espaços em branco podem significar coisas diferentes. Tabulação é tratada como 4 espaços, mas é melhor não misturar o uso de espaços e tabulações. | 2086 | YueScript é uma linguagem sensível a espaço em branco. Você precisa escrever blocos de código na mesma indentação com espaço **' '** ou tabulação **'\t'**, como corpo de função, lista de valores e alguns blocos de controle. E expressões contendo diferentes espaços em branco podem significar coisas diferentes. Tabulação é tratada como 4 espaços, mas é melhor não misturar o uso de espaços e tabulações. |
| @@ -4102,14 +2093,6 @@ Uma instrução normalmente termina em uma quebra de linha. Você também pode u | |||
| 4102 | a = 1; b = 2; print a + b | 2093 | a = 1; b = 2; print a + b |
| 4103 | ``` | 2094 | ``` |
| 4104 | 2095 | ||
| 4105 | <YueDisplay> | ||
| 4106 | |||
| 4107 | ```yue | ||
| 4108 | a = 1; b = 2; print a + b | ||
| 4109 | ``` | ||
| 4110 | |||
| 4111 | </YueDisplay> | ||
| 4112 | |||
| 4113 | ## Encadeamento multilinha | 2096 | ## Encadeamento multilinha |
| 4114 | 2097 | ||
| 4115 | Você pode escrever chamadas de função encadeadas em múltiplas linhas com a mesma indentação. | 2098 | Você pode escrever chamadas de função encadeadas em múltiplas linhas com a mesma indentação. |
| @@ -4123,19 +2106,6 @@ Rx.Observable | |||
| 4123 | \subscribe print | 2106 | \subscribe print |
| 4124 | ``` | 2107 | ``` |
| 4125 | 2108 | ||
| 4126 | <YueDisplay> | ||
| 4127 | |||
| 4128 | ```yue | ||
| 4129 | Rx.Observable | ||
| 4130 | .fromRange 1, 8 | ||
| 4131 | \filter (x) -> x % 2 == 0 | ||
| 4132 | \concat Rx.Observable.of 'who do we appreciate' | ||
| 4133 | \map (value) -> value .. '!' | ||
| 4134 | \subscribe print | ||
| 4135 | ``` | ||
| 4136 | |||
| 4137 | </YueDisplay> | ||
| 4138 | |||
| 4139 | # Comentário | 2109 | # Comentário |
| 4140 | 2110 | ||
| 4141 | ```yuescript | 2111 | ```yuescript |
| @@ -4151,23 +2121,6 @@ Está OK. | |||
| 4151 | func --[[port]] 3000, --[[ip]] "192.168.1.1" | 2121 | func --[[port]] 3000, --[[ip]] "192.168.1.1" |
| 4152 | ``` | 2122 | ``` |
| 4153 | 2123 | ||
| 4154 | <YueDisplay> | ||
| 4155 | |||
| 4156 | ```yue | ||
| 4157 | -- Eu sou um comentário | ||
| 4158 | |||
| 4159 | str = --[[ | ||
| 4160 | Este é um comentário multilinha. | ||
| 4161 | Está OK. | ||
| 4162 | ]] strA \ -- comentário 1 | ||
| 4163 | .. strB \ -- comentário 2 | ||
| 4164 | .. strC | ||
| 4165 | |||
| 4166 | func --[[port]] 3000, --[[ip]] "192.168.1.1" | ||
| 4167 | ``` | ||
| 4168 | |||
| 4169 | </YueDisplay> | ||
| 4170 | |||
| 4171 | # Atributos | 2124 | # Atributos |
| 4172 | 2125 | ||
| 4173 | Suporte de sintaxe para atributos do Lua 5.4. E você ainda pode usar tanto a declaração `const` quanto `close` e obter verificação de constante e callback com escopo funcionando ao direcionar para versões do Lua abaixo da 5.4. | 2126 | Suporte de sintaxe para atributos do Lua 5.4. E você ainda pode usar tanto a declaração `const` quanto `close` e obter verificação de constante e callback com escopo funcionando ao direcionar para versões do Lua abaixo da 5.4. |
| @@ -4177,15 +2130,6 @@ const a = 123 | |||
| 4177 | close _ = <close>: -> print "Fora do escopo." | 2130 | close _ = <close>: -> print "Fora do escopo." |
| 4178 | ``` | 2131 | ``` |
| 4179 | 2132 | ||
| 4180 | <YueDisplay> | ||
| 4181 | |||
| 4182 | ```yue | ||
| 4183 | const a = 123 | ||
| 4184 | close _ = <close>: -> print "Fora do escopo." | ||
| 4185 | ``` | ||
| 4186 | |||
| 4187 | </YueDisplay> | ||
| 4188 | |||
| 4189 | Você pode fazer desestruturação com variáveis atribuídas como constante. | 2133 | Você pode fazer desestruturação com variáveis atribuídas como constante. |
| 4190 | 2134 | ||
| 4191 | ```yuescript | 2135 | ```yuescript |
| @@ -4193,15 +2137,6 @@ const {:a, :b, c, d} = tb | |||
| 4193 | -- a = 1 | 2137 | -- a = 1 |
| 4194 | ``` | 2138 | ``` |
| 4195 | 2139 | ||
| 4196 | <YueDisplay> | ||
| 4197 | |||
| 4198 | ```yue | ||
| 4199 | const {:a, :b, c, d} = tb | ||
| 4200 | -- a = 1 | ||
| 4201 | ``` | ||
| 4202 | |||
| 4203 | </YueDisplay> | ||
| 4204 | |||
| 4205 | Você também pode declarar uma variável global como `const`. | 2140 | Você também pode declarar uma variável global como `const`. |
| 4206 | 2141 | ||
| 4207 | ```yuescript | 2142 | ```yuescript |
| @@ -4209,15 +2144,6 @@ global const Constant = 123 | |||
| 4209 | -- Constant = 1 | 2144 | -- Constant = 1 |
| 4210 | ``` | 2145 | ``` |
| 4211 | 2146 | ||
| 4212 | <YueDisplay> | ||
| 4213 | |||
| 4214 | ```yue | ||
| 4215 | global const Constant = 123 | ||
| 4216 | -- Constant = 1 | ||
| 4217 | ``` | ||
| 4218 | |||
| 4219 | </YueDisplay> | ||
| 4220 | |||
| 4221 | # Operador | 2147 | # Operador |
| 4222 | 2148 | ||
| 4223 | Todos os operadores binários e unários do Lua estão disponíveis. Além disso, **!=** é um alias para **~=**, e **\\** ou **::** podem ser usados para escrever uma chamada de função encadeada como `tb\func!` ou `tb::func!`. E o YueScript oferece alguns outros operadores especiais para escrever códigos mais expressivos. | 2149 | Todos os operadores binários e unários do Lua estão disponíveis. Além disso, **!=** é um alias para **~=**, e **\\** ou **::** podem ser usados para escrever uma chamada de função encadeada como `tb\func!` ou `tb::func!`. E o YueScript oferece alguns outros operadores especiais para escrever códigos mais expressivos. |
| @@ -4227,15 +2153,6 @@ tb\func! if tb ~= nil | |||
| 4227 | tb::func! if tb != nil | 2153 | tb::func! if tb != nil |
| 4228 | ``` | 2154 | ``` |
| 4229 | 2155 | ||
| 4230 | <YueDisplay> | ||
| 4231 | |||
| 4232 | ```yue | ||
| 4233 | tb\func! if tb ~= nil | ||
| 4234 | tb::func! if tb != nil | ||
| 4235 | ``` | ||
| 4236 | |||
| 4237 | </YueDisplay> | ||
| 4238 | |||
| 4239 | ## Comparações encadeadas | 2156 | ## Comparações encadeadas |
| 4240 | 2157 | ||
| 4241 | Comparações podem ser encadeadas arbitrariamente: | 2158 | Comparações podem ser encadeadas arbitrariamente: |
| @@ -4249,19 +2166,6 @@ print 1 <= a <= 10 | |||
| 4249 | -- saída: true | 2166 | -- saída: true |
| 4250 | ``` | 2167 | ``` |
| 4251 | 2168 | ||
| 4252 | <YueDisplay> | ||
| 4253 | |||
| 4254 | ```yue | ||
| 4255 | print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 | ||
| 4256 | -- saída: true | ||
| 4257 | |||
| 4258 | a = 5 | ||
| 4259 | print 1 <= a <= 10 | ||
| 4260 | -- saída: true | ||
| 4261 | ``` | ||
| 4262 | |||
| 4263 | </YueDisplay> | ||
| 4264 | |||
| 4265 | Observe o comportamento de avaliação das comparações encadeadas: | 2169 | Observe o comportamento de avaliação das comparações encadeadas: |
| 4266 | 2170 | ||
| 4267 | ```yuescript | 2171 | ```yuescript |
| @@ -4287,33 +2191,6 @@ print v(1) > v(2) <= v(3) | |||
| 4287 | ]] | 2191 | ]] |
| 4288 | ``` | 2192 | ``` |
| 4289 | 2193 | ||
| 4290 | <YueDisplay> | ||
| 4291 | |||
| 4292 | ```yue | ||
| 4293 | v = (x) -> | ||
| 4294 | print x | ||
| 4295 | x | ||
| 4296 | |||
| 4297 | print v(1) < v(2) <= v(3) | ||
| 4298 | --[[ | ||
| 4299 | saída: | ||
| 4300 | 2 | ||
| 4301 | 1 | ||
| 4302 | 3 | ||
| 4303 | true | ||
| 4304 | ]] | ||
| 4305 | |||
| 4306 | print v(1) > v(2) <= v(3) | ||
| 4307 | --[[ | ||
| 4308 | saída: | ||
| 4309 | 2 | ||
| 4310 | 1 | ||
| 4311 | false | ||
| 4312 | ]] | ||
| 4313 | ``` | ||
| 4314 | |||
| 4315 | </YueDisplay> | ||
| 4316 | |||
| 4317 | A expressão do meio é avaliada apenas uma vez, em vez de duas vezes como seria se a expressão fosse escrita como `v(1) < v(2) and v(2) <= v(3)`. No entanto, a ordem das avaliações em uma comparação encadeada é indefinida. É fortemente recomendado não usar expressões com efeitos colaterais (como impressão) em comparações encadeadas. Se efeitos colaterais forem necessários, o operador de curto-circuito `and` deve ser usado explicitamente. | 2194 | A expressão do meio é avaliada apenas uma vez, em vez de duas vezes como seria se a expressão fosse escrita como `v(1) < v(2) and v(2) <= v(3)`. No entanto, a ordem das avaliações em uma comparação encadeada é indefinida. É fortemente recomendado não usar expressões com efeitos colaterais (como impressão) em comparações encadeadas. Se efeitos colaterais forem necessários, o operador de curto-circuito `and` deve ser usado explicitamente. |
| 4318 | 2195 | ||
| 4319 | ## Anexar à tabela | 2196 | ## Anexar à tabela |
| @@ -4325,15 +2202,6 @@ tab = [] | |||
| 4325 | tab[] = "Value" | 2202 | tab[] = "Value" |
| 4326 | ``` | 2203 | ``` |
| 4327 | 2204 | ||
| 4328 | <YueDisplay> | ||
| 4329 | |||
| 4330 | ```yue | ||
| 4331 | tab = [] | ||
| 4332 | tab[] = "Value" | ||
| 4333 | ``` | ||
| 4334 | |||
| 4335 | </YueDisplay> | ||
| 4336 | |||
| 4337 | Você também pode usar o operador spread `...` para anexar todos os elementos de uma lista a outra: | 2205 | Você também pode usar o operador spread `...` para anexar todos os elementos de uma lista a outra: |
| 4338 | 2206 | ||
| 4339 | ```yuescript | 2207 | ```yuescript |
| @@ -4343,17 +2211,6 @@ tbA[] = ...tbB | |||
| 4343 | -- tbA agora é [1, 2, 3, 4, 5, 6] | 2211 | -- tbA agora é [1, 2, 3, 4, 5, 6] |
| 4344 | ``` | 2212 | ``` |
| 4345 | 2213 | ||
| 4346 | <YueDisplay> | ||
| 4347 | |||
| 4348 | ```yue | ||
| 4349 | tbA = [1, 2, 3] | ||
| 4350 | tbB = [4, 5, 6] | ||
| 4351 | tbA[] = ...tbB | ||
| 4352 | -- tbA agora é [1, 2, 3, 4, 5, 6] | ||
| 4353 | ``` | ||
| 4354 | |||
| 4355 | </YueDisplay> | ||
| 4356 | |||
| 4357 | ## Spread de tabela | 2214 | ## Spread de tabela |
| 4358 | 2215 | ||
| 4359 | Você pode concatenar tabelas de array ou tabelas hash usando o operador spread `...` antes de expressões em literais de tabela. | 2216 | Você pode concatenar tabelas de array ou tabelas hash usando o operador spread `...` antes de expressões em literais de tabela. |
| @@ -4375,27 +2232,6 @@ b = {4, 5, y: 1} | |||
| 4375 | merge = {...a, ...b} | 2232 | merge = {...a, ...b} |
| 4376 | ``` | 2233 | ``` |
| 4377 | 2234 | ||
| 4378 | <YueDisplay> | ||
| 4379 | |||
| 4380 | ```yue | ||
| 4381 | parts = | ||
| 4382 | * "shoulders" | ||
| 4383 | * "knees" | ||
| 4384 | lyrics = | ||
| 4385 | * "head" | ||
| 4386 | * ...parts | ||
| 4387 | * "and" | ||
| 4388 | * "toes" | ||
| 4389 | |||
| 4390 | copy = {...other} | ||
| 4391 | |||
| 4392 | a = {1, 2, 3, x: 1} | ||
| 4393 | b = {4, 5, y: 1} | ||
| 4394 | merge = {...a, ...b} | ||
| 4395 | ``` | ||
| 4396 | |||
| 4397 | </YueDisplay> | ||
| 4398 | |||
| 4399 | ## Indexação reversa de tabela | 2235 | ## Indexação reversa de tabela |
| 4400 | 2236 | ||
| 4401 | Você pode usar o operador **#** para obter os últimos elementos de uma tabela. | 2237 | Você pode usar o operador **#** para obter os últimos elementos de uma tabela. |
| @@ -4406,16 +2242,6 @@ second_last = data.items[#-1] | |||
| 4406 | data.items[#] = 1 | 2242 | data.items[#] = 1 |
| 4407 | ``` | 2243 | ``` |
| 4408 | 2244 | ||
| 4409 | <YueDisplay> | ||
| 4410 | |||
| 4411 | ```yue | ||
| 4412 | last = data.items[#] | ||
| 4413 | second_last = data.items[#-1] | ||
| 4414 | data.items[#] = 1 | ||
| 4415 | ``` | ||
| 4416 | |||
| 4417 | </YueDisplay> | ||
| 4418 | |||
| 4419 | ## Metatable | 2245 | ## Metatable |
| 4420 | 2246 | ||
| 4421 | O operador **<>** pode ser usado como atalho para manipulação de metatable. | 2247 | O operador **<>** pode ser usado como atalho para manipulação de metatable. |
| @@ -4440,26 +2266,6 @@ print d.value | |||
| 4440 | close _ = <close>: -> print "fora do escopo" | 2266 | close _ = <close>: -> print "fora do escopo" |
| 4441 | ``` | 2267 | ``` |
| 4442 | 2268 | ||
| 4443 | <YueDisplay> | ||
| 4444 | |||
| 4445 | ```yue | ||
| 4446 | mt = {} | ||
| 4447 | add = (right) => <>: mt, value: @value + right.value | ||
| 4448 | mt.__add = add | ||
| 4449 | |||
| 4450 | a = <>: mt, value: 1 | ||
| 4451 | -- definir campo com variável de mesmo nome | ||
| 4452 | b = :<add>, value: 2 | ||
| 4453 | c = <add>: mt.__add, value: 3 | ||
| 4454 | |||
| 4455 | d = a + b + c | ||
| 4456 | print d.value | ||
| 4457 | |||
| 4458 | close _ = <close>: -> print "fora do escopo" | ||
| 4459 | ``` | ||
| 4460 | |||
| 4461 | </YueDisplay> | ||
| 4462 | |||
| 4463 | ### Acesso à metatable | 2269 | ### Acesso à metatable |
| 4464 | 2270 | ||
| 4465 | Acesse a metatable com **<>** ou nome do metamétodo cercado por **<>** ou escrevendo alguma expressão em **<>**. | 2271 | Acesse a metatable com **<>** ou nome do metamétodo cercado por **<>** ou escrevendo alguma expressão em **<>**. |
| @@ -4474,19 +2280,6 @@ tb.<> = __index: {item: "hello"} | |||
| 4474 | print tb.item | 2280 | print tb.item |
| 4475 | ``` | 2281 | ``` |
| 4476 | 2282 | ||
| 4477 | <YueDisplay> | ||
| 4478 | |||
| 4479 | ```yue | ||
| 4480 | -- criar com metatable contendo campo "value" | ||
| 4481 | tb = <"value">: 123 | ||
| 4482 | tb.<index> = tb.<> | ||
| 4483 | print tb.value | ||
| 4484 | tb.<> = __index: {item: "hello"} | ||
| 4485 | print tb.item | ||
| 4486 | ``` | ||
| 4487 | |||
| 4488 | </YueDisplay> | ||
| 4489 | |||
| 4490 | ### Desestruturação de metatable | 2283 | ### Desestruturação de metatable |
| 4491 | 2284 | ||
| 4492 | Desestruture a metatable com chave de metamétodo cercada por **<>**. | 2285 | Desestruture a metatable com chave de metamétodo cercada por **<>**. |
| @@ -4496,15 +2289,6 @@ Desestruture a metatable com chave de metamétodo cercada por **<>**. | |||
| 4496 | print item, new, close, getter | 2289 | print item, new, close, getter |
| 4497 | ``` | 2290 | ``` |
| 4498 | 2291 | ||
| 4499 | <YueDisplay> | ||
| 4500 | |||
| 4501 | ```yue | ||
| 4502 | {item, :new, :<close>, <index>: getter} = tb | ||
| 4503 | print item, new, close, getter | ||
| 4504 | ``` | ||
| 4505 | |||
| 4506 | </YueDisplay> | ||
| 4507 | |||
| 4508 | ## Existência | 2292 | ## Existência |
| 4509 | 2293 | ||
| 4510 | O operador **?** pode ser usado em diversos contextos para verificar existência. | 2294 | O operador **?** pode ser usado em diversos contextos para verificar existência. |
| @@ -4524,25 +2308,6 @@ with? io.open "test.txt", "w" | |||
| 4524 | \close! | 2308 | \close! |
| 4525 | ``` | 2309 | ``` |
| 4526 | 2310 | ||
| 4527 | <YueDisplay> | ||
| 4528 | |||
| 4529 | ```yue | ||
| 4530 | func?! | ||
| 4531 | print abc?["hello world"]?.xyz | ||
| 4532 | |||
| 4533 | x = tab?.value | ||
| 4534 | len = utf8?.len or string?.len or (o) -> #o | ||
| 4535 | |||
| 4536 | if print and x? | ||
| 4537 | print x | ||
| 4538 | |||
| 4539 | with? io.open "test.txt", "w" | ||
| 4540 | \write "hello" | ||
| 4541 | \close! | ||
| 4542 | ``` | ||
| 4543 | |||
| 4544 | </YueDisplay> | ||
| 4545 | |||
| 4546 | ## Pipe | 2311 | ## Pipe |
| 4547 | 2312 | ||
| 4548 | Em vez de uma série de chamadas de função aninhadas, você pode encaminhar valores com o operador **|>**. | 2313 | Em vez de uma série de chamadas de função aninhadas, você pode encaminhar valores com o operador **|>**. |
| @@ -4561,24 +2326,6 @@ readFile "example.txt" | |||
| 4561 | 2326 | ||
| 4562 | ``` | 2327 | ``` |
| 4563 | 2328 | ||
| 4564 | <YueDisplay> | ||
| 4565 | |||
| 4566 | ```yue | ||
| 4567 | "hello" |> print | ||
| 4568 | 1 |> print 2 -- insere o item do pipe como primeiro argumento | ||
| 4569 | 2 |> print 1, _, 3 -- pipe com um placeholder | ||
| 4570 | |||
| 4571 | -- expressão pipe em multilinha | ||
| 4572 | readFile "example.txt" | ||
| 4573 | |> extract language, {} | ||
| 4574 | |> parse language | ||
| 4575 | |> emit | ||
| 4576 | |> render | ||
| 4577 | |||
| 4578 | ``` | ||
| 4579 | |||
| 4580 | </YueDisplay> | ||
| 4581 | |||
| 4582 | ## Coalescência de nil | 2329 | ## Coalescência de nil |
| 4583 | 2330 | ||
| 4584 | O operador de coalescência de nil **??** retorna o valor do operando esquerdo se não for **nil**; caso contrário, avalia o operando direito e retorna seu resultado. O operador **??** não avalia seu operando direito se o operando esquerdo avaliar para não-nil. | 2331 | O operador de coalescência de nil **??** retorna o valor do operando esquerdo se não for **nil**; caso contrário, avalia o operando direito e retorna seu resultado. O operador **??** não avalia seu operando direito se o operando esquerdo avaliar para não-nil. |
| @@ -4591,17 +2338,6 @@ func a ?? {} | |||
| 4591 | a ??= false | 2338 | a ??= false |
| 4592 | ``` | 2339 | ``` |
| 4593 | 2340 | ||
| 4594 | <YueDisplay> | ||
| 4595 | |||
| 4596 | ```yue | ||
| 4597 | local a, b, c, d | ||
| 4598 | a = b ?? c ?? d | ||
| 4599 | func a ?? {} | ||
| 4600 | a ??= false | ||
| 4601 | ``` | ||
| 4602 | |||
| 4603 | </YueDisplay> | ||
| 4604 | |||
| 4605 | ## Objeto implícito | 2341 | ## Objeto implícito |
| 4606 | 2342 | ||
| 4607 | Você pode escrever uma lista de estruturas implícitas que começa com o símbolo **\*** ou **-** dentro de um bloco de tabela. Se você está criando objeto implícito, os campos do objeto devem estar com a mesma indentação. | 2343 | Você pode escrever uma lista de estruturas implícitas que começa com o símbolo **\*** ou **-** dentro de um bloco de tabela. Se você está criando objeto implícito, os campos do objeto devem estar com a mesma indentação. |
| @@ -4649,52 +2385,6 @@ tb = | |||
| 4649 | 2385 | ||
| 4650 | ``` | 2386 | ``` |
| 4651 | 2387 | ||
| 4652 | <YueDisplay> | ||
| 4653 | |||
| 4654 | ```yue | ||
| 4655 | -- atribuição com objeto implícito | ||
| 4656 | list = | ||
| 4657 | * 1 | ||
| 4658 | * 2 | ||
| 4659 | * 3 | ||
| 4660 | |||
| 4661 | -- chamada de função com objeto implícito | ||
| 4662 | func | ||
| 4663 | * 1 | ||
| 4664 | * 2 | ||
| 4665 | * 3 | ||
| 4666 | |||
| 4667 | -- retorno com objeto implícito | ||
| 4668 | f = -> | ||
| 4669 | return | ||
| 4670 | * 1 | ||
| 4671 | * 2 | ||
| 4672 | * 3 | ||
| 4673 | |||
| 4674 | -- tabela com objeto implícito | ||
| 4675 | tb = | ||
| 4676 | name: "abc" | ||
| 4677 | |||
| 4678 | values: | ||
| 4679 | - "a" | ||
| 4680 | - "b" | ||
| 4681 | - "c" | ||
| 4682 | |||
| 4683 | objects: | ||
| 4684 | - name: "a" | ||
| 4685 | value: 1 | ||
| 4686 | func: => @value + 1 | ||
| 4687 | tb: | ||
| 4688 | fieldA: 1 | ||
| 4689 | |||
| 4690 | - name: "b" | ||
| 4691 | value: 2 | ||
| 4692 | func: => @value + 2 | ||
| 4693 | tb: { } | ||
| 4694 | ``` | ||
| 4695 | |||
| 4696 | </YueDisplay> | ||
| 4697 | |||
| 4698 | # Literais | 2388 | # Literais |
| 4699 | 2389 | ||
| 4700 | Todos os literais primitivos do Lua podem ser usados. Isso se aplica a números, strings, booleanos e **nil**. | 2390 | Todos os literais primitivos do Lua podem ser usados. Isso se aplica a números, strings, booleanos e **nil**. |
| @@ -4710,19 +2400,6 @@ some_string = "Aqui está uma string | |||
| 4710 | print "Tenho #{math.random! * 100}% de certeza." | 2400 | print "Tenho #{math.random! * 100}% de certeza." |
| 4711 | ``` | 2401 | ``` |
| 4712 | 2402 | ||
| 4713 | <YueDisplay> | ||
| 4714 | |||
| 4715 | ```yue | ||
| 4716 | some_string = "Aqui está uma string | ||
| 4717 | que tem uma quebra de linha." | ||
| 4718 | |||
| 4719 | -- Você pode misturar expressões em literais de string usando a sintaxe #{}. | ||
| 4720 | -- Interpolação de string está disponível apenas em strings com aspas duplas. | ||
| 4721 | print "Tenho #{math.random! * 100}% de certeza." | ||
| 4722 | ``` | ||
| 4723 | |||
| 4724 | </YueDisplay> | ||
| 4725 | |||
| 4726 | ## Literais numéricos | 2403 | ## Literais numéricos |
| 4727 | 2404 | ||
| 4728 | Você pode usar underscores em um literal numérico para aumentar a legibilidade. | 2405 | Você pode usar underscores em um literal numérico para aumentar a legibilidade. |
| @@ -4733,16 +2410,6 @@ hex = 0xEF_BB_BF | |||
| 4733 | binary = 0B10011 | 2410 | binary = 0B10011 |
| 4734 | ``` | 2411 | ``` |
| 4735 | 2412 | ||
| 4736 | <YueDisplay> | ||
| 4737 | |||
| 4738 | ```yue | ||
| 4739 | integer = 1_000_000 | ||
| 4740 | hex = 0xEF_BB_BF | ||
| 4741 | binary = 0B10011 | ||
| 4742 | ``` | ||
| 4743 | |||
| 4744 | </YueDisplay> | ||
| 4745 | |||
| 4746 | ## String multilinha estilo YAML | 2413 | ## String multilinha estilo YAML |
| 4747 | 2414 | ||
| 4748 | O prefixo `|` introduz um literal de string multilinha no estilo YAML: | 2415 | O prefixo `|` introduz um literal de string multilinha no estilo YAML: |
| @@ -4755,18 +2422,6 @@ str = | | |||
| 4755 | - #{expr} | 2422 | - #{expr} |
| 4756 | ``` | 2423 | ``` |
| 4757 | 2424 | ||
| 4758 | <YueDisplay> | ||
| 4759 | |||
| 4760 | ```yue | ||
| 4761 | str = | | ||
| 4762 | key: value | ||
| 4763 | list: | ||
| 4764 | - item1 | ||
| 4765 | - #{expr} | ||
| 4766 | ``` | ||
| 4767 | |||
| 4768 | </YueDisplay> | ||
| 4769 | |||
| 4770 | Isso permite escrever texto estruturado multilinha convenientemente. Todas as quebras de linha e indentação são preservadas em relação à primeira linha não vazia, e expressões dentro de `#{...}` são interpoladas automaticamente como `tostring(expr)`. | 2425 | Isso permite escrever texto estruturado multilinha convenientemente. Todas as quebras de linha e indentação são preservadas em relação à primeira linha não vazia, e expressões dentro de `#{...}` são interpoladas automaticamente como `tostring(expr)`. |
| 4771 | 2426 | ||
| 4772 | A string multilinha YAML detecta automaticamente o prefixo comum de espaço em branco à esquerda (indentação mínima em todas as linhas não vazias) e remove-o de todas as linhas. Isso facilita a indentação visual do seu código sem afetar o conteúdo da string resultante. | 2427 | A string multilinha YAML detecta automaticamente o prefixo comum de espaço em branco à esquerda (indentação mínima em todas as linhas não vazias) e remove-o de todas as linhas. Isso facilita a indentação visual do seu código sem afetar o conteúdo da string resultante. |
| @@ -4779,18 +2434,6 @@ fn = -> | |||
| 4779 | return str | 2434 | return str |
| 4780 | ``` | 2435 | ``` |
| 4781 | 2436 | ||
| 4782 | <YueDisplay> | ||
| 4783 | |||
| 4784 | ```yue | ||
| 4785 | fn = -> | ||
| 4786 | str = | | ||
| 4787 | foo: | ||
| 4788 | bar: baz | ||
| 4789 | return str | ||
| 4790 | ``` | ||
| 4791 | |||
| 4792 | </YueDisplay> | ||
| 4793 | |||
| 4794 | A indentação interna é preservada em relação ao prefixo comum removido, permitindo estruturas aninhadas limpas. | 2437 | A indentação interna é preservada em relação ao prefixo comum removido, permitindo estruturas aninhadas limpas. |
| 4795 | 2438 | ||
| 4796 | Todos os caracteres especiais como aspas (`"`) e barras invertidas (`\`) no bloco YAML Multiline são escapados automaticamente para que a string Lua gerada seja sintaticamente válida e se comporte como esperado. | 2439 | Todos os caracteres especiais como aspas (`"`) e barras invertidas (`\`) no bloco YAML Multiline são escapados automaticamente para que a string Lua gerada seja sintaticamente válida e se comporte como esperado. |
| @@ -4801,16 +2444,6 @@ str = | | |||
| 4801 | note: 'Ele disse: "#{Hello}!"' | 2444 | note: 'Ele disse: "#{Hello}!"' |
| 4802 | ``` | 2445 | ``` |
| 4803 | 2446 | ||
| 4804 | <YueDisplay> | ||
| 4805 | |||
| 4806 | ```yue | ||
| 4807 | str = | | ||
| 4808 | path: "C:\Program Files\App" | ||
| 4809 | note: 'Ele disse: "#{Hello}!"' | ||
| 4810 | ``` | ||
| 4811 | |||
| 4812 | </YueDisplay> | ||
| 4813 | |||
| 4814 | # Módulo | 2447 | # Módulo |
| 4815 | 2448 | ||
| 4816 | ## Import | 2449 | ## Import |
| @@ -4842,35 +2475,6 @@ do | |||
| 4842 | import "export" as {one, two, Something:{umm:{ch}}} | 2475 | import "export" as {one, two, Something:{umm:{ch}}} |
| 4843 | ``` | 2476 | ``` |
| 4844 | 2477 | ||
| 4845 | <YueDisplay> | ||
| 4846 | |||
| 4847 | ```yue | ||
| 4848 | -- usado como desestruturação de tabela | ||
| 4849 | do | ||
| 4850 | import insert, concat from table | ||
| 4851 | -- reporta erro ao atribuir a insert, concat | ||
| 4852 | import C, Ct, Cmt from require "lpeg" | ||
| 4853 | -- atalho para require implícito | ||
| 4854 | import x, y, z from 'mymodule' | ||
| 4855 | -- import com estilo Python | ||
| 4856 | from 'module' import a, b, c | ||
| 4857 | |||
| 4858 | -- atalho para requerer um módulo | ||
| 4859 | do | ||
| 4860 | import 'module' | ||
| 4861 | import 'module_x' | ||
| 4862 | import "d-a-s-h-e-s" | ||
| 4863 | import "module.part" | ||
| 4864 | |||
| 4865 | -- requerer módulo com aliasing ou desestruturação de tabela | ||
| 4866 | do | ||
| 4867 | import "player" as PlayerModule | ||
| 4868 | import "lpeg" as :C, :Ct, :Cmt | ||
| 4869 | import "export" as {one, two, Something:{umm:{ch}}} | ||
| 4870 | ``` | ||
| 4871 | |||
| 4872 | </YueDisplay> | ||
| 4873 | |||
| 4874 | ## Import Global | 2478 | ## Import Global |
| 4875 | 2479 | ||
| 4876 | Você pode importar globais específicos para variáveis locais com `import`. Ao importar uma cadeia de acessos a variáveis globais, o último campo será atribuído à variável local. | 2480 | Você pode importar globais específicos para variáveis locais com `import`. Ao importar uma cadeia de acessos a variáveis globais, o último campo será atribuído à variável local. |
| @@ -4882,17 +2486,6 @@ do | |||
| 4882 | print concat ["a", tostring 1] | 2486 | print concat ["a", tostring 1] |
| 4883 | ``` | 2487 | ``` |
| 4884 | 2488 | ||
| 4885 | <YueDisplay> | ||
| 4886 | |||
| 4887 | ```yue | ||
| 4888 | do | ||
| 4889 | import tostring | ||
| 4890 | import table.concat | ||
| 4891 | print concat ["a", tostring 1] | ||
| 4892 | ``` | ||
| 4893 | |||
| 4894 | </YueDisplay> | ||
| 4895 | |||
| 4896 | ### Importação automática de variável global | 2489 | ### Importação automática de variável global |
| 4897 | 2490 | ||
| 4898 | Você pode colocar `import global` no topo de um bloco para importar automaticamente todos os nomes que não foram explicitamente declarados ou atribuídos no escopo atual como globais. Essas importações implícitas são tratadas como consts locais que referenciam os globais correspondentes na posição da instrução. | 2491 | Você pode colocar `import global` no topo de um bloco para importar automaticamente todos os nomes que não foram explicitamente declarados ou atribuídos no escopo atual como globais. Essas importações implícitas são tratadas como consts locais que referenciam os globais correspondentes na posição da instrução. |
| @@ -4914,25 +2507,6 @@ do | |||
| 4914 | FLAG = 123 | 2507 | FLAG = 123 |
| 4915 | ``` | 2508 | ``` |
| 4916 | 2509 | ||
| 4917 | <YueDisplay> | ||
| 4918 | |||
| 4919 | ```yue | ||
| 4920 | do | ||
| 4921 | import global | ||
| 4922 | print "hello" | ||
| 4923 | math.random 3 | ||
| 4924 | -- print = nil -- erro: globais importados são const | ||
| 4925 | |||
| 4926 | do | ||
| 4927 | -- variável global explícita não será importada | ||
| 4928 | import global | ||
| 4929 | global FLAG | ||
| 4930 | print FLAG | ||
| 4931 | FLAG = 123 | ||
| 4932 | ``` | ||
| 4933 | |||
| 4934 | </YueDisplay> | ||
| 4935 | |||
| 4936 | ## Export | 2510 | ## Export |
| 4937 | 2511 | ||
| 4938 | A instrução export oferece uma forma concisa de definir módulos. | 2512 | A instrução export oferece uma forma concisa de definir módulos. |
| @@ -4957,26 +2531,6 @@ export class Something | |||
| 4957 | umm: "cool" | 2531 | umm: "cool" |
| 4958 | ``` | 2532 | ``` |
| 4959 | 2533 | ||
| 4960 | <YueDisplay> | ||
| 4961 | |||
| 4962 | ```yue | ||
| 4963 | export a, b, c = 1, 2, 3 | ||
| 4964 | export cool = "cat" | ||
| 4965 | |||
| 4966 | export What = if this | ||
| 4967 | "abc" | ||
| 4968 | else | ||
| 4969 | "def" | ||
| 4970 | |||
| 4971 | export y = -> | ||
| 4972 | hallo = 3434 | ||
| 4973 | |||
| 4974 | export class Something | ||
| 4975 | umm: "cool" | ||
| 4976 | ``` | ||
| 4977 | |||
| 4978 | </YueDisplay> | ||
| 4979 | |||
| 4980 | Fazendo export nomeado com desestruturação. | 2534 | Fazendo export nomeado com desestruturação. |
| 4981 | 2535 | ||
| 4982 | ```yuescript | 2536 | ```yuescript |
| @@ -4984,15 +2538,6 @@ export :loadstring, to_lua: tolua = yue | |||
| 4984 | export {itemA: {:fieldA = 'default'}} = tb | 2538 | export {itemA: {:fieldA = 'default'}} = tb |
| 4985 | ``` | 2539 | ``` |
| 4986 | 2540 | ||
| 4987 | <YueDisplay> | ||
| 4988 | |||
| 4989 | ```yue | ||
| 4990 | export :loadstring, to_lua: tolua = yue | ||
| 4991 | export {itemA: {:fieldA = 'default'}} = tb | ||
| 4992 | ``` | ||
| 4993 | |||
| 4994 | </YueDisplay> | ||
| 4995 | |||
| 4996 | Exportar itens nomeados do módulo sem criar variáveis locais. | 2541 | Exportar itens nomeados do módulo sem criar variáveis locais. |
| 4997 | 2542 | ||
| 4998 | ```yuescript | 2543 | ```yuescript |
| @@ -5001,16 +2546,6 @@ export.<index> = items | |||
| 5001 | export["a-b-c"] = 123 | 2546 | export["a-b-c"] = 123 |
| 5002 | ``` | 2547 | ``` |
| 5003 | 2548 | ||
| 5004 | <YueDisplay> | ||
| 5005 | |||
| 5006 | ```yue | ||
| 5007 | export.itemA = tb | ||
| 5008 | export.<index> = items | ||
| 5009 | export["a-b-c"] = 123 | ||
| 5010 | ``` | ||
| 5011 | |||
| 5012 | </YueDisplay> | ||
| 5013 | |||
| 5014 | ### Export sem nome | 2549 | ### Export sem nome |
| 5015 | 2550 | ||
| 5016 | Export sem nome adicionará o item alvo na parte array da tabela exportada. | 2551 | Export sem nome adicionará o item alvo na parte array da tabela exportada. |
| @@ -5028,23 +2563,6 @@ export with tmp | |||
| 5028 | j = 2000 | 2563 | j = 2000 |
| 5029 | ``` | 2564 | ``` |
| 5030 | 2565 | ||
| 5031 | <YueDisplay> | ||
| 5032 | |||
| 5033 | ```yue | ||
| 5034 | d, e, f = 3, 2, 1 | ||
| 5035 | export d, e, f | ||
| 5036 | |||
| 5037 | export if this | ||
| 5038 | 123 | ||
| 5039 | else | ||
| 5040 | 456 | ||
| 5041 | |||
| 5042 | export with tmp | ||
| 5043 | j = 2000 | ||
| 5044 | ``` | ||
| 5045 | |||
| 5046 | </YueDisplay> | ||
| 5047 | |||
| 5048 | ### Export padrão | 2566 | ### Export padrão |
| 5049 | 2567 | ||
| 5050 | Usar a palavra-chave **default** na instrução export para substituir a tabela exportada por qualquer coisa. | 2568 | Usar a palavra-chave **default** na instrução export para substituir a tabela exportada por qualquer coisa. |
| @@ -5055,16 +2573,6 @@ export default -> | |||
| 5055 | 123 | 2573 | 123 |
| 5056 | ``` | 2574 | ``` |
| 5057 | 2575 | ||
| 5058 | <YueDisplay> | ||
| 5059 | |||
| 5060 | ```yue | ||
| 5061 | export default -> | ||
| 5062 | print "hello" | ||
| 5063 | 123 | ||
| 5064 | ``` | ||
| 5065 | |||
| 5066 | </YueDisplay> | ||
| 5067 | |||
| 5068 | # Licença: MIT | 2576 | # Licença: MIT |
| 5069 | 2577 | ||
| 5070 | Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\> | 2578 | Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\> |
diff --git a/doc/yue-zh.md b/doc/yue-zh.md index 93e21d8..d8b5346 100644 --- a/doc/yue-zh.md +++ b/doc/yue-zh.md | |||
| @@ -1,11 +1,5 @@ | |||
| 1 | --- | ||
| 2 | title: 参考手册 | ||
| 3 | --- | ||
| 4 | |||
| 5 | # 月之脚本文档 | 1 | # 月之脚本文档 |
| 6 | 2 | ||
| 7 | <img src="/image/yuescript.svg" width="250px" height="250px" alt="logo" style="padding-top: 3em;padding-bottom: 2em;"/> | ||
| 8 | |||
| 9 | 欢迎来到 <b>月之脚本(YueScript)</b> 官方文档!<br/> | 3 | 欢迎来到 <b>月之脚本(YueScript)</b> 官方文档!<br/> |
| 10 | 这里收录了语言特性、用法、参考示例和资源。<br/> | 4 | 这里收录了语言特性、用法、参考示例和资源。<br/> |
| 11 | 请选择左侧的章节索引或目录,开启你的月之脚本之旅 ☽ | 5 | 请选择左侧的章节索引或目录,开启你的月之脚本之旅 ☽ |
| @@ -21,17 +15,6 @@ do | |||
| 21 | print var -- 这里是nil | 15 | print var -- 这里是nil |
| 22 | ``` | 16 | ``` |
| 23 | 17 | ||
| 24 | <YueDisplay> | ||
| 25 | |||
| 26 | ```yue | ||
| 27 | do | ||
| 28 | var = "hello" | ||
| 29 | print var | ||
| 30 | print var -- 这里是nil | ||
| 31 | ``` | ||
| 32 | |||
| 33 | </YueDisplay> | ||
| 34 | |||
| 35 |   月之脚本的 **do** 也可以用作表达式。允许你将多行代码的处理合并为一个表达式,并将 do 语句代码块的最后一个语句作为表达式返回的结果。`do` 表达式支持通过 `break` 打断执行流并提前返回多个值。 | 18 |   月之脚本的 **do** 也可以用作表达式。允许你将多行代码的处理合并为一个表达式,并将 do 语句代码块的最后一个语句作为表达式返回的结果。`do` 表达式支持通过 `break` 打断执行流并提前返回多个值。 |
| 36 | 19 | ||
| 37 | ```yuescript | 20 | ```yuescript |
| @@ -42,18 +25,6 @@ status, value = do | |||
| 42 | break "small", n | 25 | break "small", n |
| 43 | ``` | 26 | ``` |
| 44 | 27 | ||
| 45 | <YueDisplay> | ||
| 46 | |||
| 47 | ```yue | ||
| 48 | status, value = do | ||
| 49 | n = 12 | ||
| 50 | if n > 10 | ||
| 51 | break "large", n | ||
| 52 | break "small", n | ||
| 53 | ``` | ||
| 54 | |||
| 55 | </YueDisplay> | ||
| 56 | |||
| 57 | ```yuescript | 28 | ```yuescript |
| 58 | counter = do | 29 | counter = do |
| 59 | i = 0 | 30 | i = 0 |
| @@ -65,21 +36,6 @@ print counter! | |||
| 65 | print counter! | 36 | print counter! |
| 66 | ``` | 37 | ``` |
| 67 | 38 | ||
| 68 | <YueDisplay> | ||
| 69 | |||
| 70 | ```yue | ||
| 71 | counter = do | ||
| 72 | i = 0 | ||
| 73 | -> | ||
| 74 | i += 1 | ||
| 75 | i | ||
| 76 | |||
| 77 | print counter! | ||
| 78 | print counter! | ||
| 79 | ``` | ||
| 80 | |||
| 81 | </YueDisplay> | ||
| 82 | |||
| 83 | ```yuescript | 39 | ```yuescript |
| 84 | tbl = { | 40 | tbl = { |
| 85 | key: do | 41 | key: do |
| @@ -88,18 +44,6 @@ tbl = { | |||
| 88 | } | 44 | } |
| 89 | ``` | 45 | ``` |
| 90 | 46 | ||
| 91 | <YueDisplay> | ||
| 92 | |||
| 93 | ```yue | ||
| 94 | tbl = { | ||
| 95 | key: do | ||
| 96 | print "分配键值!" | ||
| 97 | 1234 | ||
| 98 | } | ||
| 99 | ``` | ||
| 100 | |||
| 101 | </YueDisplay> | ||
| 102 | |||
| 103 | # 代码行修饰 | 47 | # 代码行修饰 |
| 104 | 48 | ||
| 105 |   为了方便编写代码,循环语句和 if 语句可以应用于单行代码语句的末尾: | 49 |   为了方便编写代码,循环语句和 if 语句可以应用于单行代码语句的末尾: |
| @@ -108,28 +52,12 @@ tbl = { | |||
| 108 | print "你好,世界" if name == "Rob" | 52 | print "你好,世界" if name == "Rob" |
| 109 | ``` | 53 | ``` |
| 110 | 54 | ||
| 111 | <YueDisplay> | ||
| 112 | |||
| 113 | ```yue | ||
| 114 | print "你好,世界" if name == "Rob" | ||
| 115 | ``` | ||
| 116 | |||
| 117 | </YueDisplay> | ||
| 118 | |||
| 119 |   修饰 for 循环的示例: | 55 |   修饰 for 循环的示例: |
| 120 | 56 | ||
| 121 | ```yuescript | 57 | ```yuescript |
| 122 | print "项目: ", item for item in *items | 58 | print "项目: ", item for item in *items |
| 123 | ``` | 59 | ``` |
| 124 | 60 | ||
| 125 | <YueDisplay> | ||
| 126 | |||
| 127 | ```yue | ||
| 128 | print "项目: ", item for item in *items | ||
| 129 | ``` | ||
| 130 | |||
| 131 | </YueDisplay> | ||
| 132 | |||
| 133 |   修饰 while 循环的示例: | 61 |   修饰 while 循环的示例: |
| 134 | 62 | ||
| 135 | ```yuescript | 63 | ```yuescript |
| @@ -138,16 +66,6 @@ game\update! while game\isRunning! | |||
| 138 | reader\parse_line! until reader\eof! | 66 | reader\parse_line! until reader\eof! |
| 139 | ``` | 67 | ``` |
| 140 | 68 | ||
| 141 | <YueDisplay> | ||
| 142 | |||
| 143 | ```yue | ||
| 144 | game\update! while game\isRunning! | ||
| 145 | |||
| 146 | reader\parse_line! until reader\eof! | ||
| 147 | ``` | ||
| 148 | |||
| 149 | </YueDisplay> | ||
| 150 | |||
| 151 | # 宏 | 69 | # 宏 |
| 152 | 70 | ||
| 153 | ## 常见用法 | 71 | ## 常见用法 |
| @@ -183,39 +101,6 @@ if $and f1!, f2!, f3! | |||
| 183 | print "OK" | 101 | print "OK" |
| 184 | ``` | 102 | ``` |
| 185 | 103 | ||
| 186 | <YueDisplay> | ||
| 187 | |||
| 188 | ```yue | ||
| 189 | macro PI2 = -> math.pi * 2 | ||
| 190 | area = $PI2 * 5 | ||
| 191 | |||
| 192 | macro HELLO = -> "'你好 世界'" | ||
| 193 | print $HELLO | ||
| 194 | |||
| 195 | macro config = (debugging) -> | ||
| 196 | global debugMode = debugging == "true" | ||
| 197 | "" | ||
| 198 | |||
| 199 | macro asserts = (cond) -> | ||
| 200 | debugMode and "assert #{cond}" or "" | ||
| 201 | |||
| 202 | macro assert = (cond) -> | ||
| 203 | debugMode and "assert #{cond}" or "#{cond}" | ||
| 204 | |||
| 205 | $config true | ||
| 206 | $asserts item ~= nil | ||
| 207 | |||
| 208 | $config false | ||
| 209 | value = $assert item | ||
| 210 | |||
| 211 | -- 宏函数参数传递的表达式会被转换为字符串 | ||
| 212 | macro and = (...) -> "#{ table.concat {...}, ' and ' }" | ||
| 213 | if $and f1!, f2!, f3! | ||
| 214 | print "OK" | ||
| 215 | ``` | ||
| 216 | |||
| 217 | </YueDisplay> | ||
| 218 | |||
| 219 | ## 直接插入代码 | 104 | ## 直接插入代码 |
| 220 | 105 | ||
| 221 |   宏函数可以返回一个包含月之脚本代码的字符串,或是一个包含 Lua 代码字符串的配置表。 | 106 |   宏函数可以返回一个包含月之脚本代码的字符串,或是一个包含 Lua 代码字符串的配置表。 |
| @@ -246,36 +131,6 @@ end | |||
| 246 | ]==] | 131 | ]==] |
| 247 | ``` | 132 | ``` |
| 248 | 133 | ||
| 249 | <YueDisplay> | ||
| 250 | |||
| 251 | ```yue | ||
| 252 | macro yueFunc = (var) -> "local #{var} = ->" | ||
| 253 | $yueFunc funcA | ||
| 254 | funcA = -> "无法访问宏生成月之脚本里定义的变量" | ||
| 255 | |||
| 256 | macro luaFunc = (var) -> { | ||
| 257 | code: "local function #{var}() end" | ||
| 258 | type: "lua" | ||
| 259 | } | ||
| 260 | $luaFunc funcB | ||
| 261 | funcB = -> "无法访问宏生成 Lua 代码里定义的变量" | ||
| 262 | |||
| 263 | macro lua = (code) -> { | ||
| 264 | :code | ||
| 265 | type: "lua" | ||
| 266 | } | ||
| 267 | |||
| 268 | -- raw字符串的开始和结束符号会自动被去除了再传入宏函数 | ||
| 269 | $lua[==[ | ||
| 270 | -- 插入原始Lua代码 | ||
| 271 | if cond then | ||
| 272 | print("输出") | ||
| 273 | end | ||
| 274 | ]==] | ||
| 275 | ``` | ||
| 276 | |||
| 277 | </YueDisplay> | ||
| 278 | |||
| 279 | ## 导出宏 | 134 | ## 导出宏 |
| 280 | 135 | ||
| 281 |   宏函数可以从一个模块中导出,并在另一个模块中导入。你必须将导出的宏函数放在一个单独的文件中使用,而且只有宏定义、宏导入和宏展开可以放入这个宏导出模块中。 | 136 |   宏函数可以从一个模块中导出,并在另一个模块中导入。你必须将导出的宏函数放在一个单独的文件中使用,而且只有宏定义、宏导入和宏展开可以放入这个宏导出模块中。 |
| @@ -295,28 +150,6 @@ import "utils" as { | |||
| 295 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | 150 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ |
| 296 | ``` | 151 | ``` |
| 297 | 152 | ||
| 298 | <YueDisplay> | ||
| 299 | |||
| 300 | ```yue | ||
| 301 | -- 文件: utils.yue | ||
| 302 | export macro map = (items, action) -> "[#{action} for _ in *#{items}]" | ||
| 303 | export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" | ||
| 304 | export macro foreach = (items, action) -> "for _ in *#{items} | ||
| 305 | #{action}" | ||
| 306 | |||
| 307 | -- 文件 main.yue | ||
| 308 | -- 在浏览器中不支持import函数,请在真实环境中尝试 | ||
| 309 | --[[ | ||
| 310 | import "utils" as { | ||
| 311 | $, -- 表示导入所有宏的符号 | ||
| 312 | $foreach: $each -- 重命名宏 $foreach 为 $each | ||
| 313 | } | ||
| 314 | [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ | ||
| 315 | ]] | ||
| 316 | ``` | ||
| 317 | |||
| 318 | </YueDisplay> | ||
| 319 | |||
| 320 | ## 内置宏 | 153 | ## 内置宏 |
| 321 | 154 | ||
| 322 |   月之脚本中有一些内置可以直接使用的宏,但你可以通过声明相同名称的宏来覆盖它们。 | 155 |   月之脚本中有一些内置可以直接使用的宏,但你可以通过声明相同名称的宏来覆盖它们。 |
| @@ -326,15 +159,6 @@ print $FILE -- 获取当前模块名称的字符串 | |||
| 326 | print $LINE -- 获取当前代码行数:2 | 159 | print $LINE -- 获取当前代码行数:2 |
| 327 | ``` | 160 | ``` |
| 328 | 161 | ||
| 329 | <YueDisplay> | ||
| 330 | |||
| 331 | ```yue | ||
| 332 | print $FILE -- 获取当前模块名称的字符串 | ||
| 333 | print $LINE -- 获取当前代码行数:2 | ||
| 334 | ``` | ||
| 335 | |||
| 336 | </YueDisplay> | ||
| 337 | |||
| 338 | ## 用宏生成宏 | 162 | ## 用宏生成宏 |
| 339 | 163 | ||
| 340 |   在月之脚本中,宏函数允许你在编译时生成代码。通过嵌套的宏函数,你可以创建更复杂的生成模式。这个特性允许你定义一个宏函数,用它来生成另一个宏函数,从而实现更加动态的代码生成。 | 164 |   在月之脚本中,宏函数允许你在编译时生成代码。通过嵌套的宏函数,你可以创建更复杂的生成模式。这个特性允许你定义一个宏函数,用它来生成另一个宏函数,从而实现更加动态的代码生成。 |
| @@ -357,28 +181,6 @@ print "有效的枚举类型:", $BodyType Static | |||
| 357 | -- print "编译报错的枚举类型:", $BodyType Unknown | 181 | -- print "编译报错的枚举类型:", $BodyType Unknown |
| 358 | ``` | 182 | ``` |
| 359 | 183 | ||
| 360 | <YueDisplay> | ||
| 361 | |||
| 362 | ```yue | ||
| 363 | macro Enum = (...) -> | ||
| 364 | items = {...} | ||
| 365 | itemSet = {item, true for item in *items} | ||
| 366 | (item) -> | ||
| 367 | error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] | ||
| 368 | "\"#{item}\"" | ||
| 369 | |||
| 370 | macro BodyType = $Enum( | ||
| 371 | Static | ||
| 372 | Dynamic | ||
| 373 | Kinematic | ||
| 374 | ) | ||
| 375 | |||
| 376 | print "有效的枚举类型:", $BodyType Static | ||
| 377 | -- print "编译报错的枚举类型:", $BodyType Unknown | ||
| 378 | ``` | ||
| 379 | |||
| 380 | </YueDisplay> | ||
| 381 | |||
| 382 | ## 宏参数检查 | 184 | ## 宏参数检查 |
| 383 | 185 | ||
| 384 |   可以直接在参数列表中声明期望的 AST 节点类型,并在编译时检查传入的宏参数是否符合预期。 | 186 |   可以直接在参数列表中声明期望的 AST 节点类型,并在编译时检查传入的宏参数是否符合预期。 |
| @@ -393,20 +195,6 @@ macro printNumAndStr = (num `Num, str `String) -> | | |||
| 393 | $printNumAndStr 123, "hello" | 195 | $printNumAndStr 123, "hello" |
| 394 | ``` | 196 | ``` |
| 395 | 197 | ||
| 396 | <YueDisplay> | ||
| 397 | |||
| 398 | ```yue | ||
| 399 | macro printNumAndStr = (num `Num, str `String) -> | | ||
| 400 | print( | ||
| 401 | #{num} | ||
| 402 | #{str} | ||
| 403 | ) | ||
| 404 | |||
| 405 | $printNumAndStr 123, "hello" | ||
| 406 | ``` | ||
| 407 | |||
| 408 | </YueDisplay> | ||
| 409 | |||
| 410 |   如果需要做更加灵活的参数检查操作,可以使用内置的 `$is_ast` 宏函数在合适的位置进行手动检查。 | 198 |   如果需要做更加灵活的参数检查操作,可以使用内置的 `$is_ast` 宏函数在合适的位置进行手动检查。 |
| 411 | 199 | ||
| 412 | ```yuescript | 200 | ```yuescript |
| @@ -418,19 +206,6 @@ macro printNumAndStr = (num, str) -> | |||
| 418 | $printNumAndStr 123, "hello" | 206 | $printNumAndStr 123, "hello" |
| 419 | ``` | 207 | ``` |
| 420 | 208 | ||
| 421 | <YueDisplay> | ||
| 422 | |||
| 423 | ```yue | ||
| 424 | macro printNumAndStr = (num, str) -> | ||
| 425 | error "expected Num as first argument" unless $is_ast Num, num | ||
| 426 | error "expected String as second argument" unless $is_ast String, str | ||
| 427 | "print(#{num}, #{str})" | ||
| 428 | |||
| 429 | $printNumAndStr 123, "hello" | ||
| 430 | ``` | ||
| 431 | |||
| 432 | </YueDisplay> | ||
| 433 | |||
| 434 |   更多关于可用 AST 节点的详细信息,请参考 [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp) 中大写的规则定义。 | 209 |   更多关于可用 AST 节点的详细信息,请参考 [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp) 中大写的规则定义。 |
| 435 | 210 | ||
| 436 | # 错误处理 | 211 | # 错误处理 |
| @@ -465,38 +240,6 @@ catch err | |||
| 465 | print result | 240 | print result |
| 466 | ``` | 241 | ``` |
| 467 | 242 | ||
| 468 | <YueDisplay> | ||
| 469 | |||
| 470 | ```yue | ||
| 471 | try | ||
| 472 | func 1, 2, 3 | ||
| 473 | catch err | ||
| 474 | print yue.traceback err | ||
| 475 | |||
| 476 | success, result = try | ||
| 477 | func 1, 2, 3 | ||
| 478 | catch err | ||
| 479 | yue.traceback err | ||
| 480 | |||
| 481 | try func 1, 2, 3 | ||
| 482 | catch err | ||
| 483 | print yue.traceback err | ||
| 484 | |||
| 485 | success, result = try func 1, 2, 3 | ||
| 486 | |||
| 487 | try | ||
| 488 | print "尝试中" | ||
| 489 | func 1, 2, 3 | ||
| 490 | |||
| 491 | -- 使用if赋值模式 | ||
| 492 | if success, result := try func 1, 2, 3 | ||
| 493 | catch err | ||
| 494 | print yue.traceback err | ||
| 495 | print result | ||
| 496 | ``` | ||
| 497 | |||
| 498 | </YueDisplay> | ||
| 499 | |||
| 500 | ## 错误处理简化 | 243 | ## 错误处理简化 |
| 501 | 244 | ||
| 502 |   `try?` 是 `try` 的功能简化语法,它不再返回 `try` 语句的布尔状态,并在成功时直接返回 `try` 代码块的结果,失败时返回 `nil` 值而非错误对象。 | 245 |   `try?` 是 `try` 的功能简化语法,它不再返回 `try` 语句的布尔状态,并在成功时直接返回 `try` 代码块的结果,失败时返回 `nil` 值而非错误对象。 |
| @@ -519,44 +262,14 @@ catch e | |||
| 519 | e | 262 | e |
| 520 | ``` | 263 | ``` |
| 521 | 264 | ||
| 522 | <YueDisplay> | ||
| 523 | |||
| 524 | ```yue | ||
| 525 | a, b, c = try? func! | ||
| 526 | |||
| 527 | -- 与空值合并运算符一起使用 | ||
| 528 | a = (try? func!) ?? "default" | ||
| 529 | |||
| 530 | -- 作为函数参数 | ||
| 531 | f try? func! | ||
| 532 | |||
| 533 | -- 带 catch 块的 try! | ||
| 534 | f try? | ||
| 535 | print 123 | ||
| 536 | func! | ||
| 537 | catch e | ||
| 538 | print e | ||
| 539 | e | ||
| 540 | ``` | ||
| 541 | |||
| 542 | </YueDisplay> | ||
| 543 | |||
| 544 | # 表格字面量 | 265 | # 表格字面量 |
| 545 | 266 | ||
| 546 |   和 Lua 一样,表格可以通过花括号进行定义。 | 267 |   和 Lua 一样,表格可以通过花括号进行定义。 |
| 547 | 268 | ||
| 548 | ```yuescript | 269 | ```yuescript |
| 549 | some_values = [1, 2, 3, 4] | 270 | some_values = {1, 2, 3, 4} |
| 550 | ``` | ||
| 551 | |||
| 552 | <YueDisplay> | ||
| 553 | |||
| 554 | ```yue | ||
| 555 | some_values = [1, 2, 3, 4] | ||
| 556 | ``` | 271 | ``` |
| 557 | 272 | ||
| 558 | </YueDisplay> | ||
| 559 | |||
| 560 |   但与Lua不同的是,给表格中的键赋值是用 **:**(而不是 **=**)。 | 273 |   但与Lua不同的是,给表格中的键赋值是用 **:**(而不是 **=**)。 |
| 561 | 274 | ||
| 562 | ```yuescript | 275 | ```yuescript |
| @@ -567,18 +280,6 @@ some_values = { | |||
| 567 | } | 280 | } |
| 568 | ``` | 281 | ``` |
| 569 | 282 | ||
| 570 | <YueDisplay> | ||
| 571 | |||
| 572 | ```yue | ||
| 573 | some_values = { | ||
| 574 | name: "Bill", | ||
| 575 | age: 200, | ||
| 576 | ["favorite food"]: "rice" | ||
| 577 | } | ||
| 578 | ``` | ||
| 579 | |||
| 580 | </YueDisplay> | ||
| 581 | |||
| 582 |   如果只分配一个键值对的表格,可以省略花括号。 | 283 |   如果只分配一个键值对的表格,可以省略花括号。 |
| 583 | 284 | ||
| 584 | ```yuescript | 285 | ```yuescript |
| @@ -588,17 +289,6 @@ profile = | |||
| 588 | favorite_foods: ["冰淇淋", "甜甜圈"] | 289 | favorite_foods: ["冰淇淋", "甜甜圈"] |
| 589 | ``` | 290 | ``` |
| 590 | 291 | ||
| 591 | <YueDisplay> | ||
| 592 | |||
| 593 | ```yue | ||
| 594 | profile = | ||
| 595 | height: "4英尺", | ||
| 596 | shoe_size: 13, | ||
| 597 | favorite_foods: ["冰淇淋", "甜甜圈"] | ||
| 598 | ``` | ||
| 599 | |||
| 600 | </YueDisplay> | ||
| 601 | |||
| 602 |   可以使用换行符而不使用逗号(或两者都用)来分隔表格中的值: | 292 |   可以使用换行符而不使用逗号(或两者都用)来分隔表格中的值: |
| 603 | 293 | ||
| 604 | ```yuescript | 294 | ```yuescript |
| @@ -610,19 +300,6 @@ values = { | |||
| 610 | } | 300 | } |
| 611 | ``` | 301 | ``` |
| 612 | 302 | ||
| 613 | <YueDisplay> | ||
| 614 | |||
| 615 | ```yue | ||
| 616 | values = { | ||
| 617 | 1, 2, 3, 4 | ||
| 618 | 5, 6, 7, 8 | ||
| 619 | name: "超人" | ||
| 620 | occupation: "打击犯罪" | ||
| 621 | } | ||
| 622 | ``` | ||
| 623 | |||
| 624 | </YueDisplay> | ||
| 625 | |||
| 626 |   创建单行表格字面量时,也可以省略花括号: | 303 |   创建单行表格字面量时,也可以省略花括号: |
| 627 | 304 | ||
| 628 | ```yuescript | 305 | ```yuescript |
| @@ -631,16 +308,6 @@ my_function dance: "探戈", partner: "无" | |||
| 631 | y = type: "狗", legs: 4, tails: 1 | 308 | y = type: "狗", legs: 4, tails: 1 |
| 632 | ``` | 309 | ``` |
| 633 | 310 | ||
| 634 | <YueDisplay> | ||
| 635 | |||
| 636 | ```yue | ||
| 637 | my_function dance: "探戈", partner: "无" | ||
| 638 | |||
| 639 | y = type: "狗", legs: 4, tails: 1 | ||
| 640 | ``` | ||
| 641 | |||
| 642 | </YueDisplay> | ||
| 643 | |||
| 644 |   表格字面量的键可以使用 Lua 语言的关键字,而无需转义: | 311 |   表格字面量的键可以使用 Lua 语言的关键字,而无需转义: |
| 645 | 312 | ||
| 646 | ```yuescript | 313 | ```yuescript |
| @@ -650,17 +317,6 @@ tbl = { | |||
| 650 | } | 317 | } |
| 651 | ``` | 318 | ``` |
| 652 | 319 | ||
| 653 | <YueDisplay> | ||
| 654 | |||
| 655 | ```yue | ||
| 656 | tbl = { | ||
| 657 | do: "某事" | ||
| 658 | end: "饥饿" | ||
| 659 | } | ||
| 660 | ``` | ||
| 661 | |||
| 662 | </YueDisplay> | ||
| 663 | |||
| 664 |   如果你要构造一个由变量组成的表,并希望键与变量名相同,那么可以使用 **:** 前缀操作符: | 320 |   如果你要构造一个由变量组成的表,并希望键与变量名相同,那么可以使用 **:** 前缀操作符: |
| 665 | 321 | ||
| 666 | ```yuescript | 322 | ```yuescript |
| @@ -671,18 +327,6 @@ person = { :hair, :height, shoe_size: 40 } | |||
| 671 | print_table :hair, :height | 327 | print_table :hair, :height |
| 672 | ``` | 328 | ``` |
| 673 | 329 | ||
| 674 | <YueDisplay> | ||
| 675 | |||
| 676 | ```yue | ||
| 677 | hair = "金色" | ||
| 678 | height = 200 | ||
| 679 | person = { :hair, :height, shoe_size: 40 } | ||
| 680 | |||
| 681 | print_table :hair, :height | ||
| 682 | ``` | ||
| 683 | |||
| 684 | </YueDisplay> | ||
| 685 | |||
| 686 |   如果你希望表中字段的键是某个表达式的结果,那么可以用 **[ ]** 包裹它,就像在 Lua 中一样。如果键中有任何特殊字符,也可以直接使用字符串字面量作为键,省略方括号。 | 330 |   如果你希望表中字段的键是某个表达式的结果,那么可以用 **[ ]** 包裹它,就像在 Lua 中一样。如果键中有任何特殊字符,也可以直接使用字符串字面量作为键,省略方括号。 |
| 687 | 331 | ||
| 688 | ```yuescript | 332 | ```yuescript |
| @@ -692,17 +336,6 @@ t = { | |||
| 692 | } | 336 | } |
| 693 | ``` | 337 | ``` |
| 694 | 338 | ||
| 695 | <YueDisplay> | ||
| 696 | |||
| 697 | ```yue | ||
| 698 | t = { | ||
| 699 | [1 + 2]: "你好" | ||
| 700 | "你好 世界": true | ||
| 701 | } | ||
| 702 | ``` | ||
| 703 | |||
| 704 | </YueDisplay> | ||
| 705 | |||
| 706 |   Lua 的表同时具有数组部分和哈希部分,但有时候你会希望在书写 Lua 表时,对 Lua 表做数组和哈希不同用法的语义区分。然后你可以用 **[ ]** 而不是 **{ }** 来编写表示数组的 Lua 表,并且不允许在数组 Lua 表中写入任何键值对。 | 339 |   Lua 的表同时具有数组部分和哈希部分,但有时候你会希望在书写 Lua 表时,对 Lua 表做数组和哈希不同用法的语义区分。然后你可以用 **[ ]** 而不是 **{ }** 来编写表示数组的 Lua 表,并且不允许在数组 Lua 表中写入任何键值对。 |
| 707 | 340 | ||
| 708 | ```yuescript | 341 | ```yuescript |
| @@ -710,15 +343,6 @@ some_values = [ 1, 2, 3, 4 ] | |||
| 710 | list_with_one_element = [ 1, ] | 343 | list_with_one_element = [ 1, ] |
| 711 | ``` | 344 | ``` |
| 712 | 345 | ||
| 713 | <YueDisplay> | ||
| 714 | |||
| 715 | ```yue | ||
| 716 | some_values = [ 1, 2, 3, 4 ] | ||
| 717 | list_with_one_element = [ 1, ] | ||
| 718 | ``` | ||
| 719 | |||
| 720 | </YueDisplay> | ||
| 721 | |||
| 722 | # 推导式 | 346 | # 推导式 |
| 723 | 347 | ||
| 724 |   推导式为我们提供了一种便捷的语法,通过遍历现有对象并对其值应用表达式来构造出新的表格。月之脚本有两种推导式:列表推导式和表格推导式。它们最终都是产生 Lua 表格;列表推导式将值累积到类似数组的表格中,而表格推导式允许你在每次遍历时设置新表格的键和值。 | 348 |   推导式为我们提供了一种便捷的语法,通过遍历现有对象并对其值应用表达式来构造出新的表格。月之脚本有两种推导式:列表推导式和表格推导式。它们最终都是产生 Lua 表格;列表推导式将值累积到类似数组的表格中,而表格推导式允许你在每次遍历时设置新表格的键和值。 |
| @@ -732,43 +356,18 @@ items = [1, 2, 3, 4] | |||
| 732 | doubled = [item * 2 for i, item in ipairs items] | 356 | doubled = [item * 2 for i, item in ipairs items] |
| 733 | ``` | 357 | ``` |
| 734 | 358 | ||
| 735 | <YueDisplay> | ||
| 736 | |||
| 737 | ```yue | ||
| 738 | items = [1, 2, 3, 4] | ||
| 739 | doubled = [item * 2 for i, item in ipairs items] | ||
| 740 | ``` | ||
| 741 | |||
| 742 | </YueDisplay> | ||
| 743 | |||
| 744 |   可以使用 `when` 子句筛选新表中包含的项目: | 359 |   可以使用 `when` 子句筛选新表中包含的项目: |
| 745 | 360 | ||
| 746 | ```yuescript | 361 | ```yuescript |
| 747 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | 362 | slice = [item for i, item in ipairs items when i > 1 and i < 3] |
| 748 | ``` | 363 | ``` |
| 749 | 364 | ||
| 750 | <YueDisplay> | ||
| 751 | |||
| 752 | ```yue | ||
| 753 | slice = [item for i, item in ipairs items when i > 1 and i < 3] | ||
| 754 | ``` | ||
| 755 | |||
| 756 | </YueDisplay> | ||
| 757 | |||
| 758 |   因为我们常常需要迭代数值索引表的值,所以引入了 **\*** 操作符来做语法简化。doubled 示例可以重写为: | 365 |   因为我们常常需要迭代数值索引表的值,所以引入了 **\*** 操作符来做语法简化。doubled 示例可以重写为: |
| 759 | 366 | ||
| 760 | ```yuescript | 367 | ```yuescript |
| 761 | doubled = [item * 2 for item in *items] | 368 | doubled = [item * 2 for item in *items] |
| 762 | ``` | 369 | ``` |
| 763 | 370 | ||
| 764 | <YueDisplay> | ||
| 765 | |||
| 766 | ```yue | ||
| 767 | doubled = [item * 2 for item in *items] | ||
| 768 | ``` | ||
| 769 | |||
| 770 | </YueDisplay> | ||
| 771 | |||
| 772 |   在列表推导式中,你还可以使用展开操作符 `...` 来实现对列表嵌套层级进行扁平化的处理: | 371 |   在列表推导式中,你还可以使用展开操作符 `...` 来实现对列表嵌套层级进行扁平化的处理: |
| 773 | 372 | ||
| 774 | ```yuescript | 373 | ```yuescript |
| @@ -780,19 +379,6 @@ flat = [...v for k,v in pairs data] | |||
| 780 | -- flat 现在为 [1, 2, 3, 4, 5, 6] | 379 | -- flat 现在为 [1, 2, 3, 4, 5, 6] |
| 781 | ``` | 380 | ``` |
| 782 | 381 | ||
| 783 | <YueDisplay> | ||
| 784 | |||
| 785 | ```yue | ||
| 786 | data = | ||
| 787 | a: [1, 2, 3] | ||
| 788 | b: [4, 5, 6] | ||
| 789 | |||
| 790 | flat = [...v for k,v in pairs data] | ||
| 791 | -- flat 现在为 [1, 2, 3, 4, 5, 6] | ||
| 792 | ``` | ||
| 793 | |||
| 794 | </YueDisplay> | ||
| 795 | |||
| 796 |   for 和 when 子句可以根据需要进行链式操作。唯一的要求是推导式中至少要有一个 for 子句。 | 382 |   for 和 when 子句可以根据需要进行链式操作。唯一的要求是推导式中至少要有一个 for 子句。 |
| 797 | 383 | ||
| 798 |   使用多个 for 子句与使用多重循环的效果相同: | 384 |   使用多个 for 子句与使用多重循环的效果相同: |
| @@ -805,32 +391,12 @@ points = [ [x, y] for x in *x_coords \ | |||
| 805 | for y in *y_coords] | 391 | for y in *y_coords] |
| 806 | ``` | 392 | ``` |
| 807 | 393 | ||
| 808 | <YueDisplay> | ||
| 809 | |||
| 810 | ```yue | ||
| 811 | x_coords = [4, 5, 6, 7] | ||
| 812 | y_coords = [9, 2, 3] | ||
| 813 | |||
| 814 | points = [ [x, y] for x in *x_coords \ | ||
| 815 | for y in *y_coords] | ||
| 816 | ``` | ||
| 817 | |||
| 818 | </YueDisplay> | ||
| 819 | |||
| 820 |   在推导式中也可以使用简单的数值 for 循环: | 394 |   在推导式中也可以使用简单的数值 for 循环: |
| 821 | 395 | ||
| 822 | ```yuescript | 396 | ```yuescript |
| 823 | evens = [i for i = 1, 100 when i % 2 == 0] | 397 | evens = [i for i = 1, 100 when i % 2 == 0] |
| 824 | ``` | 398 | ``` |
| 825 | 399 | ||
| 826 | <YueDisplay> | ||
| 827 | |||
| 828 | ```yue | ||
| 829 | evens = [i for i = 1, 100 when i % 2 == 0] | ||
| 830 | ``` | ||
| 831 | |||
| 832 | </YueDisplay> | ||
| 833 | |||
| 834 | ## 表格推导式 | 400 | ## 表格推导式 |
| 835 | 401 | ||
| 836 |   表格推导式和列表推导式的语法非常相似,只是要使用 **{** 和 **}** 并从每次迭代中取两个值。 | 402 |   表格推导式和列表推导式的语法非常相似,只是要使用 **{** 和 **}** 并从每次迭代中取两个值。 |
| @@ -847,32 +413,10 @@ thing = { | |||
| 847 | thing_copy = {k, v for k, v in pairs thing} | 413 | thing_copy = {k, v for k, v in pairs thing} |
| 848 | ``` | 414 | ``` |
| 849 | 415 | ||
| 850 | <YueDisplay> | ||
| 851 | |||
| 852 | ```yue | ||
| 853 | thing = { | ||
| 854 | color: "red" | ||
| 855 | name: "fast" | ||
| 856 | width: 123 | ||
| 857 | } | ||
| 858 | |||
| 859 | thing_copy = {k, v for k, v in pairs thing} | ||
| 860 | ``` | ||
| 861 | |||
| 862 | </YueDisplay> | ||
| 863 | |||
| 864 | ```yuescript | 416 | ```yuescript |
| 865 | no_color = {k, v for k, v in pairs thing when k != "color"} | 417 | no_color = {k, v for k, v in pairs thing when k != "color"} |
| 866 | ``` | 418 | ``` |
| 867 | 419 | ||
| 868 | <YueDisplay> | ||
| 869 | |||
| 870 | ```yue | ||
| 871 | no_color = {k, v for k, v in pairs thing when k != "color"} | ||
| 872 | ``` | ||
| 873 | |||
| 874 | </YueDisplay> | ||
| 875 | |||
| 876 |   **\*** 操作符在表格推导式中能使用。在下面的例子里,我们为几个数字创建了一个平方根查找表。 | 420 |   **\*** 操作符在表格推导式中能使用。在下面的例子里,我们为几个数字创建了一个平方根查找表。 |
| 877 | 421 | ||
| 878 | ```yuescript | 422 | ```yuescript |
| @@ -880,15 +424,6 @@ numbers = [1, 2, 3, 4] | |||
| 880 | sqrts = {i, math.sqrt i for i in *numbers} | 424 | sqrts = {i, math.sqrt i for i in *numbers} |
| 881 | ``` | 425 | ``` |
| 882 | 426 | ||
| 883 | <YueDisplay> | ||
| 884 | |||
| 885 | ```yue | ||
| 886 | numbers = [1, 2, 3, 4] | ||
| 887 | sqrts = {i, math.sqrt i for i in *numbers} | ||
| 888 | ``` | ||
| 889 | |||
| 890 | </YueDisplay> | ||
| 891 | |||
| 892 |   表格推导式中的键值元组也可以来自单个表达式,在这种情况下,表达式在计算后应返回两个值。第一个用作键,第二个用作值: | 427 |   表格推导式中的键值元组也可以来自单个表达式,在这种情况下,表达式在计算后应返回两个值。第一个用作键,第二个用作值: |
| 893 | 428 | ||
| 894 |   在下面的示例中,我们将一些数组转换为一个表,其中每个数组里的第一项是键,第二项是值。 | 429 |   在下面的示例中,我们将一些数组转换为一个表,其中每个数组里的第一项是键,第二项是值。 |
| @@ -898,15 +433,6 @@ tuples = [ ["hello", "world"], ["foo", "bar"]] | |||
| 898 | tbl = {unpack tuple for tuple in *tuples} | 433 | tbl = {unpack tuple for tuple in *tuples} |
| 899 | ``` | 434 | ``` |
| 900 | 435 | ||
| 901 | <YueDisplay> | ||
| 902 | |||
| 903 | ```yue | ||
| 904 | tuples = [ ["hello", "world"], ["foo", "bar"]] | ||
| 905 | tbl = {unpack tuple for tuple in *tuples} | ||
| 906 | ``` | ||
| 907 | |||
| 908 | </YueDisplay> | ||
| 909 | |||
| 910 | ## 切片 | 436 | ## 切片 |
| 911 | 437 | ||
| 912 |   当使用 **\*** 操作符时,月之脚本还提供了一种特殊的语法来限制要遍历的列表范围。这个语法也相当于在 for 循环中设置迭代边界和步长。 | 438 |   当使用 **\*** 操作符时,月之脚本还提供了一种特殊的语法来限制要遍历的列表范围。这个语法也相当于在 for 循环中设置迭代边界和步长。 |
| @@ -917,42 +443,18 @@ tbl = {unpack tuple for tuple in *tuples} | |||
| 917 | slice = [item for item in *items[1, 5]] | 443 | slice = [item for item in *items[1, 5]] |
| 918 | ``` | 444 | ``` |
| 919 | 445 | ||
| 920 | <YueDisplay> | ||
| 921 | |||
| 922 | ```yue | ||
| 923 | slice = [item for item in *items[1, 5]] | ||
| 924 | ``` | ||
| 925 | |||
| 926 | </YueDisplay> | ||
| 927 | |||
| 928 |   切片的任意参数都可以省略,并会使用默认值。在如下示例中,如果省略了最大索引边界,它默认为表的长度。使下面的代码取除第一个元素之外的所有元素: | 446 |   切片的任意参数都可以省略,并会使用默认值。在如下示例中,如果省略了最大索引边界,它默认为表的长度。使下面的代码取除第一个元素之外的所有元素: |
| 929 | 447 | ||
| 930 | ```yuescript | 448 | ```yuescript |
| 931 | slice = [item for item in *items[2,]] | 449 | slice = [item for item in *items[2,]] |
| 932 | ``` | 450 | ``` |
| 933 | 451 | ||
| 934 | <YueDisplay> | ||
| 935 | |||
| 936 | ```yue | ||
| 937 | slice = [item for item in *items[2,]] | ||
| 938 | ``` | ||
| 939 | |||
| 940 | </YueDisplay> | ||
| 941 | |||
| 942 |   如果省略了最小边界,便默认会设置为 1。这里我们只提供一个步长,并留下其他边界为空。这样会使得代码取出所有奇数索引的项目:(1, 3, 5, …) | 452 |   如果省略了最小边界,便默认会设置为 1。这里我们只提供一个步长,并留下其他边界为空。这样会使得代码取出所有奇数索引的项目:(1, 3, 5, …) |
| 943 | 453 | ||
| 944 | ```yuescript | 454 | ```yuescript |
| 945 | slice = [item for item in *items[,,2]] | 455 | slice = [item for item in *items[,,2]] |
| 946 | ``` | 456 | ``` |
| 947 | 457 | ||
| 948 | <YueDisplay> | ||
| 949 | |||
| 950 | ```yue | ||
| 951 | slice = [item for item in *items[,,2]] | ||
| 952 | ``` | ||
| 953 | |||
| 954 | </YueDisplay> | ||
| 955 | |||
| 956 |   最小和最大边界都可以是负数,使用负数意味着边界是从表的末尾开始计算的。 | 458 |   最小和最大边界都可以是负数,使用负数意味着边界是从表的末尾开始计算的。 |
| 957 | 459 | ||
| 958 | ```yuescript | 460 | ```yuescript |
| @@ -960,29 +462,12 @@ slice = [item for item in *items[,,2]] | |||
| 960 | slice = [item for item in *items[-4,-1]] | 462 | slice = [item for item in *items[-4,-1]] |
| 961 | ``` | 463 | ``` |
| 962 | 464 | ||
| 963 | <YueDisplay> | ||
| 964 | |||
| 965 | ```yue | ||
| 966 | -- 取最后4个元素 | ||
| 967 | slice = [item for item in *items[-4,-1]] | ||
| 968 | ``` | ||
| 969 | |||
| 970 | </YueDisplay> | ||
| 971 | |||
| 972 |   切片的步长也可以是负数,这意味着元素会以相反的顺序被取出。 | 465 |   切片的步长也可以是负数,这意味着元素会以相反的顺序被取出。 |
| 973 | 466 | ||
| 974 | ```yuescript | 467 | ```yuescript |
| 975 | reverse_slice = [item for item in *items[-1,1,-1]] | 468 | reverse_slice = [item for item in *items[-1,1,-1]] |
| 976 | ``` | 469 | ``` |
| 977 | 470 | ||
| 978 | <YueDisplay> | ||
| 979 | |||
| 980 | ```yue | ||
| 981 | reverse_slice = [item for item in *items[-1,1,-1]] | ||
| 982 | ``` | ||
| 983 | |||
| 984 | </YueDisplay> | ||
| 985 | |||
| 986 | ### 切片表达式 | 471 | ### 切片表达式 |
| 987 | 472 | ||
| 988 |   切片也可以作为表达式来使用。可以用于获取一个表包含的子列表。 | 473 |   切片也可以作为表达式来使用。可以用于获取一个表包含的子列表。 |
| @@ -995,18 +480,6 @@ sub_list = items[2, 4] | |||
| 995 | last_four_items = items[-4, -1] | 480 | last_four_items = items[-4, -1] |
| 996 | ``` | 481 | ``` |
| 997 | 482 | ||
| 998 | <YueDisplay> | ||
| 999 | |||
| 1000 | ```yue | ||
| 1001 | -- 取第2和第4个元素作为新的列表 | ||
| 1002 | sub_list = items[2, 4] | ||
| 1003 | |||
| 1004 | -- 取最后4个元素作为新的列表 | ||
| 1005 | last_four_items = items[-4, -1] | ||
| 1006 | ``` | ||
| 1007 | |||
| 1008 | </YueDisplay> | ||
| 1009 | |||
| 1010 | # 面向对象编程 | 483 | # 面向对象编程 |
| 1011 | 484 | ||
| 1012 |   在以下的示例中,月之脚本生成的 Lua 代码可能看起来会很复杂。所以最好主要关注月之脚本代码层面的意义,然后如果你想知道关于面向对象功能的实现细节,再查看 Lua 代码。 | 485 |   在以下的示例中,月之脚本生成的 Lua 代码可能看起来会很复杂。所以最好主要关注月之脚本代码层面的意义,然后如果你想知道关于面向对象功能的实现细节,再查看 Lua 代码。 |
| @@ -1025,22 +498,6 @@ class Inventory | |||
| 1025 | @items[name] = 1 | 498 | @items[name] = 1 |
| 1026 | ``` | 499 | ``` |
| 1027 | 500 | ||
| 1028 | <YueDisplay> | ||
| 1029 | |||
| 1030 | ```yue | ||
| 1031 | class Inventory | ||
| 1032 | new: => | ||
| 1033 | @items = {} | ||
| 1034 | |||
| 1035 | add_item: (name) => | ||
| 1036 | if @items[name] | ||
| 1037 | @items[name] += 1 | ||
| 1038 | else | ||
| 1039 | @items[name] = 1 | ||
| 1040 | ``` | ||
| 1041 | |||
| 1042 | </YueDisplay> | ||
| 1043 | |||
| 1044 |   在月之脚本中采用面向对象的编程方式时,通常会使用类声明语句结合 Lua 表格字面量来做类定义。这个类的定义包含了它的所有方法和属性。在这种结构中,键名为 “new” 的成员扮演了一个重要的角色,是作为构造函数来使用。 | 501 |   在月之脚本中采用面向对象的编程方式时,通常会使用类声明语句结合 Lua 表格字面量来做类定义。这个类的定义包含了它的所有方法和属性。在这种结构中,键名为 “new” 的成员扮演了一个重要的角色,是作为构造函数来使用。 |
| 1045 | 502 | ||
| 1046 |   值得注意的是,类中的方法都采用了粗箭头函数语法。当在类的实例上调用方法时,该实例会自动作为第一个参数被传入,因此粗箭头函数用于生成一个名为 “self” 的参数。 | 503 |   值得注意的是,类中的方法都采用了粗箭头函数语法。当在类的实例上调用方法时,该实例会自动作为第一个参数被传入,因此粗箭头函数用于生成一个名为 “self” 的参数。 |
| @@ -1055,16 +512,6 @@ inv\add_item "t-shirt" | |||
| 1055 | inv\add_item "pants" | 512 | inv\add_item "pants" |
| 1056 | ``` | 513 | ``` |
| 1057 | 514 | ||
| 1058 | <YueDisplay> | ||
| 1059 | |||
| 1060 | ```yue | ||
| 1061 | inv = Inventory! | ||
| 1062 | inv\add_item "t-shirt" | ||
| 1063 | inv\add_item "pants" | ||
| 1064 | ``` | ||
| 1065 | |||
| 1066 | </YueDisplay> | ||
| 1067 | |||
| 1068 |   在月之脚本的类中,由于需要将类的实例作为参数传入到调用的方法中,因此使用了 **\\** 操作符做类的成员函数调用。 | 515 |   在月之脚本的类中,由于需要将类的实例作为参数传入到调用的方法中,因此使用了 **\\** 操作符做类的成员函数调用。 |
| 1069 | 516 | ||
| 1070 |   需要特别注意的是,类的所有属性在其实例之间是共享的。这对于函数类型的成员属性通常不会造成问题,但对于其他类型的属性,可能会导致意外的结果。 | 517 |   需要特别注意的是,类的所有属性在其实例之间是共享的。这对于函数类型的成员属性通常不会造成问题,但对于其他类型的属性,可能会导致意外的结果。 |
| @@ -1087,26 +534,6 @@ b\give_item "shirt" | |||
| 1087 | print item for item in *a.clothes | 534 | print item for item in *a.clothes |
| 1088 | ``` | 535 | ``` |
| 1089 | 536 | ||
| 1090 | <YueDisplay> | ||
| 1091 | |||
| 1092 | ```yue | ||
| 1093 | class Person | ||
| 1094 | clothes: [] | ||
| 1095 | give_item: (name) => | ||
| 1096 | table.insert @clothes, name | ||
| 1097 | |||
| 1098 | a = Person! | ||
| 1099 | b = Person! | ||
| 1100 | |||
| 1101 | a\give_item "pants" | ||
| 1102 | b\give_item "shirt" | ||
| 1103 | |||
| 1104 | -- 会同时打印出裤子和衬衫 | ||
| 1105 | print item for item in *a.clothes | ||
| 1106 | ``` | ||
| 1107 | |||
| 1108 | </YueDisplay> | ||
| 1109 | |||
| 1110 |   避免这个问题的正确方法是在构造函数中创建对象的可变状态: | 537 |   避免这个问题的正确方法是在构造函数中创建对象的可变状态: |
| 1111 | 538 | ||
| 1112 | ```yuescript | 539 | ```yuescript |
| @@ -1115,16 +542,6 @@ class Person | |||
| 1115 | @clothes = [] | 542 | @clothes = [] |
| 1116 | ``` | 543 | ``` |
| 1117 | 544 | ||
| 1118 | <YueDisplay> | ||
| 1119 | |||
| 1120 | ```yue | ||
| 1121 | class Person | ||
| 1122 | new: => | ||
| 1123 | @clothes = [] | ||
| 1124 | ``` | ||
| 1125 | |||
| 1126 | </YueDisplay> | ||
| 1127 | |||
| 1128 | ## 继承 | 545 | ## 继承 |
| 1129 | 546 | ||
| 1130 |   `extends` 关键字可以在类声明中使用,以继承另一个类的属性和方法。 | 547 |   `extends` 关键字可以在类声明中使用,以继承另一个类的属性和方法。 |
| @@ -1137,18 +554,6 @@ class BackPack extends Inventory | |||
| 1137 | super name | 554 | super name |
| 1138 | ``` | 555 | ``` |
| 1139 | 556 | ||
| 1140 | <YueDisplay> | ||
| 1141 | |||
| 1142 | ```yue | ||
| 1143 | class BackPack extends Inventory | ||
| 1144 | size: 10 | ||
| 1145 | add_item: (name) => | ||
| 1146 | if #@items > size then error "背包已满" | ||
| 1147 | super name | ||
| 1148 | ``` | ||
| 1149 | |||
| 1150 | </YueDisplay> | ||
| 1151 | |||
| 1152 |   在这一部分,我们对月之脚本中的 `Inventory` 类进行了扩展,加入了对可以携带物品数量的限制。 | 557 |   在这一部分,我们对月之脚本中的 `Inventory` 类进行了扩展,加入了对可以携带物品数量的限制。 |
| 1153 | 558 | ||
| 1154 |   在这个特定的例子中,子类并没有定义自己的构造函数。因此,当创建一个新的实例时,系统会默认调用父类的构造函数。但如果我们在子类中定义了构造函数,我们可以利用 `super` 方法来调用并执行父类的构造函数。 | 559 |   在这个特定的例子中,子类并没有定义自己的构造函数。因此,当创建一个新的实例时,系统会默认调用父类的构造函数。但如果我们在子类中定义了构造函数,我们可以利用 `super` 方法来调用并执行父类的构造函数。 |
| @@ -1164,19 +569,6 @@ class Shelf | |||
| 1164 | class Cupboard extends Shelf | 569 | class Cupboard extends Shelf |
| 1165 | ``` | 570 | ``` |
| 1166 | 571 | ||
| 1167 | <YueDisplay> | ||
| 1168 | |||
| 1169 | ```yue | ||
| 1170 | class Shelf | ||
| 1171 | @__inherited: (child) => | ||
| 1172 | print @__name, "被", child.__name, "继承" | ||
| 1173 | |||
| 1174 | -- 将打印: Shelf 被 Cupboard 继承 | ||
| 1175 | class Cupboard extends Shelf | ||
| 1176 | ``` | ||
| 1177 | |||
| 1178 | </YueDisplay> | ||
| 1179 | |||
| 1180 | ## super 关键字 | 572 | ## super 关键字 |
| 1181 | 573 | ||
| 1182 |   `super` 是一个特别的关键字,它有两种不同的使用方式:既可以当作一个对象来看待,也可以像调用函数那样使用。它仅在类的内部使用时具有特殊的功能。 | 574 |   `super` 是一个特别的关键字,它有两种不同的使用方式:既可以当作一个对象来看待,也可以像调用函数那样使用。它仅在类的内部使用时具有特殊的功能。 |
| @@ -1201,22 +593,6 @@ class MyClass extends ParentClass | |||
| 1201 | assert super == ParentClass | 593 | assert super == ParentClass |
| 1202 | ``` | 594 | ``` |
| 1203 | 595 | ||
| 1204 | <YueDisplay> | ||
| 1205 | |||
| 1206 | ```yue | ||
| 1207 | class MyClass extends ParentClass | ||
| 1208 | a_method: => | ||
| 1209 | -- 以下效果相同: | ||
| 1210 | super "你好", "世界" | ||
| 1211 | super\a_method "你好", "世界" | ||
| 1212 | super.a_method self, "你好", "世界" | ||
| 1213 | |||
| 1214 | -- super 作为值等于父类: | ||
| 1215 | assert super == ParentClass | ||
| 1216 | ``` | ||
| 1217 | |||
| 1218 | </YueDisplay> | ||
| 1219 | |||
| 1220 |   **super** 也可以用在函数存根的左侧。唯一的主要区别是,生成的函数不是绑定到 super 的值,而是绑定到 self。 | 596 |   **super** 也可以用在函数存根的左侧。唯一的主要区别是,生成的函数不是绑定到 super 的值,而是绑定到 self。 |
| 1221 | 597 | ||
| 1222 | ## 类型 | 598 | ## 类型 |
| @@ -1230,17 +606,6 @@ assert b.__class == BackPack | |||
| 1230 | print BackPack.size -- 打印 10 | 606 | print BackPack.size -- 打印 10 |
| 1231 | ``` | 607 | ``` |
| 1232 | 608 | ||
| 1233 | <YueDisplay> | ||
| 1234 | |||
| 1235 | ```yue | ||
| 1236 | b = BackPack! | ||
| 1237 | assert b.__class == BackPack | ||
| 1238 | |||
| 1239 | print BackPack.size -- 打印 10 | ||
| 1240 | ``` | ||
| 1241 | |||
| 1242 | </YueDisplay> | ||
| 1243 | |||
| 1244 | ## 类对象 | 609 | ## 类对象 |
| 1245 | 610 | ||
| 1246 |   在月之脚本中,当我们编写类的定义语句时,实际上是在创建一个类对象。这个类对象被保存在一个与该类同名的变量中。 | 611 |   在月之脚本中,当我们编写类的定义语句时,实际上是在创建一个类对象。这个类对象被保存在一个与该类同名的变量中。 |
| @@ -1259,14 +624,6 @@ print BackPack.size -- 打印 10 | |||
| 1259 | print BackPack.__name -- 打印 Backpack | 624 | print BackPack.__name -- 打印 Backpack |
| 1260 | ``` | 625 | ``` |
| 1261 | 626 | ||
| 1262 | <YueDisplay> | ||
| 1263 | |||
| 1264 | ```yue | ||
| 1265 | print BackPack.__name -- 打印 Backpack | ||
| 1266 | ``` | ||
| 1267 | |||
| 1268 | </YueDisplay> | ||
| 1269 | |||
| 1270 |   基础对象被保存在一个名为 `__base` 的特殊表中。我们可以编辑这个表,以便为那些已经创建出来的实例和还未创建的实例增加新的功能。 | 627 |   基础对象被保存在一个名为 `__base` 的特殊表中。我们可以编辑这个表,以便为那些已经创建出来的实例和还未创建的实例增加新的功能。 |
| 1271 | 628 | ||
| 1272 |   另外,如果一个类是从另一个类派生而来的,那么其父类对象则会被存储在名为 `__parent` 的地方。这种机制允许在类之间实现继承和功能扩展。 | 629 |   另外,如果一个类是从另一个类派生而来的,那么其父类对象则会被存储在名为 `__parent` 的地方。这种机制允许在类之间实现继承和功能扩展。 |
| @@ -1285,20 +642,6 @@ Things\some_func! | |||
| 1285 | assert Things().some_func == nil | 642 | assert Things().some_func == nil |
| 1286 | ``` | 643 | ``` |
| 1287 | 644 | ||
| 1288 | <YueDisplay> | ||
| 1289 | |||
| 1290 | ```yue | ||
| 1291 | class Things | ||
| 1292 | @some_func: => print "Hello from", @__name | ||
| 1293 | |||
| 1294 | Things\some_func! | ||
| 1295 | |||
| 1296 | -- 类变量在实例中不可见 | ||
| 1297 | assert Things().some_func == nil | ||
| 1298 | ``` | ||
| 1299 | |||
| 1300 | </YueDisplay> | ||
| 1301 | |||
| 1302 |   在表达式中,我们可以使用 @@ 来访问存储在 `self.__class` 中的值。因此,`@@hello` 是 `self.__class.hello` 的简写。 | 645 |   在表达式中,我们可以使用 @@ 来访问存储在 `self.__class` 中的值。因此,`@@hello` 是 `self.__class.hello` 的简写。 |
| 1303 | 646 | ||
| 1304 | ```yuescript | 647 | ```yuescript |
| @@ -1314,37 +657,12 @@ Counter! | |||
| 1314 | print Counter.count -- 输出 2 | 657 | print Counter.count -- 输出 2 |
| 1315 | ``` | 658 | ``` |
| 1316 | 659 | ||
| 1317 | <YueDisplay> | ||
| 1318 | |||
| 1319 | ```yue | ||
| 1320 | class Counter | ||
| 1321 | @count: 0 | ||
| 1322 | |||
| 1323 | new: => | ||
| 1324 | @@count += 1 | ||
| 1325 | |||
| 1326 | Counter! | ||
| 1327 | Counter! | ||
| 1328 | |||
| 1329 | print Counter.count -- 输出 2 | ||
| 1330 | ``` | ||
| 1331 | |||
| 1332 | </YueDisplay> | ||
| 1333 | |||
| 1334 |   @@ 的调用语义与 @ 类似。调用 @@ 时,会使用 Lua 的冒号语法将类作为第一个参数传入。 | 660 |   @@ 的调用语义与 @ 类似。调用 @@ 时,会使用 Lua 的冒号语法将类作为第一个参数传入。 |
| 1335 | 661 | ||
| 1336 | ```yuescript | 662 | ```yuescript |
| 1337 | @@hello 1,2,3,4 | 663 | @@hello 1,2,3,4 |
| 1338 | ``` | 664 | ``` |
| 1339 | 665 | ||
| 1340 | <YueDisplay> | ||
| 1341 | |||
| 1342 | ```yue | ||
| 1343 | @@hello 1,2,3,4 | ||
| 1344 | ``` | ||
| 1345 | |||
| 1346 | </YueDisplay> | ||
| 1347 | |||
| 1348 | ## 类声明语句 | 666 | ## 类声明语句 |
| 1349 | 667 | ||
| 1350 |   在类声明的主体中,除了键/值对外,我们还可以编写普通的表达式。在这种类声明体中的普通代码的上下文中,self 等于类对象,而不是实例对象。 | 668 |   在类声明的主体中,除了键/值对外,我们还可以编写普通的表达式。在这种类声明体中的普通代码的上下文中,self 等于类对象,而不是实例对象。 |
| @@ -1356,15 +674,6 @@ class Things | |||
| 1356 | @class_var = "hello world" | 674 | @class_var = "hello world" |
| 1357 | ``` | 675 | ``` |
| 1358 | 676 | ||
| 1359 | <YueDisplay> | ||
| 1360 | |||
| 1361 | ```yue | ||
| 1362 | class Things | ||
| 1363 | @class_var = "hello world" | ||
| 1364 | ``` | ||
| 1365 | |||
| 1366 | </YueDisplay> | ||
| 1367 | |||
| 1368 |   这些表达式会在所有属性被添加到类的基对象后执行。 | 677 |   这些表达式会在所有属性被添加到类的基对象后执行。 |
| 1369 | 678 | ||
| 1370 |   在类的主体中声明的所有变量都会限制作用域只在类声明的范围。这对于放置只有类方法可以访问的私有值或辅助函数很方便: | 679 |   在类的主体中声明的所有变量都会限制作用域只在类声明的范围。这对于放置只有类方法可以访问的私有值或辅助函数很方便: |
| @@ -1378,19 +687,6 @@ class MoreThings | |||
| 1378 | log "hello world: " .. secret | 687 | log "hello world: " .. secret |
| 1379 | ``` | 688 | ``` |
| 1380 | 689 | ||
| 1381 | <YueDisplay> | ||
| 1382 | |||
| 1383 | ```yue | ||
| 1384 | class MoreThings | ||
| 1385 | secret = 123 | ||
| 1386 | log = (msg) -> print "LOG:", msg | ||
| 1387 | |||
| 1388 | some_method: => | ||
| 1389 | log "hello world: " .. secret | ||
| 1390 | ``` | ||
| 1391 | |||
| 1392 | </YueDisplay> | ||
| 1393 | |||
| 1394 | ## @ 和 @@ 值 | 690 | ## @ 和 @@ 值 |
| 1395 | 691 | ||
| 1396 |   当 @ 和 @@ 前缀在一个名字前时,它们分别代表在 self 和 self.\_\_class 中访问的那个名字。 | 692 |   当 @ 和 @@ 前缀在一个名字前时,它们分别代表在 self 和 self.\_\_class 中访问的那个名字。 |
| @@ -1402,29 +698,12 @@ assert @ == self | |||
| 1402 | assert @@ == self.__class | 698 | assert @@ == self.__class |
| 1403 | ``` | 699 | ``` |
| 1404 | 700 | ||
| 1405 | <YueDisplay> | ||
| 1406 | |||
| 1407 | ```yue | ||
| 1408 | assert @ == self | ||
| 1409 | assert @@ == self.__class | ||
| 1410 | ``` | ||
| 1411 | |||
| 1412 | </YueDisplay> | ||
| 1413 | |||
| 1414 |   例如,使用 @@ 从实例方法快速创建同一类的新实例的方法: | 701 |   例如,使用 @@ 从实例方法快速创建同一类的新实例的方法: |
| 1415 | 702 | ||
| 1416 | ```yuescript | 703 | ```yuescript |
| 1417 | some_instance_method = (...) => @@ ... | 704 | some_instance_method = (...) => @@ ... |
| 1418 | ``` | 705 | ``` |
| 1419 | 706 | ||
| 1420 | <YueDisplay> | ||
| 1421 | |||
| 1422 | ```yue | ||
| 1423 | some_instance_method = (...) => @@ ... | ||
| 1424 | ``` | ||
| 1425 | |||
| 1426 | </YueDisplay> | ||
| 1427 | |||
| 1428 | ## 构造属性提升 | 707 | ## 构造属性提升 |
| 1429 | 708 | ||
| 1430 |   为了减少编写简单值对象定义的代码。你可以这样简单写一个类: | 709 |   为了减少编写简单值对象定义的代码。你可以这样简单写一个类: |
| @@ -1443,24 +722,6 @@ class Something | |||
| 1443 | @@baz = baz | 722 | @@baz = baz |
| 1444 | ``` | 723 | ``` |
| 1445 | 724 | ||
| 1446 | <YueDisplay> | ||
| 1447 | |||
| 1448 | ```yue | ||
| 1449 | class Something | ||
| 1450 | new: (@foo, @bar, @@biz, @@baz) => | ||
| 1451 | |||
| 1452 | -- 这是以下声明的简写形式 | ||
| 1453 | |||
| 1454 | class Something | ||
| 1455 | new: (foo, bar, biz, baz) => | ||
| 1456 | @foo = foo | ||
| 1457 | @bar = bar | ||
| 1458 | @@biz = biz | ||
| 1459 | @@baz = baz | ||
| 1460 | ``` | ||
| 1461 | |||
| 1462 | </YueDisplay> | ||
| 1463 | |||
| 1464 |   你也可以使用这种语法为一个函数初始化传入对象的字段。 | 725 |   你也可以使用这种语法为一个函数初始化传入对象的字段。 |
| 1465 | 726 | ||
| 1466 | ```yuescript | 727 | ```yuescript |
| @@ -1469,16 +730,6 @@ obj = new {}, 123, "abc" | |||
| 1469 | print obj | 730 | print obj |
| 1470 | ``` | 731 | ``` |
| 1471 | 732 | ||
| 1472 | <YueDisplay> | ||
| 1473 | |||
| 1474 | ```yue | ||
| 1475 | new = (@fieldA, @fieldB) => @ | ||
| 1476 | obj = new {}, 123, "abc" | ||
| 1477 | print obj | ||
| 1478 | ``` | ||
| 1479 | |||
| 1480 | </YueDisplay> | ||
| 1481 | |||
| 1482 | ## 类表达式 | 733 | ## 类表达式 |
| 1483 | 734 | ||
| 1484 |   类声明的语法也可以作为一个表达式使用,可以赋值给一个变量或者被返回语句返回。 | 735 |   类声明的语法也可以作为一个表达式使用,可以赋值给一个变量或者被返回语句返回。 |
| @@ -1489,16 +740,6 @@ x = class Bucket | |||
| 1489 | add_drop: => @drops += 1 | 740 | add_drop: => @drops += 1 |
| 1490 | ``` | 741 | ``` |
| 1491 | 742 | ||
| 1492 | <YueDisplay> | ||
| 1493 | |||
| 1494 | ```yue | ||
| 1495 | x = class Bucket | ||
| 1496 | drops: 0 | ||
| 1497 | add_drop: => @drops += 1 | ||
| 1498 | ``` | ||
| 1499 | |||
| 1500 | </YueDisplay> | ||
| 1501 | |||
| 1502 | ## 匿名类 | 743 | ## 匿名类 |
| 1503 | 744 | ||
| 1504 |   声明类时可以省略名称。如果类的表达式不在赋值语句中,\_\_name 属性将为 nil。如果出现在赋值语句中,赋值操作左侧的名称将代替 nil。 | 745 |   声明类时可以省略名称。如果类的表达式不在赋值语句中,\_\_name 属性将为 nil。如果出现在赋值语句中,赋值操作左侧的名称将代替 nil。 |
| @@ -1510,31 +751,12 @@ BigBucket = class extends Bucket | |||
| 1510 | assert Bucket.__name == "BigBucket" | 751 | assert Bucket.__name == "BigBucket" |
| 1511 | ``` | 752 | ``` |
| 1512 | 753 | ||
| 1513 | <YueDisplay> | ||
| 1514 | |||
| 1515 | ```yue | ||
| 1516 | BigBucket = class extends Bucket | ||
| 1517 | add_drop: => @drops += 10 | ||
| 1518 | |||
| 1519 | assert Bucket.__name == "BigBucket" | ||
| 1520 | ``` | ||
| 1521 | |||
| 1522 | </YueDisplay> | ||
| 1523 | |||
| 1524 |   你甚至可以省略掉主体,这意味着你可以这样写一个空白的匿名类: | 754 |   你甚至可以省略掉主体,这意味着你可以这样写一个空白的匿名类: |
| 1525 | 755 | ||
| 1526 | ```yuescript | 756 | ```yuescript |
| 1527 | x = class | 757 | x = class |
| 1528 | ``` | 758 | ``` |
| 1529 | 759 | ||
| 1530 | <YueDisplay> | ||
| 1531 | |||
| 1532 | ```yue | ||
| 1533 | x = class | ||
| 1534 | ``` | ||
| 1535 | |||
| 1536 | </YueDisplay> | ||
| 1537 | |||
| 1538 | ## 类混合 | 760 | ## 类混合 |
| 1539 | 761 | ||
| 1540 |   你可以通过使用 `using` 关键字来实现类混合。这意味着你可以从一个普通 Lua 表格或已定义的类对象中,复制函数到你创建的新类中。当你使用普通 Lua 表格进行类混合时,你有机会用自己的实现来重写类的索引方法(例如元方法 `__index`)。然而,当你从一个类对象做混合时,需要注意的是该类对象的元方法将不会被复制到新类。 | 762 |   你可以通过使用 `using` 关键字来实现类混合。这意味着你可以从一个普通 Lua 表格或已定义的类对象中,复制函数到你创建的新类中。当你使用普通 Lua 表格进行类混合时,你有机会用自己的实现来重写类的索引方法(例如元方法 `__index`)。然而,当你从一个类对象做混合时,需要注意的是该类对象的元方法将不会被复制到新类。 |
| @@ -1557,28 +779,6 @@ y\func! | |||
| 1557 | assert y.__class.__parent ~= X -- X 不是 Y 的父类 | 779 | assert y.__class.__parent ~= X -- X 不是 Y 的父类 |
| 1558 | ``` | 780 | ``` |
| 1559 | 781 | ||
| 1560 | <YueDisplay> | ||
| 1561 | |||
| 1562 | ```yue | ||
| 1563 | MyIndex = __index: var: 1 | ||
| 1564 | |||
| 1565 | class X using MyIndex | ||
| 1566 | func: => | ||
| 1567 | print 123 | ||
| 1568 | |||
| 1569 | x = X! | ||
| 1570 | print x.var | ||
| 1571 | |||
| 1572 | class Y using X | ||
| 1573 | |||
| 1574 | y = Y! | ||
| 1575 | y\func! | ||
| 1576 | |||
| 1577 | assert y.__class.__parent ~= X -- X 不是 Y 的父类 | ||
| 1578 | ``` | ||
| 1579 | |||
| 1580 | </YueDisplay> | ||
| 1581 | |||
| 1582 | # with 语句 | 782 | # with 语句 |
| 1583 | 783 | ||
| 1584 | 在编写 Lua 代码时,我们在创建对象后的常见操作是立即调用这个对象一系列操作函数并设置一系列属性。 | 784 | 在编写 Lua 代码时,我们在创建对象后的常见操作是立即调用这个对象一系列操作函数并设置一系列属性。 |
| @@ -1597,18 +797,6 @@ with Person! | |||
| 1597 | print .name | 797 | print .name |
| 1598 | ``` | 798 | ``` |
| 1599 | 799 | ||
| 1600 | <YueDisplay> | ||
| 1601 | |||
| 1602 | ```yue | ||
| 1603 | with Person! | ||
| 1604 | .name = "Oswald" | ||
| 1605 | \add_relative my_dad | ||
| 1606 | \save! | ||
| 1607 | print .name | ||
| 1608 | ``` | ||
| 1609 | |||
| 1610 | </YueDisplay> | ||
| 1611 | |||
| 1612 | with 语句也可以用作一个表达式,并返回它的代码块正在处理的对象。 | 800 | with 语句也可以用作一个表达式,并返回它的代码块正在处理的对象。 |
| 1613 | 801 | ||
| 1614 | ```yuescript | 802 | ```yuescript |
| @@ -1616,15 +804,6 @@ file = with File "favorite_foods.txt" | |||
| 1616 | \set_encoding "utf8" | 804 | \set_encoding "utf8" |
| 1617 | ``` | 805 | ``` |
| 1618 | 806 | ||
| 1619 | <YueDisplay> | ||
| 1620 | |||
| 1621 | ```yue | ||
| 1622 | file = with File "favorite_foods.txt" | ||
| 1623 | \set_encoding "utf8" | ||
| 1624 | ``` | ||
| 1625 | |||
| 1626 | </YueDisplay> | ||
| 1627 | |||
| 1628 | `with` 表达式支持 `break` 返回一个值: | 807 | `with` 表达式支持 `break` 返回一个值: |
| 1629 | 808 | ||
| 1630 | ```yuescript | 809 | ```yuescript |
| @@ -1632,15 +811,6 @@ result = with obj | |||
| 1632 | break .value | 811 | break .value |
| 1633 | ``` | 812 | ``` |
| 1634 | 813 | ||
| 1635 | <YueDisplay> | ||
| 1636 | |||
| 1637 | ```yue | ||
| 1638 | result = with obj | ||
| 1639 | break .value | ||
| 1640 | ``` | ||
| 1641 | |||
| 1642 | </YueDisplay> | ||
| 1643 | |||
| 1644 | 在 `with` 中使用 `break value` 后,`with` 表达式将不再返回其目标对象,而是返回 `break` 给出的值。 | 814 | 在 `with` 中使用 `break value` 后,`with` 表达式将不再返回其目标对象,而是返回 `break` 给出的值。 |
| 1645 | 815 | ||
| 1646 | ```yuescript | 816 | ```yuescript |
| @@ -1653,20 +823,6 @@ b = with obj | |||
| 1653 | -- b 是 .x,不是 obj | 823 | -- b 是 .x,不是 obj |
| 1654 | ``` | 824 | ``` |
| 1655 | 825 | ||
| 1656 | <YueDisplay> | ||
| 1657 | |||
| 1658 | ```yue | ||
| 1659 | a = with obj | ||
| 1660 | .x = 1 | ||
| 1661 | -- a 是 obj | ||
| 1662 | |||
| 1663 | b = with obj | ||
| 1664 | break .x | ||
| 1665 | -- b 是 .x,不是 obj | ||
| 1666 | ``` | ||
| 1667 | |||
| 1668 | </YueDisplay> | ||
| 1669 | |||
| 1670 | 与 `for` / `while` / `repeat` / `do` 不同,`with` 只支持一个 break 返回值。 | 826 | 与 `for` / `while` / `repeat` / `do` 不同,`with` 只支持一个 break 返回值。 |
| 1671 | 827 | ||
| 1672 | 或者… | 828 | 或者… |
| @@ -1680,19 +836,6 @@ create_person = (name, relatives) -> | |||
| 1680 | me = create_person "Leaf", [dad, mother, sister] | 836 | me = create_person "Leaf", [dad, mother, sister] |
| 1681 | ``` | 837 | ``` |
| 1682 | 838 | ||
| 1683 | <YueDisplay> | ||
| 1684 | |||
| 1685 | ```yue | ||
| 1686 | create_person = (name, relatives) -> | ||
| 1687 | with Person! | ||
| 1688 | .name = name | ||
| 1689 | \add_relative relative for relative in *relatives | ||
| 1690 | |||
| 1691 | me = create_person "Leaf", [dad, mother, sister] | ||
| 1692 | ``` | ||
| 1693 | |||
| 1694 | </YueDisplay> | ||
| 1695 | |||
| 1696 | 在此用法中,with 可以被视为K组合子(k-combinator)的一种特殊形式。 | 839 | 在此用法中,with 可以被视为K组合子(k-combinator)的一种特殊形式。 |
| 1697 | 840 | ||
| 1698 | 如果你想给表达式另外起一个名称的话,with 语句中的表达式也可以是一个赋值语句。 | 841 | 如果你想给表达式另外起一个名称的话,with 语句中的表达式也可以是一个赋值语句。 |
| @@ -1703,16 +846,6 @@ with str := "你好" | |||
| 1703 | print "大写:", \upper! | 846 | print "大写:", \upper! |
| 1704 | ``` | 847 | ``` |
| 1705 | 848 | ||
| 1706 | <YueDisplay> | ||
| 1707 | |||
| 1708 | ```yue | ||
| 1709 | with str := "你好" | ||
| 1710 | print "原始:", str | ||
| 1711 | print "大写:", \upper! | ||
| 1712 | ``` | ||
| 1713 | |||
| 1714 | </YueDisplay> | ||
| 1715 | |||
| 1716 | 你可以在 `with` 语句中使用 `[]` 访问特殊键。 | 849 | 你可以在 `with` 语句中使用 `[]` 访问特殊键。 |
| 1717 | 850 | ||
| 1718 | ```yuescript | 851 | ```yuescript |
| @@ -1725,20 +858,6 @@ with tb | |||
| 1725 | [] = "abc" -- 追加到 "tb" | 858 | [] = "abc" -- 追加到 "tb" |
| 1726 | ``` | 859 | ``` |
| 1727 | 860 | ||
| 1728 | <YueDisplay> | ||
| 1729 | |||
| 1730 | ```yue | ||
| 1731 | with tb | ||
| 1732 | [1] = 1 | ||
| 1733 | print [2] | ||
| 1734 | with [abc] | ||
| 1735 | [3] = [2]\func! | ||
| 1736 | ["key-name"] = value | ||
| 1737 | [] = "abc" -- 追加到 "tb" | ||
| 1738 | ``` | ||
| 1739 | |||
| 1740 | </YueDisplay> | ||
| 1741 | |||
| 1742 | `with?` 是 `with` 语法的一个增强版本,引入了存在性检查,用于在不显式判空的情况下安全访问可能为 nil 的对象。 | 861 | `with?` 是 `with` 语法的一个增强版本,引入了存在性检查,用于在不显式判空的情况下安全访问可能为 nil 的对象。 |
| 1743 | 862 | ||
| 1744 | ```yuescript | 863 | ```yuescript |
| @@ -1746,15 +865,6 @@ with? obj | |||
| 1746 | print obj.name | 865 | print obj.name |
| 1747 | ``` | 866 | ``` |
| 1748 | 867 | ||
| 1749 | <YueDisplay> | ||
| 1750 | |||
| 1751 | ```yue | ||
| 1752 | with? obj | ||
| 1753 | print obj.name | ||
| 1754 | ``` | ||
| 1755 | |||
| 1756 | </YueDisplay> | ||
| 1757 | |||
| 1758 | # 赋值 | 868 | # 赋值 |
| 1759 | 869 | ||
| 1760 |   月之脚本中定义的变量是动态类型的,并默认为局部变量。但你可以通过 **local** 和 **global** 声明来改变声明变量的作用范围。 | 870 |   月之脚本中定义的变量是动态类型的,并默认为局部变量。但你可以通过 **local** 和 **global** 声明来改变声明变量的作用范围。 |
| @@ -1765,16 +875,6 @@ a, b, c = 1, 2, 3 | |||
| 1765 | hello = 123 -- 访问现有的变量 | 875 | hello = 123 -- 访问现有的变量 |
| 1766 | ``` | 876 | ``` |
| 1767 | 877 | ||
| 1768 | <YueDisplay> | ||
| 1769 | |||
| 1770 | ```yue | ||
| 1771 | hello = "world" | ||
| 1772 | a, b, c = 1, 2, 3 | ||
| 1773 | hello = 123 -- 访问现有的变量 | ||
| 1774 | ``` | ||
| 1775 | |||
| 1776 | </YueDisplay> | ||
| 1777 | |||
| 1778 | ## 执行更新 | 878 | ## 执行更新 |
| 1779 | 879 | ||
| 1780 |   你可以使用各式二进制运算符执行更新赋值。 | 880 |   你可以使用各式二进制运算符执行更新赋值。 |
| @@ -1790,21 +890,6 @@ s ..= "world" -- 如果执行更新的局部变量不存在,将新建一个局 | |||
| 1790 | arg or= "默认值" | 890 | arg or= "默认值" |
| 1791 | ``` | 891 | ``` |
| 1792 | 892 | ||
| 1793 | <YueDisplay> | ||
| 1794 | |||
| 1795 | ```yue | ||
| 1796 | x = 1 | ||
| 1797 | x += 1 | ||
| 1798 | x -= 1 | ||
| 1799 | x *= 10 | ||
| 1800 | x /= 10 | ||
| 1801 | x %= 10 | ||
| 1802 | s ..= "world" -- 如果执行更新的局部变量不存在,将新建一个局部变量 | ||
| 1803 | arg or= "默认值" | ||
| 1804 | ``` | ||
| 1805 | |||
| 1806 | </YueDisplay> | ||
| 1807 | |||
| 1808 | ## 链式赋值 | 893 | ## 链式赋值 |
| 1809 | 894 | ||
| 1810 |   你可以进行链式赋值,将多个项目赋予相同的值。 | 895 |   你可以进行链式赋值,将多个项目赋予相同的值。 |
| @@ -1814,15 +899,6 @@ a = b = c = d = e = 0 | |||
| 1814 | x = y = z = f! | 899 | x = y = z = f! |
| 1815 | ``` | 900 | ``` |
| 1816 | 901 | ||
| 1817 | <YueDisplay> | ||
| 1818 | |||
| 1819 | ```yue | ||
| 1820 | a = b = c = d = e = 0 | ||
| 1821 | x = y = z = f! | ||
| 1822 | ``` | ||
| 1823 | |||
| 1824 | </YueDisplay> | ||
| 1825 | |||
| 1826 | ## 显式声明局部变量 | 902 | ## 显式声明局部变量 |
| 1827 | 903 | ||
| 1828 | ```yuescript | 904 | ```yuescript |
| @@ -1842,27 +918,6 @@ do | |||
| 1842 | B = 2 | 918 | B = 2 |
| 1843 | ``` | 919 | ``` |
| 1844 | 920 | ||
| 1845 | <YueDisplay> | ||
| 1846 | |||
| 1847 | ```yue | ||
| 1848 | do | ||
| 1849 | local a = 1 | ||
| 1850 | local * | ||
| 1851 | print "预先声明后续所有变量为局部变量" | ||
| 1852 | x = -> 1 + y + z | ||
| 1853 | y, z = 2, 3 | ||
| 1854 | global instance = Item\new! | ||
| 1855 | |||
| 1856 | do | ||
| 1857 | local X = 1 | ||
| 1858 | local ^ | ||
| 1859 | print "只预先声明后续大写的变量为局部变量" | ||
| 1860 | a = 1 | ||
| 1861 | B = 2 | ||
| 1862 | ``` | ||
| 1863 | |||
| 1864 | </YueDisplay> | ||
| 1865 | |||
| 1866 | ## 显式声明全局变量 | 921 | ## 显式声明全局变量 |
| 1867 | 922 | ||
| 1868 | ```yuescript | 923 | ```yuescript |
| @@ -1882,27 +937,6 @@ do | |||
| 1882 | local Temp = "一个局部值" | 937 | local Temp = "一个局部值" |
| 1883 | ``` | 938 | ``` |
| 1884 | 939 | ||
| 1885 | <YueDisplay> | ||
| 1886 | |||
| 1887 | ```yue | ||
| 1888 | do | ||
| 1889 | global a = 1 | ||
| 1890 | global * | ||
| 1891 | print "预先声明所有变量为全局变量" | ||
| 1892 | x = -> 1 + y + z | ||
| 1893 | y, z = 2, 3 | ||
| 1894 | |||
| 1895 | do | ||
| 1896 | global x = 1 | ||
| 1897 | global ^ | ||
| 1898 | print "只预先声明大写的变量为全局变量" | ||
| 1899 | a = 1 | ||
| 1900 | B = 2 | ||
| 1901 | local Temp = "一个局部值" | ||
| 1902 | ``` | ||
| 1903 | |||
| 1904 | </YueDisplay> | ||
| 1905 | |||
| 1906 | # 可变参数赋值 | 940 | # 可变参数赋值 |
| 1907 | 941 | ||
| 1908 |   你可以将函数返回的结果赋值给一个可变参数符号 `...`。然后使用 Lua 的方式访问其内容。 | 942 |   你可以将函数返回的结果赋值给一个可变参数符号 `...`。然后使用 Lua 的方式访问其内容。 |
| @@ -1916,19 +950,6 @@ first = select 1, ... | |||
| 1916 | print ok, count, first | 950 | print ok, count, first |
| 1917 | ``` | 951 | ``` |
| 1918 | 952 | ||
| 1919 | <YueDisplay> | ||
| 1920 | |||
| 1921 | ```yue | ||
| 1922 | list = [1, 2, 3, 4, 5] | ||
| 1923 | fn = (ok) -> ok, table.unpack list | ||
| 1924 | ok, ... = fn true | ||
| 1925 | count = select '#', ... | ||
| 1926 | first = select 1, ... | ||
| 1927 | print ok, count, first | ||
| 1928 | ``` | ||
| 1929 | |||
| 1930 | </YueDisplay> | ||
| 1931 | |||
| 1932 | # If 赋值 | 953 | # If 赋值 |
| 1933 | 954 | ||
| 1934 |   `if` 和 `elseif` 代码块可以在条件表达式的位置进行赋值。在代码执行到要计算条件时,会首先进行赋值计算,并使用赋与的值作为分支判断的条件。赋值的变量仅在条件分支的代码块内有效,这意味着如果值不是真值,那么它就不会被用到。注意,你必须使用“海象运算符” `:=` 而不是 `=` 来做赋值。 | 955 |   `if` 和 `elseif` 代码块可以在条件表达式的位置进行赋值。在代码执行到要计算条件时,会首先进行赋值计算,并使用赋与的值作为分支判断的条件。赋值的变量仅在条件分支的代码块内有效,这意味着如果值不是真值,那么它就不会被用到。注意,你必须使用“海象运算符” `:=` 而不是 `=` 来做赋值。 |
| @@ -1938,15 +959,6 @@ if user := database.find_user "moon" | |||
| 1938 | print user.name | 959 | print user.name |
| 1939 | ``` | 960 | ``` |
| 1940 | 961 | ||
| 1941 | <YueDisplay> | ||
| 1942 | |||
| 1943 | ```yue | ||
| 1944 | if user := database.find_user "moon" | ||
| 1945 | print user.name | ||
| 1946 | ``` | ||
| 1947 | |||
| 1948 | </YueDisplay> | ||
| 1949 | |||
| 1950 | ```yuescript | 962 | ```yuescript |
| 1951 | if hello := os.getenv "hello" | 963 | if hello := os.getenv "hello" |
| 1952 | print "你有 hello", hello | 964 | print "你有 hello", hello |
| @@ -1956,19 +968,6 @@ else | |||
| 1956 | print "什么都没有 :(" | 968 | print "什么都没有 :(" |
| 1957 | ``` | 969 | ``` |
| 1958 | 970 | ||
| 1959 | <YueDisplay> | ||
| 1960 | |||
| 1961 | ```yue | ||
| 1962 | if hello := os.getenv "hello" | ||
| 1963 | print "你有 hello", hello | ||
| 1964 | elseif world := os.getenv "world" | ||
| 1965 | print "你有 world", world | ||
| 1966 | else | ||
| 1967 | print "什么都没有 :(" | ||
| 1968 | ``` | ||
| 1969 | |||
| 1970 | </YueDisplay> | ||
| 1971 | |||
| 1972 |   使用多个返回值的 If 赋值。只有第一个值会被检查,其他值都有同样的作用域。 | 971 |   使用多个返回值的 If 赋值。只有第一个值会被检查,其他值都有同样的作用域。 |
| 1973 | 972 | ||
| 1974 | ```yuescript | 973 | ```yuescript |
| @@ -1977,16 +976,6 @@ if success, result := pcall -> "无报错地获取结果" | |||
| 1977 | print "好的" | 976 | print "好的" |
| 1978 | ``` | 977 | ``` |
| 1979 | 978 | ||
| 1980 | <YueDisplay> | ||
| 1981 | |||
| 1982 | ```yue | ||
| 1983 | if success, result := pcall -> "无报错地获取结果" | ||
| 1984 | print result -- 变量 result 是有作用域的 | ||
| 1985 | print "好的" | ||
| 1986 | ``` | ||
| 1987 | |||
| 1988 | </YueDisplay> | ||
| 1989 | |||
| 1990 | ## While 赋值 | 979 | ## While 赋值 |
| 1991 | 980 | ||
| 1992 |   你可以在 while 循环中同样使用赋值来获取循环条件的值。 | 981 |   你可以在 while 循环中同样使用赋值来获取循环条件的值。 |
| @@ -1997,16 +986,6 @@ while byte := stream\read_one! | |||
| 1997 | print byte | 986 | print byte |
| 1998 | ``` | 987 | ``` |
| 1999 | 988 | ||
| 2000 | <YueDisplay> | ||
| 2001 | |||
| 2002 | ```yue | ||
| 2003 | while byte := stream\read_one! | ||
| 2004 | -- 对 byte 做一些操作 | ||
| 2005 | print byte | ||
| 2006 | ``` | ||
| 2007 | |||
| 2008 | </YueDisplay> | ||
| 2009 | |||
| 2010 | # 解构赋值 | 989 | # 解构赋值 |
| 2011 | 990 | ||
| 2012 |   解构赋值是一种快速从 Lua 表中按名称或基于数组中的位置提取值的方法。 | 991 |   解构赋值是一种快速从 Lua 表中按名称或基于数组中的位置提取值的方法。 |
| @@ -2022,17 +1001,6 @@ thing = [1, 2] | |||
| 2022 | print a, b | 1001 | print a, b |
| 2023 | ``` | 1002 | ``` |
| 2024 | 1003 | ||
| 2025 | <YueDisplay> | ||
| 2026 | |||
| 2027 | ```yue | ||
| 2028 | thing = [1, 2] | ||
| 2029 | |||
| 2030 | [a, b] = thing | ||
| 2031 | print a, b | ||
| 2032 | ``` | ||
| 2033 | |||
| 2034 | </YueDisplay> | ||
| 2035 | |||
| 2036 |   在解构表格字面量中,键代表从右侧读取的键,值代表读取的值将被赋予的名称。 | 1004 |   在解构表格字面量中,键代表从右侧读取的键,值代表读取的值将被赋予的名称。 |
| 2037 | 1005 | ||
| 2038 | ```yuescript | 1006 | ```yuescript |
| @@ -2048,23 +1016,6 @@ print hello, the_day | |||
| 2048 | :day = obj -- 可以不带大括号进行简单的解构 | 1016 | :day = obj -- 可以不带大括号进行简单的解构 |
| 2049 | ``` | 1017 | ``` |
| 2050 | 1018 | ||
| 2051 | <YueDisplay> | ||
| 2052 | |||
| 2053 | ```yue | ||
| 2054 | obj = { | ||
| 2055 | hello: "world" | ||
| 2056 | day: "tuesday" | ||
| 2057 | length: 20 | ||
| 2058 | } | ||
| 2059 | |||
| 2060 | {hello: hello, day: the_day} = obj | ||
| 2061 | print hello, the_day | ||
| 2062 | |||
| 2063 | :day = obj -- 可以不带大括号进行简单的解构 | ||
| 2064 | ``` | ||
| 2065 | |||
| 2066 | </YueDisplay> | ||
| 2067 | |||
| 2068 |   这也适用于嵌套的数据结构: | 1019 |   这也适用于嵌套的数据结构: |
| 2069 | 1020 | ||
| 2070 | ```yuescript | 1021 | ```yuescript |
| @@ -2080,23 +1031,6 @@ obj2 = { | |||
| 2080 | print first, second, color | 1031 | print first, second, color |
| 2081 | ``` | 1032 | ``` |
| 2082 | 1033 | ||
| 2083 | <YueDisplay> | ||
| 2084 | |||
| 2085 | ```yue | ||
| 2086 | obj2 = { | ||
| 2087 | numbers: [1,2,3,4] | ||
| 2088 | properties: { | ||
| 2089 | color: "green" | ||
| 2090 | height: 13.5 | ||
| 2091 | } | ||
| 2092 | } | ||
| 2093 | |||
| 2094 | {numbers: [first, second], properties: {color: color}} = obj2 | ||
| 2095 | print first, second, color | ||
| 2096 | ``` | ||
| 2097 | |||
| 2098 | </YueDisplay> | ||
| 2099 | |||
| 2100 |   如果解构语句很复杂,也可以任意将其分散在几行中。稍微复杂一些的示例: | 1034 |   如果解构语句很复杂,也可以任意将其分散在几行中。稍微复杂一些的示例: |
| 2101 | 1035 | ||
| 2102 | ```yuescript | 1036 | ```yuescript |
| @@ -2108,75 +1042,30 @@ print first, second, color | |||
| 2108 | } = obj2 | 1042 | } = obj2 |
| 2109 | ``` | 1043 | ``` |
| 2110 | 1044 | ||
| 2111 | <YueDisplay> | ||
| 2112 | |||
| 2113 | ```yue | ||
| 2114 | { | ||
| 2115 | numbers: [first, second] | ||
| 2116 | properties: { | ||
| 2117 | color: color | ||
| 2118 | } | ||
| 2119 | } = obj2 | ||
| 2120 | ``` | ||
| 2121 | |||
| 2122 | </YueDisplay> | ||
| 2123 | |||
| 2124 |   有时候我们会需要从 Lua 表中提取值并将它们赋给与键同名的局部变量。为了避免编写重复代码,我们可以使用 **:** 前缀操作符: | 1045 |   有时候我们会需要从 Lua 表中提取值并将它们赋给与键同名的局部变量。为了避免编写重复代码,我们可以使用 **:** 前缀操作符: |
| 2125 | 1046 | ||
| 2126 | ```yuescript | 1047 | ```yuescript |
| 2127 | {:concat, :insert} = table | 1048 | {:concat, :insert} = table |
| 2128 | ``` | 1049 | ``` |
| 2129 | 1050 | ||
| 2130 | <YueDisplay> | ||
| 2131 | |||
| 2132 | ```yue | ||
| 2133 | {:concat, :insert} = table | ||
| 2134 | ``` | ||
| 2135 | |||
| 2136 | </YueDisplay> | ||
| 2137 | |||
| 2138 |   这样的用法与导入语法有些相似。但我们可以通过混合语法重命名我们想要提取的字段: | 1051 |   这样的用法与导入语法有些相似。但我们可以通过混合语法重命名我们想要提取的字段: |
| 2139 | 1052 | ||
| 2140 | ```yuescript | 1053 | ```yuescript |
| 2141 | {:mix, :max, random: rand} = math | 1054 | {:mix, :max, random: rand} = math |
| 2142 | ``` | 1055 | ``` |
| 2143 | 1056 | ||
| 2144 | <YueDisplay> | ||
| 2145 | |||
| 2146 | ```yue | ||
| 2147 | {:mix, :max, random: rand} = math | ||
| 2148 | ``` | ||
| 2149 | |||
| 2150 | </YueDisplay> | ||
| 2151 | |||
| 2152 |   在进行解构时,你可以指定默认值,如: | 1057 |   在进行解构时,你可以指定默认值,如: |
| 2153 | 1058 | ||
| 2154 | ```yuescript | 1059 | ```yuescript |
| 2155 | {:name = "nameless", :job = "jobless"} = person | 1060 | {:name = "nameless", :job = "jobless"} = person |
| 2156 | ``` | 1061 | ``` |
| 2157 | 1062 | ||
| 2158 | <YueDisplay> | ||
| 2159 | |||
| 2160 | ```yue | ||
| 2161 | {:name = "nameless", :job = "jobless"} = person | ||
| 2162 | ``` | ||
| 2163 | |||
| 2164 | </YueDisplay> | ||
| 2165 | |||
| 2166 |   在进行列表解构时,你可以使用`_`作为占位符: | 1063 |   在进行列表解构时,你可以使用`_`作为占位符: |
| 2167 | 1064 | ||
| 2168 | ```yuescript | 1065 | ```yuescript |
| 2169 | [_, two, _, four] = items | 1066 | [_, two, _, four] = items |
| 2170 | ``` | 1067 | ``` |
| 2171 | 1068 | ||
| 2172 | <YueDisplay> | ||
| 2173 | |||
| 2174 | ```yue | ||
| 2175 | [_, two, _, four] = items | ||
| 2176 | ``` | ||
| 2177 | |||
| 2178 | </YueDisplay> | ||
| 2179 | |||
| 2180 | ## 范围解构 | 1069 | ## 范围解构 |
| 2181 | 1070 | ||
| 2182 |   你可以使用展开运算符 `...` 在列表解构中来捕获一个范围的值到子列表中。这在当你想要从列表的开头和结尾提取特定元素,同时收集中间的元素时非常有用。 | 1071 |   你可以使用展开运算符 `...` 在列表解构中来捕获一个范围的值到子列表中。这在当你想要从列表的开头和结尾提取特定元素,同时收集中间的元素时非常有用。 |
| @@ -2189,18 +1078,6 @@ print bulk -- 打印: {"second", "third", "fourth"} | |||
| 2189 | print last -- 打印: last | 1078 | print last -- 打印: last |
| 2190 | ``` | 1079 | ``` |
| 2191 | 1080 | ||
| 2192 | <YueDisplay> | ||
| 2193 | |||
| 2194 | ```yue | ||
| 2195 | orders = ["first", "second", "third", "fourth", "last"] | ||
| 2196 | [first, ...bulk, last] = orders | ||
| 2197 | print first -- 打印: first | ||
| 2198 | print bulk -- 打印: {"second", "third", "fourth"} | ||
| 2199 | print last -- 打印: last | ||
| 2200 | ``` | ||
| 2201 | |||
| 2202 | </YueDisplay> | ||
| 2203 | |||
| 2204 |   展开运算符可以用在不同的位置来捕获不同的范围,并且你可以使用 `_` 作为占位符来表示你想跳过对应范围的捕获: | 1081 |   展开运算符可以用在不同的位置来捕获不同的范围,并且你可以使用 `_` 作为占位符来表示你想跳过对应范围的捕获: |
| 2205 | 1082 | ||
| 2206 | ```yuescript | 1083 | ```yuescript |
| @@ -2214,21 +1091,6 @@ print last -- 打印: last | |||
| 2214 | [first, ..._, last] = orders | 1091 | [first, ..._, last] = orders |
| 2215 | ``` | 1092 | ``` |
| 2216 | 1093 | ||
| 2217 | <YueDisplay> | ||
| 2218 | |||
| 2219 | ```yue | ||
| 2220 | -- 捕获第一个元素之后的所有元素 | ||
| 2221 | [first, ...rest] = orders | ||
| 2222 | |||
| 2223 | -- 捕获最后一个元素之前的所有元素 | ||
| 2224 | [...start, last] = orders | ||
| 2225 | |||
| 2226 | -- 跳过中间的元素,只捕获第一个和最后一个元素 | ||
| 2227 | [first, ..._, last] = orders | ||
| 2228 | ``` | ||
| 2229 | |||
| 2230 | </YueDisplay> | ||
| 2231 | |||
| 2232 | ## 在其它地方的解构赋值 | 1094 | ## 在其它地方的解构赋值 |
| 2233 | 1095 | ||
| 2234 |   解构赋值也可以出现在其它隐式进行赋值的地方。一个例子是用在 for 循环中: | 1096 |   解构赋值也可以出现在其它隐式进行赋值的地方。一个例子是用在 for 循环中: |
| @@ -2243,20 +1105,6 @@ for [left, right] in *tuples | |||
| 2243 | print left, right | 1105 | print left, right |
| 2244 | ``` | 1106 | ``` |
| 2245 | 1107 | ||
| 2246 | <YueDisplay> | ||
| 2247 | |||
| 2248 | ```yue | ||
| 2249 | tuples = [ | ||
| 2250 | ["hello", "world"] | ||
| 2251 | ["egg", "head"] | ||
| 2252 | ] | ||
| 2253 | |||
| 2254 | for [left, right] in *tuples | ||
| 2255 | print left, right | ||
| 2256 | ``` | ||
| 2257 | |||
| 2258 | </YueDisplay> | ||
| 2259 | |||
| 2260 |   我们知道数组表中的每个元素都是一个两项的元组,所以我们可以直接在 for 语句的名称子句中使用解构来解包它。 | 1108 |   我们知道数组表中的每个元素都是一个两项的元组,所以我们可以直接在 for 语句的名称子句中使用解构来解包它。 |
| 2261 | 1109 | ||
| 2262 | # 使用 using 语句:防止破坏性赋值 | 1110 | # 使用 using 语句:防止破坏性赋值 |
| @@ -2279,26 +1127,6 @@ my_func! | |||
| 2279 | print i -- 将打印 0 | 1127 | print i -- 将打印 0 |
| 2280 | ``` | 1128 | ``` |
| 2281 | 1129 | ||
| 2282 | <YueDisplay> | ||
| 2283 | |||
| 2284 | ```yue | ||
| 2285 | i = 100 | ||
| 2286 | |||
| 2287 | -- 许多代码行... | ||
| 2288 | |||
| 2289 | my_func = -> | ||
| 2290 | i = 10 | ||
| 2291 | while i > 0 | ||
| 2292 | print i | ||
| 2293 | i -= 1 | ||
| 2294 | |||
| 2295 | my_func! | ||
| 2296 | |||
| 2297 | print i -- 将打印 0 | ||
| 2298 | ``` | ||
| 2299 | |||
| 2300 | </YueDisplay> | ||
| 2301 | |||
| 2302 |   在 `my_func` 中,我们不小心覆盖了变量 `i` 的值。虽然在这个例子中这个问题很明显,但在一个庞大的或者是由多人共同维护的代码库中,很难追踪每个变量的声明情况。 | 1130 |   在 `my_func` 中,我们不小心覆盖了变量 `i` 的值。虽然在这个例子中这个问题很明显,但在一个庞大的或者是由多人共同维护的代码库中,很难追踪每个变量的声明情况。 |
| 2303 | 1131 | ||
| 2304 |   如果我们可以明确指出哪些变量是我们想在当前作用域内修改的,并且防止我们不小心更改了其他作用域中同名的变量,那将大有裨益。 | 1132 |   如果我们可以明确指出哪些变量是我们想在当前作用域内修改的,并且防止我们不小心更改了其他作用域中同名的变量,那将大有裨益。 |
| @@ -2315,20 +1143,6 @@ my_func! | |||
| 2315 | print i -- 打印 100,i 没有受到影响 | 1143 | print i -- 打印 100,i 没有受到影响 |
| 2316 | ``` | 1144 | ``` |
| 2317 | 1145 | ||
| 2318 | <YueDisplay> | ||
| 2319 | |||
| 2320 | ```yue | ||
| 2321 | i = 100 | ||
| 2322 | |||
| 2323 | my_func = (using nil) -> | ||
| 2324 | i = "hello" -- 这里创建了一个新的局部变量 | ||
| 2325 | |||
| 2326 | my_func! | ||
| 2327 | print i -- 打印 100,i 没有受到影响 | ||
| 2328 | ``` | ||
| 2329 | |||
| 2330 | </YueDisplay> | ||
| 2331 | |||
| 2332 |   using子句中可以填写多个用逗号分隔名称。指定可以访问和修改的外部变量的名称: | 1146 |   using子句中可以填写多个用逗号分隔名称。指定可以访问和修改的外部变量的名称: |
| 2333 | 1147 | ||
| 2334 | ```yuescript | 1148 | ```yuescript |
| @@ -2344,23 +1158,6 @@ my_func(22) | |||
| 2344 | print i, k -- 这些已经被更新 | 1158 | print i, k -- 这些已经被更新 |
| 2345 | ``` | 1159 | ``` |
| 2346 | 1160 | ||
| 2347 | <YueDisplay> | ||
| 2348 | |||
| 2349 | ```yue | ||
| 2350 | tmp = 1213 | ||
| 2351 | i, k = 100, 50 | ||
| 2352 | |||
| 2353 | my_func = (add using k, i) -> | ||
| 2354 | tmp = tmp + add -- 创建了一个新的局部tmp | ||
| 2355 | i += tmp | ||
| 2356 | k += tmp | ||
| 2357 | |||
| 2358 | my_func(22) | ||
| 2359 | print i, k -- 这些已经被更新 | ||
| 2360 | ``` | ||
| 2361 | |||
| 2362 | </YueDisplay> | ||
| 2363 | |||
| 2364 | # 使用方法 | 1161 | # 使用方法 |
| 2365 | 1162 | ||
| 2366 | ## Lua 模块 | 1163 | ## Lua 模块 |
| @@ -2527,55 +1324,6 @@ with apple | |||
| 2527 | export 🌛 = "月之脚本" | 1324 | export 🌛 = "月之脚本" |
| 2528 | ``` | 1325 | ``` |
| 2529 | 1326 | ||
| 2530 | <YueDisplay> | ||
| 2531 | |||
| 2532 | ```yue | ||
| 2533 | -- 导入语法 | ||
| 2534 | import p, to_lua from "yue" | ||
| 2535 | |||
| 2536 | -- 隐式对象 | ||
| 2537 | inventory = | ||
| 2538 | equipment: | ||
| 2539 | - "sword" | ||
| 2540 | - "shield" | ||
| 2541 | items: | ||
| 2542 | - name: "potion" | ||
| 2543 | count: 10 | ||
| 2544 | - name: "bread" | ||
| 2545 | count: 3 | ||
| 2546 | |||
| 2547 | -- 列表推导 | ||
| 2548 | map = (arr, action) -> | ||
| 2549 | [action item for item in *arr] | ||
| 2550 | |||
| 2551 | filter = (arr, cond) -> | ||
| 2552 | [item for item in *arr when cond item] | ||
| 2553 | |||
| 2554 | reduce = (arr, init, action): init -> | ||
| 2555 | init = action init, item for item in *arr | ||
| 2556 | |||
| 2557 | -- 管道操作符 | ||
| 2558 | [1, 2, 3] | ||
| 2559 | |> map (x) -> x * 2 | ||
| 2560 | |> filter (x) -> x > 4 | ||
| 2561 | |> reduce 0, (a, b) -> a + b | ||
| 2562 | |||
| 2563 | |||
| 2564 | -- 元表操作 | ||
| 2565 | apple = | ||
| 2566 | size: 15 | ||
| 2567 | <index>: | ||
| 2568 | color: 0x00ffff | ||
| 2569 | |||
| 2570 | with apple | ||
| 2571 | p .size, .color, .<index> if .<>? | ||
| 2572 | |||
| 2573 | -- 类似js的导出语法 | ||
| 2574 | export 🌛 = "月之脚本" | ||
| 2575 | ``` | ||
| 2576 | |||
| 2577 | </YueDisplay> | ||
| 2578 | |||
| 2579 | ## 关于 Dora SSR | 1327 | ## 关于 Dora SSR |
| 2580 | 1328 | ||
| 2581 | 月之脚本是与开源游戏引擎 [Dora SSR](https://github.com/Dora-SSR/Dora-SSR) 一起开发和维护的。它已被用于创建引擎工具、游戏原型和演示,在实际的游戏项目中验证其能力,同时它也帮助增强了 Dora SSR 游戏引擎的开发体验。 | 1329 | 月之脚本是与开源游戏引擎 [Dora SSR](https://github.com/Dora-SSR/Dora-SSR) 一起开发和维护的。它已被用于创建引擎工具、游戏原型和演示,在实际的游戏项目中验证其能力,同时它也帮助增强了 Dora SSR 游戏引擎的开发体验。 |
| @@ -2634,18 +1382,6 @@ else | |||
| 2634 | print "没有硬币" | 1382 | print "没有硬币" |
| 2635 | ``` | 1383 | ``` |
| 2636 | 1384 | ||
| 2637 | <YueDisplay> | ||
| 2638 | |||
| 2639 | ```yue | ||
| 2640 | have_coins = false | ||
| 2641 | if have_coins | ||
| 2642 | print "有硬币" | ||
| 2643 | else | ||
| 2644 | print "没有硬币" | ||
| 2645 | ``` | ||
| 2646 | |||
| 2647 | </YueDisplay> | ||
| 2648 | |||
| 2649 |   对于简单的语句,也可以使用简短的语法: | 1385 |   对于简单的语句,也可以使用简短的语法: |
| 2650 | 1386 | ||
| 2651 | ```yuescript | 1387 | ```yuescript |
| @@ -2653,15 +1389,6 @@ have_coins = false | |||
| 2653 | if have_coins then print "有硬币" else print "没有硬币" | 1389 | if have_coins then print "有硬币" else print "没有硬币" |
| 2654 | ``` | 1390 | ``` |
| 2655 | 1391 | ||
| 2656 | <YueDisplay> | ||
| 2657 | |||
| 2658 | ```yue | ||
| 2659 | have_coins = false | ||
| 2660 | if have_coins then print "有硬币" else print "没有硬币" | ||
| 2661 | ``` | ||
| 2662 | |||
| 2663 | </YueDisplay> | ||
| 2664 | |||
| 2665 |   因为 if 语句可以用作表达式,所以也可以这样写: | 1392 |   因为 if 语句可以用作表达式,所以也可以这样写: |
| 2666 | 1393 | ||
| 2667 | ```yuescript | 1394 | ```yuescript |
| @@ -2669,15 +1396,6 @@ have_coins = false | |||
| 2669 | print if have_coins then "有硬币" else "没有硬币" | 1396 | print if have_coins then "有硬币" else "没有硬币" |
| 2670 | ``` | 1397 | ``` |
| 2671 | 1398 | ||
| 2672 | <YueDisplay> | ||
| 2673 | |||
| 2674 | ```yue | ||
| 2675 | have_coins = false | ||
| 2676 | print if have_coins then "有硬币" else "没有硬币" | ||
| 2677 | ``` | ||
| 2678 | |||
| 2679 | </YueDisplay> | ||
| 2680 | |||
| 2681 |   条件语句也可以作为表达式用在返回语句和赋值语句中: | 1399 |   条件语句也可以作为表达式用在返回语句和赋值语句中: |
| 2682 | 1400 | ||
| 2683 | ```yuescript | 1401 | ```yuescript |
| @@ -2695,25 +1413,6 @@ else | |||
| 2695 | print message -- 打印: 我很高 | 1413 | print message -- 打印: 我很高 |
| 2696 | ``` | 1414 | ``` |
| 2697 | 1415 | ||
| 2698 | <YueDisplay> | ||
| 2699 | |||
| 2700 | ```yue | ||
| 2701 | is_tall = (name) -> | ||
| 2702 | if name == "Rob" | ||
| 2703 | true | ||
| 2704 | else | ||
| 2705 | false | ||
| 2706 | |||
| 2707 | message = if is_tall "Rob" | ||
| 2708 | "我很高" | ||
| 2709 | else | ||
| 2710 | "我不是很高" | ||
| 2711 | |||
| 2712 | print message -- 打印: 我很高 | ||
| 2713 | ``` | ||
| 2714 | |||
| 2715 | </YueDisplay> | ||
| 2716 | |||
| 2717 |   if 的反义词是 unless(相当于 if not,正如“如果”对应“除非”): | 1416 |   if 的反义词是 unless(相当于 if not,正如“如果”对应“除非”): |
| 2718 | 1417 | ||
| 2719 | ```yuescript | 1418 | ```yuescript |
| @@ -2721,27 +1420,10 @@ unless os.date("%A") == "Monday" | |||
| 2721 | print "今天不是星期一!" | 1420 | print "今天不是星期一!" |
| 2722 | ``` | 1421 | ``` |
| 2723 | 1422 | ||
| 2724 | <YueDisplay> | ||
| 2725 | |||
| 2726 | ```yue | ||
| 2727 | unless os.date("%A") == "Monday" | ||
| 2728 | print "今天不是星期一!" | ||
| 2729 | ``` | ||
| 2730 | |||
| 2731 | </YueDisplay> | ||
| 2732 | |||
| 2733 | ```yuescript | 1423 | ```yuescript |
| 2734 | print "你真幸运!" unless math.random! > 0.1 | 1424 | print "你真幸运!" unless math.random! > 0.1 |
| 2735 | ``` | 1425 | ``` |
| 2736 | 1426 | ||
| 2737 | <YueDisplay> | ||
| 2738 | |||
| 2739 | ```yue | ||
| 2740 | print "你真幸运!" unless math.random! > 0.1 | ||
| 2741 | ``` | ||
| 2742 | |||
| 2743 | </YueDisplay> | ||
| 2744 | |||
| 2745 | ## 范围表达式 | 1427 | ## 范围表达式 |
| 2746 | 1428 | ||
| 2747 |   你可以使用范围表达式来编写进行范围检查的代码。 | 1429 |   你可以使用范围表达式来编写进行范围检查的代码。 |
| @@ -2756,20 +1438,6 @@ if a in list | |||
| 2756 | print "检查`a`是否在列表中" | 1438 | print "检查`a`是否在列表中" |
| 2757 | ``` | 1439 | ``` |
| 2758 | 1440 | ||
| 2759 | <YueDisplay> | ||
| 2760 | |||
| 2761 | ```yue | ||
| 2762 | a = 5 | ||
| 2763 | |||
| 2764 | if a in [1, 3, 5, 7] | ||
| 2765 | print "检查离散值的相等性" | ||
| 2766 | |||
| 2767 | if a in list | ||
| 2768 | print "检查`a`是否在列表中" | ||
| 2769 | ``` | ||
| 2770 | |||
| 2771 | </YueDisplay> | ||
| 2772 | |||
| 2773 | `in` 运算符也可以用于表,并支持 `not in` 变体来进行否定检查: | 1441 | `in` 运算符也可以用于表,并支持 `not in` 变体来进行否定检查: |
| 2774 | 1442 | ||
| 2775 | ```yuescript | 1443 | ```yuescript |
| @@ -2783,21 +1451,6 @@ not_exist = item not in list | |||
| 2783 | check = -> value not in table | 1451 | check = -> value not in table |
| 2784 | ``` | 1452 | ``` |
| 2785 | 1453 | ||
| 2786 | <YueDisplay> | ||
| 2787 | |||
| 2788 | ```yue | ||
| 2789 | has = "foo" in {"bar", "foo"} | ||
| 2790 | |||
| 2791 | if a in {1, 2, 3} | ||
| 2792 | print "a 在表中" | ||
| 2793 | |||
| 2794 | not_exist = item not in list | ||
| 2795 | |||
| 2796 | check = -> value not in table | ||
| 2797 | ``` | ||
| 2798 | |||
| 2799 | </YueDisplay> | ||
| 2800 | |||
| 2801 | 单元素列表或表会检查与该元素的相等性: | 1454 | 单元素列表或表会检查与该元素的相等性: |
| 2802 | 1455 | ||
| 2803 | ```yuescript | 1456 | ```yuescript |
| @@ -2812,22 +1465,6 @@ with tb | |||
| 2812 | c = a in [1] | 1465 | c = a in [1] |
| 2813 | ``` | 1466 | ``` |
| 2814 | 1467 | ||
| 2815 | <YueDisplay> | ||
| 2816 | |||
| 2817 | ```yue | ||
| 2818 | -- [1,] 检查 value == 1 | ||
| 2819 | c = a in [1,] | ||
| 2820 | |||
| 2821 | -- {1} 也是检查 value == 1 | ||
| 2822 | c = a in {1} | ||
| 2823 | |||
| 2824 | -- 没有逗号,[1] 是索引访问(tb[1]) | ||
| 2825 | with tb | ||
| 2826 | c = a in [1] | ||
| 2827 | ``` | ||
| 2828 | |||
| 2829 | </YueDisplay> | ||
| 2830 | |||
| 2831 | # for 循环 | 1468 | # for 循环 |
| 2832 | 1469 | ||
| 2833 |   Lua 中有两种 for 循环形式,数字型和通用型: | 1470 |   Lua 中有两种 for 循环形式,数字型和通用型: |
| @@ -2843,21 +1480,6 @@ for key, value in pairs object | |||
| 2843 | print key, value | 1480 | print key, value |
| 2844 | ``` | 1481 | ``` |
| 2845 | 1482 | ||
| 2846 | <YueDisplay> | ||
| 2847 | |||
| 2848 | ```yue | ||
| 2849 | for i = 10, 20 | ||
| 2850 | print i | ||
| 2851 | |||
| 2852 | for k = 1, 15, 2 -- 提供了一个遍历的步长 | ||
| 2853 | print k | ||
| 2854 | |||
| 2855 | for key, value in pairs object | ||
| 2856 | print key, value | ||
| 2857 | ``` | ||
| 2858 | |||
| 2859 | </YueDisplay> | ||
| 2860 | |||
| 2861 |   可以使用切片和 **\*** 操作符,就像在列表推导中一样: | 1483 |   可以使用切片和 **\*** 操作符,就像在列表推导中一样: |
| 2862 | 1484 | ||
| 2863 | ```yuescript | 1485 | ```yuescript |
| @@ -2865,15 +1487,6 @@ for item in *items[2, 4] | |||
| 2865 | print item | 1487 | print item |
| 2866 | ``` | 1488 | ``` |
| 2867 | 1489 | ||
| 2868 | <YueDisplay> | ||
| 2869 | |||
| 2870 | ```yue | ||
| 2871 | for item in *items[2, 4] | ||
| 2872 | print item | ||
| 2873 | ``` | ||
| 2874 | |||
| 2875 | </YueDisplay> | ||
| 2876 | |||
| 2877 |   当代码语句只有一行时,循环语句也都可以写作更短的语法: | 1490 |   当代码语句只有一行时,循环语句也都可以写作更短的语法: |
| 2878 | 1491 | ||
| 2879 | ```yuescript | 1492 | ```yuescript |
| @@ -2882,16 +1495,6 @@ for item in *items do print item | |||
| 2882 | for j = 1, 10, 3 do print j | 1495 | for j = 1, 10, 3 do print j |
| 2883 | ``` | 1496 | ``` |
| 2884 | 1497 | ||
| 2885 | <YueDisplay> | ||
| 2886 | |||
| 2887 | ```yue | ||
| 2888 | for item in *items do print item | ||
| 2889 | |||
| 2890 | for j = 1, 10, 3 do print j | ||
| 2891 | ``` | ||
| 2892 | |||
| 2893 | </YueDisplay> | ||
| 2894 | |||
| 2895 |   for 循环也可以用作表达式。for 循环主体中的最后一条语句会被强制转换为一个返回值的表达式,并会将表达式计算结果的值追加到一个作为结果的数组表中。 | 1498 |   for 循环也可以用作表达式。for 循环主体中的最后一条语句会被强制转换为一个返回值的表达式,并会将表达式计算结果的值追加到一个作为结果的数组表中。 |
| 2896 | 1499 | ||
| 2897 |   将每个偶数加倍: | 1500 |   将每个偶数加倍: |
| @@ -2904,18 +1507,6 @@ doubled_evens = for i = 1, 20 | |||
| 2904 | i | 1507 | i |
| 2905 | ``` | 1508 | ``` |
| 2906 | 1509 | ||
| 2907 | <YueDisplay> | ||
| 2908 | |||
| 2909 | ```yue | ||
| 2910 | doubled_evens = for i = 1, 20 | ||
| 2911 | if i % 2 == 0 | ||
| 2912 | i * 2 | ||
| 2913 | else | ||
| 2914 | i | ||
| 2915 | ``` | ||
| 2916 | |||
| 2917 | </YueDisplay> | ||
| 2918 | |||
| 2919 |   此外,for 循环还支持带返回值的 break 语句,这样循环本身就可以作为一个表达式,在满足条件时提前退出并返回有意义的结果。for 循环表达式支持 `break` 返回多个值。 | 1510 |   此外,for 循环还支持带返回值的 break 语句,这样循环本身就可以作为一个表达式,在满足条件时提前退出并返回有意义的结果。for 循环表达式支持 `break` 返回多个值。 |
| 2920 | 1511 | ||
| 2921 |   例如,查找第一个大于 10 的数字: | 1512 |   例如,查找第一个大于 10 的数字: |
| @@ -2925,29 +1516,11 @@ first_large = for n in *numbers | |||
| 2925 | break n if n > 10 | 1516 | break n if n > 10 |
| 2926 | ``` | 1517 | ``` |
| 2927 | 1518 | ||
| 2928 | <YueDisplay> | ||
| 2929 | |||
| 2930 | ```yue | ||
| 2931 | first_large = for n in *numbers | ||
| 2932 | break n if n > 10 | ||
| 2933 | ``` | ||
| 2934 | |||
| 2935 | </YueDisplay> | ||
| 2936 | |||
| 2937 | ```yuescript | 1519 | ```yuescript |
| 2938 | key, score = for k, v in pairs data | 1520 | key, score = for k, v in pairs data |
| 2939 | break k, v * 10 if k == "target" | 1521 | break k, v * 10 if k == "target" |
| 2940 | ``` | 1522 | ``` |
| 2941 | 1523 | ||
| 2942 | <YueDisplay> | ||
| 2943 | |||
| 2944 | ```yue | ||
| 2945 | key, score = for k, v in pairs data | ||
| 2946 | break k, v * 10 if k == "target" | ||
| 2947 | ``` | ||
| 2948 | |||
| 2949 | </YueDisplay> | ||
| 2950 | |||
| 2951 |   你还可以结合 for 循环表达式与 continue 语句来过滤值。 | 1524 |   你还可以结合 for 循环表达式与 continue 语句来过滤值。 |
| 2952 | 1525 | ||
| 2953 |   注意出现在函数体末尾的 for 循环,不会被当作是一个表达式并将循环结果累积到一个列表中作为返回值(相反,函数将返回 nil)。如果要函数末尾的循环转换为列表表达式,可以显式地使用返回语句加 for 循环表达式。 | 1526 |   注意出现在函数体末尾的 for 循环,不会被当作是一个表达式并将循环结果累积到一个列表中作为返回值(相反,函数将返回 nil)。如果要函数末尾的循环转换为列表表达式,可以显式地使用返回语句加 for 循环表达式。 |
| @@ -2960,18 +1533,6 @@ print func_a! -- 打印 nil | |||
| 2960 | print func_b! -- 打印 table 对象 | 1533 | print func_b! -- 打印 table 对象 |
| 2961 | ``` | 1534 | ``` |
| 2962 | 1535 | ||
| 2963 | <YueDisplay> | ||
| 2964 | |||
| 2965 | ```yue | ||
| 2966 | func_a = -> for i = 1, 10 do print i | ||
| 2967 | func_b = -> return for i = 1, 10 do i | ||
| 2968 | |||
| 2969 | print func_a! -- 打印 nil | ||
| 2970 | print func_b! -- 打印 table 对象 | ||
| 2971 | ``` | ||
| 2972 | |||
| 2973 | </YueDisplay> | ||
| 2974 | |||
| 2975 |   这样做是为了避免在不需要返回循环结果的函数,创建无效的返回值表格。 | 1536 |   这样做是为了避免在不需要返回循环结果的函数,创建无效的返回值表格。 |
| 2976 | 1537 | ||
| 2977 | # continue 语句 | 1538 | # continue 语句 |
| @@ -2986,18 +1547,6 @@ while i < 10 | |||
| 2986 | print i | 1547 | print i |
| 2987 | ``` | 1548 | ``` |
| 2988 | 1549 | ||
| 2989 | <YueDisplay> | ||
| 2990 | |||
| 2991 | ```yue | ||
| 2992 | i = 0 | ||
| 2993 | while i < 10 | ||
| 2994 | i += 1 | ||
| 2995 | continue if i % 2 == 0 | ||
| 2996 | print i | ||
| 2997 | ``` | ||
| 2998 | |||
| 2999 | </YueDisplay> | ||
| 3000 | |||
| 3001 |   继续语句也可以与各种循环表达式一起使用,以防止当前的循环迭代结果累积到结果列表中。以下示例将数组表过滤为仅包含偶数的数组: | 1550 |   继续语句也可以与各种循环表达式一起使用,以防止当前的循环迭代结果累积到结果列表中。以下示例将数组表过滤为仅包含偶数的数组: |
| 3002 | 1551 | ||
| 3003 | ```yuescript | 1552 | ```yuescript |
| @@ -3007,17 +1556,6 @@ odds = for x in *my_numbers | |||
| 3007 | x | 1556 | x |
| 3008 | ``` | 1557 | ``` |
| 3009 | 1558 | ||
| 3010 | <YueDisplay> | ||
| 3011 | |||
| 3012 | ```yue | ||
| 3013 | my_numbers = [1, 2, 3, 4, 5, 6] | ||
| 3014 | odds = for x in *my_numbers | ||
| 3015 | continue if x % 2 == 1 | ||
| 3016 | x | ||
| 3017 | ``` | ||
| 3018 | |||
| 3019 | </YueDisplay> | ||
| 3020 | |||
| 3021 | # switch 语句 | 1559 | # switch 语句 |
| 3022 | 1560 | ||
| 3023 |   switch 语句是为了简化检查一系列相同值的if语句而提供的简写语法。要注意用于比较检查的目标值只会计算一次。和 if 语句一样,switch 语句在最后可以接一个 else 代码块来处理没有匹配的情况。在生成的 Lua 代码中,进行比较是使用 == 操作符完成的。switch 语句中也可以使用赋值表达式来储存临时变量值。 | 1561 |   switch 语句是为了简化检查一系列相同值的if语句而提供的简写语法。要注意用于比较检查的目标值只会计算一次。和 if 语句一样,switch 语句在最后可以接一个 else 代码块来处理没有匹配的情况。在生成的 Lua 代码中,进行比较是使用 == 操作符完成的。switch 语句中也可以使用赋值表达式来储存临时变量值。 |
| @@ -3032,20 +1570,6 @@ switch name := "Dan" | |||
| 3032 | print "我不认识你,你的名字是#{name}" | 1570 | print "我不认识你,你的名字是#{name}" |
| 3033 | ``` | 1571 | ``` |
| 3034 | 1572 | ||
| 3035 | <YueDisplay> | ||
| 3036 | |||
| 3037 | ```yue | ||
| 3038 | switch name := "Dan" | ||
| 3039 | when "Robert" | ||
| 3040 | print "你是Robert" | ||
| 3041 | when "Dan", "Daniel" | ||
| 3042 | print "你的名字是Dan" | ||
| 3043 | else | ||
| 3044 | print "我不认识你,你的名字是#{name}" | ||
| 3045 | ``` | ||
| 3046 | |||
| 3047 | </YueDisplay> | ||
| 3048 | |||
| 3049 |   switch 语句的 when 子句中可以通过使用逗号分隔的列表来匹配多个值。 | 1573 |   switch 语句的 when 子句中可以通过使用逗号分隔的列表来匹配多个值。 |
| 3050 | 1574 | ||
| 3051 |   switch 语句也可以作为表达式使用,下面我们可以将 switch 语句返回的结果分配给一个变量: | 1575 |   switch 语句也可以作为表达式使用,下面我们可以将 switch 语句返回的结果分配给一个变量: |
| @@ -3061,21 +1585,6 @@ next_number = switch b | |||
| 3061 | error "数字数得太大了!" | 1585 | error "数字数得太大了!" |
| 3062 | ``` | 1586 | ``` |
| 3063 | 1587 | ||
| 3064 | <YueDisplay> | ||
| 3065 | |||
| 3066 | ```yue | ||
| 3067 | b = 1 | ||
| 3068 | next_number = switch b | ||
| 3069 | when 1 | ||
| 3070 | 2 | ||
| 3071 | when 2 | ||
| 3072 | 3 | ||
| 3073 | else | ||
| 3074 | error "数字数得太大了!" | ||
| 3075 | ``` | ||
| 3076 | |||
| 3077 | </YueDisplay> | ||
| 3078 | |||
| 3079 |   我们可以使用 then 关键字在 when 子句的同一行上编写处理代码。else 代码块的后续代码中要写在同一行上不需要额外的关键字。 | 1588 |   我们可以使用 then 关键字在 when 子句的同一行上编写处理代码。else 代码块的后续代码中要写在同一行上不需要额外的关键字。 |
| 3080 | 1589 | ||
| 3081 | ```yuescript | 1590 | ```yuescript |
| @@ -3085,17 +1594,6 @@ msg = switch math.random(1, 5) | |||
| 3085 | else "不太幸运" | 1594 | else "不太幸运" |
| 3086 | ``` | 1595 | ``` |
| 3087 | 1596 | ||
| 3088 | <YueDisplay> | ||
| 3089 | |||
| 3090 | ```yue | ||
| 3091 | msg = switch math.random(1, 5) | ||
| 3092 | when 1 then "你很幸运" | ||
| 3093 | when 2 then "你差点很幸运" | ||
| 3094 | else "不太幸运" | ||
| 3095 | ``` | ||
| 3096 | |||
| 3097 | </YueDisplay> | ||
| 3098 | |||
| 3099 |   如果在编写 switch 语句时希望少写一个缩进,那么你可以把第一个 when 子句放在 switch 开始语句的第一行,然后后续的子语句就都可以都少写一个缩进。 | 1597 |   如果在编写 switch 语句时希望少写一个缩进,那么你可以把第一个 when 子句放在 switch 开始语句的第一行,然后后续的子语句就都可以都少写一个缩进。 |
| 3100 | 1598 | ||
| 3101 | ```yuescript | 1599 | ```yuescript |
| @@ -3111,23 +1609,6 @@ else | |||
| 3111 | print "不太幸运" | 1609 | print "不太幸运" |
| 3112 | ``` | 1610 | ``` |
| 3113 | 1611 | ||
| 3114 | <YueDisplay> | ||
| 3115 | |||
| 3116 | ```yue | ||
| 3117 | switch math.random(1, 5) | ||
| 3118 | when 1 | ||
| 3119 | print "你很幸运" -- 两个缩进级别 | ||
| 3120 | else | ||
| 3121 | print "不太幸运" | ||
| 3122 | |||
| 3123 | switch math.random(1, 5) when 1 | ||
| 3124 | print "你很幸运" -- 一个缩进级别 | ||
| 3125 | else | ||
| 3126 | print "不太幸运" | ||
| 3127 | ``` | ||
| 3128 | |||
| 3129 | </YueDisplay> | ||
| 3130 | |||
| 3131 |   值得注意的是,在生成 Lua 代码时,我们要做检查的目标变量会放在 == 表达式的右侧。当你希望给 when 子句的比较对象定义一个 \_\_eq 元方法来重载判断逻辑时,可能会有用。 | 1612 |   值得注意的是,在生成 Lua 代码时,我们要做检查的目标变量会放在 == 表达式的右侧。当你希望给 when 子句的比较对象定义一个 \_\_eq 元方法来重载判断逻辑时,可能会有用。 |
| 3132 | 1613 | ||
| 3133 | ## 表格匹配 | 1614 | ## 表格匹配 |
| @@ -3149,25 +1630,6 @@ for item in *items | |||
| 3149 | print "尺寸 #{width}, #{height}" | 1630 | print "尺寸 #{width}, #{height}" |
| 3150 | ``` | 1631 | ``` |
| 3151 | 1632 | ||
| 3152 | <YueDisplay> | ||
| 3153 | |||
| 3154 | ```yue | ||
| 3155 | items = | ||
| 3156 | * x: 100 | ||
| 3157 | y: 200 | ||
| 3158 | * width: 300 | ||
| 3159 | height: 400 | ||
| 3160 | |||
| 3161 | for item in *items | ||
| 3162 | switch item | ||
| 3163 | when :x, :y | ||
| 3164 | print "Vec2 #{x}, #{y}" | ||
| 3165 | when :width, :height | ||
| 3166 | print "尺寸 #{width}, #{height}" | ||
| 3167 | ``` | ||
| 3168 | |||
| 3169 | </YueDisplay> | ||
| 3170 | |||
| 3171 |   你可以使用默认值来选择性地解构表格的某些字段。 | 1633 |   你可以使用默认值来选择性地解构表格的某些字段。 |
| 3172 | 1634 | ||
| 3173 | ```yuescript | 1635 | ```yuescript |
| @@ -3180,20 +1642,6 @@ switch item | |||
| 3180 | print "Vec2 #{x}, #{y}" -- 表格解构仍然会通过 | 1642 | print "Vec2 #{x}, #{y}" -- 表格解构仍然会通过 |
| 3181 | ``` | 1643 | ``` |
| 3182 | 1644 | ||
| 3183 | <YueDisplay> | ||
| 3184 | |||
| 3185 | ```yue | ||
| 3186 | item = {} | ||
| 3187 | |||
| 3188 | {pos: {:x = 50, :y = 200}} = item -- 获取错误:尝试索引nil值(字段'pos') | ||
| 3189 | |||
| 3190 | switch item | ||
| 3191 | when {pos: {:x = 50, :y = 200}} | ||
| 3192 | print "Vec2 #{x}, #{y}" -- 表格解构仍然会通过 | ||
| 3193 | ``` | ||
| 3194 | |||
| 3195 | </YueDisplay> | ||
| 3196 | |||
| 3197 |   你也可以匹配数组元素、表格字段,甚至使用数组或表格字面量来匹配嵌套的结构。 | 1645 |   你也可以匹配数组元素、表格字段,甚至使用数组或表格字面量来匹配嵌套的结构。 |
| 3198 | 1646 | ||
| 3199 |   匹配数组元素。 | 1647 |   匹配数组元素。 |
| @@ -3208,20 +1656,6 @@ switch tb | |||
| 3208 | print "1, 2, #{b}" | 1656 | print "1, 2, #{b}" |
| 3209 | ``` | 1657 | ``` |
| 3210 | 1658 | ||
| 3211 | <YueDisplay> | ||
| 3212 | |||
| 3213 | ```yue | ||
| 3214 | switch tb | ||
| 3215 | when [1, 2, 3] | ||
| 3216 | print "1, 2, 3" | ||
| 3217 | when [1, b, 3] | ||
| 3218 | print "1, #{b}, 3" | ||
| 3219 | when [1, 2, b = 3] -- 变量b有默认值 | ||
| 3220 | print "1, 2, #{b}" | ||
| 3221 | ``` | ||
| 3222 | |||
| 3223 | </YueDisplay> | ||
| 3224 | |||
| 3225 |   匹配表格字段。 | 1659 |   匹配表格字段。 |
| 3226 | 1660 | ||
| 3227 | ```yuescript | 1661 | ```yuescript |
| @@ -3234,20 +1668,6 @@ switch tb | |||
| 3234 | print "无效值" | 1668 | print "无效值" |
| 3235 | ``` | 1669 | ``` |
| 3236 | 1670 | ||
| 3237 | <YueDisplay> | ||
| 3238 | |||
| 3239 | ```yue | ||
| 3240 | switch tb | ||
| 3241 | when success: true, :result | ||
| 3242 | print "成功", result | ||
| 3243 | when success: false | ||
| 3244 | print "失败", result | ||
| 3245 | else | ||
| 3246 | print "无效值" | ||
| 3247 | ``` | ||
| 3248 | |||
| 3249 | </YueDisplay> | ||
| 3250 | |||
| 3251 |   匹配嵌套的表格结构。 | 1671 |   匹配嵌套的表格结构。 |
| 3252 | 1672 | ||
| 3253 | ```yuescript | 1673 | ```yuescript |
| @@ -3260,20 +1680,6 @@ switch tb | |||
| 3260 | print "无效值" | 1680 | print "无效值" |
| 3261 | ``` | 1681 | ``` |
| 3262 | 1682 | ||
| 3263 | <YueDisplay> | ||
| 3264 | |||
| 3265 | ```yue | ||
| 3266 | switch tb | ||
| 3267 | when data: {type: "success", :content} | ||
| 3268 | print "成功", content | ||
| 3269 | when data: {type: "error", :content} | ||
| 3270 | print "失败", content | ||
| 3271 | else | ||
| 3272 | print "无效值" | ||
| 3273 | ``` | ||
| 3274 | |||
| 3275 | </YueDisplay> | ||
| 3276 | |||
| 3277 |   匹配表格数组。 | 1683 |   匹配表格数组。 |
| 3278 | 1684 | ||
| 3279 | ```yuescript | 1685 | ```yuescript |
| @@ -3287,21 +1693,6 @@ switch tb | |||
| 3287 | print "匹配成功", fourth | 1693 | print "匹配成功", fourth |
| 3288 | ``` | 1694 | ``` |
| 3289 | 1695 | ||
| 3290 | <YueDisplay> | ||
| 3291 | |||
| 3292 | ```yue | ||
| 3293 | switch tb | ||
| 3294 | when [ | ||
| 3295 | {a: 1, b: 2} | ||
| 3296 | {a: 3, b: 4} | ||
| 3297 | {a: 5, b: 6} | ||
| 3298 | fourth | ||
| 3299 | ] | ||
| 3300 | print "匹配成功", fourth | ||
| 3301 | ``` | ||
| 3302 | |||
| 3303 | </YueDisplay> | ||
| 3304 | |||
| 3305 |   匹配一个列表并捕获特定范围内的元素。 | 1696 |   匹配一个列表并捕获特定范围内的元素。 |
| 3306 | 1697 | ||
| 3307 | ```yuescript | 1698 | ```yuescript |
| @@ -3313,19 +1704,6 @@ switch segments | |||
| 3313 | print "Action:", action -- 打印: "view" | 1704 | print "Action:", action -- 打印: "view" |
| 3314 | ``` | 1705 | ``` |
| 3315 | 1706 | ||
| 3316 | <YueDisplay> | ||
| 3317 | |||
| 3318 | ```yue | ||
| 3319 | segments = ["admin", "users", "logs", "view"] | ||
| 3320 | switch segments | ||
| 3321 | when [...groups, resource, action] | ||
| 3322 | print "Group:", groups -- 打印: {"admin", "users"} | ||
| 3323 | print "Resource:", resource -- 打印: "logs" | ||
| 3324 | print "Action:", action -- 打印: "view" | ||
| 3325 | ``` | ||
| 3326 | |||
| 3327 | </YueDisplay> | ||
| 3328 | |||
| 3329 | # while 循环 | 1707 | # while 循环 |
| 3330 | 1708 | ||
| 3331 |   在月之脚本中的 while 循环支持几种不同的写法: | 1709 |   在月之脚本中的 while 循环支持几种不同的写法: |
| @@ -3339,19 +1717,6 @@ while i > 0 | |||
| 3339 | while running == true do my_function! | 1717 | while running == true do my_function! |
| 3340 | ``` | 1718 | ``` |
| 3341 | 1719 | ||
| 3342 | <YueDisplay> | ||
| 3343 | |||
| 3344 | ```yue | ||
| 3345 | i = 10 | ||
| 3346 | while i > 0 | ||
| 3347 | print i | ||
| 3348 | i -= 1 | ||
| 3349 | |||
| 3350 | while running == true do my_function! | ||
| 3351 | ``` | ||
| 3352 | |||
| 3353 | </YueDisplay> | ||
| 3354 | |||
| 3355 | ```yuescript | 1720 | ```yuescript |
| 3356 | i = 10 | 1721 | i = 10 |
| 3357 | until i == 0 | 1722 | until i == 0 |
| @@ -3361,18 +1726,6 @@ until i == 0 | |||
| 3361 | until running == false do my_function! | 1726 | until running == false do my_function! |
| 3362 | ``` | 1727 | ``` |
| 3363 | 1728 | ||
| 3364 | <YueDisplay> | ||
| 3365 | |||
| 3366 | ```yue | ||
| 3367 | i = 10 | ||
| 3368 | until i == 0 | ||
| 3369 | print i | ||
| 3370 | i -= 1 | ||
| 3371 | until running == false do my_function! | ||
| 3372 | ``` | ||
| 3373 | |||
| 3374 | </YueDisplay> | ||
| 3375 | |||
| 3376 |   像 for 循环的语法一样,while 循环也可以作为一个表达式使用。while / until 循环表达式支持 `break` 返回多个值。 | 1729 |   像 for 循环的语法一样,while 循环也可以作为一个表达式使用。while / until 循环表达式支持 `break` 返回多个值。 |
| 3377 | 1730 | ||
| 3378 | ```yuescript | 1731 | ```yuescript |
| @@ -3381,16 +1734,6 @@ value, doubled = while true | |||
| 3381 | break n, n * 2 if n > 10 | 1734 | break n, n * 2 if n > 10 |
| 3382 | ``` | 1735 | ``` |
| 3383 | 1736 | ||
| 3384 | <YueDisplay> | ||
| 3385 | |||
| 3386 | ```yue | ||
| 3387 | value, doubled = while true | ||
| 3388 | n = get_next! | ||
| 3389 | break n, n * 2 if n > 10 | ||
| 3390 | ``` | ||
| 3391 | |||
| 3392 | </YueDisplay> | ||
| 3393 | |||
| 3394 |   为了使函数返回 while 循环的累积列表值,必须明确使用返回语句返回 while 循环表达式。 | 1737 |   为了使函数返回 while 循环的累积列表值,必须明确使用返回语句返回 while 循环表达式。 |
| 3395 | 1738 | ||
| 3396 | ## repeat 循环 | 1739 | ## repeat 循环 |
| @@ -3405,18 +1748,6 @@ repeat | |||
| 3405 | until i == 0 | 1748 | until i == 0 |
| 3406 | ``` | 1749 | ``` |
| 3407 | 1750 | ||
| 3408 | <YueDisplay> | ||
| 3409 | |||
| 3410 | ```yue | ||
| 3411 | i = 10 | ||
| 3412 | repeat | ||
| 3413 | print i | ||
| 3414 | i -= 1 | ||
| 3415 | until i == 0 | ||
| 3416 | ``` | ||
| 3417 | |||
| 3418 | </YueDisplay> | ||
| 3419 | |||
| 3420 |   repeat 循环表达式同样支持 `break` 返回多个值: | 1751 |   repeat 循环表达式同样支持 `break` 返回多个值: |
| 3421 | 1752 | ||
| 3422 | ```yuescript | 1753 | ```yuescript |
| @@ -3427,18 +1758,6 @@ value, scaled = repeat | |||
| 3427 | until false | 1758 | until false |
| 3428 | ``` | 1759 | ``` |
| 3429 | 1760 | ||
| 3430 | <YueDisplay> | ||
| 3431 | |||
| 3432 | ```yue | ||
| 3433 | i = 1 | ||
| 3434 | value, scaled = repeat | ||
| 3435 | break i, i * 100 if i > 3 | ||
| 3436 | i += 1 | ||
| 3437 | until false | ||
| 3438 | ``` | ||
| 3439 | |||
| 3440 | </YueDisplay> | ||
| 3441 | |||
| 3442 | # 函数存根 | 1761 | # 函数存根 |
| 3443 | 1762 | ||
| 3444 |   在编程中,将对象的方法作为函数类型的值进行传递是一种常见做法,尤其是在将实例方法作为回调函数传递给其他函数的情形中。当目标函数需要将该对象作为其第一个参数时,我们需要找到一种方式将对象和函数绑定在一起,以便能够正确地调用该函数。 | 1763 |   在编程中,将对象的方法作为函数类型的值进行传递是一种常见做法,尤其是在将实例方法作为回调函数传递给其他函数的情形中。当目标函数需要将该对象作为其第一个参数时,我们需要找到一种方式将对象和函数绑定在一起,以便能够正确地调用该函数。 |
| @@ -3466,29 +1785,6 @@ run_callback my_object.write | |||
| 3466 | run_callback my_object\write | 1785 | run_callback my_object\write |
| 3467 | ``` | 1786 | ``` |
| 3468 | 1787 | ||
| 3469 | <YueDisplay> | ||
| 3470 | |||
| 3471 | ```yue | ||
| 3472 | my_object = { | ||
| 3473 | value: 1000 | ||
| 3474 | write: => print "值为:", @value | ||
| 3475 | } | ||
| 3476 | |||
| 3477 | run_callback = (func) -> | ||
| 3478 | print "运行回调..." | ||
| 3479 | func! | ||
| 3480 | |||
| 3481 | -- 这样写不起作用: | ||
| 3482 | -- 函数没有引用my_object | ||
| 3483 | run_callback my_object.write | ||
| 3484 | |||
| 3485 | -- 函数存根语法 | ||
| 3486 | -- 让我们把对象捆绑到一个新函数中 | ||
| 3487 | run_callback my_object\write | ||
| 3488 | ``` | ||
| 3489 | |||
| 3490 | </YueDisplay> | ||
| 3491 | |||
| 3492 | # 反向回调 | 1788 | # 反向回调 |
| 3493 | 1789 | ||
| 3494 |   反向回调用于减少函数回调的嵌套。它们使用指向左侧的箭头,并且默认会被定义为传入后续函数调用的最后一个参数。它的语法大部分与常规箭头函数相同,只是它指向另一方向,并且后续的函数体不需要进行缩进。 | 1790 |   反向回调用于减少函数回调的嵌套。它们使用指向左侧的箭头,并且默认会被定义为传入后续函数调用的最后一个参数。它的语法大部分与常规箭头函数相同,只是它指向另一方向,并且后续的函数体不需要进行缩进。 |
| @@ -3498,15 +1794,6 @@ x <- f | |||
| 3498 | print "hello" .. x | 1794 | print "hello" .. x |
| 3499 | ``` | 1795 | ``` |
| 3500 | 1796 | ||
| 3501 | <YueDisplay> | ||
| 3502 | |||
| 3503 | ```yue | ||
| 3504 | x <- f | ||
| 3505 | print "hello" .. x | ||
| 3506 | ``` | ||
| 3507 | |||
| 3508 | </YueDisplay> | ||
| 3509 | |||
| 3510 |   月之脚本也提供了粗箭头反向回调函数。 | 1797 |   月之脚本也提供了粗箭头反向回调函数。 |
| 3511 | 1798 | ||
| 3512 | ```yuescript | 1799 | ```yuescript |
| @@ -3514,15 +1801,6 @@ print "hello" .. x | |||
| 3514 | print @value | 1801 | print @value |
| 3515 | ``` | 1802 | ``` |
| 3516 | 1803 | ||
| 3517 | <YueDisplay> | ||
| 3518 | |||
| 3519 | ```yue | ||
| 3520 | <= f | ||
| 3521 | print @value | ||
| 3522 | ``` | ||
| 3523 | |||
| 3524 | </YueDisplay> | ||
| 3525 | |||
| 3526 |   你可以通过一个占位符指定回调函数的传参位置。 | 1804 |   你可以通过一个占位符指定回调函数的传参位置。 |
| 3527 | 1805 | ||
| 3528 | ```yuescript | 1806 | ```yuescript |
| @@ -3530,15 +1808,6 @@ print @value | |||
| 3530 | x * 2 | 1808 | x * 2 |
| 3531 | ``` | 1809 | ``` |
| 3532 | 1810 | ||
| 3533 | <YueDisplay> | ||
| 3534 | |||
| 3535 | ```yue | ||
| 3536 | (x) <- map _, [1, 2, 3] | ||
| 3537 | x * 2 | ||
| 3538 | ``` | ||
| 3539 | |||
| 3540 | </YueDisplay> | ||
| 3541 | |||
| 3542 |   如果你希望在反向回调处理后继续编写更多其它的代码,可以使用 do 语句将不属于反向回调的代码分隔开。对于非粗箭头函数的反向回调,回调返回值的括号也是可以省略的。 | 1811 |   如果你希望在反向回调处理后继续编写更多其它的代码,可以使用 do 语句将不属于反向回调的代码分隔开。对于非粗箭头函数的反向回调,回调返回值的括号也是可以省略的。 |
| 3543 | 1812 | ||
| 3544 | ```yuescript | 1813 | ```yuescript |
| @@ -3550,19 +1819,6 @@ result, msg = do | |||
| 3550 | print result, msg | 1819 | print result, msg |
| 3551 | ``` | 1820 | ``` |
| 3552 | 1821 | ||
| 3553 | <YueDisplay> | ||
| 3554 | |||
| 3555 | ```yue | ||
| 3556 | result, msg = do | ||
| 3557 | data <- readAsync "文件名.txt" | ||
| 3558 | print data | ||
| 3559 | info <- processAsync data | ||
| 3560 | check info | ||
| 3561 | print result, msg | ||
| 3562 | ``` | ||
| 3563 | |||
| 3564 | </YueDisplay> | ||
| 3565 | |||
| 3566 | # 函数字面量 | 1822 | # 函数字面量 |
| 3567 | 1823 | ||
| 3568 |   所有函数都是使用月之脚本的函数表达式创建的。一个简单的函数可以用箭头表示为:**->**。 | 1824 |   所有函数都是使用月之脚本的函数表达式创建的。一个简单的函数可以用箭头表示为:**->**。 |
| @@ -3572,15 +1828,6 @@ my_function = -> | |||
| 3572 | my_function() -- 调用空函数 | 1828 | my_function() -- 调用空函数 |
| 3573 | ``` | 1829 | ``` |
| 3574 | 1830 | ||
| 3575 | <YueDisplay> | ||
| 3576 | |||
| 3577 | ```yue | ||
| 3578 | my_function = -> | ||
| 3579 | my_function() -- 调用空函数 | ||
| 3580 | ``` | ||
| 3581 | |||
| 3582 | </YueDisplay> | ||
| 3583 | |||
| 3584 |   函数体可以是紧跟在箭头后的一个语句,或者是在后面的行上使用同样缩进的一系列语句: | 1831 |   函数体可以是紧跟在箭头后的一个语句,或者是在后面的行上使用同样缩进的一系列语句: |
| 3585 | 1832 | ||
| 3586 | ```yuescript | 1833 | ```yuescript |
| @@ -3591,18 +1838,6 @@ func_b = -> | |||
| 3591 | print "这个值是:", value | 1838 | print "这个值是:", value |
| 3592 | ``` | 1839 | ``` |
| 3593 | 1840 | ||
| 3594 | <YueDisplay> | ||
| 3595 | |||
| 3596 | ```yue | ||
| 3597 | func_a = -> print "你好,世界" | ||
| 3598 | |||
| 3599 | func_b = -> | ||
| 3600 | value = 100 | ||
| 3601 | print "这个值是:", value | ||
| 3602 | ``` | ||
| 3603 | |||
| 3604 | </YueDisplay> | ||
| 3605 | |||
| 3606 |   如果一个函数没有参数,可以使用 **\!** 操作符调用它,而不是空括号。使用 **\!** 调用没有参数的函数是推荐的写法。 | 1841 |   如果一个函数没有参数,可以使用 **\!** 操作符调用它,而不是空括号。使用 **\!** 调用没有参数的函数是推荐的写法。 |
| 3607 | 1842 | ||
| 3608 | ```yuescript | 1843 | ```yuescript |
| @@ -3610,29 +1845,12 @@ func_a! | |||
| 3610 | func_b() | 1845 | func_b() |
| 3611 | ``` | 1846 | ``` |
| 3612 | 1847 | ||
| 3613 | <YueDisplay> | ||
| 3614 | |||
| 3615 | ```yue | ||
| 3616 | func_a! | ||
| 3617 | func_b() | ||
| 3618 | ``` | ||
| 3619 | |||
| 3620 | </YueDisplay> | ||
| 3621 | |||
| 3622 |   带有参数的函数可以通过在箭头前加上括号中的参数名列表来进行创建: | 1848 |   带有参数的函数可以通过在箭头前加上括号中的参数名列表来进行创建: |
| 3623 | 1849 | ||
| 3624 | ```yuescript | 1850 | ```yuescript |
| 3625 | sum = (x, y) -> print "数字的和", x + y | 1851 | sum = (x, y) -> print "数字的和", x + y |
| 3626 | ``` | 1852 | ``` |
| 3627 | 1853 | ||
| 3628 | <YueDisplay> | ||
| 3629 | |||
| 3630 | ```yue | ||
| 3631 | sum = (x, y) -> print "数字的和", x + y | ||
| 3632 | ``` | ||
| 3633 | |||
| 3634 | </YueDisplay> | ||
| 3635 | |||
| 3636 |   函数可以通过在函数名后列出参数来调用。当对函数做嵌套的调用时,后面列出的参数会应用于左侧最近的函数。 | 1854 |   函数可以通过在函数名后列出参数来调用。当对函数做嵌套的调用时,后面列出的参数会应用于左侧最近的函数。 |
| 3637 | 1855 | ||
| 3638 | ```yuescript | 1856 | ```yuescript |
| @@ -3642,31 +1860,12 @@ print sum 10, 20 | |||
| 3642 | a b c "a", "b", "c" | 1860 | a b c "a", "b", "c" |
| 3643 | ``` | 1861 | ``` |
| 3644 | 1862 | ||
| 3645 | <YueDisplay> | ||
| 3646 | |||
| 3647 | ```yue | ||
| 3648 | sum 10, 20 | ||
| 3649 | print sum 10, 20 | ||
| 3650 | |||
| 3651 | a b c "a", "b", "c" | ||
| 3652 | ``` | ||
| 3653 | |||
| 3654 | </YueDisplay> | ||
| 3655 | |||
| 3656 |   为了避免在调用函数时产生歧义,也可以使用括号将参数括起来。比如在以下的例子中是必需的,这样才能确保参数被传入到正确的函数。 | 1863 |   为了避免在调用函数时产生歧义,也可以使用括号将参数括起来。比如在以下的例子中是必需的,这样才能确保参数被传入到正确的函数。 |
| 3657 | 1864 | ||
| 3658 | ```yuescript | 1865 | ```yuescript |
| 3659 | print "x:", sum(10, 20), "y:", sum(30, 40) | 1866 | print "x:", sum(10, 20), "y:", sum(30, 40) |
| 3660 | ``` | 1867 | ``` |
| 3661 | 1868 | ||
| 3662 | <YueDisplay> | ||
| 3663 | |||
| 3664 | ```yue | ||
| 3665 | print "x:", sum(10, 20), "y:", sum(30, 40) | ||
| 3666 | ``` | ||
| 3667 | |||
| 3668 | </YueDisplay> | ||
| 3669 | |||
| 3670 |   注意:函数名与开始括号之间不能有任何空格。 | 1869 |   注意:函数名与开始括号之间不能有任何空格。 |
| 3671 | 1870 | ||
| 3672 |   函数会将函数体中的最后一个语句强制转换为返回语句,这被称作隐式返回: | 1871 |   函数会将函数体中的最后一个语句强制转换为返回语句,这被称作隐式返回: |
| @@ -3676,29 +1875,12 @@ sum = (x, y) -> x + y | |||
| 3676 | print "数字的和是", sum 10, 20 | 1875 | print "数字的和是", sum 10, 20 |
| 3677 | ``` | 1876 | ``` |
| 3678 | 1877 | ||
| 3679 | <YueDisplay> | ||
| 3680 | |||
| 3681 | ```yue | ||
| 3682 | sum = (x, y) -> x + y | ||
| 3683 | print "数字的和是", sum 10, 20 | ||
| 3684 | ``` | ||
| 3685 | |||
| 3686 | </YueDisplay> | ||
| 3687 | |||
| 3688 |   如果你需要做显式返回,可以使用 return 关键字: | 1878 |   如果你需要做显式返回,可以使用 return 关键字: |
| 3689 | 1879 | ||
| 3690 | ```yuescript | 1880 | ```yuescript |
| 3691 | sum = (x, y) -> return x + y | 1881 | sum = (x, y) -> return x + y |
| 3692 | ``` | 1882 | ``` |
| 3693 | 1883 | ||
| 3694 | <YueDisplay> | ||
| 3695 | |||
| 3696 | ```yue | ||
| 3697 | sum = (x, y) -> return x + y | ||
| 3698 | ``` | ||
| 3699 | |||
| 3700 | </YueDisplay> | ||
| 3701 | |||
| 3702 |   就像在Lua中一样,函数可以返回多个值。最后一个语句必须是由逗号分隔的值列表: | 1884 |   就像在Lua中一样,函数可以返回多个值。最后一个语句必须是由逗号分隔的值列表: |
| 3703 | 1885 | ||
| 3704 | ```yuescript | 1886 | ```yuescript |
| @@ -3706,15 +1888,6 @@ mystery = (x, y) -> x + y, x - y | |||
| 3706 | a, b = mystery 10, 20 | 1888 | a, b = mystery 10, 20 |
| 3707 | ``` | 1889 | ``` |
| 3708 | 1890 | ||
| 3709 | <YueDisplay> | ||
| 3710 | |||
| 3711 | ```yue | ||
| 3712 | mystery = (x, y) -> x + y, x - y | ||
| 3713 | a, b = mystery 10, 20 | ||
| 3714 | ``` | ||
| 3715 | |||
| 3716 | </YueDisplay> | ||
| 3717 | |||
| 3718 | ## 粗箭头 | 1891 | ## 粗箭头 |
| 3719 | 1892 | ||
| 3720 |   因为在 Lua 中调用方法时,经常习惯将对象作为第一个参数传入,所以月之脚本提供了一种特殊的语法来创建自动包含 self 参数的函数。 | 1893 |   因为在 Lua 中调用方法时,经常习惯将对象作为第一个参数传入,所以月之脚本提供了一种特殊的语法来创建自动包含 self 参数的函数。 |
| @@ -3723,14 +1896,6 @@ a, b = mystery 10, 20 | |||
| 3723 | func = (num) => @value + num | 1896 | func = (num) => @value + num |
| 3724 | ``` | 1897 | ``` |
| 3725 | 1898 | ||
| 3726 | <YueDisplay> | ||
| 3727 | |||
| 3728 | ```yue | ||
| 3729 | func = (num) => @value + num | ||
| 3730 | ``` | ||
| 3731 | |||
| 3732 | </YueDisplay> | ||
| 3733 | |||
| 3734 | ## 参数默认值 | 1899 | ## 参数默认值 |
| 3735 | 1900 | ||
| 3736 |   可以为函数的参数提供默认值。如果参数的值为 nil,则确定该参数为空。任何具有默认值的 nil 参数在函数体运行之前都会被替换。 | 1901 |   可以为函数的参数提供默认值。如果参数的值为 nil,则确定该参数为空。任何具有默认值的 nil 参数在函数体运行之前都会被替换。 |
| @@ -3741,16 +1906,6 @@ my_function = (name = "某物", height = 100) -> | |||
| 3741 | print "我的高度是", height | 1906 | print "我的高度是", height |
| 3742 | ``` | 1907 | ``` |
| 3743 | 1908 | ||
| 3744 | <YueDisplay> | ||
| 3745 | |||
| 3746 | ```yue | ||
| 3747 | my_function = (name = "某物", height = 100) -> | ||
| 3748 | print "你好,我是", name | ||
| 3749 | print "我的高度是", height | ||
| 3750 | ``` | ||
| 3751 | |||
| 3752 | </YueDisplay> | ||
| 3753 | |||
| 3754 |   函数参数的默认值表达式在函数体中会按参数声明的顺序进行计算。因此,在默认值的表达式中可以访问先前声明的参数。 | 1909 |   函数参数的默认值表达式在函数体中会按参数声明的顺序进行计算。因此,在默认值的表达式中可以访问先前声明的参数。 |
| 3755 | 1910 | ||
| 3756 | ```yuescript | 1911 | ```yuescript |
| @@ -3758,15 +1913,6 @@ some_args = (x = 100, y = x + 1000) -> | |||
| 3758 | print x + y | 1913 | print x + y |
| 3759 | ``` | 1914 | ``` |
| 3760 | 1915 | ||
| 3761 | <YueDisplay> | ||
| 3762 | |||
| 3763 | ```yue | ||
| 3764 | some_args = (x = 100, y = x + 1000) -> | ||
| 3765 | print x + y | ||
| 3766 | ``` | ||
| 3767 | |||
| 3768 | </YueDisplay> | ||
| 3769 | |||
| 3770 | ## 注意事项 | 1916 | ## 注意事项 |
| 3771 | 1917 | ||
| 3772 |   由于月之脚本支持无需括号的表达式式函数调用,因此为了避免因空白字符造成的解析歧义,需要进行一些限制。 | 1918 |   由于月之脚本支持无需括号的表达式式函数调用,因此为了避免因空白字符造成的解析歧义,需要进行一些限制。 |
| @@ -3780,17 +1926,6 @@ c = x -y | |||
| 3780 | d = x- z | 1926 | d = x- z |
| 3781 | ``` | 1927 | ``` |
| 3782 | 1928 | ||
| 3783 | <YueDisplay> | ||
| 3784 | |||
| 3785 | ```yue | ||
| 3786 | a = x - 10 | ||
| 3787 | b = x-10 | ||
| 3788 | c = x -y | ||
| 3789 | d = x- z | ||
| 3790 | ``` | ||
| 3791 | |||
| 3792 | </YueDisplay> | ||
| 3793 | |||
| 3794 |   当函数调用的第一个参数是字符串字面量时,可以通过空白控制其优先级。在 Lua 中,常见的写法是调用仅有一个字符串或表字面量参数的函数时省略括号。 | 1929 |   当函数调用的第一个参数是字符串字面量时,可以通过空白控制其优先级。在 Lua 中,常见的写法是调用仅有一个字符串或表字面量参数的函数时省略括号。 |
| 3795 | 1930 | ||
| 3796 |   当变量名和字符串字面量之间没有空格时,函数的调用优先级高于后续表达式,因此此时无法再传入其他参数。 | 1931 |   当变量名和字符串字面量之间没有空格时,函数的调用优先级高于后续表达式,因此此时无法再传入其他参数。 |
| @@ -3802,15 +1937,6 @@ x = func"hello" + 100 | |||
| 3802 | y = func "hello" + 100 | 1937 | y = func "hello" + 100 |
| 3803 | ``` | 1938 | ``` |
| 3804 | 1939 | ||
| 3805 | <YueDisplay> | ||
| 3806 | |||
| 3807 | ```yue | ||
| 3808 | x = func"hello" + 100 | ||
| 3809 | y = func "hello" + 100 | ||
| 3810 | ``` | ||
| 3811 | |||
| 3812 | </YueDisplay> | ||
| 3813 | |||
| 3814 | ## 多行参数 | 1940 | ## 多行参数 |
| 3815 | 1941 | ||
| 3816 |   当调用接收大量参数的函数时,将参数列表分成多行是很方便的。由于月之脚本语言对空白字符的敏感性,做参数列表的分割时务必要小心。 | 1942 |   当调用接收大量参数的函数时,将参数列表分成多行是很方便的。由于月之脚本语言对空白字符的敏感性,做参数列表的分割时务必要小心。 |
| @@ -3827,20 +1953,6 @@ cool_func 1, 2, | |||
| 3827 | 7, 8 | 1953 | 7, 8 |
| 3828 | ``` | 1954 | ``` |
| 3829 | 1955 | ||
| 3830 | <YueDisplay> | ||
| 3831 | |||
| 3832 | ```yue | ||
| 3833 | my_func 5, 4, 3, | ||
| 3834 | 8, 9, 10 | ||
| 3835 | |||
| 3836 | cool_func 1, 2, | ||
| 3837 | 3, 4, | ||
| 3838 | 5, 6, | ||
| 3839 | 7, 8 | ||
| 3840 | ``` | ||
| 3841 | |||
| 3842 | </YueDisplay> | ||
| 3843 | |||
| 3844 |   这种调用方式可以做嵌套。并通过缩进级别来确定参数属于哪一个函数。 | 1956 |   这种调用方式可以做嵌套。并通过缩进级别来确定参数属于哪一个函数。 |
| 3845 | 1957 | ||
| 3846 | ```yuescript | 1958 | ```yuescript |
| @@ -3850,17 +1962,6 @@ my_func 5, 6, 7, | |||
| 3850 | 5, 4 | 1962 | 5, 4 |
| 3851 | ``` | 1963 | ``` |
| 3852 | 1964 | ||
| 3853 | <YueDisplay> | ||
| 3854 | |||
| 3855 | ```yue | ||
| 3856 | my_func 5, 6, 7, | ||
| 3857 | 6, another_func 6, 7, 8, | ||
| 3858 | 9, 1, 2, | ||
| 3859 | 5, 4 | ||
| 3860 | ``` | ||
| 3861 | |||
| 3862 | </YueDisplay> | ||
| 3863 | |||
| 3864 |   因为 Lua 表也使用逗号作为分隔符,这种缩进语法有助于让值成为参数列表的一部分,而不是 Lua 表的一部分。 | 1965 |   因为 Lua 表也使用逗号作为分隔符,这种缩进语法有助于让值成为参数列表的一部分,而不是 Lua 表的一部分。 |
| 3865 | 1966 | ||
| 3866 | ```yuescript | 1967 | ```yuescript |
| @@ -3871,18 +1972,6 @@ x = [ | |||
| 3871 | ] | 1972 | ] |
| 3872 | ``` | 1973 | ``` |
| 3873 | 1974 | ||
| 3874 | <YueDisplay> | ||
| 3875 | |||
| 3876 | ```yue | ||
| 3877 | x = [ | ||
| 3878 | 1, 2, 3, 4, a_func 4, 5, | ||
| 3879 | 5, 6, | ||
| 3880 | 8, 9, 10 | ||
| 3881 | ] | ||
| 3882 | ``` | ||
| 3883 | |||
| 3884 | </YueDisplay> | ||
| 3885 | |||
| 3886 |   有个不常见的写法可以注意一下,如果我们将在后面使用较低的缩进,我们可以为函数参数提供更深的缩进来区分列表的归属。 | 1975 |   有个不常见的写法可以注意一下,如果我们将在后面使用较低的缩进,我们可以为函数参数提供更深的缩进来区分列表的归属。 |
| 3887 | 1976 | ||
| 3888 | ```yuescript | 1977 | ```yuescript |
| @@ -3892,17 +1981,6 @@ y = [ my_func 1, 2, 3, | |||
| 3892 | ] | 1981 | ] |
| 3893 | ``` | 1982 | ``` |
| 3894 | 1983 | ||
| 3895 | <YueDisplay> | ||
| 3896 | |||
| 3897 | ```yue | ||
| 3898 | y = [ my_func 1, 2, 3, | ||
| 3899 | 4, 5, | ||
| 3900 | 5, 6, 7 | ||
| 3901 | ] | ||
| 3902 | ``` | ||
| 3903 | |||
| 3904 | </YueDisplay> | ||
| 3905 | |||
| 3906 |   对于其它有代码块跟随的语句,比如条件语句,也可以通过小心安排缩进来做类似的事。比如我们可以通过调整缩进级别来控制一些值归属于哪个语句: | 1984 |   对于其它有代码块跟随的语句,比如条件语句,也可以通过小心安排缩进来做类似的事。比如我们可以通过调整缩进级别来控制一些值归属于哪个语句: |
| 3907 | 1985 | ||
| 3908 | ```yuescript | 1986 | ```yuescript |
| @@ -3919,24 +1997,6 @@ if func 1, 2, 3, | |||
| 3919 | print "我在if内部" | 1997 | print "我在if内部" |
| 3920 | ``` | 1998 | ``` |
| 3921 | 1999 | ||
| 3922 | <YueDisplay> | ||
| 3923 | |||
| 3924 | ```yue | ||
| 3925 | if func 1, 2, 3, | ||
| 3926 | "你好", | ||
| 3927 | "世界" | ||
| 3928 | print "你好" | ||
| 3929 | print "我在if内部" | ||
| 3930 | |||
| 3931 | if func 1, 2, 3, | ||
| 3932 | "你好", | ||
| 3933 | "世界" | ||
| 3934 | print "你好" | ||
| 3935 | print "我在if内部" | ||
| 3936 | ``` | ||
| 3937 | |||
| 3938 | </YueDisplay> | ||
| 3939 | |||
| 3940 | ## 参数解构 | 2000 | ## 参数解构 |
| 3941 | 2001 | ||
| 3942 |   月之脚本支持在函数形参位置对传入对象进行解构。适用两类解构表子面量: | 2002 |   月之脚本支持在函数形参位置对传入对象进行解构。适用两类解构表子面量: |
| @@ -3958,23 +2018,6 @@ arg1 = {a: 0} | |||
| 3958 | f2 arg1, arg2 | 2018 | f2 arg1, arg2 |
| 3959 | ``` | 2019 | ``` |
| 3960 | 2020 | ||
| 3961 | <YueDisplay> | ||
| 3962 | |||
| 3963 | ```yue | ||
| 3964 | f1 = (:a, :b, :c) -> | ||
| 3965 | print a, b, c | ||
| 3966 | |||
| 3967 | f1 a: 1, b: "2", c: {} | ||
| 3968 | |||
| 3969 | f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) -> | ||
| 3970 | print a1, b, c | ||
| 3971 | |||
| 3972 | arg1 = {a: 0} | ||
| 3973 | f2 arg1, arg2 | ||
| 3974 | ``` | ||
| 3975 | |||
| 3976 | </YueDisplay> | ||
| 3977 | |||
| 3978 | ## 前置返回表达式 | 2021 | ## 前置返回表达式 |
| 3979 | 2022 | ||
| 3980 |   在深度嵌套的函数体中,为了提升返回值的可读性及编写便利性,我们新增了 “前置返回表达式” 语法。其形式如下: | 2023 |   在深度嵌套的函数体中,为了提升返回值的可读性及编写便利性,我们新增了 “前置返回表达式” 语法。其形式如下: |
| @@ -3988,19 +2031,6 @@ findFirstEven = (list): nil -> | |||
| 3988 | return sub | 2031 | return sub |
| 3989 | ``` | 2032 | ``` |
| 3990 | 2033 | ||
| 3991 | <YueDisplay> | ||
| 3992 | |||
| 3993 | ```yue | ||
| 3994 | findFirstEven = (list): nil -> | ||
| 3995 | for item in *list | ||
| 3996 | if type(item) == "table" | ||
| 3997 | for sub in *item | ||
| 3998 | if sub % 2 == 0 | ||
| 3999 | return sub | ||
| 4000 | ``` | ||
| 4001 | |||
| 4002 | </YueDisplay> | ||
| 4003 | |||
| 4004 |   这个写法等价于: | 2034 |   这个写法等价于: |
| 4005 | 2035 | ||
| 4006 | ```yuescript | 2036 | ```yuescript |
| @@ -4013,20 +2043,6 @@ findFirstEven = (list) -> | |||
| 4013 | nil | 2043 | nil |
| 4014 | ``` | 2044 | ``` |
| 4015 | 2045 | ||
| 4016 | <YueDisplay> | ||
| 4017 | |||
| 4018 | ```yue | ||
| 4019 | findFirstEven = (list) -> | ||
| 4020 | for item in *list | ||
| 4021 | if type(item) == "table" | ||
| 4022 | for sub in *item | ||
| 4023 | if sub % 2 == 0 | ||
| 4024 | return sub | ||
| 4025 | nil | ||
| 4026 | ``` | ||
| 4027 | |||
| 4028 | </YueDisplay> | ||
| 4029 | |||
| 4030 |   唯一的区别在于:你可以将函数的返回值表达式提前写在 `->` 或 `=>` 前,用以指示该函数应隐式返回该表达式的值。这样即使在多层循环或条件判断的场景下,也无需编写尾行悬挂的返回表达式,逻辑结构会更加直观清晰。 | 2046 |   唯一的区别在于:你可以将函数的返回值表达式提前写在 `->` 或 `=>` 前,用以指示该函数应隐式返回该表达式的值。这样即使在多层循环或条件判断的场景下,也无需编写尾行悬挂的返回表达式,逻辑结构会更加直观清晰。 |
| 4031 | 2047 | ||
| 4032 | ## 命名变长参数 | 2048 | ## 命名变长参数 |
| @@ -4055,32 +2071,6 @@ process = (...args) -> | |||
| 4055 | process 1, nil, 3, nil, 5 | 2071 | process 1, nil, 3, nil, 5 |
| 4056 | ``` | 2072 | ``` |
| 4057 | 2073 | ||
| 4058 | <YueDisplay> | ||
| 4059 | |||
| 4060 | ```yue | ||
| 4061 | f = (...t) -> | ||
| 4062 | print "参数个数:", t.n | ||
| 4063 | print "表长度:", #t | ||
| 4064 | for i = 1, t.n | ||
| 4065 | print t[i] | ||
| 4066 | |||
| 4067 | f 1, 2, 3 | ||
| 4068 | f "a", "b", "c", "d" | ||
| 4069 | f! | ||
| 4070 | |||
| 4071 | -- 处理包含 nil 的情况 | ||
| 4072 | process = (...args) -> | ||
| 4073 | sum = 0 | ||
| 4074 | for i = 1, args.n | ||
| 4075 | if args[i] != nil and type(args[i]) == "number" | ||
| 4076 | sum += args[i] | ||
| 4077 | sum | ||
| 4078 | |||
| 4079 | process 1, nil, 3, nil, 5 | ||
| 4080 | ``` | ||
| 4081 | |||
| 4082 | </YueDisplay> | ||
| 4083 | |||
| 4084 | # 空白 | 2074 | # 空白 |
| 4085 | 2075 | ||
| 4086 |   月之脚本是一个对空白敏感的语言。你必须在相同的缩进中使用空格 **' '** 或制表符 **'\t'** 来编写一些代码块,如函数体、值列表和一些控制块。包含不同空白的表达式可能意味着不同的事情。制表符被视为4个空格,但最好不要混合使用空格和制表符。 | 2076 |   月之脚本是一个对空白敏感的语言。你必须在相同的缩进中使用空格 **' '** 或制表符 **'\t'** 来编写一些代码块,如函数体、值列表和一些控制块。包含不同空白的表达式可能意味着不同的事情。制表符被视为4个空格,但最好不要混合使用空格和制表符。 |
| @@ -4093,14 +2083,6 @@ process 1, nil, 3, nil, 5 | |||
| 4093 | a = 1; b = 2; print a + b | 2083 | a = 1; b = 2; print a + b |
| 4094 | ``` | 2084 | ``` |
| 4095 | 2085 | ||
| 4096 | <YueDisplay> | ||
| 4097 | |||
| 4098 | ```yue | ||
| 4099 | a = 1; b = 2; print a + b | ||
| 4100 | ``` | ||
| 4101 | |||
| 4102 | </YueDisplay> | ||
| 4103 | |||
| 4104 | ## 多行链式调用 | 2086 | ## 多行链式调用 |
| 4105 | 2087 | ||
| 4106 |   你可以使用相同的缩进来编写多行链式函数调用。 | 2088 |   你可以使用相同的缩进来编写多行链式函数调用。 |
| @@ -4114,19 +2096,6 @@ Rx.Observable | |||
| 4114 | \subscribe print | 2096 | \subscribe print |
| 4115 | ``` | 2097 | ``` |
| 4116 | 2098 | ||
| 4117 | <YueDisplay> | ||
| 4118 | |||
| 4119 | ```yue | ||
| 4120 | Rx.Observable | ||
| 4121 | .fromRange 1, 8 | ||
| 4122 | \filter (x) -> x % 2 == 0 | ||
| 4123 | \concat Rx.Observable.of 'who do we appreciate' | ||
| 4124 | \map (value) -> value .. '!' | ||
| 4125 | \subscribe print | ||
| 4126 | ``` | ||
| 4127 | |||
| 4128 | </YueDisplay> | ||
| 4129 | |||
| 4130 | # 注释 | 2099 | # 注释 |
| 4131 | 2100 | ||
| 4132 | ```yuescript | 2101 | ```yuescript |
| @@ -4142,23 +2111,6 @@ str = --[[ | |||
| 4142 | func --[[端口]] 3000, --[[ip]] "192.168.1.1" | 2111 | func --[[端口]] 3000, --[[ip]] "192.168.1.1" |
| 4143 | ``` | 2112 | ``` |
| 4144 | 2113 | ||
| 4145 | <YueDisplay> | ||
| 4146 | |||
| 4147 | ```yue | ||
| 4148 | -- 我是一个注释 | ||
| 4149 | |||
| 4150 | str = --[[ | ||
| 4151 | 这是一个多行注释。 | ||
| 4152 | 没问题。 | ||
| 4153 | ]] strA \ -- 注释 1 | ||
| 4154 | .. strB \ -- 注释 2 | ||
| 4155 | .. strC | ||
| 4156 | |||
| 4157 | func --[[端口]] 3000, --[[ip]] "192.168.1.1" | ||
| 4158 | ``` | ||
| 4159 | |||
| 4160 | </YueDisplay> | ||
| 4161 | |||
| 4162 | # 属性 | 2114 | # 属性 |
| 4163 | 2115 | ||
| 4164 |   月之脚本现在提供了 Lua 5.4 新增的叫做属性的语法支持。在月之脚本编译到的 Lua 目标版本低于 5.4 时,你仍然可以同时使用`const` 和 `close` 的属性声明语法,并获得常量检查和作用域回调的功能。 | 2116 |   月之脚本现在提供了 Lua 5.4 新增的叫做属性的语法支持。在月之脚本编译到的 Lua 目标版本低于 5.4 时,你仍然可以同时使用`const` 和 `close` 的属性声明语法,并获得常量检查和作用域回调的功能。 |
| @@ -4168,15 +2120,6 @@ const a = 123 | |||
| 4168 | close _ = <close>: -> print "超出范围。" | 2120 | close _ = <close>: -> print "超出范围。" |
| 4169 | ``` | 2121 | ``` |
| 4170 | 2122 | ||
| 4171 | <YueDisplay> | ||
| 4172 | |||
| 4173 | ```yue | ||
| 4174 | const a = 123 | ||
| 4175 | close _ = <close>: -> print "超出范围。" | ||
| 4176 | ``` | ||
| 4177 | |||
| 4178 | </YueDisplay> | ||
| 4179 | |||
| 4180 |   你可以对进行解构得到的变量标记为常量。 | 2123 |   你可以对进行解构得到的变量标记为常量。 |
| 4181 | 2124 | ||
| 4182 | ```yuescript | 2125 | ```yuescript |
| @@ -4184,15 +2127,6 @@ const {:a, :b, c, d} = tb | |||
| 4184 | -- a = 1 | 2127 | -- a = 1 |
| 4185 | ``` | 2128 | ``` |
| 4186 | 2129 | ||
| 4187 | <YueDisplay> | ||
| 4188 | |||
| 4189 | ```yue | ||
| 4190 | const {:a, :b, c, d} = tb | ||
| 4191 | -- a = 1 | ||
| 4192 | ``` | ||
| 4193 | |||
| 4194 | </YueDisplay> | ||
| 4195 | |||
| 4196 |   你也可以声明全局变量为常量。 | 2130 |   你也可以声明全局变量为常量。 |
| 4197 | 2131 | ||
| 4198 | ```yuescript | 2132 | ```yuescript |
| @@ -4200,15 +2134,6 @@ global const Constant = 123 | |||
| 4200 | -- Constant = 1 | 2134 | -- Constant = 1 |
| 4201 | ``` | 2135 | ``` |
| 4202 | 2136 | ||
| 4203 | <YueDisplay> | ||
| 4204 | |||
| 4205 | ```yue | ||
| 4206 | global const Constant = 123 | ||
| 4207 | -- Constant = 1 | ||
| 4208 | ``` | ||
| 4209 | |||
| 4210 | </YueDisplay> | ||
| 4211 | |||
| 4212 | # 操作符 | 2137 | # 操作符 |
| 4213 | 2138 | ||
| 4214 |   Lua 的所有二元和一元操作符在月之脚本中都是可用的。此外,**!=** 符号是 **~=** 的别名,而 **\\** 或 **::** 均可用于编写链式函数调用,如写作 `tb\func!` 或 `tb::func!`。此外月之脚本还提供了一些其他特殊的操作符,以编写更具表达力的代码。 | 2139 |   Lua 的所有二元和一元操作符在月之脚本中都是可用的。此外,**!=** 符号是 **~=** 的别名,而 **\\** 或 **::** 均可用于编写链式函数调用,如写作 `tb\func!` 或 `tb::func!`。此外月之脚本还提供了一些其他特殊的操作符,以编写更具表达力的代码。 |
| @@ -4218,15 +2143,6 @@ tb\func! if tb ~= nil | |||
| 4218 | tb::func! if tb != nil | 2143 | tb::func! if tb != nil |
| 4219 | ``` | 2144 | ``` |
| 4220 | 2145 | ||
| 4221 | <YueDisplay> | ||
| 4222 | |||
| 4223 | ```yue | ||
| 4224 | tb\func! if tb ~= nil | ||
| 4225 | tb::func! if tb != nil | ||
| 4226 | ``` | ||
| 4227 | |||
| 4228 | </YueDisplay> | ||
| 4229 | |||
| 4230 | ## 链式比较 | 2146 | ## 链式比较 |
| 4231 | 2147 | ||
| 4232 |   你可以在月之脚本中进行比较表达式的链式书写: | 2148 |   你可以在月之脚本中进行比较表达式的链式书写: |
| @@ -4240,19 +2156,6 @@ print 1 <= a <= 10 | |||
| 4240 | -- 输出:true | 2156 | -- 输出:true |
| 4241 | ``` | 2157 | ``` |
| 4242 | 2158 | ||
| 4243 | <YueDisplay> | ||
| 4244 | |||
| 4245 | ```yue | ||
| 4246 | print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 | ||
| 4247 | -- 输出:true | ||
| 4248 | |||
| 4249 | a = 5 | ||
| 4250 | print 1 <= a <= 10 | ||
| 4251 | -- 输出:true | ||
| 4252 | ``` | ||
| 4253 | |||
| 4254 | </YueDisplay> | ||
| 4255 | |||
| 4256 |   可以注意一下链式比较表达式的求值行为: | 2159 |   可以注意一下链式比较表达式的求值行为: |
| 4257 | 2160 | ||
| 4258 | ```yuescript | 2161 | ```yuescript |
| @@ -4278,33 +2181,6 @@ print v(1) > v(2) <= v(3) | |||
| 4278 | ]] | 2181 | ]] |
| 4279 | ``` | 2182 | ``` |
| 4280 | 2183 | ||
| 4281 | <YueDisplay> | ||
| 4282 | |||
| 4283 | ```yue | ||
| 4284 | v = (x) -> | ||
| 4285 | print x | ||
| 4286 | x | ||
| 4287 | |||
| 4288 | print v(1) < v(2) <= v(3) | ||
| 4289 | --[[ | ||
| 4290 | 输出: | ||
| 4291 | 2 | ||
| 4292 | 1 | ||
| 4293 | 3 | ||
| 4294 | true | ||
| 4295 | ]] | ||
| 4296 | |||
| 4297 | print v(1) > v(2) <= v(3) | ||
| 4298 | --[[ | ||
| 4299 | 输出: | ||
| 4300 | 2 | ||
| 4301 | 1 | ||
| 4302 | false | ||
| 4303 | ]] | ||
| 4304 | ``` | ||
| 4305 | |||
| 4306 | </YueDisplay> | ||
| 4307 | |||
| 4308 |   在上面的例子里,中间的表达式 `v(2)` 仅被计算一次,如果把表达式写成 `v(1) < v(2) and v(2) <= v(3)` 的方式,中间的 `v(2)` 才会被计算两次。在链式比较中,求值的顺序往往是未定义的。所以强烈建议不要在链式比较中使用具有副作用(比如做打印操作)的表达式。如果需要使用有副作用的函数,应明确使用短路 `and` 运算符来做连接。 | 2184 |   在上面的例子里,中间的表达式 `v(2)` 仅被计算一次,如果把表达式写成 `v(1) < v(2) and v(2) <= v(3)` 的方式,中间的 `v(2)` 才会被计算两次。在链式比较中,求值的顺序往往是未定义的。所以强烈建议不要在链式比较中使用具有副作用(比如做打印操作)的表达式。如果需要使用有副作用的函数,应明确使用短路 `and` 运算符来做连接。 |
| 4309 | 2185 | ||
| 4310 | ## 表追加 | 2186 | ## 表追加 |
| @@ -4316,15 +2192,6 @@ tab = [] | |||
| 4316 | tab[] = "Value" | 2192 | tab[] = "Value" |
| 4317 | ``` | 2193 | ``` |
| 4318 | 2194 | ||
| 4319 | <YueDisplay> | ||
| 4320 | |||
| 4321 | ```yue | ||
| 4322 | tab = [] | ||
| 4323 | tab[] = "Value" | ||
| 4324 | ``` | ||
| 4325 | |||
| 4326 | </YueDisplay> | ||
| 4327 | |||
| 4328 |   你还可以使用展开操作符 `...` 来将一个列表中的所有元素追加到另一个列表中: | 2195 |   你还可以使用展开操作符 `...` 来将一个列表中的所有元素追加到另一个列表中: |
| 4329 | 2196 | ||
| 4330 | ```yuescript | 2197 | ```yuescript |
| @@ -4334,17 +2201,6 @@ tbA[] = ...tbB | |||
| 4334 | -- tbA 现在为 [1, 2, 3, 4, 5, 6] | 2201 | -- tbA 现在为 [1, 2, 3, 4, 5, 6] |
| 4335 | ``` | 2202 | ``` |
| 4336 | 2203 | ||
| 4337 | <YueDisplay> | ||
| 4338 | |||
| 4339 | ```yue | ||
| 4340 | tbA = [1, 2, 3] | ||
| 4341 | tbB = [4, 5, 6] | ||
| 4342 | tbA[] = ...tbB | ||
| 4343 | -- tbA 现在为 [1, 2, 3, 4, 5, 6] | ||
| 4344 | ``` | ||
| 4345 | |||
| 4346 | </YueDisplay> | ||
| 4347 | |||
| 4348 | ## 表扩展 | 2204 | ## 表扩展 |
| 4349 | 2205 | ||
| 4350 |   你可以使用前置 `...` 操作符在 Lua 表中插入数组表或哈希表。 | 2206 |   你可以使用前置 `...` 操作符在 Lua 表中插入数组表或哈希表。 |
| @@ -4366,27 +2222,6 @@ b = {4, 5, y: 1} | |||
| 4366 | merge = {...a, ...b} | 2222 | merge = {...a, ...b} |
| 4367 | ``` | 2223 | ``` |
| 4368 | 2224 | ||
| 4369 | <YueDisplay> | ||
| 4370 | |||
| 4371 | ```yue | ||
| 4372 | parts = | ||
| 4373 | * "shoulders" | ||
| 4374 | * "knees" | ||
| 4375 | lyrics = | ||
| 4376 | * "head" | ||
| 4377 | * ...parts | ||
| 4378 | * "and" | ||
| 4379 | * "toes" | ||
| 4380 | |||
| 4381 | copy = {...other} | ||
| 4382 | |||
| 4383 | a = {1, 2, 3, x: 1} | ||
| 4384 | b = {4, 5, y: 1} | ||
| 4385 | merge = {...a, ...b} | ||
| 4386 | ``` | ||
| 4387 | |||
| 4388 | </YueDisplay> | ||
| 4389 | |||
| 4390 | ## 表反向索引 | 2225 | ## 表反向索引 |
| 4391 | 2226 | ||
| 4392 |   你可以使用 **#** 操作符来反向索引表中的元素。 | 2227 |   你可以使用 **#** 操作符来反向索引表中的元素。 |
| @@ -4397,16 +2232,6 @@ second_last = data.items[#-1] | |||
| 4397 | data.items[#] = 1 | 2232 | data.items[#] = 1 |
| 4398 | ``` | 2233 | ``` |
| 4399 | 2234 | ||
| 4400 | <YueDisplay> | ||
| 4401 | |||
| 4402 | ```yue | ||
| 4403 | last = data.items[#] | ||
| 4404 | second_last = data.items[#-1] | ||
| 4405 | data.items[#] = 1 | ||
| 4406 | ``` | ||
| 4407 | |||
| 4408 | </YueDisplay> | ||
| 4409 | |||
| 4410 | ## 元表 | 2235 | ## 元表 |
| 4411 | 2236 | ||
| 4412 |   **<>** 操作符可提供元表操作的快捷方式。 | 2237 |   **<>** 操作符可提供元表操作的快捷方式。 |
| @@ -4431,26 +2256,6 @@ print d.value | |||
| 4431 | close _ = <close>: -> print "超出范围" | 2256 | close _ = <close>: -> print "超出范围" |
| 4432 | ``` | 2257 | ``` |
| 4433 | 2258 | ||
| 4434 | <YueDisplay> | ||
| 4435 | |||
| 4436 | ```yue | ||
| 4437 | mt = {} | ||
| 4438 | add = (right) => <>: mt, value: @value + right.value | ||
| 4439 | mt.__add = add | ||
| 4440 | |||
| 4441 | a = <>: mt, value: 1 | ||
| 4442 | -- 使用与临时变量名相同的字段名,将临时变量赋值给元表 | ||
| 4443 | b = :<add>, value: 2 | ||
| 4444 | c = <add>: mt.__add, value: 3 | ||
| 4445 | |||
| 4446 | d = a + b + c | ||
| 4447 | print d.value | ||
| 4448 | |||
| 4449 | close _ = <close>: -> print "超出范围" | ||
| 4450 | ``` | ||
| 4451 | |||
| 4452 | </YueDisplay> | ||
| 4453 | |||
| 4454 | ### 元表访问 | 2259 | ### 元表访问 |
| 4455 | 2260 | ||
| 4456 |   使用 **<>** 或被 **<>** 包围的元方法名或在 **<>** 中编写某些表达式来访问元表。 | 2261 |   使用 **<>** 或被 **<>** 包围的元方法名或在 **<>** 中编写某些表达式来访问元表。 |
| @@ -4465,19 +2270,6 @@ tb.<> = __index: {item: "hello"} | |||
| 4465 | print tb.item | 2270 | print tb.item |
| 4466 | ``` | 2271 | ``` |
| 4467 | 2272 | ||
| 4468 | <YueDisplay> | ||
| 4469 | |||
| 4470 | ```yue | ||
| 4471 | -- 使用包含字段 "value" 的元表创建 | ||
| 4472 | tb = <"value">: 123 | ||
| 4473 | tb.<index> = tb.<> | ||
| 4474 | print tb.value | ||
| 4475 | tb.<> = __index: {item: "hello"} | ||
| 4476 | print tb.item | ||
| 4477 | ``` | ||
| 4478 | |||
| 4479 | </YueDisplay> | ||
| 4480 | |||
| 4481 | ### 元表解构 | 2273 | ### 元表解构 |
| 4482 | 2274 | ||
| 4483 |   使用被 **<>** 包围的元方法键解构元表。 | 2275 |   使用被 **<>** 包围的元方法键解构元表。 |
| @@ -4487,15 +2279,6 @@ print tb.item | |||
| 4487 | print item, new, close, getter | 2279 | print item, new, close, getter |
| 4488 | ``` | 2280 | ``` |
| 4489 | 2281 | ||
| 4490 | <YueDisplay> | ||
| 4491 | |||
| 4492 | ```yue | ||
| 4493 | {item, :new, :<close>, <index>: getter} = tb | ||
| 4494 | print item, new, close, getter | ||
| 4495 | ``` | ||
| 4496 | |||
| 4497 | </YueDisplay> | ||
| 4498 | |||
| 4499 | ## 存在性 | 2282 | ## 存在性 |
| 4500 | 2283 | ||
| 4501 |   **?** 运算符可以在多种上下文中用来检查存在性。 | 2284 |   **?** 运算符可以在多种上下文中用来检查存在性。 |
| @@ -4515,25 +2298,6 @@ with? io.open "test.txt", "w" | |||
| 4515 | \close! | 2298 | \close! |
| 4516 | ``` | 2299 | ``` |
| 4517 | 2300 | ||
| 4518 | <YueDisplay> | ||
| 4519 | |||
| 4520 | ```yue | ||
| 4521 | func?! | ||
| 4522 | print abc?["你好 世界"]?.xyz | ||
| 4523 | |||
| 4524 | x = tab?.value | ||
| 4525 | len = utf8?.len or string?.len or (o) -> #o | ||
| 4526 | |||
| 4527 | if print and x? | ||
| 4528 | print x | ||
| 4529 | |||
| 4530 | with? io.open "test.txt", "w" | ||
| 4531 | \write "你好" | ||
| 4532 | \close! | ||
| 4533 | ``` | ||
| 4534 | |||
| 4535 | </YueDisplay> | ||
| 4536 | |||
| 4537 | ## 管道 | 2301 | ## 管道 |
| 4538 | 2302 | ||
| 4539 |   与其使用一系列嵌套的函数调用,你还可以考虑使用运算符 **|>** 来传递值。 | 2303 |   与其使用一系列嵌套的函数调用,你还可以考虑使用运算符 **|>** 来传递值。 |
| @@ -4552,24 +2316,6 @@ readFile "example.txt" | |||
| 4552 | 2316 | ||
| 4553 | ``` | 2317 | ``` |
| 4554 | 2318 | ||
| 4555 | <YueDisplay> | ||
| 4556 | |||
| 4557 | ```yue | ||
| 4558 | "你好" |> print | ||
| 4559 | 1 |> print 2 -- 将管道项作为第一个参数插入 | ||
| 4560 | 2 |> print 1, _, 3 -- 带有占位符的管道 | ||
| 4561 | |||
| 4562 | -- 多行的管道表达式 | ||
| 4563 | readFile "example.txt" | ||
| 4564 | |> extract language, {} | ||
| 4565 | |> parse language | ||
| 4566 | |> emit | ||
| 4567 | |> render | ||
| 4568 | |||
| 4569 | ``` | ||
| 4570 | |||
| 4571 | </YueDisplay> | ||
| 4572 | |||
| 4573 | ## 空值合并 | 2319 | ## 空值合并 |
| 4574 | 2320 | ||
| 4575 |   如果其左操作数不是 **nil**,则nil合并运算符 **??** 返回其左操作数的值;否则,它将计算右操作数并返回其结果。如果左操作数计算结果为非 nil 的值,**??** 运算符将不再计算其右操作数。 | 2321 |   如果其左操作数不是 **nil**,则nil合并运算符 **??** 返回其左操作数的值;否则,它将计算右操作数并返回其结果。如果左操作数计算结果为非 nil 的值,**??** 运算符将不再计算其右操作数。 |
| @@ -4582,17 +2328,6 @@ func a ?? {} | |||
| 4582 | a ??= false | 2328 | a ??= false |
| 4583 | ``` | 2329 | ``` |
| 4584 | 2330 | ||
| 4585 | <YueDisplay> | ||
| 4586 | |||
| 4587 | ```yue | ||
| 4588 | local a, b, c, d | ||
| 4589 | a = b ?? c ?? d | ||
| 4590 | func a ?? {} | ||
| 4591 | a ??= false | ||
| 4592 | ``` | ||
| 4593 | |||
| 4594 | </YueDisplay> | ||
| 4595 | |||
| 4596 | ## 隐式对象 | 2331 | ## 隐式对象 |
| 4597 | 2332 | ||
| 4598 |   你可以在表格块内使用符号 **\*** 或是 **-** 开始编写一系列隐式结构。如果你正在创建隐式对象,对象的字段必须具有相同的缩进。 | 2333 |   你可以在表格块内使用符号 **\*** 或是 **-** 开始编写一系列隐式结构。如果你正在创建隐式对象,对象的字段必须具有相同的缩进。 |
| @@ -4639,52 +2374,6 @@ tb = | |||
| 4639 | tb: { } | 2374 | tb: { } |
| 4640 | ``` | 2375 | ``` |
| 4641 | 2376 | ||
| 4642 | <YueDisplay> | ||
| 4643 | |||
| 4644 | ```yue | ||
| 4645 | -- 赋值时使用隐式对象 | ||
| 4646 | list = | ||
| 4647 | * 1 | ||
| 4648 | * 2 | ||
| 4649 | * 3 | ||
| 4650 | |||
| 4651 | -- 函数调用时使用隐式对象 | ||
| 4652 | func | ||
| 4653 | * 1 | ||
| 4654 | * 2 | ||
| 4655 | * 3 | ||
| 4656 | |||
| 4657 | -- 返回时使用隐式对象 | ||
| 4658 | f = -> | ||
| 4659 | return | ||
| 4660 | * 1 | ||
| 4661 | * 2 | ||
| 4662 | * 3 | ||
| 4663 | |||
| 4664 | -- 表格时使用隐式对象 | ||
| 4665 | tb = | ||
| 4666 | name: "abc" | ||
| 4667 | |||
| 4668 | values: | ||
| 4669 | - "a" | ||
| 4670 | - "b" | ||
| 4671 | - "c" | ||
| 4672 | |||
| 4673 | objects: | ||
| 4674 | - name: "a" | ||
| 4675 | value: 1 | ||
| 4676 | func: => @value + 1 | ||
| 4677 | tb: | ||
| 4678 | fieldA: 1 | ||
| 4679 | |||
| 4680 | - name: "b" | ||
| 4681 | value: 2 | ||
| 4682 | func: => @value + 2 | ||
| 4683 | tb: { } | ||
| 4684 | ``` | ||
| 4685 | |||
| 4686 | </YueDisplay> | ||
| 4687 | |||
| 4688 | # 字面量 | 2377 | # 字面量 |
| 4689 | 2378 | ||
| 4690 |   Lua 中的所有基本字面量都可以在月之脚本中使用。包括数字、字符串、布尔值和 **nil**。 | 2379 |   Lua 中的所有基本字面量都可以在月之脚本中使用。包括数字、字符串、布尔值和 **nil**。 |
| @@ -4700,19 +2389,6 @@ some_string = "这是一个字符串 | |||
| 4700 | print "我有#{math.random! * 100}%的把握。" | 2389 | print "我有#{math.random! * 100}%的把握。" |
| 4701 | ``` | 2390 | ``` |
| 4702 | 2391 | ||
| 4703 | <YueDisplay> | ||
| 4704 | |||
| 4705 | ```yue | ||
| 4706 | some_string = "这是一个字符串 | ||
| 4707 | 并包括一个换行。" | ||
| 4708 | |||
| 4709 | -- 使用#{}语法可以将表达式插入到字符串字面量中。 | ||
| 4710 | -- 字符串插值只在双引号字符串中可用。 | ||
| 4711 | print "我有#{math.random! * 100}%的把握。" | ||
| 4712 | ``` | ||
| 4713 | |||
| 4714 | </YueDisplay> | ||
| 4715 | |||
| 4716 | ## 数字字面量 | 2392 | ## 数字字面量 |
| 4717 | 2393 | ||
| 4718 |   你可以在数字字面量中使用下划线来增加可读性。 | 2394 |   你可以在数字字面量中使用下划线来增加可读性。 |
| @@ -4723,16 +2399,6 @@ hex = 0xEF_BB_BF | |||
| 4723 | binary = 0B10011 | 2399 | binary = 0B10011 |
| 4724 | ``` | 2400 | ``` |
| 4725 | 2401 | ||
| 4726 | <YueDisplay> | ||
| 4727 | |||
| 4728 | ```yue | ||
| 4729 | integer = 1_000_000 | ||
| 4730 | hex = 0xEF_BB_BF | ||
| 4731 | binary = 0B10011 | ||
| 4732 | ``` | ||
| 4733 | |||
| 4734 | </YueDisplay> | ||
| 4735 | |||
| 4736 | ## YAML 风格字符串 | 2402 | ## YAML 风格字符串 |
| 4737 | 2403 | ||
| 4738 |   使用 `|` 前缀标记一个多行 YAML 风格字符串: | 2404 |   使用 `|` 前缀标记一个多行 YAML 风格字符串: |
| @@ -4745,18 +2411,6 @@ str = | | |||
| 4745 | - #{expr} | 2411 | - #{expr} |
| 4746 | ``` | 2412 | ``` |
| 4747 | 2413 | ||
| 4748 | <YueDisplay> | ||
| 4749 | |||
| 4750 | ```yue | ||
| 4751 | str = | | ||
| 4752 | key: value | ||
| 4753 | list: | ||
| 4754 | - item1 | ||
| 4755 | - #{expr} | ||
| 4756 | ``` | ||
| 4757 | |||
| 4758 | </YueDisplay> | ||
| 4759 | |||
| 4760 |   其效果类似于原生 Lua 的多行拼接,所有文本(含换行)将被保留下来,并支持 `#{...}` 语法,通过 `tostring(expr)` 插入表达式结果。 | 2414 |   其效果类似于原生 Lua 的多行拼接,所有文本(含换行)将被保留下来,并支持 `#{...}` 语法,通过 `tostring(expr)` 插入表达式结果。 |
| 4761 | 2415 | ||
| 4762 |   YAML 风格的多行字符串会自动检测首行后最小的公共缩进,并从所有行中删除该前缀空白字符。这让你可以在代码中对齐文本,但输出字符串不会带多余缩进。 | 2416 |   YAML 风格的多行字符串会自动检测首行后最小的公共缩进,并从所有行中删除该前缀空白字符。这让你可以在代码中对齐文本,但输出字符串不会带多余缩进。 |
| @@ -4769,18 +2423,6 @@ fn = -> | |||
| 4769 | return str | 2423 | return str |
| 4770 | ``` | 2424 | ``` |
| 4771 | 2425 | ||
| 4772 | <YueDisplay> | ||
| 4773 | |||
| 4774 | ```yue | ||
| 4775 | fn = -> | ||
| 4776 | str = | | ||
| 4777 | foo: | ||
| 4778 | bar: baz | ||
| 4779 | return str | ||
| 4780 | ``` | ||
| 4781 | |||
| 4782 | </YueDisplay> | ||
| 4783 | |||
| 4784 |   输出字符串中的 foo: 对齐到行首,不会带有函数缩进空格。保留内部缩进的相对结构,适合书写结构化嵌套样式的内容。 | 2426 |   输出字符串中的 foo: 对齐到行首,不会带有函数缩进空格。保留内部缩进的相对结构,适合书写结构化嵌套样式的内容。 |
| 4785 | 2427 | ||
| 4786 |   支持自动处理字符中的引号、反斜杠等特殊符号,无需手动转义: | 2428 |   支持自动处理字符中的引号、反斜杠等特殊符号,无需手动转义: |
| @@ -4791,16 +2433,6 @@ str = | | |||
| 4791 | note: 'He said: "#{Hello}!"' | 2433 | note: 'He said: "#{Hello}!"' |
| 4792 | ``` | 2434 | ``` |
| 4793 | 2435 | ||
| 4794 | <YueDisplay> | ||
| 4795 | |||
| 4796 | ```yue | ||
| 4797 | str = | | ||
| 4798 | path: "C:\Program Files\App" | ||
| 4799 | note: 'He said: "#{Hello}!"' | ||
| 4800 | ``` | ||
| 4801 | |||
| 4802 | </YueDisplay> | ||
| 4803 | |||
| 4804 | # 模块 | 2436 | # 模块 |
| 4805 | 2437 | ||
| 4806 | ## 导入 | 2438 | ## 导入 |
| @@ -4832,35 +2464,6 @@ do | |||
| 4832 | import "export" as {one, two, Something:{umm:{ch}}} | 2464 | import "export" as {one, two, Something:{umm:{ch}}} |
| 4833 | ``` | 2465 | ``` |
| 4834 | 2466 | ||
| 4835 | <YueDisplay> | ||
| 4836 | |||
| 4837 | ```yue | ||
| 4838 | -- 用作表解构 | ||
| 4839 | do | ||
| 4840 | import insert, concat from table | ||
| 4841 | -- 当给 insert, concat 变量赋值时,编译器会报告错误 | ||
| 4842 | import C, Ct, Cmt from require "lpeg" | ||
| 4843 | -- 快捷写法引入模块的子项 | ||
| 4844 | import x, y, z from 'mymodule' | ||
| 4845 | -- 使用Python风格的导入 | ||
| 4846 | from 'module' import a, b, c | ||
| 4847 | |||
| 4848 | -- 快捷地导入一个模块 | ||
| 4849 | do | ||
| 4850 | import 'module' | ||
| 4851 | import 'module_x' | ||
| 4852 | import "d-a-s-h-e-s" | ||
| 4853 | import "module.part" | ||
| 4854 | |||
| 4855 | -- 导入模块后起一个别名使用,或是进行导入模块表的解构 | ||
| 4856 | do | ||
| 4857 | import "player" as PlayerModule | ||
| 4858 | import "lpeg" as :C, :Ct, :Cmt | ||
| 4859 | import "export" as {one, two, Something:{umm:{ch}}} | ||
| 4860 | ``` | ||
| 4861 | |||
| 4862 | </YueDisplay> | ||
| 4863 | |||
| 4864 | ## 导入全局变量 | 2467 | ## 导入全局变量 |
| 4865 | 2468 | ||
| 4866 |   你可以使用 `import` 将指定的全局变量导入到本地变量中。当导入一系列对全局变量的链式访问时,最后一个访问的字段将被赋值给本地变量。 | 2469 |   你可以使用 `import` 将指定的全局变量导入到本地变量中。当导入一系列对全局变量的链式访问时,最后一个访问的字段将被赋值给本地变量。 |
| @@ -4872,17 +2475,6 @@ do | |||
| 4872 | print concat ["a", tostring 1] | 2475 | print concat ["a", tostring 1] |
| 4873 | ``` | 2476 | ``` |
| 4874 | 2477 | ||
| 4875 | <YueDisplay> | ||
| 4876 | |||
| 4877 | ```yue | ||
| 4878 | do | ||
| 4879 | import tostring | ||
| 4880 | import table.concat | ||
| 4881 | print concat ["a", tostring 1] | ||
| 4882 | ``` | ||
| 4883 | |||
| 4884 | </YueDisplay> | ||
| 4885 | |||
| 4886 | ### 自动全局变量导入 | 2478 | ### 自动全局变量导入 |
| 4887 | 2479 | ||
| 4888 |   在一个代码块的顶部写 `import global`,会将当前作用域中尚未显式声明或赋值过的变量名,自动导入为本地常量,并在该语句的位置绑定到同名的全局变量。 | 2480 |   在一个代码块的顶部写 `import global`,会将当前作用域中尚未显式声明或赋值过的变量名,自动导入为本地常量,并在该语句的位置绑定到同名的全局变量。 |
| @@ -4904,25 +2496,6 @@ do | |||
| 4904 | FLAG = 123 | 2496 | FLAG = 123 |
| 4905 | ``` | 2497 | ``` |
| 4906 | 2498 | ||
| 4907 | <YueDisplay> | ||
| 4908 | |||
| 4909 | ```yue | ||
| 4910 | do | ||
| 4911 | import global | ||
| 4912 | print "hello" | ||
| 4913 | math.random 3 | ||
| 4914 | -- print = nil -- 报错:自动导入的全局变量是常量 | ||
| 4915 | |||
| 4916 | do | ||
| 4917 | -- 被显式声明为全局的变量不会被自动导入 | ||
| 4918 | import global | ||
| 4919 | global FLAG | ||
| 4920 | print FLAG | ||
| 4921 | FLAG = 123 | ||
| 4922 | ``` | ||
| 4923 | |||
| 4924 | </YueDisplay> | ||
| 4925 | |||
| 4926 | ## 导出 | 2499 | ## 导出 |
| 4927 | 2500 | ||
| 4928 |   导出语句提供了一种简洁的方式来定义当前的模块。 | 2501 |   导出语句提供了一种简洁的方式来定义当前的模块。 |
| @@ -4947,26 +2520,6 @@ export class Something | |||
| 4947 | umm: "cool" | 2520 | umm: "cool" |
| 4948 | ``` | 2521 | ``` |
| 4949 | 2522 | ||
| 4950 | <YueDisplay> | ||
| 4951 | |||
| 4952 | ```yue | ||
| 4953 | export a, b, c = 1, 2, 3 | ||
| 4954 | export cool = "cat" | ||
| 4955 | |||
| 4956 | export What = if this | ||
| 4957 | "abc" | ||
| 4958 | else | ||
| 4959 | "def" | ||
| 4960 | |||
| 4961 | export y = -> | ||
| 4962 | hallo = 3434 | ||
| 4963 | |||
| 4964 | export class Something | ||
| 4965 | umm: "cool" | ||
| 4966 | ``` | ||
| 4967 | |||
| 4968 | </YueDisplay> | ||
| 4969 | |||
| 4970 |   使用解构进行命名导出。 | 2523 |   使用解构进行命名导出。 |
| 4971 | 2524 | ||
| 4972 | ```yuescript | 2525 | ```yuescript |
| @@ -4974,15 +2527,6 @@ export :loadstring, to_lua: tolua = yue | |||
| 4974 | export {itemA: {:fieldA = '默认值'}} = tb | 2527 | export {itemA: {:fieldA = '默认值'}} = tb |
| 4975 | ``` | 2528 | ``` |
| 4976 | 2529 | ||
| 4977 | <YueDisplay> | ||
| 4978 | |||
| 4979 | ```yue | ||
| 4980 | export :loadstring, to_lua: tolua = yue | ||
| 4981 | export {itemA: {:fieldA = '默认值'}} = tb | ||
| 4982 | ``` | ||
| 4983 | |||
| 4984 | </YueDisplay> | ||
| 4985 | |||
| 4986 |   从模块导出命名项目时,可以不用创建局部变量。 | 2530 |   从模块导出命名项目时,可以不用创建局部变量。 |
| 4987 | 2531 | ||
| 4988 | ```yuescript | 2532 | ```yuescript |
| @@ -4991,16 +2535,6 @@ export.<index> = items | |||
| 4991 | export["a-b-c"] = 123 | 2535 | export["a-b-c"] = 123 |
| 4992 | ``` | 2536 | ``` |
| 4993 | 2537 | ||
| 4994 | <YueDisplay> | ||
| 4995 | |||
| 4996 | ```yue | ||
| 4997 | export.itemA = tb | ||
| 4998 | export.<index> = items | ||
| 4999 | export["a-b-c"] = 123 | ||
| 5000 | ``` | ||
| 5001 | |||
| 5002 | </YueDisplay> | ||
| 5003 | |||
| 5004 | ### 未命名导出 | 2538 | ### 未命名导出 |
| 5005 | 2539 | ||
| 5006 |   未命名导出会将要导出的目标项目添加到导出表的数组部分。 | 2540 |   未命名导出会将要导出的目标项目添加到导出表的数组部分。 |
| @@ -5018,23 +2552,6 @@ export with tmp | |||
| 5018 | j = 2000 | 2552 | j = 2000 |
| 5019 | ``` | 2553 | ``` |
| 5020 | 2554 | ||
| 5021 | <YueDisplay> | ||
| 5022 | |||
| 5023 | ```yue | ||
| 5024 | d, e, f = 3, 2, 1 | ||
| 5025 | export d, e, f | ||
| 5026 | |||
| 5027 | export if this | ||
| 5028 | 123 | ||
| 5029 | else | ||
| 5030 | 456 | ||
| 5031 | |||
| 5032 | export with tmp | ||
| 5033 | j = 2000 | ||
| 5034 | ``` | ||
| 5035 | |||
| 5036 | </YueDisplay> | ||
| 5037 | |||
| 5038 | ### 默认导出 | 2555 | ### 默认导出 |
| 5039 | 2556 | ||
| 5040 |   在导出语句中使用 **default** 关键字,来替换导出的表为一个目标的对象。 | 2557 |   在导出语句中使用 **default** 关键字,来替换导出的表为一个目标的对象。 |
| @@ -5045,16 +2562,6 @@ export default -> | |||
| 5045 | 123 | 2562 | 123 |
| 5046 | ``` | 2563 | ``` |
| 5047 | 2564 | ||
| 5048 | <YueDisplay> | ||
| 5049 | |||
| 5050 | ```yue | ||
| 5051 | export default -> | ||
| 5052 | print "你好" | ||
| 5053 | 123 | ||
| 5054 | ``` | ||
| 5055 | |||
| 5056 | </YueDisplay> | ||
| 5057 | |||
| 5058 | # MIT 许可证 | 2565 | # MIT 许可证 |
| 5059 | 2566 | ||
| 5060 | 版权 (c) 2017-2026 李瑾 \<dragon-fly@qq.com\> | 2567 | 版权 (c) 2017-2026 李瑾 \<dragon-fly@qq.com\> |
diff --git a/spec/inputs/compile_doc.yue b/spec/inputs/compile_doc.yue index 161c077..c26fced 100644 --- a/spec/inputs/compile_doc.yue +++ b/spec/inputs/compile_doc.yue | |||
| @@ -61,5 +61,9 @@ for [compiledFile, docFile, docFiles] in *docs | |||
| 61 | close output = with io.open "#{outputFolder}/#{compiledFile}", "w+" | 61 | close output = with io.open "#{outputFolder}/#{compiledFile}", "w+" |
| 62 | \write table.concat codes | 62 | \write table.concat codes |
| 63 | close output2 = with io.open "#{docFolder}/#{docFile}", "w+" | 63 | close output2 = with io.open "#{docFolder}/#{docFile}", "w+" |
| 64 | \write table.concat docTexts, "\n" | 64 | \write (table |
| 65 | .concat docTexts, "\n" | ||
| 66 | \gsub "<img .-/>\n\n", "" | ||
| 67 | \gsub "%-%-%-.-%-%-%-\n\n", "" | ||
| 68 | \gsub "<YueDisplay>.-</YueDisplay>\n\n", "") | ||
| 65 | 69 | ||
diff --git a/spec/outputs/compile_doc.lua b/spec/outputs/compile_doc.lua index ad1b065..e8fd719 100644 --- a/spec/outputs/compile_doc.lua +++ b/spec/outputs/compile_doc.lua | |||
| @@ -120,7 +120,7 @@ for _index_0 = 1, #docs do | |||
| 120 | local _close_0 <close> = output | 120 | local _close_0 <close> = output |
| 121 | local output2 | 121 | local output2 |
| 122 | local _with_0 = io.open(tostring(docFolder) .. "/" .. tostring(docFile), "w+") | 122 | local _with_0 = io.open(tostring(docFolder) .. "/" .. tostring(docFile), "w+") |
| 123 | _with_0:write(table.concat(docTexts, "\n")) | 123 | _with_0:write((table.concat(docTexts, "\n"):gsub("<img .-/>\n\n", ""):gsub("%-%-%-.-%-%-%-\n\n", ""):gsub("<YueDisplay>.-</YueDisplay>\n\n", ""))) |
| 124 | output2 = _with_0 | 124 | output2 = _with_0 |
| 125 | local _close_1 <close> = output2 | 125 | local _close_1 <close> = output2 |
| 126 | end | 126 | end |
