From 1f83d504bc344ffd3c8b4120b3865fd6c11a9e2d Mon Sep 17 00:00:00 2001 From: Li Jin Date: Fri, 6 Feb 2026 11:54:32 +0800 Subject: Updated docs. --- doc/docs/de/doc/advanced/do.md | 16 +- doc/docs/de/doc/advanced/line-decorators.md | 16 +- doc/docs/de/doc/advanced/macro.md | 115 ++-- doc/docs/de/doc/advanced/module.md | 74 +-- doc/docs/de/doc/advanced/try.md | 28 +- doc/docs/de/doc/assignment/assignment.md | 28 +- .../de/doc/assignment/destructuring-assignment.md | 90 +-- doc/docs/de/doc/assignment/if-assignment.md | 35 +- ...ng-clause-controlling-destructive-assignment.md | 36 +- doc/docs/de/doc/assignment/varargs-assignment.md | 4 +- doc/docs/de/doc/control-flow/conditionals.md | 65 +-- doc/docs/de/doc/control-flow/continue.md | 4 +- doc/docs/de/doc/control-flow/for-loop.md | 36 +- doc/docs/de/doc/control-flow/switch.md | 130 ++--- doc/docs/de/doc/control-flow/while-loop.md | 10 +- doc/docs/de/doc/data-structures/comprehensions.md | 74 +-- doc/docs/de/doc/data-structures/table-literals.md | 64 +-- doc/docs/de/doc/functions/backcalls.md | 16 +- doc/docs/de/doc/functions/function-literals.md | 161 +++--- doc/docs/de/doc/functions/function-stubs.md | 32 +- doc/docs/de/doc/getting-started/installation.md | 22 +- doc/docs/de/doc/getting-started/introduction.md | 56 +- doc/docs/de/doc/getting-started/usage.md | 124 ++-- doc/docs/de/doc/language-basics/attributes.md | 12 +- doc/docs/de/doc/language-basics/comment.md | 26 +- doc/docs/de/doc/language-basics/literals.md | 42 +- doc/docs/de/doc/language-basics/operator.md | 143 ++--- doc/docs/de/doc/language-basics/whitespace.md | 12 +- .../de/doc/objects/object-oriented-programming.md | 204 +++---- doc/docs/de/doc/objects/with-statement.md | 43 +- doc/docs/de/doc/reference/license-mit.md | 24 +- doc/docs/de/doc/reference/the-yuescript-library.md | 632 ++++++++++----------- doc/docs/doc/control-flow/conditionals.md | 11 - doc/docs/doc/getting-started/introduction.md | 4 +- doc/docs/doc/reference/license-mit.md | 2 - doc/docs/id-id/doc/advanced/do.md | 8 +- doc/docs/id-id/doc/advanced/line-decorators.md | 8 +- doc/docs/id-id/doc/advanced/macro.md | 66 +-- doc/docs/id-id/doc/advanced/module.md | 58 +- doc/docs/id-id/doc/advanced/try.md | 20 +- doc/docs/id-id/doc/assignment/assignment.md | 40 +- .../doc/assignment/destructuring-assignment.md | 50 +- doc/docs/id-id/doc/assignment/if-assignment.md | 18 +- ...ng-clause-controlling-destructive-assignment.md | 36 +- .../id-id/doc/assignment/varargs-assignment.md | 4 +- doc/docs/id-id/doc/control-flow/conditionals.md | 69 +-- doc/docs/id-id/doc/control-flow/continue.md | 6 +- doc/docs/id-id/doc/control-flow/for-loop.md | 24 +- doc/docs/id-id/doc/control-flow/switch.md | 32 +- doc/docs/id-id/doc/control-flow/while-loop.md | 8 +- .../id-id/doc/data-structures/comprehensions.md | 64 +-- .../id-id/doc/data-structures/table-literals.md | 20 +- doc/docs/id-id/doc/functions/backcalls.md | 10 +- doc/docs/id-id/doc/functions/function-literals.md | 86 +-- doc/docs/id-id/doc/functions/function-stubs.md | 24 +- doc/docs/id-id/doc/getting-started/installation.md | 24 +- doc/docs/id-id/doc/getting-started/introduction.md | 16 +- doc/docs/id-id/doc/getting-started/usage.md | 117 ++-- doc/docs/id-id/doc/index.md | 10 +- doc/docs/id-id/doc/language-basics/attributes.md | 8 +- doc/docs/id-id/doc/language-basics/comment.md | 22 +- doc/docs/id-id/doc/language-basics/literals.md | 30 +- doc/docs/id-id/doc/language-basics/operator.md | 90 +-- doc/docs/id-id/doc/language-basics/whitespace.md | 12 +- .../doc/objects/object-oriented-programming.md | 158 +++--- doc/docs/id-id/doc/objects/with-statement.md | 27 +- doc/docs/id-id/doc/reference/license-mit.md | 37 +- .../id-id/doc/reference/the-yuescript-library.md | 554 +++++++++--------- doc/docs/id-id/index.md | 20 +- doc/docs/id-id/try/index.md | 4 +- doc/docs/pt-br/doc/advanced/do.md | 8 +- doc/docs/pt-br/doc/advanced/line-decorators.md | 8 +- doc/docs/pt-br/doc/advanced/macro.md | 65 ++- doc/docs/pt-br/doc/advanced/module.md | 62 +- doc/docs/pt-br/doc/advanced/try.md | 20 +- doc/docs/pt-br/doc/assignment/assignment.md | 48 +- .../doc/assignment/destructuring-assignment.md | 66 +-- doc/docs/pt-br/doc/assignment/if-assignment.md | 34 +- ...ng-clause-controlling-destructive-assignment.md | 36 +- .../pt-br/doc/assignment/varargs-assignment.md | 4 +- doc/docs/pt-br/doc/control-flow/conditionals.md | 69 +-- doc/docs/pt-br/doc/control-flow/continue.md | 4 +- doc/docs/pt-br/doc/control-flow/for-loop.md | 36 +- doc/docs/pt-br/doc/control-flow/switch.md | 130 ++--- doc/docs/pt-br/doc/control-flow/while-loop.md | 10 +- .../pt-br/doc/data-structures/comprehensions.md | 64 +-- .../pt-br/doc/data-structures/table-literals.md | 20 +- doc/docs/pt-br/doc/functions/backcalls.md | 8 +- doc/docs/pt-br/doc/functions/function-literals.md | 94 +-- doc/docs/pt-br/doc/functions/function-stubs.md | 24 +- doc/docs/pt-br/doc/getting-started/installation.md | 24 +- doc/docs/pt-br/doc/getting-started/introduction.md | 40 +- doc/docs/pt-br/doc/getting-started/usage.md | 105 ++-- doc/docs/pt-br/doc/language-basics/attributes.md | 12 +- doc/docs/pt-br/doc/language-basics/comment.md | 22 +- doc/docs/pt-br/doc/language-basics/literals.md | 46 +- doc/docs/pt-br/doc/language-basics/operator.md | 116 ++-- doc/docs/pt-br/doc/language-basics/whitespace.md | 12 +- .../doc/objects/object-oriented-programming.md | 158 +++--- doc/docs/pt-br/doc/objects/with-statement.md | 27 +- doc/docs/pt-br/doc/reference/license-mit.md | 34 +- .../pt-br/doc/reference/the-yuescript-library.md | 632 ++++++++++----------- doc/docs/zh/doc/control-flow/conditionals.md | 11 - doc/docs/zh/doc/reference/license-mit.md | 2 - 104 files changed, 3077 insertions(+), 3145 deletions(-) (limited to 'doc') diff --git a/doc/docs/de/doc/advanced/do.md b/doc/docs/de/doc/advanced/do.md index 4990d6f..6f81f9d 100644 --- a/doc/docs/de/doc/advanced/do.md +++ b/doc/docs/de/doc/advanced/do.md @@ -1,25 +1,25 @@ # Do -When used as a statement, do works just like it does in Lua. +Als Statement verhält sich `do` wie in Lua. ```yuescript do - var = "hello" + var = "hallo" print var -print var -- nil here +print var -- nil hier ``` ```yue do - var = "hello" + var = "hallo" print var -print var -- nil here +print var -- nil hier ``` -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. +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. ```yuescript counter = do @@ -49,7 +49,7 @@ print counter! ```yuescript tbl = { key: do - print "assigning key!" + print "Schlüssel wird zugewiesen!" 1234 } ``` @@ -58,7 +58,7 @@ tbl = { ```yue tbl = { key: do - print "assigning key!" + print "Schlüssel wird zugewiesen!" 1234 } ``` diff --git a/doc/docs/de/doc/advanced/line-decorators.md b/doc/docs/de/doc/advanced/line-decorators.md index 292bc77..dd26925 100644 --- a/doc/docs/de/doc/advanced/line-decorators.md +++ b/doc/docs/de/doc/advanced/line-decorators.md @@ -1,32 +1,32 @@ -# Line Decorators +# Line-Decorators -For convenience, the for loop and if statement can be applied to single statements at the end of the line: +Zur Vereinfachung können `for`-Schleifen und `if`-Anweisungen auf einzelne Anweisungen am Zeilenende angewendet werden: ```yuescript -print "hello world" if name == "Rob" +print "Hallo Welt" if name == "Rob" ``` ```yue -print "hello world" if name == "Rob" +print "Hallo Welt" if name == "Rob" ``` -And with basic loops: +Und mit einfachen Schleifen: ```yuescript -print "item: ", item for item in *items +print "Element: ", item for item in *items ``` ```yue -print "item: ", item for item in *items +print "Element: ", item for item in *items ``` -And with while loops: +Und mit `while`-Schleifen: ```yuescript game\update! while game\isRunning! diff --git a/doc/docs/de/doc/advanced/macro.md b/doc/docs/de/doc/advanced/macro.md index 6d194c3..a3e155a 100644 --- a/doc/docs/de/doc/advanced/macro.md +++ b/doc/docs/de/doc/advanced/macro.md @@ -1,14 +1,14 @@ -# Macro +# Makros -## Common Usage +## Häufige Verwendung -Macro function is used for evaluating a string in the compile time and insert the generated codes into final compilation. +Makrofunktionen werden verwendet, um zur Compile-Zeit einen String auszuwerten und den generierten Code in die finale Kompilierung einzufügen. ```yuescript macro PI2 = -> math.pi * 2 area = $PI2 * 5 -macro HELLO = -> "'hello world'" +macro HELLO = -> "'Hallo Welt'" print $HELLO macro config = (debugging) -> @@ -27,7 +27,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- übergebene Ausdrücke werden als Strings behandelt macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -38,7 +38,7 @@ if $and f1!, f2!, f3! macro PI2 = -> math.pi * 2 area = $PI2 * 5 -macro HELLO = -> "'hello world'" +macro HELLO = -> "'Hallo Welt'" print $HELLO macro config = (debugging) -> @@ -57,7 +57,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- übergebene Ausdrücke werden als Strings behandelt macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -65,31 +65,32 @@ if $and f1!, f2!, f3! -## Insert Raw Codes +## Rohcode einfügen + +Eine Makrofunktion kann entweder einen YueScript-String oder eine Konfigurationstabelle mit Lua-Code zurückgeben. -A macro function can either return a YueScript string or a config table containing Lua codes. ```yuescript macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA -funcA = -> "fail to assign to the Yue macro defined variable" +funcA = -> "Zuweisung an die vom Yue-Makro definierte Variable schlägt fehl" macro luaFunc = (var) -> { code: "local function #{var}() end" type: "lua" } $luaFunc funcB -funcB = -> "fail to assign to the Lua macro defined variable" +funcB = -> "Zuweisung an die vom Lua-Makro definierte Variable schlägt fehl" macro lua = (code) -> { :code type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- führende und abschließende Symbole des Raw-Strings werden automatisch getrimmt $lua[==[ --- raw Lua codes insertion +-- Einfügen von rohem Lua-Code if cond then - print("output") + print("Ausgabe") end ]==] ``` @@ -98,63 +99,64 @@ end ```yue macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA -funcA = -> "fail to assign to the Yue macro defined variable" +funcA = -> "Zuweisung an die vom Yue-Makro definierte Variable schlägt fehl" macro luaFunc = (var) -> { code: "local function #{var}() end" type: "lua" } $luaFunc funcB -funcB = -> "fail to assign to the Lua macro defined variable" +funcB = -> "Zuweisung an die vom Lua-Makro definierte Variable schlägt fehl" macro lua = (code) -> { :code type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- führende und abschließende Symbole des Raw-Strings werden automatisch getrimmt $lua[==[ --- raw Lua codes insertion +-- Einfügen von rohem Lua-Code if cond then - print("output") + print("Ausgabe") end ]==] ``` -## Export Macro +## Makros exportieren + +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. -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. ```yuescript --- file: utils.yue +-- Datei: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" --- file main.yue +-- Datei main.yue import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- Symbol zum Importieren aller Makros + $foreach: $each -- Makro $foreach in $each umbenennen } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ``` ```yue --- file: utils.yue +-- Datei: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" --- file main.yue --- import function is not available in browser, try it in a real environment +-- Datei main.yue +-- Import-Funktion im Browser nicht verfügbar, in echter Umgebung testen --[[ import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- Symbol zum Importieren aller Makros + $foreach: $each -- Makro $foreach in $each umbenennen } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ]] @@ -162,32 +164,33 @@ import "utils" as { -## Builtin Macro +## Eingebaute Makros + +Es gibt einige eingebaute Makros, aber du kannst sie überschreiben, indem du Makros mit denselben Namen deklarierst. -There are some builtin macros but you can override them by declaring macros with the same names. ```yuescript -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- String des aktuellen Modulnamens +print $LINE -- gibt 2 aus ``` ```yue -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- String des aktuellen Modulnamens +print $LINE -- gibt 2 aus ``` -## Generating Macros with Macros +## Makros mit Makros erzeugen -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. +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. ```yuescript macro Enum = (...) -> items = {...} itemSet = {item, true for item in *items} (item) -> - error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] + error "erhalten: \"#{item}\", erwartet eines von #{table.concat items, ', '}" unless itemSet[item] "\"#{item}\"" macro BodyType = $Enum( @@ -196,8 +199,8 @@ macro BodyType = $Enum( Kinematic ) -print "Valid enum type:", $BodyType Static --- print "Compilation error with enum type:", $BodyType Unknown +print "Gültiger Enum-Typ:", $BodyType Static +-- print "Kompilierungsfehler bei Enum-Typ:", $BodyType Unknown ``` @@ -207,7 +210,7 @@ macro Enum = (...) -> items = {...} itemSet = {item, true for item in *items} (item) -> - error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] + error "erhalten: \"#{item}\", erwartet eines von #{table.concat items, ', '}" unless itemSet[item] "\"#{item}\"" macro BodyType = $Enum( @@ -216,15 +219,15 @@ macro BodyType = $Enum( Kinematic ) -print "Valid enum type:", $BodyType Static --- print "Compilation error with enum type:", $BodyType Unknown +print "Gültiger Enum-Typ:", $BodyType Static +-- print "Kompilierungsfehler bei Enum-Typ:", $BodyType Unknown ``` -## Argument Validation +## Argument-Validierung -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. +Du kannst erwartete AST-Knotentypen in der Argumentliste deklarieren und zur Compile-Zeit prüfen, ob die übergebenen Makroargumente den Erwartungen entsprechen. ```yuescript macro printNumAndStr = (num `Num, str `String) -> | @@ -233,7 +236,7 @@ macro printNumAndStr = (num `Num, str `String) -> | #{str} ) -$printNumAndStr 123, "hello" +$printNumAndStr 123, "hallo" ``` @@ -244,32 +247,32 @@ macro printNumAndStr = (num `Num, str `String) -> | #{str} ) -$printNumAndStr 123, "hello" +$printNumAndStr 123, "hallo" ``` -If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. +Wenn du flexiblere Argumentprüfungen brauchst, kannst du das eingebaute Makro `$is_ast` verwenden, um manuell an der passenden Stelle zu prüfen. ```yuescript macro printNumAndStr = (num, str) -> - error "expected Num as first argument" unless $is_ast Num, num - error "expected String as second argument" unless $is_ast String, str + error "als erstes Argument Num erwartet" unless $is_ast Num, num + error "als zweites Argument String erwartet" unless $is_ast String, str "print(#{num}, #{str})" -$printNumAndStr 123, "hello" +$printNumAndStr 123, "hallo" ``` ```yue macro printNumAndStr = (num, str) -> - error "expected Num as first argument" unless $is_ast Num, num - error "expected String as second argument" unless $is_ast String, str + error "als erstes Argument Num erwartet" unless $is_ast Num, num + error "als zweites Argument String erwartet" unless $is_ast String, str "print(#{num}, #{str})" -$printNumAndStr 123, "hello" +$printNumAndStr 123, "hallo" ``` -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). +Weitere Details zu verfügbaren AST-Knoten findest du in den großgeschriebenen Definitionen in `yue_parser.cpp`. diff --git a/doc/docs/de/doc/advanced/module.md b/doc/docs/de/doc/advanced/module.md index c955092..bdc5d86 100644 --- a/doc/docs/de/doc/advanced/module.md +++ b/doc/docs/de/doc/advanced/module.md @@ -2,27 +2,27 @@ ## Import -The import statement is a syntax sugar for requiring a module or help extracting items from an imported module. The imported items are const by default. +Die `import`-Anweisung ist syntaktischer Zucker für `require` und hilft beim Extrahieren von Einträgen aus importierten Modulen. Importierte Elemente sind standardmäßig `const`. ```yuescript --- used as table destructuring +-- als Tabellen-Destrukturierung do import insert, concat from table - -- report error when assigning to insert, concat + -- Fehler beim Zuweisen zu insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- Kurzform für implizites Require import x, y, z from 'mymodule' - -- import with Python style + -- Import im Python-Stil from 'module' import a, b, c --- shortcut for requring a module +-- Kurzform zum Laden eines Moduls do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- Modul mit Alias oder Tabellen-Destrukturierung laden do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -31,24 +31,24 @@ do ```yue --- used as table destructuring +-- als Tabellen-Destrukturierung do import insert, concat from table - -- report error when assigning to insert, concat + -- Fehler beim Zuweisen zu insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- Kurzform für implizites Require import x, y, z from 'mymodule' - -- import with Python style + -- Import im Python-Stil from 'module' import a, b, c --- shortcut for requring a module +-- Kurzform zum Laden eines Moduls do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- Modul mit Alias oder Tabellen-Destrukturierung laden do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -57,9 +57,9 @@ do -## Import Global +## Import von Globals -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. +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. ```yuescript do @@ -78,21 +78,21 @@ do -### Automatic Global Variable Import +### Automatischer Global-Import -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. +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. -Names that are explicitly declared as globals in the same scope will not be imported, so you can still assign to them. +Namen, die im selben Scope explizit als `global` deklariert werden, werden nicht importiert, sodass du sie weiterhin zuweisen kannst. ```yuescript do import global - print "hello" + print "hallo" math.random 3 - -- print = nil -- error: imported globals are const + -- print = nil -- Fehler: importierte Globals sind const do - -- explicit global variable will not be imported + -- explizite globale Variable wird nicht importiert import global global FLAG print FLAG @@ -103,12 +103,12 @@ do ```yue do import global - print "hello" + print "hallo" math.random 3 - -- print = nil -- error: imported globals are const + -- print = nil -- Fehler: importierte Globals sind const do - -- explicit global variable will not be imported + -- explizite globale Variable wird nicht importiert import global global FLAG print FLAG @@ -119,15 +119,15 @@ do ## Export -The export statement offers a concise way to define modules. +Die `export`-Anweisung bietet eine knappe Möglichkeit, Module zu definieren. -### Named Export +### Benannter Export -Named export will define a local variable as well as adding a field in the exported table. +Benannter Export definiert eine lokale Variable und fügt ein Feld in die exportierte Tabelle ein. ```yuescript export a, b, c = 1, 2, 3 -export cool = "cat" +export cool = "Katze" export What = if this "abc" @@ -144,7 +144,7 @@ export class Something ```yue export a, b, c = 1, 2, 3 -export cool = "cat" +export cool = "Katze" export What = if this "abc" @@ -160,7 +160,7 @@ export class Something -Doing named export with destructuring. +Benannter Export mit Destructuring. ```yuescript export :loadstring, to_lua: tolua = yue @@ -175,7 +175,7 @@ export {itemA: {:fieldA = 'default'}} = tb -Export named items from module without creating local variables. +Benannte Elemente aus dem Modul exportieren, ohne lokale Variablen zu erstellen. ```yuescript export.itemA = tb @@ -192,9 +192,9 @@ export["a-b-c"] = 123 -### Unnamed Export +### Unbenannter Export -Unnamed export will add the target item into the array part of the exported table. +Unbenannter Export fügt das Ziel-Element in den Array-Teil der exportierten Tabelle ein. ```yuescript d, e, f = 3, 2, 1 @@ -225,20 +225,20 @@ export with tmp -### Default Export +### Default-Export -Using the **default** keyword in export statement to replace the exported table with any thing. +Mit dem Schlüsselwort **default** in einer `export`-Anweisung wird die exportierte Tabelle durch ein beliebiges Objekt ersetzt. ```yuescript export default -> - print "hello" + print "hallo" 123 ``` ```yue export default -> - print "hello" + print "hallo" 123 ``` diff --git a/doc/docs/de/doc/advanced/try.md b/doc/docs/de/doc/advanced/try.md index 23c7877..4550e92 100644 --- a/doc/docs/de/doc/advanced/try.md +++ b/doc/docs/de/doc/advanced/try.md @@ -1,6 +1,6 @@ # Try -The syntax for Lua error handling in a common form. +Die Syntax für Fehlerbehandlung in Lua in einer gängigen Form. ```yuescript try @@ -20,10 +20,10 @@ catch err success, result = try func 1, 2, 3 try - print "trying" + print "Versuche" func 1, 2, 3 --- working with if assignment pattern +-- Verwendung mit if-Zuweisungsmuster if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -49,10 +49,10 @@ catch err success, result = try func 1, 2, 3 try - print "trying" + print "Versuche" func 1, 2, 3 --- working with if assignment pattern +-- Verwendung mit if-Zuweisungsmuster if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -63,18 +63,18 @@ catch err ## Try? -`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. +`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. ```yuescript a, b, c = try? func! --- with nil coalescing operator -a = (try? func!) ?? "default" +-- mit Nil-Verschmelzungs-Operator +a = (try? func!) ?? "Standardwert" --- as function argument +-- als Funktionsargument f try? func! --- with catch block +-- mit catch-Block f try? print 123 func! @@ -87,13 +87,13 @@ catch e ```yue a, b, c = try? func! --- with nil coalescing operator -a = (try? func!) ?? "default" +-- mit Nil-Verschmelzungs-Operator +a = (try? func!) ?? "Standardwert" --- as function argument +-- als Funktionsargument f try? func! --- with catch block +-- mit catch-Block f try? print 123 func! diff --git a/doc/docs/de/doc/assignment/assignment.md b/doc/docs/de/doc/assignment/assignment.md index 4dac6f4..b74501f 100644 --- a/doc/docs/de/doc/assignment/assignment.md +++ b/doc/docs/de/doc/assignment/assignment.md @@ -1,25 +1,26 @@ -# Assignment +# Zuweisung -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. +Variablen sind dynamisch typisiert und standardmäßig `local`. Du kannst den Geltungsbereich mit den Statements **local** und **global** ändern. ```yuescript hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- nutzt die bestehende Variable ``` ```yue hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- nutzt die bestehende Variable ``` -## Perform Update +## Update-Zuweisung + +Du kannst Update-Zuweisungen mit vielen binären Operatoren durchführen. -You can perform update assignment with many binary operators. ```yuescript x = 1 x += 1 @@ -27,7 +28,7 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist +s ..= "world" -- legt eine neue lokale Variable an, wenn sie nicht existiert arg or= "default value" ``` @@ -39,15 +40,16 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist +s ..= "world" -- legt eine neue lokale Variable an, wenn sie nicht existiert arg or= "default value" ``` -## Chaining Assignment +## Verkettete Zuweisung + +Mit verketteten Zuweisungen kannst du mehrere Variablen auf denselben Wert setzen. -You can do chaining assignment to assign multiple items to hold the same value. ```yuescript a = b = c = d = e = 0 x = y = z = f! @@ -61,7 +63,8 @@ x = y = z = f! -## Explicit Locals +## Explizite Locals + ```yuescript do local a = 1 @@ -99,7 +102,8 @@ do -## Explicit Globals +## Explizite Globals + ```yuescript do global a = 1 diff --git a/doc/docs/de/doc/assignment/destructuring-assignment.md b/doc/docs/de/doc/assignment/destructuring-assignment.md index e7b8046..0a08e22 100644 --- a/doc/docs/de/doc/assignment/destructuring-assignment.md +++ b/doc/docs/de/doc/assignment/destructuring-assignment.md @@ -1,10 +1,10 @@ -# Destructuring Assignment +# Destructuring-Zuweisung -Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. +Destructuring-Zuweisung ist eine Möglichkeit, schnell Werte aus einer Tabelle nach Name oder Position in array-basierten Tabellen zu extrahieren. -Typically when you see a table literal, {1,2,3}, it is on the right hand side of an assignment because it is a value. Destructuring assignment swaps the role of the table literal, and puts it on the left hand side of an assign statement. +Normalerweise steht ein Tabellenliteral wie `{1,2,3}` auf der rechten Seite einer Zuweisung, weil es ein Wert ist. Destructuring-Zuweisung tauscht die Rolle des Tabellenliterals und setzt es auf die linke Seite der Zuweisung. -This is best explained with examples. Here is how you would unpack the first two values from a table: +Am besten lässt sich das mit Beispielen erklären. So entpackst du die ersten zwei Werte einer Tabelle: ```yuescript thing = [1, 2] @@ -23,44 +23,44 @@ print a, b -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. +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. ```yuescript obj = { - hello: "world" - day: "tuesday" + hello: "Welt" + day: "Dienstag" length: 20 } {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- einfache Destructuring-Zuweisung ohne Klammern ist ok ``` ```yue obj = { - hello: "world" - day: "tuesday" + hello: "Welt" + day: "Dienstag" length: 20 } {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- einfache Destructuring-Zuweisung ohne Klammern ist ok ``` -This also works with nested data structures as well: +Das funktioniert auch mit verschachtelten Datenstrukturen: ```yuescript obj2 = { numbers: [1, 2, 3, 4] properties: { - color: "green" + color: "grün" height: 13.5 } } @@ -74,7 +74,7 @@ print first, second, color obj2 = { numbers: [1, 2, 3, 4] properties: { - color: "green" + color: "grün" height: 13.5 } } @@ -85,7 +85,7 @@ print first, second, color -If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: +Wenn die Destructuring-Anweisung kompliziert ist, kannst du sie gerne auf mehrere Zeilen verteilen. Ein etwas komplexeres Beispiel: ```yuescript { @@ -108,7 +108,7 @@ If the destructuring statement is complicated, feel free to spread it out over a -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: +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: ```yuescript {:concat, :insert} = table @@ -121,7 +121,7 @@ It's common to extract values from at table and assign them the local variables -This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: +Das ist effektiv dasselbe wie `import`, aber du kannst Felder umbenennen, indem du die Syntax mischst: ```yuescript {:mix, :max, random: rand} = math @@ -134,20 +134,20 @@ This is effectively the same as import, but we can rename fields we want to extr -You can write default values while doing destructuring like: +Du kannst Standardwerte beim Destructuring angeben, z. B.: ```yuescript -{:name = "nameless", :job = "jobless"} = person +{:name = "namenlos", :job = "arbeitlos"} = person ``` ```yue -{:name = "nameless", :job = "jobless"} = person +{:name = "namenlos", :job = "arbeitlos"} = person ``` -You can use `_` as placeholder when doing a list destructuring: +Du kannst `_` als Platzhalter verwenden, wenn du eine Listen-Destructuring-Zuweisung machst: ```yuescript [_, two, _, four] = items @@ -160,64 +160,64 @@ You can use `_` as placeholder when doing a list destructuring: -## Range Destructuring +## Bereichs-Destructuring -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. +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. ```yuescript -orders = ["first", "second", "third", "fourth", "last"] +orders = ["erster", "zweiter", "dritter", "vierter", "letzter"] [first, ...bulk, last] = orders -print first -- prints: first -print bulk -- prints: {"second", "third", "fourth"} -print last -- prints: last +print first -- gibt aus: erster +print bulk -- gibt aus: {"zweiter", "dritter", "vierter"} +print last -- gibt aus: letzter ``` ```yue -orders = ["first", "second", "third", "fourth", "last"] +orders = ["erster", "zweiter", "dritter", "vierter", "letzter"] [first, ...bulk, last] = orders -print first -- prints: first -print bulk -- prints: {"second", "third", "fourth"} -print last -- prints: last +print first -- gibt aus: erster +print bulk -- gibt aus: {"zweiter", "dritter", "vierter"} +print last -- gibt aus: letzter ``` -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: +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: ```yuescript --- Capture everything after first element +-- Alles nach dem ersten Element erfassen [first, ...rest] = orders --- Capture everything before last element +-- Alles vor dem letzten Element erfassen [...start, last] = orders --- Capture things except the middle elements +-- Alles außer den mittleren Elementen erfassen [first, ..._, last] = orders ``` ```yue --- Capture everything after first element +-- Alles nach dem ersten Element erfassen [first, ...rest] = orders --- Capture everything before last element +-- Alles vor dem letzten Element erfassen [...start, last] = orders --- Capture things except the middle elements +-- Alles außer den mittleren Elementen erfassen [first, ..._, last] = orders ``` -## Destructuring In Other Places +## Destructuring an anderen Stellen -Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: +Destructuring kann auch an Stellen vorkommen, an denen eine Zuweisung implizit erfolgt. Ein Beispiel ist eine `for`-Schleife: ```yuescript tuples = [ - ["hello", "world"] - ["egg", "head"] + ["hallo", "Welt"] + ["Ei", "Kopf"] ] for [left, right] in *tuples @@ -227,8 +227,8 @@ for [left, right] in *tuples ```yue tuples = [ - ["hello", "world"] - ["egg", "head"] + ["hallo", "Welt"] + ["Ei", "Kopf"] ] for [left, right] in *tuples @@ -237,4 +237,4 @@ for [left, right] in *tuples -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. +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. diff --git a/doc/docs/de/doc/assignment/if-assignment.md b/doc/docs/de/doc/assignment/if-assignment.md index 02984e8..884a8d2 100644 --- a/doc/docs/de/doc/assignment/if-assignment.md +++ b/doc/docs/de/doc/assignment/if-assignment.md @@ -1,6 +1,6 @@ -# If Assignment +# If-Zuweisung -`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. +`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. ```yuescript if user := database.find_user "moon" @@ -17,55 +17,56 @@ if user := database.find_user "moon" ```yuescript if hello := os.getenv "hello" - print "You have hello", hello + print "Du hast hello", hello elseif world := os.getenv "world" - print "you have world", world + print "Du hast world", world else - print "nothing :(" + print "nichts :(" ``` ```yue if hello := os.getenv "hello" - print "You have hello", hello + print "Du hast hello", hello elseif world := os.getenv "world" - print "you have world", world + print "Du hast world", world else - print "nothing :(" + print "nichts :(" ``` -If assignment with multiple return values. Only the first value is getting checked, other values are scoped. +If-Zuweisung mit mehreren Rückgabewerten. Nur der erste Wert wird geprüft, andere Werte bleiben im Scope. + ```yuescript -if success, result := pcall -> "get result without problems" - print result -- variable result is scoped +if success, result := pcall -> "Ergebnis ohne Probleme erhalten" + print result -- Variable result ist im Scope print "OK" ``` ```yue -if success, result := pcall -> "get result without problems" - print result -- variable result is scoped +if success, result := pcall -> "Ergebnis ohne Probleme erhalten" + print result -- Variable result ist im Scope print "OK" ``` -## While Assignment +## While-Zuweisung -You can also use if assignment in a while loop to get the value as the loop condition. +Du kannst if-Zuweisung auch in einer while-Schleife verwenden, um den Wert als Schleifenbedingung zu nutzen. ```yuescript while byte := stream\read_one! - -- do something with the byte + -- mit dem Byte etwas anfangen print byte ``` ```yue while byte := stream\read_one! - -- do something with the byte + -- mit dem Byte etwas anfangen print byte ``` diff --git a/doc/docs/de/doc/assignment/the-using-clause-controlling-destructive-assignment.md b/doc/docs/de/doc/assignment/the-using-clause-controlling-destructive-assignment.md index fb9b740..63bf016 100644 --- a/doc/docs/de/doc/assignment/the-using-clause-controlling-destructive-assignment.md +++ b/doc/docs/de/doc/assignment/the-using-clause-controlling-destructive-assignment.md @@ -1,11 +1,11 @@ -# The Using Clause; Controlling Destructive Assignment +# Die Using-Klausel: Destruktive Zuweisung kontrollieren -While lexical scoping can be a great help in reducing the complexity of the code we write, things can get unwieldy as the code size increases. Consider the following snippet: +Lexikalisches Scoping kann die Komplexität des Codes stark reduzieren, aber mit wachsendem Codeumfang kann es unübersichtlich werden. Betrachte folgendes Beispiel: ```yuescript i = 100 --- many lines of code... +-- viele Zeilen Code... my_func = -> i = 10 @@ -15,14 +15,14 @@ my_func = -> my_func! -print i -- will print 0 +print i -- wird 0 ausgeben ``` ```yue i = 100 --- many lines of code... +-- viele Zeilen Code... my_func = -> i = 10 @@ -32,25 +32,25 @@ my_func = -> my_func! -print i -- will print 0 +print i -- wird 0 ausgeben ``` -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. +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. -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. +Es wäre hilfreich, anzugeben, welche Variablen aus dem umschließenden Scope wir verändern wollen, um versehentliche Änderungen zu vermeiden. -The using keyword lets us do that. using nil makes sure that no closed variables are overwritten in assignment. The using clause is placed after the argument list in a function, or in place of it if there are no arguments. +Das Schlüsselwort `using` ermöglicht das. `using nil` stellt sicher, dass keine geschlossenen Variablen bei Zuweisungen überschrieben werden. Die `using`-Klausel steht nach der Argumentliste einer Funktion oder ersetzt sie, wenn es keine Argumente gibt. ```yuescript i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- hier wird eine neue lokale Variable erstellt my_func! -print i -- prints 100, i is unaffected +print i -- gibt 100 aus, i bleibt unverändert ``` @@ -58,27 +58,27 @@ print i -- prints 100, i is unaffected i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- hier wird eine neue lokale Variable erstellt my_func! -print i -- prints 100, i is unaffected +print i -- gibt 100 aus, i bleibt unverändert ``` -Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: +Mehrere Namen können durch Kommas getrennt werden. Closure-Werte können weiterhin gelesen, aber nicht verändert werden: ```yuescript tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- ein neues lokales tmp wird erstellt i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- diese wurden aktualisiert ``` @@ -87,12 +87,12 @@ tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- ein neues lokales tmp wird erstellt i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- diese wurden aktualisiert ``` diff --git a/doc/docs/de/doc/assignment/varargs-assignment.md b/doc/docs/de/doc/assignment/varargs-assignment.md index 1d66680..b211a8a 100644 --- a/doc/docs/de/doc/assignment/varargs-assignment.md +++ b/doc/docs/de/doc/assignment/varargs-assignment.md @@ -1,6 +1,6 @@ -# Varargs Assignment +# Varargs-Zuweisung -You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. +Du kannst Rückgabewerte einer Funktion dem Varargs-Symbol `...` zuweisen und dann den Inhalt auf die Lua-Weise auslesen. ```yuescript list = [1, 2, 3, 4, 5] diff --git a/doc/docs/de/doc/control-flow/conditionals.md b/doc/docs/de/doc/control-flow/conditionals.md index 5ba81cf..d20e6e3 100644 --- a/doc/docs/de/doc/control-flow/conditionals.md +++ b/doc/docs/de/doc/control-flow/conditionals.md @@ -1,55 +1,55 @@ -# Conditionals +# Bedingungen ```yuescript have_coins = false if have_coins - print "Got coins" + print "Münzen erhalten" else - print "No coins" + print "Keine Münzen" ``` ```yue have_coins = false if have_coins - print "Got coins" + print "Münzen erhalten" else - print "No coins" + print "Keine Münzen" ``` -A short syntax for single statements can also be used: +Eine Kurzsyntax für einzelne Anweisungen kann ebenfalls verwendet werden: ```yuescript have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Münzen erhalten" else print "Keine Münzen" ``` ```yue have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Münzen erhalten" else print "Keine Münzen" ``` -Because if statements can be used as expressions, this can also be written as: +Da `if`-Anweisungen als Ausdrücke verwendet werden können, kann man das auch so schreiben: ```yuescript have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Münzen erhalten" else "Keine Münzen" ``` ```yue have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Münzen erhalten" else "Keine Münzen" ``` -Conditionals can also be used in return statements and assignments: +Bedingungen können auch in `return`-Anweisungen und Zuweisungen verwendet werden: ```yuescript is_tall = (name) -> @@ -59,11 +59,11 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Ich bin sehr groß" else - "I am not so tall" + "Ich bin nicht so groß" -print message -- prints: I am very tall +print message -- gibt aus: Ich bin sehr groß ``` @@ -75,26 +75,26 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Ich bin sehr groß" else - "I am not so tall" + "Ich bin nicht so groß" -print message -- prints: I am very tall +print message -- gibt aus: Ich bin sehr groß ``` -The opposite of if is unless: +Das Gegenteil von `if` ist `unless`: ```yuescript unless os.date("%A") == "Monday" - print "it is not Monday!" + print "Es ist nicht Montag!" ``` ```yue unless os.date("%A") == "Monday" - print "it is not Monday!" + print "Es ist nicht Montag!" ``` @@ -110,18 +110,18 @@ print "You're lucky!" unless math.random! > 0.1 -## In Expression +## In-Ausdruck -You can write range checking code with an `in-expression`. +Mit einem `in`-Ausdruck kannst du Bereichsprüfungen schreiben. ```yuescript a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "Gleichheitsprüfung mit diskreten Werten" if a in list - print "checking if `a` is in a list" + print "Prüfen, ob `a` in einer Liste ist" ``` @@ -129,21 +129,10 @@ if a in list a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "Gleichheitsprüfung mit diskreten Werten" if a in list - print "checking if `a` is in a list" -``` - - - -```yuescript -print "You're lucky!" unless math.random! > 0.1 -``` - - -```yue -print "You're lucky!" unless math.random! > 0.1 + print "Prüfen, ob `a` in einer Liste ist" ``` diff --git a/doc/docs/de/doc/control-flow/continue.md b/doc/docs/de/doc/control-flow/continue.md index b000765..a6210d4 100644 --- a/doc/docs/de/doc/control-flow/continue.md +++ b/doc/docs/de/doc/control-flow/continue.md @@ -1,6 +1,6 @@ # Continue -A continue statement can be used to skip the current iteration in a loop. +Eine `continue`-Anweisung überspringt die aktuelle Iteration einer Schleife. ```yuescript i = 0 @@ -21,7 +21,7 @@ while i < 10 -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: +`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: ```yuescript my_numbers = [1, 2, 3, 4, 5, 6] diff --git a/doc/docs/de/doc/control-flow/for-loop.md b/doc/docs/de/doc/control-flow/for-loop.md index cabcde5..3bf63d4 100644 --- a/doc/docs/de/doc/control-flow/for-loop.md +++ b/doc/docs/de/doc/control-flow/for-loop.md @@ -1,12 +1,12 @@ -# For Loop +# For-Schleife -There are two for loop forms, just like in Lua. A numeric one and a generic one: +Es gibt zwei Formen der `for`-Schleife, genau wie in Lua: eine numerische und eine generische. ```yuescript for i = 10, 20 print i -for k = 1, 15, 2 -- an optional step provided +for k = 1, 15, 2 -- ein optionaler Schritt print k for key, value in pairs object @@ -18,7 +18,7 @@ for key, value in pairs object for i = 10, 20 print i -for k = 1, 15, 2 -- an optional step provided +for k = 1, 15, 2 -- ein optionaler Schritt print k for key, value in pairs object @@ -27,7 +27,7 @@ for key, value in pairs object -The slicing and **\*** operators can be used, just like with comprehensions: +Die Slicing- und **\***-Operatoren können verwendet werden, genau wie bei Comprehensions: ```yuescript for item in *items[2, 4] @@ -42,7 +42,7 @@ for item in *items[2, 4] -A shorter syntax is also available for all variations when the body is only a single line: +Eine kürzere Syntax ist für alle Varianten verfügbar, wenn der Rumpf nur eine Zeile hat: ```yuescript for item in *items do print item @@ -59,9 +59,9 @@ for j = 1, 10, 3 do print j -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. +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. -Doubling every even number: +Alle geraden Zahlen verdoppeln: ```yuescript doubled_evens = for i = 1, 20 @@ -82,9 +82,9 @@ doubled_evens = for i = 1, 20 -In addition, for loops support break with a return value, allowing the loop itself to be used as an expression that exits early with a meaningful result. +Zusätzlich unterstützen `for`-Schleifen `break` mit Rückgabewert, sodass die Schleife selbst als Ausdruck verwendet werden kann, der früh mit einem sinnvollen Ergebnis endet. -For example, to find the first number greater than 10: +Beispiel: die erste Zahl größer als 10 finden: ```yuescript first_large = for n in *numbers @@ -99,18 +99,18 @@ first_large = for n in *numbers -This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. +Diese `break`-mit-Wert-Syntax ermöglicht knappe und ausdrucksstarke Such- bzw. Early-Exit-Muster direkt in Schleifenausdrücken. -You can also filter values by combining the for loop expression with the continue statement. +Du kannst Werte auch filtern, indem du den `for`-Ausdruck mit `continue` kombinierst. -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. +`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. ```yuescript func_a = -> for i = 1, 10 do print i func_b = -> return for i = 1, 10 do i -print func_a! -- prints nil -print func_b! -- prints table object +print func_a! -- gibt nil aus +print func_b! -- gibt Tabellenobjekt aus ``` @@ -118,10 +118,10 @@ print func_b! -- prints table object func_a = -> for i = 1, 10 do print i func_b = -> return for i = 1, 10 do i -print func_a! -- prints nil -print func_b! -- prints table object +print func_a! -- gibt nil aus +print func_b! -- gibt Tabellenobjekt aus ``` -This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. +Das verhindert die unnötige Erstellung von Tabellen in Funktionen, die die Ergebnisse der Schleife nicht zurückgeben müssen. diff --git a/doc/docs/de/doc/control-flow/switch.md b/doc/docs/de/doc/control-flow/switch.md index f503a80..81e08bd 100644 --- a/doc/docs/de/doc/control-flow/switch.md +++ b/doc/docs/de/doc/control-flow/switch.md @@ -1,33 +1,33 @@ # Switch -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. +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. ```yuescript switch name := "Dan" when "Robert" - print "You are Robert" + print "Du bist Robert" when "Dan", "Daniel" - print "Your name, it's Dan" + print "Dein Name ist Dan" else - print "I don't know about you with name #{name}" + print "Ich kenne dich nicht mit dem Namen #{name}" ``` ```yue switch name := "Dan" when "Robert" - print "You are Robert" + print "Du bist Robert" when "Dan", "Daniel" - print "Your name, it's Dan" + print "Dein Name ist Dan" else - print "I don't know about you with name #{name}" + print "Ich kenne dich nicht mit dem Namen #{name}" ``` -A switch when clause can match against multiple values by listing them out comma separated. +Eine `when`-Klausel kann mehrere Werte prüfen, indem sie kommasepariert aufgelistet werden. -Switches can be used as expressions as well, here we can assign the result of the switch to a variable: +`switch` kann auch als Ausdruck verwendet werden. Hier wird das Ergebnis der `switch`-Anweisung einer Variable zugewiesen: ```yuescript b = 1 @@ -37,7 +37,7 @@ next_number = switch b when 2 3 else - error "can't count that high!" + error "so hoch kann ich nicht zählen!" ``` @@ -49,66 +49,66 @@ next_number = switch b when 2 3 else - error "can't count that high!" + error "so hoch kann ich nicht zählen!" ``` -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. +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. ```yuescript msg = switch math.random(1, 5) - when 1 then "you are lucky" - when 2 then "you are almost lucky" - else "not so lucky" + when 1 then "Du hast Glück" + when 2 then "Du hast fast Glück" + else "nicht so viel Glück" ``` ```yue msg = switch math.random(1, 5) - when 1 then "you are lucky" - when 2 then "you are almost lucky" - else "not so lucky" + when 1 then "Du hast Glück" + when 2 then "Du hast fast Glück" + else "nicht so viel Glück" ``` -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. +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. ```yuescript switch math.random(1, 5) when 1 - print "you are lucky" -- two indents + print "Du hast Glück" -- zwei Einrückungen else - print "not so lucky" + print "nicht so viel Glück" switch math.random(1, 5) when 1 - print "you are lucky" -- one indent + print "Du hast Glück" -- eine Einrückung else - print "not so lucky" + print "nicht so viel Glück" ``` ```yue switch math.random(1, 5) when 1 - print "you are lucky" -- two indents + print "Du hast Glück" -- zwei Einrückungen else - print "not so lucky" + print "nicht so viel Glück" switch math.random(1, 5) when 1 - print "you are lucky" -- one indent + print "Du hast Glück" -- eine Einrückung else - print "not so lucky" + print "nicht so viel Glück" ``` -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. +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. -## Table Matching +## Tabellen-Matching -You can do table matching in a switch when clause, if the table can be destructured by a specific structure and get non-nil values. +Du kannst in einer `switch`-`when`-Klausel Tabellen-Matching verwenden, wenn die Tabelle durch eine bestimmte Struktur destrukturiert werden kann und dabei nicht-`nil`-Werte liefert. ```yuescript items = @@ -122,7 +122,7 @@ for item in *items when :x, :y print "Vec2 #{x}, #{y}" when :width, :height - print "size #{width}, #{height}" + print "Größe #{width}, #{height}" ``` @@ -138,39 +138,39 @@ for item in *items when :x, :y print "Vec2 #{x}, #{y}" when :width, :height - print "size #{width}, #{height}" + print "Größe #{width}, #{height}" ``` -You can use default values to optionally destructure the table for some fields. +Du kannst Standardwerte verwenden, um bestimmte Felder optional zu destrukturieren. ```yuescript item = {} -{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') +{pos: {:x = 50, :y = 200}} = item -- Fehler: Versuch, einen nil-Wert zu indexieren (Feld 'pos') switch item when {pos: {:x = 50, :y = 200}} - print "Vec2 #{x}, #{y}" -- table destructuring will still pass + print "Vec2 #{x}, #{y}" -- Tabellen-Destrukturierung greift trotzdem ``` ```yue item = {} -{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') +{pos: {:x = 50, :y = 200}} = item -- Fehler: Versuch, einen nil-Wert zu indexieren (Feld 'pos') switch item when {pos: {:x = 50, :y = 200}} - print "Vec2 #{x}, #{y}" -- table destructuring will still pass + print "Vec2 #{x}, #{y}" -- Tabellen-Destrukturierung greift trotzdem ``` -You can also match against array elements, table fields, and even nested structures with array or table literals. +Du kannst auch gegen Array-Elemente, Tabellenfelder und sogar verschachtelte Strukturen mit Array- oder Tabellenliteralen matchen. -Match against array elements. +Matchen gegen Array-Elemente. ```yuescript switch tb @@ -178,7 +178,7 @@ switch tb print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" - when [1, 2, b = 3] -- b has a default value + when [1, 2, b = 3] -- b hat einen Standardwert print "1, 2, #{b}" ``` @@ -189,63 +189,63 @@ switch tb print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" - when [1, 2, b = 3] -- b has a default value + when [1, 2, b = 3] -- b hat einen Standardwert print "1, 2, #{b}" ``` -Match against table fields with destructuring. +Matchen gegen Tabellenfelder mit Destructuring. ```yuescript switch tb when success: true, :result - print "success", result + print "Erfolg", result when success: false - print "failed", result + print "fehlgeschlagen", result else - print "invalid" + print "ungültig" ``` ```yue switch tb when success: true, :result - print "success", result + print "Erfolg", result when success: false - print "failed", result + print "fehlgeschlagen", result else - print "invalid" + print "ungültig" ``` -Match against nested table structures. +Matchen gegen verschachtelte Tabellenstrukturen. ```yuescript switch tb when data: {type: "success", :content} - print "success", content + print "Erfolg", content when data: {type: "error", :content} - print "failed", content + print "fehlgeschlagen", content else - print "invalid" + print "ungültig" ``` ```yue switch tb when data: {type: "success", :content} - print "success", content + print "Erfolg", content when data: {type: "error", :content} - print "failed", content + print "fehlgeschlagen", content else - print "invalid" + print "ungültig" ``` -Match against array of tables. +Matchen gegen Array von Tabellen. ```yuescript switch tb @@ -255,7 +255,7 @@ switch tb {a: 5, b: 6} fourth ] - print "matched", fourth + print "getroffen", fourth ``` @@ -267,20 +267,20 @@ switch tb {a: 5, b: 6} fourth ] - print "matched", fourth + print "getroffen", fourth ``` -Match against a list and capture a range of elements. +Matchen gegen eine Liste und einen Bereich von Elementen erfassen. ```yuescript segments = ["admin", "users", "logs", "view"] switch segments when [...groups, resource, action] - print "Group:", groups -- prints: {"admin", "users"} - print "Resource:", resource -- prints: "logs" - print "Action:", action -- prints: "view" + print "Gruppe:", groups -- gibt aus: {"admin", "users"} + print "Ressource:", resource -- gibt aus: "logs" + print "Aktion:", action -- gibt aus: "view" ``` @@ -288,9 +288,9 @@ switch segments segments = ["admin", "users", "logs", "view"] switch segments when [...groups, resource, action] - print "Group:", groups -- prints: {"admin", "users"} - print "Resource:", resource -- prints: "logs" - print "Action:", action -- prints: "view" + print "Gruppe:", groups -- gibt aus: {"admin", "users"} + print "Ressource:", resource -- gibt aus: "logs" + print "Aktion:", action -- gibt aus: "view" ``` diff --git a/doc/docs/de/doc/control-flow/while-loop.md b/doc/docs/de/doc/control-flow/while-loop.md index 502935e..a875bf9 100644 --- a/doc/docs/de/doc/control-flow/while-loop.md +++ b/doc/docs/de/doc/control-flow/while-loop.md @@ -1,6 +1,6 @@ -# While Loop +# While-Schleife -The while loop also comes in four variations: +Die `while`-Schleife gibt es ebenfalls in vier Variationen: ```yuescript i = 10 @@ -43,11 +43,11 @@ until running == false do my_function! -Like for loops, the while loop can also be used an expression. Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. +Wie bei `for`-Schleifen kann die `while`-Schleife auch als Ausdruck verwendet werden. Damit eine Funktion den akkumulierten Wert einer `while`-Schleife zurückgibt, muss die Anweisung explizit mit `return` zurückgegeben werden. -## Repeat Loop +## Repeat-Schleife -The repeat loop comes from Lua: +Die `repeat`-Schleife stammt aus Lua: ```yuescript i = 10 diff --git a/doc/docs/de/doc/data-structures/comprehensions.md b/doc/docs/de/doc/data-structures/comprehensions.md index 3a92167..7e00c57 100644 --- a/doc/docs/de/doc/data-structures/comprehensions.md +++ b/doc/docs/de/doc/data-structures/comprehensions.md @@ -1,10 +1,10 @@ # Comprehensions -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. +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. -## List Comprehensions +## Listen-Comprehensions -The following creates a copy of the items table but with all the values doubled. +Das folgende Beispiel erstellt eine Kopie der `items`-Tabelle, aber mit verdoppelten Werten. ```yuescript items = [ 1, 2, 3, 4 ] @@ -19,7 +19,7 @@ doubled = [item * 2 for i, item in ipairs items] -The items included in the new table can be restricted with a when clause: +Die Elemente in der neuen Tabelle können mit einer `when`-Klausel eingeschränkt werden: ```yuescript slice = [item for i, item in ipairs items when i > 1 and i < 3] @@ -32,7 +32,7 @@ slice = [item for i, item in ipairs items when i > 1 and i < 3] -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: +Da es üblich ist, über die Werte einer numerisch indizierten Tabelle zu iterieren, gibt es den **\***-Operator. Das Verdopplungsbeispiel kann so umgeschrieben werden: ```yuescript doubled = [item * 2 for item in *items] @@ -45,7 +45,7 @@ doubled = [item * 2 for item in *items] -In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: +In Listen-Comprehensions kannst du außerdem den Spread-Operator `...` verwenden, um verschachtelte Listen zu flatten und einen Flat-Map-Effekt zu erzielen: ```yuescript data = @@ -53,7 +53,7 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat ist jetzt [1, 2, 3, 4, 5, 6] ``` @@ -63,14 +63,14 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat ist jetzt [1, 2, 3, 4, 5, 6] ``` -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. +Die `for`- und `when`-Klauseln können beliebig oft verkettet werden. Die einzige Anforderung ist, dass eine Comprehension mindestens eine `for`-Klausel enthält. -Using multiple for clauses is the same as using nested loops: +Mehrere `for`-Klauseln entsprechen verschachtelten Schleifen: ```yuescript x_coords = [4, 5, 6, 7] @@ -91,7 +91,7 @@ for y in *y_coords] -Numeric for loops can also be used in comprehensions: +Numerische `for`-Schleifen können ebenfalls in Comprehensions verwendet werden: ```yuescript evens = [i for i = 1, 100 when i % 2 == 0] @@ -104,16 +104,16 @@ evens = [i for i = 1, 100 when i % 2 == 0] -## Table Comprehensions +## Tabellen-Comprehensions -The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. +Die Syntax für Tabellen-Comprehensions ist sehr ähnlich, unterscheidet sich jedoch dadurch, dass **{** und **}** verwendet werden und pro Iteration zwei Werte erzeugt werden. -This example makes a copy of the tablething: +Dieses Beispiel erstellt eine Kopie von `thing`: ```yuescript thing = { - color: "red" - name: "fast" + color: "rot" + name: "schnell" width: 123 } @@ -123,8 +123,8 @@ thing_copy = {k, v for k, v in pairs thing} ```yue thing = { - color: "red" - name: "fast" + color: "rot" + name: "schnell" width: 123 } @@ -144,7 +144,7 @@ no_color = {k, v for k, v in pairs thing when k != "color"} -The **\*** operator is also supported. Here we create a square root look up table for a few numbers. +Der **\***-Operator wird ebenfalls unterstützt. Hier erstellen wir eine Nachschlagetabelle für Quadratwurzeln einiger Zahlen. ```yuescript numbers = [1, 2, 3, 4] @@ -159,18 +159,18 @@ sqrts = {i, math.sqrt i for i in *numbers} -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: +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: -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. +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. ```yuescript -tuples = [ ["hello", "world"], ["foo", "bar"]] +tuples = [ ["hallo", "Welt"], ["foo", "bar"]] tbl = {unpack tuple for tuple in *tuples} ``` ```yue -tuples = [ ["hello", "world"], ["foo", "bar"]] +tuples = [ ["hallo", "Welt"], ["foo", "bar"]] tbl = {unpack tuple for tuple in *tuples} ``` @@ -178,9 +178,9 @@ tbl = {unpack tuple for tuple in *tuples} ## Slicing -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. +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. -Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive: +Hier setzen wir die minimalen und maximalen Grenzen und nehmen alle Elemente mit Indizes zwischen 1 und 5 (inklusive): ```yuescript slice = [item for item in *items[1, 5]] @@ -193,7 +193,7 @@ slice = [item for item in *items[1, 5]] -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: +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: ```yuescript slice = [item for item in *items[2,]] @@ -206,7 +206,7 @@ slice = [item for item in *items[2,]] -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, …) +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, …): ```yuescript slice = [item for item in *items[,,2]] @@ -219,22 +219,22 @@ slice = [item for item in *items[,,2]] -Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. +Sowohl die Mindest- als auch die Maximalgrenze können negativ sein; dann werden die Grenzen vom Ende der Tabelle gezählt. ```yuescript --- take the last 4 items +-- die letzten 4 Elemente nehmen slice = [item for item in *items[-4,-1]] ``` ```yue --- take the last 4 items +-- die letzten 4 Elemente nehmen slice = [item for item in *items[-4,-1]] ``` -The step size can also be negative, which means that the items are taken in reverse order. +Die Schrittweite kann ebenfalls negativ sein, wodurch die Elemente in umgekehrter Reihenfolge genommen werden. ```yuescript reverse_slice = [item for item in *items[-1,1,-1]] @@ -247,24 +247,24 @@ reverse_slice = [item for item in *items[-1,1,-1]] -### Slicing Expression +### Slicing-Ausdruck -Slicing can also be used as an expression. This is useful for getting a sub-list of a table. +Slicing kann auch als Ausdruck verwendet werden. Das ist nützlich, um eine Teilliste einer Tabelle zu erhalten. ```yuescript --- take the 2nd and 4th items as a new list +-- das 2. und 4. Element als neue Liste nehmen sub_list = items[2, 4] --- take the last 4 items +-- die letzten 4 Elemente nehmen last_four_items = items[-4, -1] ``` ```yue --- take the 2nd and 4th items as a new list +-- das 2. und 4. Element als neue Liste nehmen sub_list = items[2, 4] --- take the last 4 items +-- die letzten 4 Elemente nehmen last_four_items = items[-4, -1] ``` diff --git a/doc/docs/de/doc/data-structures/table-literals.md b/doc/docs/de/doc/data-structures/table-literals.md index c1adcab..46181d7 100644 --- a/doc/docs/de/doc/data-structures/table-literals.md +++ b/doc/docs/de/doc/data-structures/table-literals.md @@ -1,6 +1,6 @@ -# Table Literals +# Tabellenliterale -Like in Lua, tables are delimited in curly braces. +Wie in Lua werden Tabellen mit geschweiften Klammern definiert. ```yuescript some_values = [1, 2, 3, 4] @@ -13,13 +13,13 @@ some_values = [1, 2, 3, 4] -Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). +Anders als in Lua weist man einem Schlüssel in einer Tabelle mit **:** (statt **=**) einen Wert zu. ```yuescript some_values = { name: "Bill", age: 200, - ["favorite food"]: "rice" + ["Lieblingsessen"]: "Reis" } ``` @@ -28,39 +28,39 @@ some_values = { some_values = { name: "Bill", age: 200, - ["favorite food"]: "rice" + ["Lieblingsessen"]: "Reis" } ``` -The curly braces can be left off if a single table of key value pairs is being assigned. +Die geschweiften Klammern können weggelassen werden, wenn eine einzelne Tabelle aus Schlüssel-Wert-Paaren zugewiesen wird. ```yuescript profile = - height: "4 feet", + height: "4 Fuß", shoe_size: 13, - favorite_foods: ["ice cream", "donuts"] + favorite_foods: ["Eis", "Donuts"] ``` ```yue profile = - height: "4 feet", + height: "4 Fuß", shoe_size: 13, - favorite_foods: ["ice cream", "donuts"] + favorite_foods: ["Eis", "Donuts"] ``` -Newlines can be used to delimit values instead of a comma (or both): +Zeilenumbrüche können Werte statt eines Kommas trennen (oder zusätzlich): ```yuescript values = { 1, 2, 3, 4 5, 6, 7, 8 - name: "superman" - occupation: "crime fighting" + name: "Superman" + occupation: "Verbrechensbekämpfung" } ``` @@ -69,50 +69,50 @@ values = { values = { 1, 2, 3, 4 5, 6, 7, 8 - name: "superman" - occupation: "crime fighting" + name: "Superman" + occupation: "Verbrechensbekämpfung" } ``` -When creating a single line table literal, the curly braces can also be left off: +Beim Erstellen eines einzeiligen Tabellenliterals können die geschweiften Klammern ebenfalls weggelassen werden: ```yuescript -my_function dance: "Tango", partner: "none" +my_function dance: "Tango", partner: "keiner" -y = type: "dog", legs: 4, tails: 1 +y = type: "Hund", legs: 4, tails: 1 ``` ```yue -my_function dance: "Tango", partner: "none" +my_function dance: "Tango", partner: "keiner" -y = type: "dog", legs: 4, tails: 1 +y = type: "Hund", legs: 4, tails: 1 ``` -The keys of a table literal can be language keywords without being escaped: +Die Schlüssel eines Tabellenliterals können Sprach-Schlüsselwörter sein, ohne sie zu escapen: ```yuescript tbl = { - do: "something" - end: "hunger" + do: "etwas" + end: "Hunger" } ``` ```yue tbl = { - do: "something" - end: "hunger" + do: "etwas" + end: "Hunger" } ``` -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: +Wenn du eine Tabelle aus Variablen konstruierst und die Schlüssel den Variablennamen entsprechen sollen, kannst du den Präfix-Operator **:** verwenden: ```yuescript hair = "golden" @@ -133,26 +133,26 @@ print_table :hair, :height -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. +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. ```yuescript t = { - [1 + 2]: "hello" - "hello world": true + [1 + 2]: "hallo" + "Hallo Welt": true } ``` ```yue t = { - [1 + 2]: "hello" - "hello world": true + [1 + 2]: "hallo" + "Hallo Welt": true } ``` -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. +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. ```yuescript some_values = [1, 2, 3, 4] diff --git a/doc/docs/de/doc/functions/backcalls.md b/doc/docs/de/doc/functions/backcalls.md index e34331e..dbac86b 100644 --- a/doc/docs/de/doc/functions/backcalls.md +++ b/doc/docs/de/doc/functions/backcalls.md @@ -1,21 +1,21 @@ # Backcalls -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. +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. ```yuescript x <- f -print "hello" .. x +print "hallo" .. x ``` ```yue x <- f -print "hello" .. x +print "hallo" .. x ``` -Fat arrow functions are also available. +Fat-Arrow-Funktionen sind ebenfalls verfügbar. ```yuescript <= f @@ -30,7 +30,7 @@ print @value -You can specify a placeholder for where you want the backcall function to go as a parameter. +Du kannst einen Platzhalter angeben, an welcher Stelle die Backcall-Funktion als Parameter eingesetzt werden soll. ```yuescript (x) <- map _, [1, 2, 3] @@ -45,11 +45,11 @@ x * 2 -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. +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. ```yuescript result, msg = do - data <- readAsync "filename.txt" + data <- readAsync "dateiname.txt" print data info <- processAsync data check info @@ -59,7 +59,7 @@ print result, msg ```yue result, msg = do - data <- readAsync "filename.txt" + data <- readAsync "dateiname.txt" print data info <- processAsync data check info diff --git a/doc/docs/de/doc/functions/function-literals.md b/doc/docs/de/doc/functions/function-literals.md index 316e07c..d3bfb11 100644 --- a/doc/docs/de/doc/functions/function-literals.md +++ b/doc/docs/de/doc/functions/function-literals.md @@ -1,42 +1,42 @@ -# Function Literals +# Funktionsliterale -All functions are created using a function expression. A simple function is denoted using the arrow: **->**. +Alle Funktionen werden mit einem Funktionsausdruck erstellt. Eine einfache Funktion wird mit dem Pfeil **->** notiert. ```yuescript my_function = -> -my_function() -- call the empty function +my_function() -- leere Funktion aufrufen ``` ```yue my_function = -> -my_function() -- call the empty function +my_function() -- leere Funktion aufrufen ``` -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: +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: ```yuescript -func_a = -> print "hello world" +func_a = -> print "Hallo Welt" func_b = -> value = 100 - print "The value:", value + print "Der Wert:", value ``` ```yue -func_a = -> print "hello world" +func_a = -> print "Hallo Welt" func_b = -> value = 100 - print "The value:", value + print "Der Wert:", value ``` -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. +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. ```yuescript func_a! @@ -51,20 +51,20 @@ func_b() -Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: +Funktionen mit Argumenten werden erstellt, indem der Pfeil von einer Argumentliste in Klammern eingeleitet wird: ```yuescript -sum = (x, y) -> print "sum", x + y +sum = (x, y) -> print "Summe", x + y ``` ```yue -sum = (x, y) -> print "sum", x + y +sum = (x, y) -> print "Summe", x + y ``` -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. +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. ```yuescript sum 10, 20 @@ -83,7 +83,7 @@ a b c "a", "b", "c" -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. +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. ```yuescript print "x:", sum(10, 20), "y:", sum(30, 40) @@ -96,24 +96,24 @@ print "x:", sum(10, 20), "y:", sum(30, 40) -There must not be any space between the opening parenthesis and the function. +Zwischen öffnender Klammer und Funktionsname darf kein Leerzeichen stehen. -Functions will coerce the last statement in their body into a return statement, this is called implicit return: +Funktionen wandeln die letzte Anweisung im Funktionskörper in ein `return` um. Das nennt sich implizites Return: ```yuescript sum = (x, y) -> x + y -print "The sum is ", sum 10, 20 +print "Die Summe ist ", sum 10, 20 ``` ```yue sum = (x, y) -> x + y -print "The sum is ", sum 10, 20 +print "Die Summe ist ", sum 10, 20 ``` -And if you need to explicitly return, you can use the return keyword: +Wenn du explizit zurückgeben willst, verwende `return`: ```yuescript sum = (x, y) -> return x + y @@ -126,7 +126,7 @@ sum = (x, y) -> return x + y -Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: +Wie in Lua können Funktionen mehrere Werte zurückgeben. Die letzte Anweisung muss eine Liste von Werten sein, getrennt durch Kommas: ```yuescript mystery = (x, y) -> x + y, x - y @@ -143,7 +143,7 @@ a, b = mystery 10, 20 ## Fat Arrows -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. +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. ```yuescript func = (num) => @value + num @@ -156,26 +156,26 @@ func = (num) => @value + num -## Argument Defaults +## Standardwerte für Argumente -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. +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. ```yuescript -my_function = (name = "something", height = 100) -> - print "Hello I am", name - print "My height is", height +my_function = (name = "etwas", height = 100) -> + print "Hallo, ich bin", name + print "Meine Größe ist", height ``` ```yue -my_function = (name = "something", height = 100) -> - print "Hello I am", name - print "My height is", height +my_function = (name = "etwas", height = 100) -> + print "Hallo, ich bin", name + print "Meine Größe ist", height ``` -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. +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. ```yuescript some_args = (x = 100, y = x + 1000) -> @@ -190,11 +190,11 @@ some_args = (x = 100, y = x + 1000) -> -## Considerations +## Hinweise -Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. +Aufgrund der ausdrucksstarken, klammerlosen Funktionsaufrufe müssen einige Einschränkungen gelten, um Parsing-Mehrdeutigkeiten mit Leerraum zu vermeiden. -The minus sign plays two roles, a unary negation operator and a binary subtraction operator. Consider how the following examples compile: +Das Minuszeichen hat zwei Rollen: unäre Negation und binäre Subtraktion. Sieh dir an, wie die folgenden Beispiele kompiliert werden: ```yuescript a = x - 10 @@ -213,30 +213,30 @@ d = x- z -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. +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. -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. +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. -Where there is a space following a variable and a string literal, the function call acts as show above. The string literal belongs to any following expressions (if they exist), which serves as the argument list. +Steht ein Leerzeichen zwischen Variable und String-Literal, verhält sich der Aufruf wie oben gezeigt. Das String-Literal gehört dann zu nachfolgenden Ausdrücken (falls vorhanden) und dient als Argumentliste. ```yuescript -x = func"hello" + 100 -y = func "hello" + 100 +x = func"hallo" + 100 +y = func "hallo" + 100 ``` ```yue -x = func"hello" + 100 -y = func "hello" + 100 +x = func"hallo" + 100 +y = func "hallo" + 100 ``` -## Multi-line arguments +## Mehrzeilige Argumente -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. +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. -If an argument list is to be continued onto the next line, the current line must end in a comma. And the following line must be indented more than the current indentation. Once indented, all other argument lines must be at the same level of indentation to be part of the argument list +Wenn eine Argumentliste in der nächsten Zeile fortgesetzt wird, muss die aktuelle Zeile mit einem Komma enden. Die folgende Zeile muss stärker eingerückt sein als die aktuelle. Sobald eingerückt, müssen alle weiteren Argumentzeilen auf derselben Einrückungsebene liegen, um Teil der Argumentliste zu sein. ```yuescript my_func 5, 4, 3, @@ -261,7 +261,7 @@ cool_func 1, 2, -This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. +Diese Art des Aufrufs kann verschachtelt werden. Die Einrückungsebene bestimmt, zu welcher Funktion die Argumente gehören. ```yuescript my_func 5, 6, 7, @@ -280,7 +280,7 @@ my_func 5, 6, 7, -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. +Da Tabellen ebenfalls das Komma als Trennzeichen verwenden, hilft diese Einrückungssyntax dabei, Werte zur Argumentliste gehören zu lassen, statt zur Tabelle. ```yuescript x = [ @@ -301,7 +301,7 @@ x = [ -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. +Obwohl es selten ist: Du kannst Funktionsargumente tiefer einrücken, wenn du weißt, dass du später eine geringere Einrückungsebene verwenden wirst. ```yuescript y = [ my_func 1, 2, 3, @@ -320,46 +320,45 @@ y = [ my_func 1, 2, 3, -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: +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: ```yuescript if func 1, 2, 3, - "hello", - "world" - print "hello" - print "I am inside if" + "hallo", + "Welt" + print "hallo" + print "Ich bin innerhalb der if-Bedingung" if func 1, 2, 3, - "hello", - "world" - print "hello" - print "I am inside if" + "hallo", + "Welt" + print "hallo" + print "Ich bin innerhalb der if-Bedingung" ``` ```yue if func 1, 2, 3, - "hello", - "world" - print "hello" - print "I am inside if" + "hallo", + "Welt" + print "hallo" + print "Ich bin innerhalb der if-Bedingung" if func 1, 2, 3, - "hello", - "world" - print "hello" - print "I am inside if" + "hallo", + "Welt" + print "hallo" + print "Ich bin innerhalb der if-Bedingung" ``` -## Parameter Destructuring +## Parameter-Destructuring -YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: +YueScript unterstützt jetzt Destructuring von Funktionsparametern, wenn das Argument ein Objekt ist. Es gibt zwei Formen von Destructuring-Tabellenliteralen: -* **Curly-brace wrapped literals/object parameters**, allowing optional default values when fields are missing (e.g., `{:a, :b}`, `{a: a1 = 123}`). - -* **Unwrapped simple table syntax**, starting with a sequence of key-value or shorthand bindings and continuing until another expression terminates it (e.g., `:a, b: b1, :c`). This form extracts multiple fields from the same object. +* **Geschweifte Klammern/Objektparameter**, die optionale Standardwerte erlauben, wenn Felder fehlen (z. B. `{:a, :b}`, `{a: a1 = 123}`). +* **Unverpackte einfache Tabellensyntax**, die mit einer Sequenz aus Key-Value- oder Shorthand-Bindings beginnt und so lange läuft, bis ein anderer Ausdruck sie beendet (z. B. `:a, b: b1, :c`). Diese Form extrahiert mehrere Felder aus demselben Objekt. ```yuescript f1 = (:a, :b, :c) -> @@ -390,9 +389,9 @@ f2 arg1, arg2 -## Prefixed Return Expression +## Präfixiertes Return-Expression -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: +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: ```yuescript findFirstEven = (list): nil -> @@ -415,7 +414,7 @@ findFirstEven = (list): nil -> -This is equivalent to: +Das ist äquivalent zu: ```yuescript findFirstEven = (list) -> @@ -440,16 +439,16 @@ findFirstEven = (list) -> -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. +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. -## Named Varargs +## Benannte Varargs -You can use the `(...t) ->` syntax to automatically store varargs into a named table. This table will contain all passed arguments (including `nil` values), and the `n` field of the table will store the actual number of arguments passed (including `nil` values). +Mit der Syntax `(...t) ->` kannst du Varargs automatisch in einer benannten Tabelle speichern. Diese Tabelle enthält alle übergebenen Argumente (einschließlich `nil`-Werten), und das Feld `n` der Tabelle speichert die tatsächliche Anzahl übergebener Argumente (einschließlich `nil`-Werten). ```yuescript f = (...t) -> - print "argument count:", t.n - print "table length:", #t + print "Anzahl der Argumente:", t.n + print "Tabellenlänge:", #t for i = 1, t.n print t[i] @@ -457,7 +456,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Fälle mit nil-Werten behandeln process = (...args) -> sum = 0 for i = 1, args.n @@ -471,8 +470,8 @@ process 1, nil, 3, nil, 5 ```yue f = (...t) -> - print "argument count:", t.n - print "table length:", #t + print "Anzahl der Argumente:", t.n + print "Tabellenlänge:", #t for i = 1, t.n print t[i] @@ -480,7 +479,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Fälle mit nil-Werten behandeln process = (...args) -> sum = 0 for i = 1, args.n diff --git a/doc/docs/de/doc/functions/function-stubs.md b/doc/docs/de/doc/functions/function-stubs.md index 57a8b0c..66b3ddb 100644 --- a/doc/docs/de/doc/functions/function-stubs.md +++ b/doc/docs/de/doc/functions/function-stubs.md @@ -1,27 +1,27 @@ -# Function Stubs +# Funktions-Stubs -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. +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. -The function stub syntax is a shorthand for creating a new closure function that bundles both the object and function. This new function calls the wrapped function in the correct context of the object. +Die Funktions-Stub-Syntax ist eine Kurzform, um eine neue Closure-Funktion zu erstellen, die sowohl Objekt als auch Funktion bündelt. Diese neue Funktion ruft die umschlossene Funktion im richtigen Kontext des Objekts auf. -Its syntax is the same as calling an instance method with the \ operator but with no argument list provided. +Die Syntax entspricht dem Aufruf einer Instanzmethode mit dem `\`-Operator, jedoch ohne Argumentliste. ```yuescript my_object = { value: 1000 - write: => print "the value:", @value + write: => print "der Wert:", @value } run_callback = (func) -> - print "running callback..." + print "Callback wird ausgeführt..." func! --- this will not work: --- the function has to no reference to my_object +-- das funktioniert nicht: +-- die Funktion darf keine Referenz auf my_object haben run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- Funktions-Stub-Syntax +-- bindet das Objekt in eine neue Funktion ein run_callback my_object\write ``` @@ -29,19 +29,19 @@ run_callback my_object\write ```yue my_object = { value: 1000 - write: => print "the value:", @value + write: => print "der Wert:", @value } run_callback = (func) -> - print "running callback..." + print "Callback wird ausgeführt..." func! --- this will not work: --- the function has to no reference to my_object +-- das funktioniert nicht: +-- die Funktion darf keine Referenz auf my_object haben run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- Funktions-Stub-Syntax +-- bindet das Objekt in eine neue Funktion ein run_callback my_object\write ``` diff --git a/doc/docs/de/doc/getting-started/installation.md b/doc/docs/de/doc/getting-started/installation.md index a93ddfd..78187c7 100644 --- a/doc/docs/de/doc/getting-started/installation.md +++ b/doc/docs/de/doc/getting-started/installation.md @@ -1,43 +1,43 @@ # Installation -## Lua Module +## Lua-Modul -Install [luarocks](https://luarocks.org), a package manager for Lua modules. Then install it as a Lua module and executable with: +Installiere [luarocks](https://luarocks.org), einen Paketmanager für Lua-Module. Installiere YueScript dann als Lua-Modul und ausführbare Datei mit: ```shell luarocks install yuescript ``` -Or you can build `yue.so` file with: +Oder du kannst die Datei `yue.so` bauen mit: ```shell make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua ``` -Then get the binary file from path **bin/shared/yue.so**. +Anschließend findest du die Binärdatei unter **bin/shared/yue.so**. -## Build Binary Tool +## Binär-Tool bauen -Clone this repo, then build and install executable with: +Klone dieses Repo und baue/installiere die ausführbare Datei mit: ```shell make install ``` -Build YueScript tool without macro feature: +YueScript-Tool ohne Makro-Feature bauen: ```shell make install NO_MACRO=true ``` -Build YueScript tool without built-in Lua binary: +YueScript-Tool ohne eingebautes Lua-Binary bauen: ```shell make install NO_LUA=true ``` -## Download Precompiled Binary +## Vorgefertigtes Binary herunterladen -You can download precompiled binary files, including binary executable files compatible with different Lua versions and library files. +Du kannst vorkompilierte Binärdateien herunterladen, inklusive ausführbarer Dateien für unterschiedliche Lua-Versionen und Bibliotheksdateien. -Download precompiled binary files from [here](https://github.com/IppClub/YueScript/releases). +Lade vorkompilierte Binärdateien von [hier](https://github.com/IppClub/YueScript/releases) herunter. diff --git a/doc/docs/de/doc/getting-started/introduction.md b/doc/docs/de/doc/getting-started/introduction.md index a9a9389..38354c1 100644 --- a/doc/docs/de/doc/getting-started/introduction.md +++ b/doc/docs/de/doc/getting-started/introduction.md @@ -1,27 +1,27 @@ -# Introduction +# Einführung -YueScript is a dynamic language that compiles to Lua. And it's a [MoonScript](https://github.com/leafo/moonscript) dialect. The codes written in YueScript are expressive and extremely concise. And it is suitable for writing some changing application logic with more maintainable codes and runs in a Lua embeded environment such as games or website servers. +YueScript ist eine dynamische Sprache, die zu Lua kompiliert. Sie ist ein Dialekt von [MoonScript](https://github.com/leafo/moonscript). Code, der in YueScript geschrieben wird, ist ausdrucksstark und sehr kompakt. YueScript eignet sich zum Schreiben von veränderlicher Anwendungslogik mit besser wartbarem Code und läuft in eingebetteten Lua-Umgebungen wie Spielen oder Webservern. -Yue (月) is the name of moon in Chinese and it's pronounced as [jyɛ]. +Yue (月) ist das chinesische Wort für Mond und wird als [jyɛ] ausgesprochen. -## An Overview of YueScript +## Ein Überblick über YueScript ```yuescript --- import syntax +-- Import-Syntax import p, to_lua from "yue" --- object literals +-- Objekt-Literale inventory = equipment: - - "sword" - - "shield" + - "Schwert" + - "Schild" items: - - name: "potion" + - name: "Trank" count: 10 - - name: "bread" + - name: "Brot" count: 3 --- list comprehension +-- Listen-Abstraktion map = (arr, action) -> [action item for item in *arr] @@ -31,14 +31,14 @@ filter = (arr, cond) -> reduce = (arr, init, action): init -> init = action init, item for item in *arr --- pipe operator +-- Pipe-Operator [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print --- metatable manipulation +-- Metatable-Manipulation apple = size: 15 : @@ -47,28 +47,28 @@ apple = with apple p .size, .color, . if .<>? --- js-like export syntax -export 🌛 = "月之脚本" +-- export-Syntax (ähnlich wie in JavaScript) +export 🌛 = "Skript des Mondes" ``` ```yue --- import syntax +-- Import-Syntax import p, to_lua from "yue" --- object literals +-- Objekt-Literale inventory = equipment: - - "sword" - - "shield" + - "Schwert" + - "Schild" items: - - name: "potion" + - name: "Trank" count: 10 - - name: "bread" + - name: "Brot" count: 3 --- list comprehension +-- Listen-Abstraktion map = (arr, action) -> [action item for item in *arr] @@ -78,14 +78,14 @@ filter = (arr, cond) -> reduce = (arr, init, action): init -> init = action init, item for item in *arr --- pipe operator +-- Pipe-Operator [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print --- metatable manipulation +-- Metatable-Manipulation apple = size: 15 : @@ -94,12 +94,12 @@ apple = with apple p .size, .color, . if .<>? --- js-like export syntax -export 🌛 = "月之脚本" +-- export-Syntax (ähnlich wie in JavaScript) +export 🌛 = "Skript des Mondes" ``` -## About Dora SSR +## Über Dora SSR -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. \ No newline at end of file +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. diff --git a/doc/docs/de/doc/getting-started/usage.md b/doc/docs/de/doc/getting-started/usage.md index 45161c6..f3c9333 100644 --- a/doc/docs/de/doc/getting-started/usage.md +++ b/doc/docs/de/doc/getting-started/usage.md @@ -1,20 +1,20 @@ -# Usage +# Verwendung -## Lua Module +## Lua-Modul -Use YueScript module in Lua: +YueScript-Modul in Lua verwenden: -* **Case 1** +* **Fall 1** - Require "your_yuescript_entry.yue" in Lua. + "your_yuescript_entry.yue" in Lua require'n. ```Lua require("yue")("your_yuescript_entry") ``` - And this code still works when you compile "your_yuescript_entry.yue" to "your_yuescript_entry.lua" in the same path. In the rest YueScript files just use the normal **require** or **import**. The code line numbers in error messages will also be handled correctly. + Dieser Code funktioniert weiterhin, wenn du "your_yuescript_entry.yue" im gleichen Pfad zu "your_yuescript_entry.lua" kompilierst. In den restlichen YueScript-Dateien verwendest du einfach normales **require** oder **import**. Die Zeilennummern in Fehlermeldungen werden korrekt behandelt. -* **Case 2** +* **Fall 2** - Require YueScript module and rewite message by hand. + YueScript-Modul require'n und das Fehlermapping manuell umschreiben. ```lua local yue = require("yue") @@ -26,15 +26,15 @@ Use YueScript module in Lua: end) ``` -* **Case 3** +* **Fall 3** - Use the YueScript compiler function in Lua. + Die YueScript-Compilerfunktion in Lua verwenden. ```lua local yue = require("yue") local codes, err, globals = yue.to_lua([[ f = -> - print "hello world" + print "Hallo Welt" f! ]],{ implicit_return_root = true, @@ -48,64 +48,66 @@ Use YueScript module in Lua: }) ``` -## YueScript Tool +## YueScript-Tool -Use YueScript tool with: +YueScript-Tool verwenden mit: ```shell > yue -h -Usage: yue - [options] [] ... - yue -e [args...] - yue -w [] [options] - yue - - -Notes: - - '-' / '--' must be the first and only argument. - - '-o/--output' can not be used with multiple input files. - - '-w/--watch' can not be used with file input (directory only). - - with '-e/--execute', remaining tokens are treated as script args. - -Options: - -h, --help Show this help message and exit. - -e , --execute Execute a file or raw codes - -m, --minify Generate minified codes - -r, --rewrite Rewrite output to match original line numbers - -t , --output-to - Specify where to place compiled files - -o , --output Write output to file - -p, --print Write output to standard out - -b, --benchmark Dump compile time (doesn't write output) - -g, --globals Dump global variables used in NAME LINE COLUMN - -s, --spaces Use spaces in generated codes instead of tabs - -l, --line-numbers Write line numbers from source codes - -j, --no-implicit-return Disable implicit return at end of file - -c, --reserve-comments Reserve comments before statement from source codes - -w [], --watch [] - Watch changes and compile every file under directory - -v, --version Print version - - Read from standard in, print to standard out - (Must be first and only argument) - -- Same as '-' (kept for backward compatibility) - - --target Specify the Lua version that codes will be generated to - (version can only be 5.1 to 5.5) - --path Append an extra Lua search path string to package.path - --= Pass compiler option in key=value form (existing behavior) - - Execute without options to enter REPL, type symbol '$' - in a single line to start/stop multi-line mode +Verwendung: yue + [Optionen] [] ... + yue -e [argumente...] + yue -w [] [optionen] + yue - + +Hinweise: + - '-' / '--' muss das erste und einzige Argument sein. + - '-o/--output' kann nicht mit mehreren Eingabedateien verwendet werden. + - '-w/--watch' kann nicht mit Dateieingabe verwendet werden (nur Verzeichnisse). + - Mit '-e/--execute' werden verbleibende Tokens als Skriptargumente behandelt. + +Optionen: + -h, --help Zeigt diese Hilfemeldung an und beendet das Programm. + -e , --execute Datei oder Quellcode ausführen + -m, --minify Minimierten Code erzeugen + -r, --rewrite Ausgabe so umschreiben, dass die Zeilennummern dem Original entsprechen + -t , --output-to + Ziel für kompilierte Dateien angeben + -o , --output + Schreibe die Ausgabe in eine Datei + -p, --print Schreibe die Ausgabe auf die Standardausgabe + -b, --benchmark Gibt die Kompilierungszeit aus (keine Ausgabe schreiben) + -g, --globals Gibt verwendete globale Variablen im Format NAME ZEILE SPALTE aus + -s, --spaces Verwende Leerzeichen anstelle von Tabs im generierten Code + -l, --line-numbers Schreibe Zeilennummern aus dem Quellcode + -j, --no-implicit-return Deaktiviert implizites Rückgabe am Datei-Ende + -c, --reserve-comments Kommentare aus dem Quellcode vor Anweisungen beibehalten + -w [], --watch [] + Änderungen beobachten und alle Dateien im Verzeichnis kompilieren + -v, --version Version ausgeben + - Lese von Standardinput, schreibe auf Standardausgabe + (muss das erste und einzige Argument sein) + -- Wie '-', bleibt zur Abwärtskompatibilität bestehen + + --target Gib an, welche Lua-Version erzeugt werden soll + (Version nur von 5.1 bis 5.5 möglich) + --path Füge einen zusätzlichen Lua-Suchpfad zu package.path hinzu + --= Übertrage Compileroption im Schlüssel=Wert-Format (bestehendes Verhalten) + + Ohne Optionen wird die REPL gestartet, gebe das Symbol '$' + in eine einzelne Zeile ein, um den Multi-Line-Modus zu starten/beenden ``` -Use cases: -Recursively compile every YueScript file with extension **.yue** under current path: **yue .** +Anwendungsfälle: -Compile and save results to a target path: **yue -t /target/path/ .** +Rekursiv jede YueScript-Datei mit der Endung **.yue** unter dem aktuellen Pfad kompilieren: **yue .** -Compile and reserve debug info: **yue -l .** +Kompilieren und Ergebnisse in einen Zielpfad schreiben: **yue -t /target/path/ .** -Compile and generate minified codes: **yue -m .** +Kompilieren und Debug-Infos beibehalten: **yue -l .** -Execute raw codes: **yue -e 'print 123'** +Kompilieren und minifizierten Code erzeugen: **yue -m .** -Execute a YueScript file: **yue -e main.yue** +Rohcode ausführen: **yue -e 'print 123'** + +Eine YueScript-Datei ausführen: **yue -e main.yue** diff --git a/doc/docs/de/doc/language-basics/attributes.md b/doc/docs/de/doc/language-basics/attributes.md index e6fd5a7..0fa3654 100644 --- a/doc/docs/de/doc/language-basics/attributes.md +++ b/doc/docs/de/doc/language-basics/attributes.md @@ -1,21 +1,21 @@ -# Attributes +# Attribute -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. +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. ```yuescript const a = 123 -close _ = : -> print "Out of scope." +close _ = : -> print "Außerhalb des Gültigkeitsbereichs." ``` ```yue const a = 123 -close _ = : -> print "Out of scope." +close _ = : -> print "Außerhalb des Gültigkeitsbereichs." ``` -You can do desctructuring with variables attributed as constant. +Du kannst Destructuring mit als konstant markierten Variablen verwenden. ```yuescript const {:a, :b, c, d} = tb @@ -30,7 +30,7 @@ const {:a, :b, c, d} = tb -You can also declare a global variable to be `const`. +Du kannst auch eine globale Variable als `const` deklarieren. ```yuescript global const Constant = 123 diff --git a/doc/docs/de/doc/language-basics/comment.md b/doc/docs/de/doc/language-basics/comment.md index b67c97d..dec9bb0 100644 --- a/doc/docs/de/doc/language-basics/comment.md +++ b/doc/docs/de/doc/language-basics/comment.md @@ -1,30 +1,30 @@ -# Comment +# Kommentare ```yuescript --- I am a comment +-- Ich bin ein Kommentar str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Dies ist ein mehrzeiliger Kommentar. +Alles okay. +]] strA \ -- Kommentar 1 + .. strB \ -- Kommentar 2 .. strC -func --[[port]] 3000, --[[ip]] "192.168.1.1" +func --[[Port]] 3000, --[[IP]] "192.168.1.1" ``` ```yue --- I am a comment +-- Ich bin ein Kommentar str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Dies ist ein mehrzeiliger Kommentar. +Alles okay. +]] strA \ -- Kommentar 1 + .. strB \ -- Kommentar 2 .. strC -func --[[port]] 3000, --[[ip]] "192.168.1.1" +func --[[Port]] 3000, --[[IP]] "192.168.1.1" ``` diff --git a/doc/docs/de/doc/language-basics/literals.md b/doc/docs/de/doc/language-basics/literals.md index e097c62..55a5aaa 100644 --- a/doc/docs/de/doc/language-basics/literals.md +++ b/doc/docs/de/doc/language-basics/literals.md @@ -1,33 +1,33 @@ -# Literals +# Literale -All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. +Alle primitiven Literale in Lua können verwendet werden. Das gilt für Zahlen, Strings, Booleans und **nil**. -Unlike Lua, Line breaks are allowed inside of single and double quote strings without an escape sequence: +Anders als in Lua sind Zeilenumbrüche innerhalb einfacher und doppelter Anführungszeichen ohne Escape-Sequenz erlaubt: ```yuescript -some_string = "Here is a string - that has a line break in it." +some_string = "Hier ist ein String + mit einem Zeilenumbruch." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. -print "I am #{math.random! * 100}% sure." +-- Mit der #{}-Syntax kannst du Ausdrücke in String-Literale einbinden. +-- String-Interpolation gibt es nur in doppelt angeführten Strings. +print "Ich bin mir zu #{math.random! * 100}% sicher." ``` ```yue -some_string = "Here is a string - that has a line break in it." +some_string = "Hier ist ein String + mit einem Zeilenumbruch." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. -print "I am #{math.random! * 100}% sure." +-- Mit der #{}-Syntax kannst du Ausdrücke in String-Literale einbinden. +-- String-Interpolation gibt es nur in doppelt angeführten Strings. +print "Ich bin mir zu #{math.random! * 100}% sicher." ``` -## Number Literals +## Zahlenliterale -You can use underscores in a number literal to increase readability. +Du kannst Unterstriche in Zahlenliteralen verwenden, um die Lesbarkeit zu erhöhen. ```yuescript integer = 1_000_000 @@ -44,9 +44,9 @@ binary = 0B10011 -## YAML Multiline String +## YAML-Mehrzeilen-String -The `|` prefix introduces a YAML-style multiline string literal: +Das Präfix `|` führt ein mehrzeiliges String-Literal im YAML-Stil ein: ```yuescript str = | @@ -67,9 +67,9 @@ str = | -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)`. +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. -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. +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. ```yuescript fn = -> @@ -90,9 +90,9 @@ fn = -> -Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. +Die interne Einrückung bleibt relativ zum entfernten gemeinsamen Präfix erhalten, wodurch saubere, verschachtelte Strukturen möglich sind. -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. +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. ```yuescript str = | diff --git a/doc/docs/de/doc/language-basics/operator.md b/doc/docs/de/doc/language-basics/operator.md index 9a2e89b..a7b8c5c 100644 --- a/doc/docs/de/doc/language-basics/operator.md +++ b/doc/docs/de/doc/language-basics/operator.md @@ -1,6 +1,6 @@ -# Operator +# Operatoren -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. +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. ```yuescript tb\func! if tb ~= nil @@ -15,32 +15,32 @@ tb::func! if tb != nil -## Chaining Comparisons +## Verkettete Vergleiche -Comparisons can be arbitrarily chained: +Vergleiche können beliebig verkettet werden: ```yuescript print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 --- output: true +-- Ausgabe: true a = 5 print 1 <= a <= 10 --- output: true +-- Ausgabe: true ``` ```yue print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 --- output: true +-- Ausgabe: true a = 5 print 1 <= a <= 10 --- output: true +-- Ausgabe: true ``` -Note the evaluation behavior of chained comparisons: +Beachte das Auswertungsverhalten verketteter Vergleiche: ```yuescript v = (x) -> @@ -49,7 +49,7 @@ v = (x) -> print v(1) < v(2) <= v(3) --[[ - output: + Ausgabe: 2 1 3 @@ -58,7 +58,7 @@ print v(1) < v(2) <= v(3) print v(1) > v(2) <= v(3) --[[ - output: + Ausgabe: 2 1 false @@ -73,7 +73,7 @@ v = (x) -> print v(1) < v(2) <= v(3) --[[ - output: + Ausgabe: 2 1 3 @@ -82,7 +82,7 @@ print v(1) < v(2) <= v(3) print v(1) > v(2) <= v(3) --[[ - output: + Ausgabe: 2 1 false @@ -91,32 +91,32 @@ print v(1) > v(2) <= v(3) -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. +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. -## Table Appending +## Tabellenerweiterung -The **[] =** operator is used to append values to tables. +Der Operator **[] =** wird verwendet, um Werte an Tabellen anzuhängen. ```yuescript tab = [] -tab[] = "Value" +tab[] = "Wert" ``` ```yue tab = [] -tab[] = "Value" +tab[] = "Wert" ``` -You can also use the spread operator `...` to append all elements from one list to another: +Du kannst auch den Spread-Operator `...` verwenden, um alle Elemente einer Liste an eine andere anzuhängen: ```yuescript tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA ist jetzt [1, 2, 3, 4, 5, 6] ``` @@ -124,24 +124,24 @@ tbA[] = ...tbB tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA ist jetzt [1, 2, 3, 4, 5, 6] ``` -## Table Spreading +## Tabellen-Spread -You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. +Du kannst Array-Tabellen oder Hash-Tabellen mit dem Spread-Operator `...` vor Ausdrücken in Tabellenliteralen zusammenführen. ```yuescript parts = - * "shoulders" - * "knees" + * "Schultern" + * "Knie" lyrics = - * "head" + * "Kopf" * ...parts - * "and" - * "toes" + * "und" + * "Zehen" copy = {...other} @@ -153,13 +153,13 @@ merge = {...a, ...b} ```yue parts = - * "shoulders" - * "knees" + * "Schultern" + * "Knie" lyrics = - * "head" + * "Kopf" * ...parts - * "and" - * "toes" + * "und" + * "Zehen" copy = {...other} @@ -170,9 +170,9 @@ merge = {...a, ...b} -## Table Reversed Indexing +## Umgekehrter Tabellenindex -You can use the **#** operator to get the last elements of a table. +Mit dem Operator **#** kannst du auf die letzten Elemente einer Tabelle zugreifen. ```yuescript last = data.items[#] @@ -191,11 +191,11 @@ data.items[#] = 1 ## Metatable -The **<>** operator can be used as a shortcut for metatable manipulation. +Der Operator **<>** kann als Abkürzung für Metatable-Manipulation verwendet werden. -### Metatable Creation +### Metatable erstellen -Create normal table with empty bracekets **<>** or metamethod key which is surrounded by **<>**. +Erzeuge eine normale Tabelle mit leeren Klammern **<>** oder einem Metamethod-Schlüssel, der von **<>** umschlossen ist. ```yuescript mt = {} @@ -203,14 +203,14 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- Feld mit gleichnamiger Variable setzen b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value -close _ = : -> print "out of scope" +close _ = : -> print "Außerhalb des Gültigkeitsbereichs" ``` @@ -220,47 +220,47 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- Feld mit gleichnamiger Variable setzen b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value -close _ = : -> print "out of scope" +close _ = : -> print "Außerhalb des Gültigkeitsbereichs" ``` -### Metatable Accessing +### Metatable-Zugriff -Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. +Metatable mit **<>** oder einem von **<>** umschlossenen Metamethod-Namen aufrufen oder einen Ausdruck in **<>** schreiben. ```yuescript --- create with metatable containing field "value" +-- erstellen mit Metatable, das das Feld "value" enthält tb = <"value">: 123 tb. = tb.<> print tb.value -tb.<> = __index: {item: "hello"} +tb.<> = __index: {item: "hallo"} print tb.item ``` ```yue --- create with metatable containing field "value" +-- erstellen mit Metatable, das das Feld "value" enthält tb = <"value">: 123 tb. = tb.<> print tb.value -tb.<> = __index: {item: "hello"} +tb.<> = __index: {item: "hallo"} print tb.item ``` -### Metatable Destructure +### Metatable-Destrukturierung -Destruct metatable with metamethod key surrounded by **<>**. +Destrukturiere Metatable mit Metamethoden-Schlüssel, der von **<>** umschlossen ist. ```yuescript {item, :new, :, : getter} = tb @@ -275,9 +275,9 @@ print item, new, close, getter -## Existence +## Existenz -The **?** operator can be used in a variety of contexts to check for existence. +Der Operator **?** kann in verschiedenen Kontexten verwendet werden, um die Existenz zu prüfen. ```yuescript func?! @@ -314,14 +314,14 @@ with? io.open "test.txt", "w" ## Piping -Instead of a series of nested function calls, you can pipe values with operator **|>**. +Anstelle einer Reihe verschachtelter Funktionsaufrufe kannst du Werte mit dem Operator **|>** weiterleiten. ```yuescript "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder +1 |> print 2 -- Pipe-Element als erstes Argument einfügen +2 |> print 1, _, 3 -- Pipe mit Platzhalter --- pipe expression in multiline +-- Pipe-Ausdruck über mehrere Zeilen readFile "example.txt" |> extract language, {} |> parse language @@ -333,9 +333,9 @@ readFile "example.txt" ```yue "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder --- pipe expression in multiline +1 |> print 2 -- Pipe-Element als erstes Argument einfügen +2 |> print 1, _, 3 -- Pipe mit Platzhalter +-- Pipe-Ausdruck über mehrere Zeilen readFile "example.txt" |> extract language, {} |> parse language @@ -346,9 +346,10 @@ readFile "example.txt" -## Nil Coalescing +## Nil-Coalescing + +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. -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. ```yuescript local a, b, c, d a = b ?? c ?? d @@ -367,31 +368,31 @@ a ??= false -## Implicit Object +## Implizites Objekt -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. +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. ```yuescript --- assignment with implicit object +-- Zuweisung mit implizitem Objekt list = * 1 * 2 * 3 --- function call with implicit object +-- Funktionsaufruf mit implizitem Objekt func * 1 * 2 * 3 --- return with implicit object +-- Rückgabe mit implizitem Objekt f = -> return * 1 * 2 * 3 --- table with implicit object +-- Tabelle mit implizitem Objekt tb = name: "abc" @@ -416,26 +417,26 @@ tb = ```yue --- assignment with implicit object +-- Zuweisung mit implizitem Objekt list = * 1 * 2 * 3 --- function call with implicit object +-- Funktionsaufruf mit implizitem Objekt func * 1 * 2 * 3 --- return with implicit object +-- Rückgabe mit implizitem Objekt f = -> return * 1 * 2 * 3 --- table with implicit object +-- Tabelle mit implizitem Objekt tb = name: "abc" diff --git a/doc/docs/de/doc/language-basics/whitespace.md b/doc/docs/de/doc/language-basics/whitespace.md index d742a2b..9d5889d 100644 --- a/doc/docs/de/doc/language-basics/whitespace.md +++ b/doc/docs/de/doc/language-basics/whitespace.md @@ -1,10 +1,10 @@ -# Whitespace +# Leerraum -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. +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. -## Statement Separator +## Anweisungs-Trenner -A statement normally ends at a line break. You can also use a semicolon `;` to explicitly terminate a statement, which allows writing multiple statements on the same line: +Eine Anweisung endet normalerweise an einem Zeilenumbruch. Du kannst auch ein Semikolon `;` verwenden, um eine Anweisung explizit zu beenden, wodurch mehrere Anweisungen in einer Zeile möglich sind: ```yuescript a = 1; b = 2; print a + b @@ -17,9 +17,9 @@ a = 1; b = 2; print a + b -## Multiline Chaining +## Mehrzeiliges Chaining -You can write multi-line chaining function calls with a same indent. +Du kannst mehrzeilige, verkettete Funktionsaufrufe mit derselben Einrückung schreiben. ```yuescript Rx.Observable diff --git a/doc/docs/de/doc/objects/object-oriented-programming.md b/doc/docs/de/doc/objects/object-oriented-programming.md index 6a8559e..1c116a3 100644 --- a/doc/docs/de/doc/objects/object-oriented-programming.md +++ b/doc/docs/de/doc/objects/object-oriented-programming.md @@ -1,8 +1,8 @@ -# Object Oriented Programming +# Objektorientierte Programmierung -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. +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. -A simple class: +Eine einfache Klasse: ```yuescript class Inventory @@ -31,36 +31,36 @@ class Inventory -A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. +Eine Klasse wird mit einem `class`-Statement deklariert, gefolgt von einer tabellenähnlichen Deklaration mit allen Methoden und Eigenschaften. -The new property is special in that it will become the constructor. +Die Eigenschaft `new` ist besonders, da sie zum Konstruktor wird. -Notice how all the methods in the class use the fat arrow function syntax. When calling methods on a instance, the instance itself is sent in as the first argument. The fat arrow handles the creation of a self argument. +Beachte, dass alle Methoden in der Klasse die Fat-Arrow-Syntax verwenden. Beim Aufruf von Methoden auf einer Instanz wird die Instanz selbst als erstes Argument übergeben. Der Fat-Arrow übernimmt die Erstellung des `self`-Arguments. -The @ prefix on a variable name is shorthand for self.. @items becomes self.items. +Das `@`-Präfix ist Kurzform für `self.`. `@items` wird zu `self.items`. -Creating an instance of the class is done by calling the name of the class as a function. +Eine Instanz der Klasse wird erstellt, indem man den Klassennamen wie eine Funktion aufruft. ```yuescript inv = Inventory! -inv\add_item "t-shirt" -inv\add_item "pants" +inv\add_item "T-Shirt" +inv\add_item "Hose" ``` ```yue inv = Inventory! -inv\add_item "t-shirt" -inv\add_item "pants" +inv\add_item "T-Shirt" +inv\add_item "Hose" ``` -Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. +Da die Instanz bei Methodenaufrufen an die Methoden übergeben werden muss, wird der `\`-Operator verwendet. -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. +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. -Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another: +Im folgenden Beispiel wird die Eigenschaft `clothes` von allen Instanzen geteilt, sodass Änderungen in einer Instanz in einer anderen sichtbar werden: ```yuescript class Person @@ -71,10 +71,10 @@ class Person a = Person! b = Person! -a\give_item "pants" -b\give_item "shirt" +a\give_item "Hose" +b\give_item "Hemd" --- will print both pants and shirt +-- gibt sowohl Hose als auch Hemd aus print item for item in *a.clothes ``` @@ -88,16 +88,16 @@ class Person a = Person! b = Person! -a\give_item "pants" -b\give_item "shirt" +a\give_item "Hose" +b\give_item "Hemd" --- will print both pants and shirt +-- gibt sowohl Hose als auch Hemd aus print item for item in *a.clothes ``` -The proper way to avoid this problem is to create the mutable state of the object in the constructor: +Der richtige Weg, das zu vermeiden, ist, den veränderlichen Zustand im Konstruktor zu erstellen: ```yuescript class Person @@ -114,15 +114,15 @@ class Person -## Inheritance +## Vererbung -The extends keyword can be used in a class declaration to inherit the properties and methods from another class. +Das Schlüsselwort `extends` kann in einer Klassendeklaration verwendet werden, um Eigenschaften und Methoden von einer anderen Klasse zu erben. ```yuescript class BackPack extends Inventory size: 10 add_item: (name) => - if #@items > size then error "backpack is full" + if #@items > size then error "Rucksack ist voll" super name ``` @@ -131,24 +131,24 @@ class BackPack extends Inventory class BackPack extends Inventory size: 10 add_item: (name) => - if #@items > size then error "backpack is full" + if #@items > size then error "Rucksack ist voll" super name ``` -Here we extend our Inventory class, and limit the amount of items it can carry. +Hier erweitern wir unsere `Inventory`-Klasse und begrenzen die Anzahl der Elemente. -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. +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. -Whenever a class inherits from another, it sends a message to the parent class by calling the method __inherited on the parent class if it exists. The function receives two arguments, the class that is being inherited and the child class. +Wenn eine Klasse von einer anderen erbt, sendet sie eine Nachricht an die Elternklasse, indem die Methode `__inherited` der Elternklasse aufgerufen wird, falls vorhanden. Die Funktion erhält zwei Argumente: die Klasse, die vererbt wird, und die Kindklasse. ```yuescript class Shelf @__inherited: (child) => - print @__name, "was inherited by", child.__name + print @__name, "wurde vererbt von", child.__name --- will print: Shelf was inherited by Cupboard +-- gibt aus: Shelf wurde von Cupboard geerbt class Cupboard extends Shelf ``` @@ -156,9 +156,9 @@ class Cupboard extends Shelf ```yue class Shelf @__inherited: (child) => - print @__name, "was inherited by", child.__name + print @__name, "wurde vererbt von", child.__name --- will print: Shelf was inherited by Cupboard +-- gibt aus: Shelf wurde von Cupboard geerbt class Cupboard extends Shelf ``` @@ -166,27 +166,27 @@ class Cupboard extends Shelf ## Super -**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. +**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. -When called as a function, it will call the function of the same name in the parent class. The current self will automatically be passed as the first argument. (As seen in the inheritance example above) +Wenn es als Funktion aufgerufen wird, ruft es die gleichnamige Funktion in der Elternklasse auf. `self` wird automatisch als erstes Argument übergeben (wie im Vererbungsbeispiel oben). -When super is used as a normal value, it is a reference to the parent class object. +Wenn `super` als normaler Wert verwendet wird, ist es eine Referenz auf das Objekt der Elternklasse. -It can be accessed like any of object in order to retrieve values in the parent class that might have been shadowed by the child class. +Du kannst es wie jedes andere Objekt verwenden, um Werte der Elternklasse zu lesen, die von der Kindklasse überschattet wurden. -When the \ calling operator is used with super, self is inserted as the first argument instead of the value of super itself. When using . to retrieve a function, the raw function is returned. +Wenn der `\`-Aufrufoperator mit `super` verwendet wird, wird `self` als erstes Argument eingefügt statt des Wertes von `super`. Wenn man `.` zum Abrufen einer Funktion verwendet, wird die rohe Funktion zurückgegeben. -A few examples of using super in different ways: +Ein paar Beispiele für `super` in unterschiedlichen Formen: ```yuescript class MyClass extends ParentClass a_method: => - -- the following have the same effect: - super "hello", "world" - super\a_method "hello", "world" - super.a_method self, "hello", "world" + -- Folgendes hat dieselbe Wirkung: + super "hallo", "Welt" + super\a_method "hallo", "Welt" + super.a_method self, "hallo", "Welt" - -- super as a value is equal to the parent class: + -- super als Wert entspricht der Elternklasse: assert super == ParentClass ``` @@ -194,28 +194,28 @@ class MyClass extends ParentClass ```yue class MyClass extends ParentClass a_method: => - -- the following have the same effect: - super "hello", "world" - super\a_method "hello", "world" - super.a_method self, "hello", "world" + -- Folgendes hat dieselbe Wirkung: + super "hallo", "Welt" + super\a_method "hallo", "Welt" + super.a_method self, "hallo", "Welt" - -- super as a value is equal to the parent class: + -- super als Wert entspricht der Elternklasse: assert super == ParentClass ``` -**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. +**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. -## Types +## Typen -Every instance of a class carries its type with it. This is stored in the special __class property. This property holds the class object. The class object is what we call to build a new instance. We can also index the class object to retrieve class methods and properties. +Jede Instanz einer Klasse trägt ihren Typ in sich. Dieser wird in der speziellen Eigenschaft `__class` gespeichert. Diese Eigenschaft enthält das Klassenobjekt. Das Klassenobjekt wird aufgerufen, um eine neue Instanz zu erstellen. Wir können das Klassenobjekt auch indizieren, um Klassenmethoden und Eigenschaften abzurufen. ```yuescript b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- gibt 10 aus ``` @@ -223,70 +223,70 @@ print BackPack.size -- prints 10 b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- gibt 10 aus ``` -## Class Objects +## Klassenobjekte -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. +Das Klassenobjekt entsteht, wenn wir ein `class`-Statement verwenden. Es wird in einer Variablen mit dem Klassennamen gespeichert. -The class object can be called like a function in order to create new instances. That's how we created instances of classes in the examples above. +Das Klassenobjekt kann wie eine Funktion aufgerufen werden, um neue Instanzen zu erstellen. So haben wir die Instanzen in den Beispielen oben erstellt. -A class is made up of two tables. The class table itself, and the base table. The base is used as the metatable for all the instances. All properties listed in the class declaration are placed in the base. +Eine Klasse besteht aus zwei Tabellen: der Klassentabelle selbst und der Basistabelle. Die Basis wird als Metatable für alle Instanzen verwendet. Alle in der Klassendeklaration aufgeführten Eigenschaften werden in der Basis platziert. -The class object's metatable reads properties from the base if they don't exist in the class object. This means we can access functions and properties directly from the class. +Das Metatable des Klassenobjekts liest Eigenschaften aus der Basis, wenn sie im Klassenobjekt nicht existieren. Das bedeutet, dass wir Funktionen und Eigenschaften direkt von der Klasse aus aufrufen können. -It is important to note that assigning to the class object does not assign into the base, so it's not a valid way to add new methods to instances. Instead the base must explicitly be changed. See the __base field below. +Wichtig: Zuweisungen an das Klassenobjekt schreiben nicht in die Basis. Das ist keine gültige Methode, um neue Methoden zu Instanzen hinzuzufügen. Stattdessen muss die Basis explizit geändert werden. Siehe das Feld `__base` unten. -The class object has a couple special properties: +Das Klassenobjekt hat einige spezielle Eigenschaften: -The name of the class as when it was declared is stored as a string in the __name field of the class object. +Der Name der Klasse, wie sie deklariert wurde, wird im Feld `__name` gespeichert. ```yuescript -print BackPack.__name -- prints Backpack +print BackPack.__name -- gibt Backpack aus ``` ```yue -print BackPack.__name -- prints Backpack +print BackPack.__name -- gibt Backpack aus ``` -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. +Die Basistabelle ist in `__base` gespeichert. Du kannst diese Tabelle ändern, um Instanzen Funktionalität hinzuzufügen, die bereits existieren oder noch erstellt werden. -If the class extends from anything, the parent class object is stored in __parent. +Wenn die Klasse von etwas erbt, ist das Elternklassenobjekt in `__parent` gespeichert. -## Class Variables +## Klassenvariablen -We can create variables directly in the class object instead of in the base by using @ in the front of the property name in a class declaration. +Du kannst Variablen direkt im Klassenobjekt statt in der Basis erstellen, indem du in der Klassendeklaration `@` vor den Eigenschaftsnamen setzt. ```yuescript class Things - @some_func: => print "Hello from", @__name + @some_func: => print "Hallo von", @__name Things\some_func! --- class variables not visible in instances +-- Klassenvariablen in Instanzen nicht sichtbar assert Things().some_func == nil ``` ```yue class Things - @some_func: => print "Hello from", @__name + @some_func: => print "Hallo von", @__name Things\some_func! --- class variables not visible in instances +-- Klassenvariablen in Instanzen nicht sichtbar assert Things().some_func == nil ``` -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. +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`. ```yuescript class Counter @@ -298,7 +298,7 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- gibt 2 aus ``` @@ -312,12 +312,12 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- gibt 2 aus ``` -The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. +Die Aufrufsemantik von `@@` ist ähnlich wie bei `@`. Wenn du einen `@@`-Namen aufrufst, wird die Klasse als erstes Argument übergeben (Lua-`:`-Syntax). ```yuescript @@hello 1,2,3,4 @@ -330,28 +330,28 @@ The calling semantics of @@ are similar to @. Calling a @@ name will pass the cl -## Class Declaration Statements +## Klassendeklarations-Statements -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. +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. -Here is an alternative way to create a class variable compared to what's described above: +Hier ist eine alternative Möglichkeit, eine Klassenvariable zu erstellen: ```yuescript class Things - @class_var = "hello world" + @class_var = "Hallo Welt" ``` ```yue class Things - @class_var = "hello world" + @class_var = "Hallo Welt" ``` -These expressions are executed after all the properties have been added to the base. +Diese Ausdrücke werden ausgeführt, nachdem alle Eigenschaften zur Basis hinzugefügt wurden. -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: +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: ```yuescript class MoreThings @@ -359,7 +359,7 @@ class MoreThings log = (msg) -> print "LOG:", msg some_method: => - log "hello world: " .. secret + log "Hallo Welt: " .. secret ``` @@ -369,16 +369,16 @@ class MoreThings log = (msg) -> print "LOG:", msg some_method: => - log "hello world: " .. secret + log "Hallo Welt: " .. secret ``` -## @ and @@ Values +## @- und @@-Werte -When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.__class. +Wenn `@` und `@@` vor einem Namen stehen, repräsentieren sie den Namen in `self` bzw. `self.__class`. -If they are used all by themselves, they are aliases for self and self.__class. +Wenn sie alleine verwendet werden, sind sie Aliase für `self` und `self.__class`. ```yuescript assert @ == self @@ -393,7 +393,7 @@ assert @@ == self.__class -For example, a quick way to create a new instance of the same class from an instance method using @@: +Zum Beispiel kannst du mit `@@` in einer Instanzmethode schnell eine neue Instanz derselben Klasse erzeugen: ```yuescript some_instance_method = (...) => @@ ... @@ -406,15 +406,15 @@ some_instance_method = (...) => @@ ... -## Constructor Property Promotion +## Konstruktor-Property-Promotion -To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: +Um Boilerplate beim Definieren einfacher Value-Objekte zu reduzieren, kannst du eine Klasse so schreiben: ```yuescript class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- Kurzform für class Something new: (foo, bar, biz, baz) => @@ -429,7 +429,7 @@ class Something class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- Kurzform für class Something new: (foo, bar, biz, baz) => @@ -441,7 +441,7 @@ class Something -You can also use this syntax for a common function to initialize a object's fields. +Du kannst diese Syntax auch für eine gemeinsame Funktion verwenden, um Objektfelder zu initialisieren. ```yuescript new = (@fieldA, @fieldB) => @ @@ -458,9 +458,9 @@ print obj -## Class Expressions +## Klassenausdrücke -The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. +Die `class`-Syntax kann auch als Ausdruck verwendet werden, der einer Variable zugewiesen oder explizit zurückgegeben wird. ```yuescript x = class Bucket @@ -477,9 +477,9 @@ x = class Bucket -## Anonymous classes +## Anonyme Klassen -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. +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. ```yuescript BigBucket = class extends Bucket @@ -498,7 +498,7 @@ assert Bucket.__name == "BigBucket" -You can even leave off the body, meaning you can write a blank anonymous class like this: +Du kannst sogar den Körper weglassen und eine leere anonyme Klasse schreiben: ```yuescript x = class @@ -513,7 +513,7 @@ x = class ## Class Mixing -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. +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. ```yuescript MyIndex = __index: var: 1 @@ -530,7 +530,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X ist nicht die Elternklasse von Y ``` @@ -549,7 +549,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X ist nicht die Elternklasse von Y ``` diff --git a/doc/docs/de/doc/objects/with-statement.md b/doc/docs/de/doc/objects/with-statement.md index 7786803..446f837 100644 --- a/doc/docs/de/doc/objects/with-statement.md +++ b/doc/docs/de/doc/objects/with-statement.md @@ -1,13 +1,12 @@ -# With Statement +# With-Statement +Ein häufiges Muster bei der Erstellung eines Objekts ist, unmittelbar danach eine Reihe von Funktionen aufzurufen und Eigenschaften zu setzen. -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. +Das führt dazu, dass der Objektname mehrfach wiederholt wird und unnötiges Rauschen entsteht. Eine gängige Lösung ist, eine Tabelle als Argument zu übergeben, die eine Sammlung von Schlüsseln und Werten enthält, die überschrieben werden sollen. Der Nachteil ist, dass der Konstruktor dieses Objekts diese Form unterstützen muss. -This results in repeating the name of the object multiple times in code, adding unnecessary noise. A common solution to this is to pass a table in as an argument which contains a collection of keys and values to overwrite. The downside to this is that the constructor of this object must support this form. +Der `with`-Block hilft, das zu vermeiden. Innerhalb eines `with`-Blocks können wir spezielle Anweisungen verwenden, die mit `.` oder `\` beginnen und die Operationen auf das Objekt anwenden, mit dem wir gerade arbeiten. -The with block helps to alleviate this. Within a with block we can use a special statements that begin with either . or \ which represent those operations applied to the object we are using with on. - -For example, we work with a newly created object: +Zum Beispiel arbeiten wir mit einem neu erstellten Objekt: ```yuescript with Person! @@ -28,22 +27,22 @@ with Person! -The with statement can also be used as an expression which returns the value it has been giving access to. +Das `with`-Statement kann auch als Ausdruck verwendet werden und gibt den Wert zurück, auf den es Zugriff gewährt. ```yuescript -file = with File "favorite_foods.txt" +file = with File "Lieblingsessen.txt" \set_encoding "utf8" ``` ```yue -file = with File "favorite_foods.txt" +file = with File "Lieblingsessen.txt" \set_encoding "utf8" ``` -Or… +Oder … ```yuescript create_person = (name, relatives) -> @@ -66,26 +65,26 @@ me = create_person "Leaf", [dad, mother, sister] -In this usage, with can be seen as a special form of the K combinator. +In dieser Verwendung kann `with` als spezielle Form des K-Kombinators gesehen werden. -The expression in the with statement can also be an assignment, if you want to give a name to the expression. +Der Ausdruck im `with`-Statement kann auch eine Zuweisung sein, wenn du dem Ausdruck einen Namen geben willst. ```yuescript -with str := "Hello" - print "original:", str - print "upper:", \upper! +with str := "Hallo" + print "Original:", str + print "Großbuchstaben:", \upper! ``` ```yue -with str := "Hello" - print "original:", str - print "upper:", \upper! +with str := "Hallo" + print "Original:", str + print "Großbuchstaben:", \upper! ``` -You can access special keys with `[]` in a `with` statement. +Du kannst in einem `with`-Statement über `[]` auf spezielle Schlüssel zugreifen. ```yuescript with tb @@ -94,7 +93,7 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- an "tb" anhängen ``` @@ -105,12 +104,12 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- an "tb" anhängen ``` -`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. +`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. ```yuescript with? obj diff --git a/doc/docs/de/doc/reference/license-mit.md b/doc/docs/de/doc/reference/license-mit.md index f1d5d60..a5e9f70 100644 --- a/doc/docs/de/doc/reference/license-mit.md +++ b/doc/docs/de/doc/reference/license-mit.md @@ -1,23 +1,11 @@ -# License: MIT +# Lizenz: MIT -Copyright (c) 2017-2026 Li Jin \ +Hinweis: Die MIT-Lizenz ist unten im englischen Originaltext wiedergegeben. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Urheberrecht (c) 2017-2026 Li Jin -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Hiermit wird unentgeltlich jeder Person, die eine Kopie dieser Software und der zugehörigen Dokumentationsdateien (die "Software") erhält, die Erlaubnis erteilt, uneingeschränkt mit der Software zu verfahren, einschließlich und ohne Beschränkung der Rechte, die Software zu benutzen, zu kopieren, zu verändern, zusammenzuführen, zu veröffentlichen, zu verbreiten, zu unterlizenzieren und/oder zu verkaufen, sowie Personen, denen die Software zur Verfügung gestellt wird, dies ebenfalls zu gestatten, unter den folgenden Bedingungen: -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +Der obige Urheberrechtshinweis und dieser Genehmigungshinweis müssen in allen Kopien oder wesentlichen Teilen der Software enthalten sein. - +DIE SOFTWARE WIRD OHNE JEGLICHE AUSDRÜCKLICHE ODER STILLSCHWEIGENDE GARANTIE ZUR VERFÜGUNG GESTELLT, EINSCHLIESSLICH DER GARANTIEN DER MARKTGÄNGIGKEIT, DER EIGNUNG FÜR EINEN BESTIMMTEN ZWECK UND DER NICHTVERLETZUNG. IN KEINEM FALL SIND DIE AUTOREN ODER URHEBERRECHTSINHABER FÜR ANSPRÜCHE, SCHÄDEN ODER SONSTIGE HAFTUNGEN VERANTWORTLICH, SEI ES AUS EINEM VERTRAG, EINER UNERLAUBTEN HANDLUNG ODER ANDERWEITIG, DIE SICH AUS DER SOFTWARE ODER DER BENUTZUNG DER SOFTWARE ODER ANDEREN GESCHÄFTEN MIT DER SOFTWARE ERGEBEN ODER DAMIT IN ZUSAMMENHANG STEHEN. diff --git a/doc/docs/de/doc/reference/the-yuescript-library.md b/doc/docs/de/doc/reference/the-yuescript-library.md index 3761755..1838ced 100644 --- a/doc/docs/de/doc/reference/the-yuescript-library.md +++ b/doc/docs/de/doc/reference/the-yuescript-library.md @@ -1,61 +1,61 @@ -# The YueScript Library +# Die YueScript-Bibliothek -Access it by `local yue = require("yue")` in Lua. +Zugriff in Lua über `local yue = require("yue")`. ## yue -**Description:** +**Beschreibung:** -The YueScript language library. +Die YueScript-Sprachbibliothek. ### version -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The YueScript version. +Die YueScript-Version. -**Signature:** +**Signatur:** ```lua version: string ``` ### dirsep -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The file separator for the current platform. +Der Dateitrennzeichen-String der aktuellen Plattform. -**Signature:** +**Signatur:** ```lua dirsep: string ``` ### yue_compiled -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The compiled module code cache. +Der Cache für kompilierten Modulcode. -**Signature:** +**Signatur:** ```lua yue_compiled: {string: string} ``` ### to_lua -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -The YueScript compiling function. It compiles the YueScript code to Lua code. +Die YueScript-Compilerfunktion. Sie kompiliert YueScript-Code zu Lua-Code. -**Signature:** +**Signatur:** ```lua to_lua: function(code: string, config?: Config): --[[codes]] string | nil, @@ -63,682 +63,682 @@ to_lua: function(code: string, config?: Config): --[[globals]] {{string, integer, integer}} | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| code | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| code | string | Der YueScript-Code. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| string \| nil | The compiled Lua code, or nil if the compilation failed. | -| string \| nil | The error message, or nil if the compilation succeeded. | -| {{string, integer, integer}} \| nil | The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. | +| string \| nil | Der kompilierte Lua-Code oder `nil`, falls die Kompilierung fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls die Kompilierung erfolgreich war. | +| {{string, integer, integer}} \| nil | Die globalen Variablen im Code (mit Name, Zeile und Spalte) oder `nil`, wenn die Compiler-Option `lint_global` false ist. | ### file_exist -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -The source file existence checking function. Can be overridden to customize the behavior. +Prüft, ob eine Quelldatei existiert. Kann überschrieben werden, um das Verhalten anzupassen. -**Signature:** +**Signatur:** ```lua file_exist: function(filename: string): boolean ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | Der Dateiname. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| boolean | Whether the file exists. | +| boolean | Ob die Datei existiert. | ### read_file -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -The source file reading function. Can be overridden to customize the behavior. +Liest eine Quelldatei. Kann überschrieben werden, um das Verhalten anzupassen. -**Signature:** +**Signatur:** ```lua read_file: function(filename: string): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | Der Dateiname. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| string | The file content. | +| string | Der Dateiinhalt. | ### insert_loader -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Insert the YueScript loader to the package loaders (searchers). +Fügt den YueScript-Loader in die Package-Loader (Searcher) ein. -**Signature:** +**Signatur:** ```lua insert_loader: function(pos?: integer): boolean ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| pos | integer | [Optional] The position to insert the loader. Default is 3. | +| pos | integer | [Optional] Position, an der der Loader eingefügt wird. Standard ist 3. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| boolean | Whether the loader is inserted successfully. It will fail if the loader is already inserted. | +| boolean | Ob der Loader erfolgreich eingefügt wurde. Scheitert, wenn er bereits eingefügt ist. | ### remove_loader -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Remove the YueScript loader from the package loaders (searchers). +Entfernt den YueScript-Loader aus den Package-Loadern (Searchern). -**Signature:** +**Signatur:** ```lua remove_loader: function(): boolean ``` -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| boolean | Whether the loader is removed successfully. It will fail if the loader is not inserted. | +| boolean | Ob der Loader erfolgreich entfernt wurde. Scheitert, wenn er nicht eingefügt ist. | ### loadstring -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a string into a function. +Lädt YueScript-Code aus einem String in eine Funktion. -**Signature:** +**Signatur:** ```lua loadstring: function(input: string, chunkname: string, env: table, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| input | string | Der YueScript-Code. | +| chunkname | string | Der Name des Code-Chunks. | +| env | table | Die Environment-Tabelle. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Die geladene Funktion oder `nil`, falls das Laden fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls das Laden erfolgreich war. | ### loadstring -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a string into a function. +Lädt YueScript-Code aus einem String in eine Funktion. -**Signature:** +**Signatur:** ```lua loadstring: function(input: string, chunkname: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| config | Config | [Optional] The compiler options. | +| input | string | Der YueScript-Code. | +| chunkname | string | Der Name des Code-Chunks. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Die geladene Funktion oder `nil`, falls das Laden fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls das Laden erfolgreich war. | ### loadstring -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a string into a function. +Lädt YueScript-Code aus einem String in eine Funktion. -**Signature:** +**Signatur:** ```lua loadstring: function(input: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| input | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| input | string | Der YueScript-Code. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Die geladene Funktion oder `nil`, falls das Laden fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls das Laden erfolgreich war. | ### loadfile -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a file into a function. +Lädt YueScript-Code aus einer Datei in eine Funktion. -**Signature:** +**Signatur:** ```lua loadfile: function(filename: string, env: table, config?: Config): nil | function(...: any): (any...), string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | Der Dateiname. | +| env | table | Die Environment-Tabelle. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Die geladene Funktion oder `nil`, falls das Laden fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls das Laden erfolgreich war. | ### loadfile -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a file into a function. +Lädt YueScript-Code aus einer Datei in eine Funktion. -**Signature:** +**Signatur:** ```lua loadfile: function(filename: string, config?: Config): nil | function(...: any): (any...), string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | Der Dateiname. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Die geladene Funktion oder `nil`, falls das Laden fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls das Laden erfolgreich war. | ### dofile -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a file into a function and executes it. +Lädt YueScript-Code aus einer Datei in eine Funktion und führt sie aus. -**Signature:** +**Signatur:** ```lua dofile: function(filename: string, env: table, config?: Config): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | Der Dateiname. | +| env | table | Die Environment-Tabelle. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Die Rückgabewerte der geladenen Funktion. | ### dofile -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads YueScript code from a file into a function and executes it. +Lädt YueScript-Code aus einer Datei in eine Funktion und führt sie aus. -**Signature:** +**Signatur:** ```lua dofile: function(filename: string, config?: Config): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | Der Dateiname. | +| config | Config | [Optional] Die Compiler-Optionen. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Die Rückgabewerte der geladenen Funktion. | ### find_modulepath -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Resolves the YueScript module name to the file path. +Löst den YueScript-Modulnamen in einen Dateipfad auf. -**Signature:** +**Signatur:** ```lua find_modulepath: function(name: string): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| name | string | The module name. | +| name | string | Der Modulname. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| string | The file path. | +| string | Der Dateipfad. | ### pcall -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Calls a function in protected mode. -Catches any errors and returns a status code and results or error object. -Rewrites the error line number to the original line number in the YueScript code when errors occur. +Ruft eine Funktion im geschützten Modus auf. +Fängt Fehler ab und gibt einen Statuscode sowie Ergebnisse oder ein Fehlerobjekt zurück. +Schreibt die Fehlerzeilennummer bei Fehlern auf die ursprüngliche Zeilennummer im YueScript-Code um. -**Signature:** +**Signatur:** ```lua pcall: function(f: function, ...: any): boolean, any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| f | function | The function to call. | -| ... | any | Arguments to pass to the function. | +| f | function | Die aufzurufende Funktion. | +| ... | any | Argumente für die Funktion. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| boolean, ... | Status code and function results or error object. | +| boolean, ... | Statuscode und Funktionsresultate oder Fehlerobjekt. | ### require -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Loads a given module. Can be either a Lua module or a YueScript module. -Rewrites the error line number to the original line number in the YueScript code if the module is a YueScript module and loading fails. +Lädt ein Modul (Lua oder YueScript). +Schreibt die Fehlerzeilennummer auf die ursprüngliche Zeilennummer im YueScript-Code um, wenn das Modul ein YueScript-Modul ist und das Laden fehlschlägt. -**Signature:** +**Signatur:** ```lua require: function(name: string): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| modname | string | The name of the module to load. | +| modname | string | Der Name des zu ladenden Moduls. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| any | The value stored at package.loaded[modname] if the module is already loaded.Otherwise, tries to find a loader and returns the final value of package.loaded[modname] and a loader data as a second result. | +| any | Der Wert in `package.loaded[modname]`, falls das Modul bereits geladen ist. Andernfalls wird ein Loader gesucht und der finale Wert von `package.loaded[modname]` sowie Loader-Daten als zweites Ergebnis zurückgegeben. | ### p -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Inspects the structures of the passed values and prints string representations. +Inspiziert die Struktur der übergebenen Werte und gibt String-Repräsentationen aus. -**Signature:** +**Signatur:** ```lua p: function(...: any) ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| ... | any | The values to inspect. | +| ... | any | Die zu inspizierenden Werte. | ### options -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The current compiler options. +Die aktuellen Compiler-Optionen. -**Signature:** +**Signatur:** ```lua options: Config.Options ``` ### traceback -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -The traceback function that rewrites the stack trace line numbers to the original line numbers in the YueScript code. +Die Traceback-Funktion, die Stacktrace-Zeilennummern auf die ursprünglichen Zeilennummern im YueScript-Code umschreibt. -**Signature:** +**Signatur:** ```lua traceback: function(message: string): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| message | string | The traceback message. | +| message | string | Die Traceback-Nachricht. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| string | The rewritten traceback message. | +| string | Die umgeschriebene Traceback-Nachricht. | ### is_ast -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Checks whether the code matches the specified AST. +Prüft, ob der Code dem angegebenen AST entspricht. -**Signature:** +**Signatur:** ```lua is_ast: function(astName: string, code: string): boolean ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| astName | string | The AST name. | -| code | string | The code. | +| astName | string | Der AST-Name. | +| code | string | Der Code. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| boolean | Whether the code matches the AST. | +| boolean | Ob der Code dem AST entspricht. | ### AST -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The AST type definition with name, row, column and sub nodes. +Die AST-Typdefinition mit Name, Zeile, Spalte und Unterknoten. -**Signature:** +**Signatur:** ```lua type AST = {string, integer, integer, any} ``` ### to_ast -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Converts the code to the AST. +Konvertiert Code in AST. -**Signature:** +**Signatur:** ```lua to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveComment?: boolean): --[[AST]] AST | nil, --[[error]] nil | string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| code | string | The code. | -| flattenLevel | integer | [Optional] The flatten level. Higher level means more flattening. Default is 0. Maximum is 2. | -| astName | string | [Optional] The AST name. Default is "File". | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is false. | +| code | string | Der Code. | +| flattenLevel | integer | [Optional] Der Flatten-Level. Höher bedeutet mehr Flattening. Standard ist 0. Maximum ist 2. | +| astName | string | [Optional] Der AST-Name. Standard ist "File". | +| reserveComment | boolean | [Optional] Ob die ursprünglichen Kommentare beibehalten werden. Standard ist false. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| AST \| nil | The AST, or nil if the conversion failed. | -| string \| nil | The error message, or nil if the conversion succeeded. | +| AST \| nil | Der AST oder `nil`, falls die Konvertierung fehlgeschlagen ist. | +| string \| nil | Die Fehlermeldung oder `nil`, falls die Konvertierung erfolgreich war. | ### format -**Type:** Function. +**Typ:** Funktion. -**Description:** +**Beschreibung:** -Formats the YueScript code. +Formatiert den YueScript-Code. -**Signature:** +**Signatur:** ```lua format: function(code: string, tabSize?: number, reserveComment?: boolean): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| code | string | The code. | -| tabSize | integer | [Optional] The tab size. Default is 4. | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is true. | +| code | string | Der Code. | +| tabSize | integer | [Optional] Die Tab-Größe. Standard ist 4. | +| reserveComment | boolean | [Optional] Ob die ursprünglichen Kommentare beibehalten werden. Standard ist true. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| string | The formatted code. | +| string | Der formatierte Code. | ### __call -**Type:** Metamethod. +**Typ:** Metamethod. -**Description:** +**Beschreibung:** -Requires the YueScript module. -Rewrites the error line number to the original line number in the YueScript code when loading fails. +Required das YueScript-Modul. +Schreibt die Fehlerzeilennummer bei Ladefehlern auf die ursprüngliche Zeilennummer im YueScript-Code um. -**Signature:** +**Signatur:** ```lua metamethod __call: function(self: yue, module: string): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Typ | Beschreibung | | --- | --- | --- | -| module | string | The module name. | +| module | string | Der Modulname. | -**Returns:** +**Rückgabe:** -| Return Type | Description | +| Rückgabetyp | Beschreibung | | --- | --- | -| any | The module value. | +| any | Der Modulwert. | ## Config -**Description:** +**Beschreibung:** -The compiler compile options. +Die Compiler-Optionen. ### lint_global -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler should collect the global variables appearing in the code. +Ob der Compiler die globalen Variablen im Code sammeln soll. -**Signature:** +**Signatur:** ```lua lint_global: boolean ``` ### implicit_return_root -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler should do an implicit return for the root code block. +Ob der Compiler für den Root-Codeblock ein implizites Return verwenden soll. -**Signature:** +**Signatur:** ```lua implicit_return_root: boolean ``` ### reserve_line_number -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler should reserve the original line number in the compiled code. +Ob der Compiler die ursprüngliche Zeilennummer im kompilierten Code beibehalten soll. -**Signature:** +**Signatur:** ```lua reserve_line_number: boolean ``` ### reserve_comment -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler should reserve the original comments in the compiled code. +Ob der Compiler die ursprünglichen Kommentare im kompilierten Code beibehalten soll. -**Signature:** +**Signatur:** ```lua reserve_comment: boolean ``` ### space_over_tab -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler should use the space character instead of the tab character in the compiled code. +Ob der Compiler statt Tabzeichen Leerzeichen verwenden soll. -**Signature:** +**Signatur:** ```lua space_over_tab: boolean ``` ### same_module -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler should treat the code to be compiled as the same currently being compiled module. For internal use only. +Ob der Compiler den zu kompilierenden Code als dasselbe aktuell kompilierte Modul behandeln soll. Nur für internen Gebrauch. -**Signature:** +**Signatur:** ```lua same_module: boolean ``` ### line_offset -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether the compiler error message should include the line number offset. For internal use only. +Ob die Compiler-Fehlermeldung einen Zeilennummern-Offset enthalten soll. Nur für internen Gebrauch. -**Signature:** +**Signatur:** ```lua line_offset: integer ``` ### yue.Config.LuaTarget -**Type:** Enumeration. +**Typ:** Enumeration. -**Description:** +**Beschreibung:** -The target Lua version enumeration. +Die Ziel-Lua-Version. -**Signature:** +**Signatur:** ```lua enum LuaTarget "5.1" @@ -751,71 +751,71 @@ end ### options -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The extra options to be passed to the compilation function. +Zusätzliche Optionen für die Kompilierung. -**Signature:** +**Signatur:** ```lua options: Options ``` ## Options -**Description:** +**Beschreibung:** -The extra compiler options definition. +Zusätzliche Compiler-Optionen. ### target -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The target Lua version for the compilation. +Die Ziel-Lua-Version für die Kompilierung. -**Signature:** +**Signatur:** ```lua target: LuaTarget ``` ### path -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -The extra module search path. +Zusätzlicher Modul-Suchpfad. -**Signature:** +**Signatur:** ```lua path: string ``` ### dump_locals -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether to dump the local variables in the traceback error message. Default is false. +Ob lokale Variablen in Traceback-Fehlermeldungen ausgegeben werden sollen. Standard ist false. -**Signature:** +**Signatur:** ```lua dump_locals: boolean ``` ### simplified -**Type:** Field. +**Typ:** Feld. -**Description:** +**Beschreibung:** -Whether to simplify the error message. Default is true. +Ob Fehlermeldungen vereinfacht werden sollen. Standard ist true. -**Signature:** +**Signatur:** ```lua simplified: boolean ``` diff --git a/doc/docs/doc/control-flow/conditionals.md b/doc/docs/doc/control-flow/conditionals.md index 5ba81cf..1bda514 100644 --- a/doc/docs/doc/control-flow/conditionals.md +++ b/doc/docs/doc/control-flow/conditionals.md @@ -136,14 +136,3 @@ if a in list ``` - -```yuescript -print "You're lucky!" unless math.random! > 0.1 -``` - - -```yue -print "You're lucky!" unless math.random! > 0.1 -``` - - diff --git a/doc/docs/doc/getting-started/introduction.md b/doc/docs/doc/getting-started/introduction.md index a9a9389..9a76b23 100644 --- a/doc/docs/doc/getting-started/introduction.md +++ b/doc/docs/doc/getting-started/introduction.md @@ -48,7 +48,7 @@ with apple p .size, .color, . if .<>? -- js-like export syntax -export 🌛 = "月之脚本" +export 🌛 = "Script of Moon" ``` @@ -95,7 +95,7 @@ with apple p .size, .color, . if .<>? -- js-like export syntax -export 🌛 = "月之脚本" +export 🌛 = "Script of Moon" ``` diff --git a/doc/docs/doc/reference/license-mit.md b/doc/docs/doc/reference/license-mit.md index f1d5d60..49eae7e 100644 --- a/doc/docs/doc/reference/license-mit.md +++ b/doc/docs/doc/reference/license-mit.md @@ -19,5 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - diff --git a/doc/docs/id-id/doc/advanced/do.md b/doc/docs/id-id/doc/advanced/do.md index 4990d6f..ebbd2e2 100644 --- a/doc/docs/id-id/doc/advanced/do.md +++ b/doc/docs/id-id/doc/advanced/do.md @@ -1,12 +1,12 @@ # Do -When used as a statement, do works just like it does in Lua. +Saat digunakan sebagai pernyataan, `do` bekerja seperti di Lua. ```yuescript do var = "hello" print var -print var -- nil here +print var -- nil di sini ``` @@ -14,12 +14,12 @@ print var -- nil here do var = "hello" print var -print var -- nil here +print var -- nil di sini ``` -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. +`do` di YueScript juga bisa digunakan sebagai ekspresi, memungkinkan Anda menggabungkan beberapa baris menjadi satu. Hasil ekspresi `do` adalah pernyataan terakhir di badannya. ```yuescript counter = do diff --git a/doc/docs/id-id/doc/advanced/line-decorators.md b/doc/docs/id-id/doc/advanced/line-decorators.md index 292bc77..e90e205 100644 --- a/doc/docs/id-id/doc/advanced/line-decorators.md +++ b/doc/docs/id-id/doc/advanced/line-decorators.md @@ -1,6 +1,6 @@ -# Line Decorators +# Dekorator Baris -For convenience, the for loop and if statement can be applied to single statements at the end of the line: +Untuk kemudahan, loop for dan pernyataan if dapat diterapkan pada pernyataan tunggal di akhir baris: ```yuescript print "hello world" if name == "Rob" @@ -13,7 +13,7 @@ print "hello world" if name == "Rob" -And with basic loops: +Dan dengan loop dasar: ```yuescript print "item: ", item for item in *items @@ -26,7 +26,7 @@ print "item: ", item for item in *items -And with while loops: +Dan dengan loop while: ```yuescript game\update! while game\isRunning! diff --git a/doc/docs/id-id/doc/advanced/macro.md b/doc/docs/id-id/doc/advanced/macro.md index 6d194c3..ce0bafa 100644 --- a/doc/docs/id-id/doc/advanced/macro.md +++ b/doc/docs/id-id/doc/advanced/macro.md @@ -1,8 +1,8 @@ -# Macro +# Makro -## Common Usage +## Penggunaan Umum -Macro function is used for evaluating a string in the compile time and insert the generated codes into final compilation. +Fungsi macro digunakan untuk mengevaluasi string pada waktu kompilasi dan menyisipkan kode yang dihasilkan ke kompilasi akhir. ```yuescript macro PI2 = -> math.pi * 2 @@ -27,7 +27,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- ekspresi yang dikirim diperlakukan sebagai string macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -57,7 +57,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- ekspresi yang dikirim diperlakukan sebagai string macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -65,29 +65,29 @@ if $and f1!, f2!, f3! -## Insert Raw Codes +## Menyisipkan Kode Mentah -A macro function can either return a YueScript string or a config table containing Lua codes. +Fungsi macro bisa mengembalikan string YueScript atau tabel konfigurasi yang berisi kode Lua. ```yuescript macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA -funcA = -> "fail to assign to the Yue macro defined variable" +funcA = -> "gagal meng-assign ke variabel yang didefinisikan oleh macro Yue" macro luaFunc = (var) -> { code: "local function #{var}() end" type: "lua" } $luaFunc funcB -funcB = -> "fail to assign to the Lua macro defined variable" +funcB = -> "gagal meng-assign ke variabel yang didefinisikan oleh macro Lua" macro lua = (code) -> { :code type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- simbol awal dan akhir string mentah otomatis di-trim $lua[==[ --- raw Lua codes insertion +-- penyisipan kode Lua mentah if cond then print("output") end @@ -98,23 +98,23 @@ end ```yue macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA -funcA = -> "fail to assign to the Yue macro defined variable" +funcA = -> "gagal meng-assign ke variabel yang didefinisikan oleh macro Yue" macro luaFunc = (var) -> { code: "local function #{var}() end" type: "lua" } $luaFunc funcB -funcB = -> "fail to assign to the Lua macro defined variable" +funcB = -> "gagal meng-assign ke variabel yang didefinisikan oleh macro Lua" macro lua = (code) -> { :code type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- simbol awal dan akhir string mentah otomatis di-trim $lua[==[ --- raw Lua codes insertion +-- penyisipan kode Lua mentah if cond then print("output") end @@ -125,7 +125,7 @@ end ## Export Macro -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. +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. ```yuescript -- file: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" @@ -135,8 +135,8 @@ export macro foreach = (items, action) -> "for _ in *#{items} -- file main.yue import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- simbol untuk mengimpor semua macro + $foreach: $each -- ganti nama macro $foreach menjadi $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ``` @@ -150,11 +150,11 @@ export macro foreach = (items, action) -> "for _ in *#{items} #{action}" -- file main.yue --- import function is not available in browser, try it in a real environment +-- fungsi import tidak tersedia di browser, coba di lingkungan nyata --[[ import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- simbol untuk mengimpor semua macro + $foreach: $each -- ganti nama macro $foreach menjadi $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ]] @@ -162,25 +162,25 @@ import "utils" as { -## Builtin Macro +## Macro Bawaan -There are some builtin macros but you can override them by declaring macros with the same names. +Ada beberapa macro bawaan tetapi Anda bisa menimpanya dengan mendeklarasikan macro dengan nama yang sama. ```yuescript -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- mendapatkan string nama modul saat ini +print $LINE -- mendapatkan angka 2 ``` ```yue -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- mendapatkan string nama modul saat ini +print $LINE -- mendapatkan angka 2 ``` -## Generating Macros with Macros +## Menghasilkan Macro dengan Macro -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. +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. ```yuescript macro Enum = (...) -> @@ -222,9 +222,9 @@ print "Valid enum type:", $BodyType Static -## Argument Validation +## Validasi Argumen -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. +Anda dapat mendeklarasikan tipe node AST yang diharapkan dalam daftar argumen, dan memeriksa apakah argumen macro yang masuk memenuhi harapan pada waktu kompilasi. ```yuescript macro printNumAndStr = (num `Num, str `String) -> | @@ -249,7 +249,7 @@ $printNumAndStr 123, "hello" -If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. +Jika Anda membutuhkan pengecekan argumen yang lebih fleksibel, Anda dapat menggunakan fungsi macro bawaan `$is_ast` untuk memeriksa secara manual pada tempat yang tepat. ```yuescript macro printNumAndStr = (num, str) -> @@ -272,4 +272,4 @@ $printNumAndStr 123, "hello" -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). +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). diff --git a/doc/docs/id-id/doc/advanced/module.md b/doc/docs/id-id/doc/advanced/module.md index c955092..dd97a32 100644 --- a/doc/docs/id-id/doc/advanced/module.md +++ b/doc/docs/id-id/doc/advanced/module.md @@ -1,28 +1,28 @@ -# Module +# Modul ## Import -The import statement is a syntax sugar for requiring a module or help extracting items from an imported module. The imported items are const by default. +Pernyataan `import` adalah sintaks sugar untuk me-require modul atau membantu mengekstrak item dari modul yang diimpor. Item yang diimpor bersifat `const` secara default. ```yuescript --- used as table destructuring +-- digunakan sebagai destrukturisasi tabel do import insert, concat from table - -- report error when assigning to insert, concat + -- akan error saat meng-assign ke insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- shortcut untuk require implisit import x, y, z from 'mymodule' - -- import with Python style + -- import gaya Python from 'module' import a, b, c --- shortcut for requring a module +-- shortcut untuk require modul do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- require modul dengan aliasing atau destrukturisasi tabel do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -31,24 +31,24 @@ do ```yue --- used as table destructuring +-- digunakan sebagai destrukturisasi tabel do import insert, concat from table - -- report error when assigning to insert, concat + -- akan error saat meng-assign ke insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- shortcut untuk require implisit import x, y, z from 'mymodule' - -- import with Python style + -- import gaya Python from 'module' import a, b, c --- shortcut for requring a module +-- shortcut untuk require modul do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- require modul dengan aliasing atau destrukturisasi tabel do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -59,7 +59,7 @@ do ## Import Global -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. +Anda dapat mengimpor global tertentu ke variabel local dengan `import`. Saat mengimpor rangkaian akses variabel global, field terakhir akan di-assign ke variabel local. ```yuescript do @@ -78,11 +78,11 @@ do -### Automatic Global Variable Import +### Import Variabel Global Otomatis -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. +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. -Names that are explicitly declared as globals in the same scope will not be imported, so you can still assign to them. +Nama yang secara eksplisit dideklarasikan sebagai global di scope yang sama tidak akan diimpor, sehingga Anda masih bisa meng-assign ke mereka. ```yuescript do @@ -92,7 +92,7 @@ do -- print = nil -- error: imported globals are const do - -- explicit global variable will not be imported + -- variabel global eksplisit tidak akan diimpor import global global FLAG print FLAG @@ -108,7 +108,7 @@ do -- print = nil -- error: imported globals are const do - -- explicit global variable will not be imported + -- variabel global eksplisit tidak akan diimpor import global global FLAG print FLAG @@ -119,11 +119,11 @@ do ## Export -The export statement offers a concise way to define modules. +Pernyataan `export` menawarkan cara ringkas untuk mendefinisikan modul. -### Named Export +### Export Bernama -Named export will define a local variable as well as adding a field in the exported table. +Export bernama akan mendefinisikan variabel local sekaligus menambahkan field di tabel export. ```yuescript export a, b, c = 1, 2, 3 @@ -160,7 +160,7 @@ export class Something -Doing named export with destructuring. +Melakukan export bernama dengan destrukturisasi. ```yuescript export :loadstring, to_lua: tolua = yue @@ -175,7 +175,7 @@ export {itemA: {:fieldA = 'default'}} = tb -Export named items from module without creating local variables. +Export item bernama dari modul tanpa membuat variabel local. ```yuescript export.itemA = tb @@ -192,9 +192,9 @@ export["a-b-c"] = 123 -### Unnamed Export +### Export Tanpa Nama -Unnamed export will add the target item into the array part of the exported table. +Export tanpa nama akan menambahkan item target ke bagian array dari tabel export. ```yuescript d, e, f = 3, 2, 1 @@ -225,9 +225,9 @@ export with tmp -### Default Export +### Export Default -Using the **default** keyword in export statement to replace the exported table with any thing. +Gunakan kata kunci **default** dalam pernyataan export untuk mengganti tabel export dengan apa pun. ```yuescript export default -> diff --git a/doc/docs/id-id/doc/advanced/try.md b/doc/docs/id-id/doc/advanced/try.md index 23c7877..6607451 100644 --- a/doc/docs/id-id/doc/advanced/try.md +++ b/doc/docs/id-id/doc/advanced/try.md @@ -1,6 +1,6 @@ # Try -The syntax for Lua error handling in a common form. +Sintaks untuk penanganan error Lua dalam bentuk umum. ```yuescript try @@ -23,7 +23,7 @@ try print "trying" func 1, 2, 3 --- working with if assignment pattern +-- bekerja dengan pola if assignment if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -52,7 +52,7 @@ try print "trying" func 1, 2, 3 --- working with if assignment pattern +-- bekerja dengan pola if assignment if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -63,18 +63,18 @@ catch err ## Try? -`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. +`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. ```yuescript a, b, c = try? func! --- with nil coalescing operator +-- dengan operator nil coalescing a = (try? func!) ?? "default" --- as function argument +-- sebagai argumen fungsi f try? func! --- with catch block +-- dengan blok catch f try? print 123 func! @@ -87,13 +87,13 @@ catch e ```yue a, b, c = try? func! --- with nil coalescing operator +-- dengan operator nil coalescing a = (try? func!) ?? "default" --- as function argument +-- sebagai argumen fungsi f try? func! --- with catch block +-- dengan blok catch f try? print 123 func! diff --git a/doc/docs/id-id/doc/assignment/assignment.md b/doc/docs/id-id/doc/assignment/assignment.md index 4dac6f4..d9fd45d 100644 --- a/doc/docs/id-id/doc/assignment/assignment.md +++ b/doc/docs/id-id/doc/assignment/assignment.md @@ -1,25 +1,25 @@ -# Assignment +# Penugasan -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. +Variabel bersifat bertipe dinamis dan secara default dideklarasikan sebagai local. Namun Anda dapat mengubah cakupan deklarasi dengan pernyataan **local** dan **global**. ```yuescript hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- menggunakan variabel yang sudah ada ``` ```yue hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- menggunakan variabel yang sudah ada ``` -## Perform Update +## Pembaruan Nilai -You can perform update assignment with many binary operators. +Anda dapat melakukan assignment pembaruan dengan banyak operator biner. ```yuescript x = 1 x += 1 @@ -27,7 +27,7 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist +s ..= "world" -- akan menambah local baru jika variabel local belum ada arg or= "default value" ``` @@ -39,15 +39,15 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist +s ..= "world" -- akan menambah local baru jika variabel local belum ada arg or= "default value" ``` -## Chaining Assignment +## Assignment Berantai -You can do chaining assignment to assign multiple items to hold the same value. +Anda bisa melakukan assignment berantai untuk menetapkan beberapa item ke nilai yang sama. ```yuescript a = b = c = d = e = 0 x = y = z = f! @@ -61,12 +61,12 @@ x = y = z = f! -## Explicit Locals +## Local Eksplisit ```yuescript do local a = 1 local * - print "forward declare all variables as locals" + print "deklarasikan semua variabel sebagai local di awal" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! @@ -74,7 +74,7 @@ do do local X = 1 local ^ - print "only forward declare upper case variables" + print "hanya deklarasikan variabel huruf besar sebagai local di awal" a = 1 B = 2 ``` @@ -84,7 +84,7 @@ do do local a = 1 local * - print "forward declare all variables as locals" + print "deklarasikan semua variabel sebagai local di awal" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! @@ -92,26 +92,26 @@ do do local X = 1 local ^ - print "only forward declare upper case variables" + print "hanya deklarasikan variabel huruf besar sebagai local di awal" a = 1 B = 2 ``` -## Explicit Globals +## Global Eksplisit ```yuescript do global a = 1 global * - print "declare all variables as globals" + print "deklarasikan semua variabel sebagai global" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ - print "only declare upper case variables as globals" + print "hanya deklarasikan variabel huruf besar sebagai global" a = 1 B = 2 local Temp = "a local value" @@ -122,14 +122,14 @@ do do global a = 1 global * - print "declare all variables as globals" + print "deklarasikan semua variabel sebagai global" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ - print "only declare upper case variables as globals" + print "hanya deklarasikan variabel huruf besar sebagai global" a = 1 B = 2 local Temp = "a local value" diff --git a/doc/docs/id-id/doc/assignment/destructuring-assignment.md b/doc/docs/id-id/doc/assignment/destructuring-assignment.md index e7b8046..ba591fd 100644 --- a/doc/docs/id-id/doc/assignment/destructuring-assignment.md +++ b/doc/docs/id-id/doc/assignment/destructuring-assignment.md @@ -1,10 +1,10 @@ -# Destructuring Assignment +# Penugasan Destrukturisasi -Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. +Assignment destrukturisasi adalah cara cepat untuk mengekstrak nilai dari sebuah tabel berdasarkan nama kunci atau posisinya pada tabel berbasis array. -Typically when you see a table literal, {1,2,3}, it is on the right hand side of an assignment because it is a value. Destructuring assignment swaps the role of the table literal, and puts it on the left hand side of an assign statement. +Biasanya ketika Anda melihat literal tabel, `{1,2,3}`, ia berada di sisi kanan assignment karena merupakan nilai. Assignment destrukturisasi menukar peran literal tabel dan menaruhnya di sisi kiri pernyataan assignment. -This is best explained with examples. Here is how you would unpack the first two values from a table: +Ini paling mudah dijelaskan dengan contoh. Berikut cara membongkar dua nilai pertama dari sebuah tabel: ```yuescript thing = [1, 2] @@ -23,7 +23,7 @@ print a, b -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. +Di literal tabel destrukturisasi, kunci mewakili kunci yang dibaca dari sisi kanan, dan nilai mewakili nama yang akan menerima nilai tersebut. ```yuescript obj = { @@ -35,7 +35,7 @@ obj = { {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- OK untuk destrukturisasi sederhana tanpa kurung ``` @@ -49,12 +49,12 @@ obj = { {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- OK untuk destrukturisasi sederhana tanpa kurung ``` -This also works with nested data structures as well: +Ini juga bekerja pada struktur data bertingkat: ```yuescript obj2 = { @@ -85,7 +85,7 @@ print first, second, color -If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: +Jika pernyataan destrukturisasi kompleks, Anda bisa memecahnya ke beberapa baris. Contoh yang sedikit lebih rumit: ```yuescript { @@ -108,7 +108,7 @@ If the destructuring statement is complicated, feel free to spread it out over a -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: +Umumnya mengekstrak nilai dari tabel lalu menugaskannya ke variabel local dengan nama yang sama dengan kuncinya. Untuk menghindari pengulangan, kita bisa menggunakan operator prefiks **:**: ```yuescript {:concat, :insert} = table @@ -121,7 +121,7 @@ It's common to extract values from at table and assign them the local variables -This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: +Ini secara efektif sama seperti import, tetapi kita dapat mengganti nama field yang ingin diekstrak dengan menggabungkan sintaks: ```yuescript {:mix, :max, random: rand} = math @@ -134,7 +134,7 @@ This is effectively the same as import, but we can rename fields we want to extr -You can write default values while doing destructuring like: +Anda bisa menulis nilai default saat destrukturisasi seperti: ```yuescript {:name = "nameless", :job = "jobless"} = person @@ -147,7 +147,7 @@ You can write default values while doing destructuring like: -You can use `_` as placeholder when doing a list destructuring: +Anda dapat menggunakan `_` sebagai placeholder saat destrukturisasi list: ```yuescript [_, two, _, four] = items @@ -160,9 +160,9 @@ You can use `_` as placeholder when doing a list destructuring: -## Range Destructuring +## Destrukturisasi Rentang -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. +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. ```yuescript orders = ["first", "second", "third", "fourth", "last"] @@ -183,36 +183,36 @@ print last -- prints: last -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: +Operator spread dapat digunakan pada posisi berbeda untuk menangkap rentang yang berbeda, dan Anda bisa memakai `_` sebagai placeholder untuk nilai yang tidak ingin ditangkap: ```yuescript --- Capture everything after first element +-- Tangkap semuanya setelah elemen pertama [first, ...rest] = orders --- Capture everything before last element +-- Tangkap semuanya sebelum elemen terakhir [...start, last] = orders --- Capture things except the middle elements +-- Tangkap semuanya kecuali elemen tengah [first, ..._, last] = orders ``` ```yue --- Capture everything after first element +-- Tangkap semuanya setelah elemen pertama [first, ...rest] = orders --- Capture everything before last element +-- Tangkap semuanya sebelum elemen terakhir [...start, last] = orders --- Capture things except the middle elements +-- Tangkap semuanya kecuali elemen tengah [first, ..._, last] = orders ``` -## Destructuring In Other Places +## Destrukturisasi di Tempat Lain -Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: +Destrukturisasi juga dapat muncul di tempat-tempat di mana assignment terjadi secara implisit. Contohnya adalah perulangan for: ```yuescript tuples = [ @@ -237,4 +237,4 @@ for [left, right] in *tuples -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. +Kita tahu setiap elemen pada tabel array adalah tuple dua item, sehingga kita dapat membongkarnya langsung di klausa nama pada pernyataan for menggunakan destrukturisasi. diff --git a/doc/docs/id-id/doc/assignment/if-assignment.md b/doc/docs/id-id/doc/assignment/if-assignment.md index 02984e8..b30d0d9 100644 --- a/doc/docs/id-id/doc/assignment/if-assignment.md +++ b/doc/docs/id-id/doc/assignment/if-assignment.md @@ -1,6 +1,6 @@ -# If Assignment +# Penugasan pada If -`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. +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. ```yuescript if user := database.find_user "moon" @@ -36,36 +36,36 @@ else -If assignment with multiple return values. Only the first value is getting checked, other values are scoped. +Assignment if dengan beberapa nilai return. Hanya nilai pertama yang dicek, nilai lainnya tetap berada dalam scope. ```yuescript if success, result := pcall -> "get result without problems" - print result -- variable result is scoped + print result -- variabel result berada dalam scope print "OK" ``` ```yue if success, result := pcall -> "get result without problems" - print result -- variable result is scoped + print result -- variabel result berada dalam scope print "OK" ``` -## While Assignment +## Assignment pada While -You can also use if assignment in a while loop to get the value as the loop condition. +Anda juga bisa menggunakan assignment if di loop while untuk mendapatkan nilai sebagai kondisi loop. ```yuescript while byte := stream\read_one! - -- do something with the byte + -- lakukan sesuatu dengan byte print byte ``` ```yue while byte := stream\read_one! - -- do something with the byte + -- lakukan sesuatu dengan byte print byte ``` diff --git a/doc/docs/id-id/doc/assignment/the-using-clause-controlling-destructive-assignment.md b/doc/docs/id-id/doc/assignment/the-using-clause-controlling-destructive-assignment.md index fb9b740..6953138 100644 --- a/doc/docs/id-id/doc/assignment/the-using-clause-controlling-destructive-assignment.md +++ b/doc/docs/id-id/doc/assignment/the-using-clause-controlling-destructive-assignment.md @@ -1,11 +1,11 @@ -# The Using Clause; Controlling Destructive Assignment +# Klausa Using; Mengendalikan Penugasan Destruktif -While lexical scoping can be a great help in reducing the complexity of the code we write, things can get unwieldy as the code size increases. Consider the following snippet: +Meskipun scope leksikal sangat membantu mengurangi kompleksitas kode yang kita tulis, hal ini bisa menjadi sulit ketika ukuran kode membesar. Pertimbangkan cuplikan berikut: ```yuescript i = 100 --- many lines of code... +-- banyak baris kode... my_func = -> i = 10 @@ -15,14 +15,14 @@ my_func = -> my_func! -print i -- will print 0 +print i -- akan mencetak 0 ``` ```yue i = 100 --- many lines of code... +-- banyak baris kode... my_func = -> i = 10 @@ -32,25 +32,25 @@ my_func = -> my_func! -print i -- will print 0 +print i -- akan mencetak 0 ``` -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. +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. -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. +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. -The using keyword lets us do that. using nil makes sure that no closed variables are overwritten in assignment. The using clause is placed after the argument list in a function, or in place of it if there are no arguments. +Kata kunci `using` memungkinkan kita melakukan itu. `using nil` memastikan bahwa tidak ada variabel tertutup yang ditimpa dalam assignment. Klausa `using` ditempatkan setelah daftar argumen pada fungsi, atau menggantikannya jika tidak ada argumen. ```yuescript i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- variabel local baru dibuat di sini my_func! -print i -- prints 100, i is unaffected +print i -- mencetak 100, i tidak terpengaruh ``` @@ -58,27 +58,27 @@ print i -- prints 100, i is unaffected i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- variabel local baru dibuat di sini my_func! -print i -- prints 100, i is unaffected +print i -- mencetak 100, i tidak terpengaruh ``` -Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: +Beberapa nama dapat dipisahkan dengan koma. Nilai closure tetap bisa diakses, hanya saja tidak dapat dimodifikasi: ```yuescript tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- tmp local baru dibuat i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- ini telah diperbarui ``` @@ -87,12 +87,12 @@ tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- tmp local baru dibuat i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- ini telah diperbarui ``` diff --git a/doc/docs/id-id/doc/assignment/varargs-assignment.md b/doc/docs/id-id/doc/assignment/varargs-assignment.md index 1d66680..f24652f 100644 --- a/doc/docs/id-id/doc/assignment/varargs-assignment.md +++ b/doc/docs/id-id/doc/assignment/varargs-assignment.md @@ -1,6 +1,6 @@ -# Varargs Assignment +# Penugasan Varargs -You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. +Anda dapat meng-assign hasil yang dikembalikan dari sebuah fungsi ke simbol varargs `...`. Lalu akses isinya menggunakan cara Lua. ```yuescript list = [1, 2, 3, 4, 5] diff --git a/doc/docs/id-id/doc/control-flow/conditionals.md b/doc/docs/id-id/doc/control-flow/conditionals.md index 5ba81cf..4f08b16 100644 --- a/doc/docs/id-id/doc/control-flow/conditionals.md +++ b/doc/docs/id-id/doc/control-flow/conditionals.md @@ -1,55 +1,55 @@ -# Conditionals +# Kondisional ```yuescript have_coins = false if have_coins - print "Got coins" + print "Dapat koin" else - print "No coins" + print "Tidak ada koin" ``` ```yue have_coins = false if have_coins - print "Got coins" + print "Dapat koin" else - print "No coins" + print "Tidak ada koin" ``` -A short syntax for single statements can also be used: +Sintaks pendek untuk pernyataan tunggal juga bisa digunakan: ```yuescript have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Dapat koin" else print "Tidak ada koin" ``` ```yue have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Dapat koin" else print "Tidak ada koin" ``` -Because if statements can be used as expressions, this can also be written as: +Karena pernyataan if dapat digunakan sebagai ekspresi, ini juga bisa ditulis sebagai: ```yuescript have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Dapat koin" else "Tidak ada koin" ``` ```yue have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Dapat koin" else "Tidak ada koin" ``` -Conditionals can also be used in return statements and assignments: +Kondisional juga bisa digunakan di pernyataan return dan assignment: ```yuescript is_tall = (name) -> @@ -59,11 +59,11 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Saya sangat tinggi" else - "I am not so tall" + "Saya tidak terlalu tinggi" -print message -- prints: I am very tall +print message -- prints: Saya sangat tinggi ``` @@ -75,53 +75,53 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Saya sangat tinggi" else - "I am not so tall" + "Saya tidak terlalu tinggi" -print message -- prints: I am very tall +print message -- prints: Saya sangat tinggi ``` -The opposite of if is unless: +Kebalikan dari if adalah unless: ```yuescript unless os.date("%A") == "Monday" - print "it is not Monday!" + print "hari ini bukan Senin!" ``` ```yue unless os.date("%A") == "Monday" - print "it is not Monday!" + print "hari ini bukan Senin!" ``` ```yuescript -print "You're lucky!" unless math.random! > 0.1 +print "Kamu beruntung!" unless math.random! > 0.1 ``` ```yue -print "You're lucky!" unless math.random! > 0.1 +print "Kamu beruntung!" unless math.random! > 0.1 ``` -## In Expression +## Ekspresi In -You can write range checking code with an `in-expression`. +Anda dapat menulis kode pengecekan rentang dengan `ekspresi in`. ```yuescript a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "memeriksa kesamaan dengan nilai-nilai diskrit" if a in list - print "checking if `a` is in a list" + print "memeriksa apakah `a` ada di dalam daftar" ``` @@ -129,21 +129,10 @@ if a in list a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "memeriksa kesamaan dengan nilai-nilai diskrit" if a in list - print "checking if `a` is in a list" -``` - - - -```yuescript -print "You're lucky!" unless math.random! > 0.1 -``` - - -```yue -print "You're lucky!" unless math.random! > 0.1 + print "memeriksa apakah `a` ada di dalam daftar" ``` diff --git a/doc/docs/id-id/doc/control-flow/continue.md b/doc/docs/id-id/doc/control-flow/continue.md index b000765..3d7a68c 100644 --- a/doc/docs/id-id/doc/control-flow/continue.md +++ b/doc/docs/id-id/doc/control-flow/continue.md @@ -1,6 +1,6 @@ -# Continue +# Pernyataan Continue -A continue statement can be used to skip the current iteration in a loop. +Pernyataan continue dapat digunakan untuk melewati iterasi saat ini di dalam loop. ```yuescript i = 0 @@ -21,7 +21,7 @@ while i < 10 -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: +continue juga bisa digunakan bersama ekspresi loop untuk mencegah iterasi tersebut diakumulasikan ke hasil. Contoh ini memfilter tabel array menjadi hanya angka genap: ```yuescript my_numbers = [1, 2, 3, 4, 5, 6] diff --git a/doc/docs/id-id/doc/control-flow/for-loop.md b/doc/docs/id-id/doc/control-flow/for-loop.md index cabcde5..91ba22e 100644 --- a/doc/docs/id-id/doc/control-flow/for-loop.md +++ b/doc/docs/id-id/doc/control-flow/for-loop.md @@ -1,6 +1,6 @@ -# For Loop +# Perulangan For -There are two for loop forms, just like in Lua. A numeric one and a generic one: +Ada dua bentuk perulangan for, seperti di Lua. Satu numerik dan satu generik: ```yuescript for i = 10, 20 @@ -27,7 +27,7 @@ for key, value in pairs object -The slicing and **\*** operators can be used, just like with comprehensions: +Operator slicing dan **\*** dapat digunakan, seperti pada comprehension: ```yuescript for item in *items[2, 4] @@ -42,7 +42,7 @@ for item in *items[2, 4] -A shorter syntax is also available for all variations when the body is only a single line: +Sintaks yang lebih singkat juga tersedia untuk semua variasi ketika badan hanya satu baris: ```yuescript for item in *items do print item @@ -59,9 +59,9 @@ for j = 1, 10, 3 do print j -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. +Perulangan for juga bisa digunakan sebagai ekspresi. Pernyataan terakhir di badan for dipaksa menjadi ekspresi dan ditambahkan ke tabel array yang terakumulasi. -Doubling every even number: +Menggandakan setiap bilangan genap: ```yuescript doubled_evens = for i = 1, 20 @@ -82,9 +82,9 @@ doubled_evens = for i = 1, 20 -In addition, for loops support break with a return value, allowing the loop itself to be used as an expression that exits early with a meaningful result. +Selain itu, loop for mendukung break dengan nilai kembalian, sehingga loop itu sendiri bisa dipakai sebagai ekspresi yang keluar lebih awal dengan hasil bermakna. -For example, to find the first number greater than 10: +Contohnya, untuk menemukan angka pertama yang lebih besar dari 10: ```yuescript first_large = for n in *numbers @@ -99,11 +99,11 @@ first_large = for n in *numbers -This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. +Sintaks break-dengan-nilai ini memungkinkan pola pencarian atau keluar-lebih-awal yang ringkas langsung di dalam ekspresi loop. -You can also filter values by combining the for loop expression with the continue statement. +Anda juga bisa memfilter nilai dengan menggabungkan ekspresi for dengan pernyataan continue. -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. +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. ```yuescript func_a = -> for i = 1, 10 do print i @@ -123,5 +123,3 @@ print func_b! -- prints table object ``` - -This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. diff --git a/doc/docs/id-id/doc/control-flow/switch.md b/doc/docs/id-id/doc/control-flow/switch.md index f503a80..ced4748 100644 --- a/doc/docs/id-id/doc/control-flow/switch.md +++ b/doc/docs/id-id/doc/control-flow/switch.md @@ -1,6 +1,6 @@ -# Switch +# Pernyataan Switch -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. +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. ```yuescript switch name := "Dan" @@ -25,9 +25,9 @@ switch name := "Dan" -A switch when clause can match against multiple values by listing them out comma separated. +Klausa when pada switch bisa mencocokkan beberapa nilai dengan menuliskannya dipisah koma. -Switches can be used as expressions as well, here we can assign the result of the switch to a variable: +Switch juga bisa dipakai sebagai ekspresi; di sini kita dapat menetapkan hasil switch ke sebuah variabel: ```yuescript b = 1 @@ -54,7 +54,7 @@ next_number = switch b -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. +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. ```yuescript msg = switch math.random(1, 5) @@ -73,7 +73,7 @@ msg = switch math.random(1, 5) -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. +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. ```yuescript switch math.random(1, 5) @@ -104,11 +104,11 @@ else -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. +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`. -## Table Matching +## Pencocokan Tabel -You can do table matching in a switch when clause, if the table can be destructured by a specific structure and get non-nil values. +Anda bisa melakukan pencocokan tabel dalam klausa when switch, jika tabel dapat didestrukturisasi oleh struktur tertentu dan mendapatkan nilai non-nil. ```yuescript items = @@ -143,7 +143,7 @@ for item in *items -You can use default values to optionally destructure the table for some fields. +Anda dapat menggunakan nilai default untuk mendestrukturisasi tabel secara opsional pada beberapa field. ```yuescript item = {} @@ -168,9 +168,9 @@ switch item -You can also match against array elements, table fields, and even nested structures with array or table literals. +Anda juga bisa mencocokkan elemen array, field tabel, dan bahkan struktur bertingkat dengan literal array atau tabel. -Match against array elements. +Cocokkan terhadap elemen array. ```yuescript switch tb @@ -195,7 +195,7 @@ switch tb -Match against table fields with destructuring. +Cocokkan terhadap field tabel dengan destrukturisasi. ```yuescript switch tb @@ -220,7 +220,7 @@ switch tb -Match against nested table structures. +Cocokkan terhadap struktur tabel bertingkat. ```yuescript switch tb @@ -245,7 +245,7 @@ switch tb -Match against array of tables. +Cocokkan terhadap array dari tabel. ```yuescript switch tb @@ -272,7 +272,7 @@ switch tb -Match against a list and capture a range of elements. +Cocokkan terhadap daftar dan tangkap rentang elemen. ```yuescript segments = ["admin", "users", "logs", "view"] diff --git a/doc/docs/id-id/doc/control-flow/while-loop.md b/doc/docs/id-id/doc/control-flow/while-loop.md index 502935e..cd93c91 100644 --- a/doc/docs/id-id/doc/control-flow/while-loop.md +++ b/doc/docs/id-id/doc/control-flow/while-loop.md @@ -1,6 +1,6 @@ -# While Loop +# Perulangan While -The while loop also comes in four variations: +Perulangan while juga memiliki empat variasi: ```yuescript i = 10 @@ -43,11 +43,11 @@ until running == false do my_function! -Like for loops, the while loop can also be used an expression. Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. +Seperti loop for, loop while juga bisa digunakan sebagai ekspresi. Selain itu, agar sebuah fungsi mengembalikan nilai akumulasi dari loop while, pernyataannya harus di-return secara eksplisit. ## Repeat Loop -The repeat loop comes from Lua: +Loop repeat berasal dari Lua: ```yuescript i = 10 diff --git a/doc/docs/id-id/doc/data-structures/comprehensions.md b/doc/docs/id-id/doc/data-structures/comprehensions.md index 3a92167..3a2a9ff 100644 --- a/doc/docs/id-id/doc/data-structures/comprehensions.md +++ b/doc/docs/id-id/doc/data-structures/comprehensions.md @@ -1,10 +1,10 @@ -# Comprehensions +# Komprehensi -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. +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. -## List Comprehensions +## Komprehensi List -The following creates a copy of the items table but with all the values doubled. +Berikut membuat salinan tabel `items` tetapi semua nilainya digandakan. ```yuescript items = [ 1, 2, 3, 4 ] @@ -19,7 +19,7 @@ doubled = [item * 2 for i, item in ipairs items] -The items included in the new table can be restricted with a when clause: +Item yang disertakan dalam tabel baru bisa dibatasi dengan klausa `when`: ```yuescript slice = [item for i, item in ipairs items when i > 1 and i < 3] @@ -32,7 +32,7 @@ slice = [item for i, item in ipairs items when i > 1 and i < 3] -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: +Karena umum untuk mengiterasi nilai dari tabel berindeks numerik, operator **\*** diperkenalkan. Contoh `doubled` bisa ditulis ulang sebagai: ```yuescript doubled = [item * 2 for item in *items] @@ -45,7 +45,7 @@ doubled = [item * 2 for item in *items] -In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: +Dalam komprehensi list, Anda juga bisa menggunakan operator spread `...` untuk meratakan list bertingkat, menghasilkan efek flat map: ```yuescript data = @@ -53,7 +53,7 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat sekarang [1, 2, 3, 4, 5, 6] ``` @@ -63,14 +63,14 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat sekarang [1, 2, 3, 4, 5, 6] ``` -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. +Klausa `for` dan `when` dapat dirantai sebanyak yang diinginkan. Satu-satunya syarat adalah komprehensi memiliki setidaknya satu klausa `for`. -Using multiple for clauses is the same as using nested loops: +Menggunakan beberapa klausa `for` sama seperti menggunakan loop bertingkat: ```yuescript x_coords = [4, 5, 6, 7] @@ -91,7 +91,7 @@ for y in *y_coords] -Numeric for loops can also be used in comprehensions: +Perulangan for numerik juga bisa digunakan dalam komprehensi: ```yuescript evens = [i for i = 1, 100 when i % 2 == 0] @@ -104,11 +104,11 @@ evens = [i for i = 1, 100 when i % 2 == 0] -## Table Comprehensions +## Komprehensi Tabel -The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. +Sintaks untuk komprehensi tabel sangat mirip, hanya berbeda dengan penggunaan **{** dan **}** serta mengambil dua nilai dari setiap iterasi. -This example makes a copy of the tablething: +Contoh ini membuat salinan tabel `thing`: ```yuescript thing = { @@ -144,7 +144,7 @@ no_color = {k, v for k, v in pairs thing when k != "color"} -The **\*** operator is also supported. Here we create a square root look up table for a few numbers. +Operator **\*** juga didukung. Di sini kita membuat tabel lookup akar kuadrat untuk beberapa angka. ```yuescript numbers = [1, 2, 3, 4] @@ -159,9 +159,9 @@ sqrts = {i, math.sqrt i for i in *numbers} -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: +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: -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. +Dalam contoh ini kita mengonversi array pasangan menjadi tabel di mana item pertama dalam pasangan menjadi kunci dan item kedua menjadi nilai. ```yuescript tuples = [ ["hello", "world"], ["foo", "bar"]] @@ -178,9 +178,9 @@ tbl = {unpack tuple for tuple in *tuples} ## Slicing -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. +Sintaks khusus disediakan untuk membatasi item yang diiterasi saat menggunakan operator **\***. Ini setara dengan mengatur batas iterasi dan ukuran langkah pada loop for. -Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive: +Di sini kita bisa menetapkan batas minimum dan maksimum, mengambil semua item dengan indeks antara 1 dan 5 (inklusif): ```yuescript slice = [item for item in *items[1, 5]] @@ -193,7 +193,7 @@ slice = [item for item in *items[1, 5]] -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: +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: ```yuescript slice = [item for item in *items[2,]] @@ -206,7 +206,7 @@ slice = [item for item in *items[2,]] -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, …) +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, …) ```yuescript slice = [item for item in *items[,,2]] @@ -219,22 +219,22 @@ slice = [item for item in *items[,,2]] -Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. +Batas minimum dan maksimum bisa bernilai negatif, yang berarti batas dihitung dari akhir tabel. ```yuescript --- take the last 4 items +-- ambil 4 item terakhir slice = [item for item in *items[-4,-1]] ``` ```yue --- take the last 4 items +-- ambil 4 item terakhir slice = [item for item in *items[-4,-1]] ``` -The step size can also be negative, which means that the items are taken in reverse order. +Ukuran langkah juga bisa negatif, yang berarti item diambil dalam urutan terbalik. ```yuescript reverse_slice = [item for item in *items[-1,1,-1]] @@ -247,24 +247,24 @@ reverse_slice = [item for item in *items[-1,1,-1]] -### Slicing Expression +### Ekspresi Slicing -Slicing can also be used as an expression. This is useful for getting a sub-list of a table. +Slicing juga bisa digunakan sebagai ekspresi. Ini berguna untuk mendapatkan sub-list dari sebuah tabel. ```yuescript --- take the 2nd and 4th items as a new list +-- ambil item ke-2 dan ke-4 sebagai list baru sub_list = items[2, 4] --- take the last 4 items +-- ambil 4 item terakhir last_four_items = items[-4, -1] ``` ```yue --- take the 2nd and 4th items as a new list +-- ambil item ke-2 dan ke-4 sebagai list baru sub_list = items[2, 4] --- take the last 4 items +-- ambil 4 item terakhir last_four_items = items[-4, -1] ``` diff --git a/doc/docs/id-id/doc/data-structures/table-literals.md b/doc/docs/id-id/doc/data-structures/table-literals.md index c1adcab..df32f1c 100644 --- a/doc/docs/id-id/doc/data-structures/table-literals.md +++ b/doc/docs/id-id/doc/data-structures/table-literals.md @@ -1,6 +1,6 @@ -# Table Literals +# Literal Tabel -Like in Lua, tables are delimited in curly braces. +Seperti di Lua, tabel dibatasi dengan kurung kurawal. ```yuescript some_values = [1, 2, 3, 4] @@ -13,7 +13,7 @@ some_values = [1, 2, 3, 4] -Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). +Berbeda dengan Lua, assignment nilai ke sebuah kunci di tabel dilakukan dengan **:** (bukan **=**). ```yuescript some_values = { @@ -34,7 +34,7 @@ some_values = { -The curly braces can be left off if a single table of key value pairs is being assigned. +Kurung kurawal dapat dihilangkan jika hanya satu tabel pasangan key-value yang di-assign. ```yuescript profile = @@ -53,7 +53,7 @@ profile = -Newlines can be used to delimit values instead of a comma (or both): +Baris baru dapat digunakan untuk memisahkan nilai sebagai ganti koma (atau keduanya): ```yuescript values = { @@ -76,7 +76,7 @@ values = { -When creating a single line table literal, the curly braces can also be left off: +Saat membuat literal tabel satu baris, kurung kurawal juga bisa dihilangkan: ```yuescript my_function dance: "Tango", partner: "none" @@ -93,7 +93,7 @@ y = type: "dog", legs: 4, tails: 1 -The keys of a table literal can be language keywords without being escaped: +Kunci literal tabel dapat berupa kata kunci bahasa tanpa perlu di-escape: ```yuescript tbl = { @@ -112,7 +112,7 @@ tbl = { -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: +Jika Anda membangun tabel dari variabel dan ingin kunci sama dengan nama variabel, maka operator prefiks **:** dapat digunakan: ```yuescript hair = "golden" @@ -133,7 +133,7 @@ print_table :hair, :height -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. +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. ```yuescript t = { @@ -152,7 +152,7 @@ t = { -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. +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. ```yuescript some_values = [1, 2, 3, 4] diff --git a/doc/docs/id-id/doc/functions/backcalls.md b/doc/docs/id-id/doc/functions/backcalls.md index e34331e..8d542ee 100644 --- a/doc/docs/id-id/doc/functions/backcalls.md +++ b/doc/docs/id-id/doc/functions/backcalls.md @@ -1,6 +1,6 @@ -# Backcalls +# Backcall -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. +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. ```yuescript x <- f @@ -15,7 +15,7 @@ print "hello" .. x -Fat arrow functions are also available. +Fungsi panah tebal juga tersedia. ```yuescript <= f @@ -30,7 +30,7 @@ print @value -You can specify a placeholder for where you want the backcall function to go as a parameter. +Anda dapat menentukan placeholder untuk posisi fungsi backcall sebagai parameter. ```yuescript (x) <- map _, [1, 2, 3] @@ -45,7 +45,7 @@ x * 2 -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. +Jika Anda ingin menulis kode lanjutan setelah backcall, Anda dapat memisahkannya dengan pernyataan `do`. Tanda kurung dapat dihilangkan untuk fungsi panah non-tebal. ```yuescript result, msg = do diff --git a/doc/docs/id-id/doc/functions/function-literals.md b/doc/docs/id-id/doc/functions/function-literals.md index 316e07c..589a26d 100644 --- a/doc/docs/id-id/doc/functions/function-literals.md +++ b/doc/docs/id-id/doc/functions/function-literals.md @@ -1,21 +1,21 @@ -# Function Literals +# Literal Fungsi -All functions are created using a function expression. A simple function is denoted using the arrow: **->**. +Semua fungsi dibuat menggunakan ekspresi fungsi. Fungsi sederhana ditandai dengan panah: **->**. ```yuescript my_function = -> -my_function() -- call the empty function +my_function() -- memanggil fungsi kosong ``` ```yue my_function = -> -my_function() -- call the empty function +my_function() -- memanggil fungsi kosong ``` -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: +Badan fungsi bisa berupa satu pernyataan yang ditulis langsung setelah panah, atau berupa serangkaian pernyataan yang diindentasi di baris berikutnya: ```yuescript func_a = -> print "hello world" @@ -36,7 +36,7 @@ func_b = -> -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. +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. ```yuescript func_a! @@ -51,7 +51,7 @@ func_b() -Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: +Fungsi dengan argumen dapat dibuat dengan menaruh daftar nama argumen dalam tanda kurung sebelum panah: ```yuescript sum = (x, y) -> print "sum", x + y @@ -64,7 +64,7 @@ sum = (x, y) -> print "sum", x + y -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. +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. ```yuescript sum 10, 20 @@ -83,7 +83,7 @@ a b c "a", "b", "c" -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. +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. ```yuescript print "x:", sum(10, 20), "y:", sum(30, 40) @@ -96,9 +96,9 @@ print "x:", sum(10, 20), "y:", sum(30, 40) -There must not be any space between the opening parenthesis and the function. +Tidak boleh ada spasi antara tanda kurung buka dan nama fungsi. -Functions will coerce the last statement in their body into a return statement, this is called implicit return: +Fungsi akan memaksa pernyataan terakhir di badannya menjadi pernyataan return, ini disebut return implisit: ```yuescript sum = (x, y) -> x + y @@ -113,7 +113,7 @@ print "The sum is ", sum 10, 20 -And if you need to explicitly return, you can use the return keyword: +Dan jika Anda perlu return secara eksplisit, Anda bisa menggunakan kata kunci `return`: ```yuescript sum = (x, y) -> return x + y @@ -126,7 +126,7 @@ sum = (x, y) -> return x + y -Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: +Seperti di Lua, fungsi dapat mengembalikan beberapa nilai. Pernyataan terakhir harus berupa daftar nilai yang dipisahkan koma: ```yuescript mystery = (x, y) -> x + y, x - y @@ -141,9 +141,9 @@ a, b = mystery 10, 20 -## Fat Arrows +## Panah Tebal -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. +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`. ```yuescript func = (num) => @value + num @@ -156,9 +156,9 @@ func = (num) => @value + num -## Argument Defaults +## Nilai Default Argumen -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. +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. ```yuescript my_function = (name = "something", height = 100) -> @@ -175,7 +175,7 @@ my_function = (name = "something", height = 100) -> -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. +Ekspresi nilai default argumen dievaluasi di dalam badan fungsi sesuai urutan deklarasi argumen. Karena itu, nilai default dapat mengakses argumen yang dideklarasikan sebelumnya. ```yuescript some_args = (x = 100, y = x + 1000) -> @@ -190,11 +190,11 @@ some_args = (x = 100, y = x + 1000) -> -## Considerations +## Pertimbangan -Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. +Karena cara pemanggilan fungsi tanpa tanda kurung yang ekspresif, beberapa pembatasan harus diterapkan untuk menghindari ambiguitas parsing yang melibatkan spasi. -The minus sign plays two roles, a unary negation operator and a binary subtraction operator. Consider how the following examples compile: +Tanda minus memiliki dua peran, operator negasi unari dan operator pengurangan biner. Perhatikan bagaimana contoh berikut dikompilasi: ```yuescript a = x - 10 @@ -213,11 +213,11 @@ d = x- z -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. +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. -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. +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. -Where there is a space following a variable and a string literal, the function call acts as show above. The string literal belongs to any following expressions (if they exist), which serves as the argument list. +Ketika ada spasi setelah variabel dan literal string, pemanggilan fungsi bertindak seperti yang dijelaskan di atas. Literal string menjadi milik ekspresi berikutnya (jika ada), yang berfungsi sebagai daftar argumen. ```yuescript x = func"hello" + 100 @@ -232,11 +232,11 @@ y = func "hello" + 100 -## Multi-line arguments +## Argumen Multi-baris -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. +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. -If an argument list is to be continued onto the next line, the current line must end in a comma. And the following line must be indented more than the current indentation. Once indented, all other argument lines must be at the same level of indentation to be part of the argument list +Jika daftar argumen akan dilanjutkan ke baris berikutnya, baris saat ini harus diakhiri dengan koma. Dan baris berikutnya harus lebih terindentasi daripada indentasi saat ini. Setelah diindentasi, semua baris argumen lainnya harus berada pada tingkat indentasi yang sama agar menjadi bagian dari daftar argumen. ```yuescript my_func 5, 4, 3, @@ -261,7 +261,7 @@ cool_func 1, 2, -This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. +Jenis pemanggilan ini dapat dinest. Tingkat indentasi digunakan untuk menentukan argumen milik fungsi yang mana. ```yuescript my_func 5, 6, 7, @@ -280,7 +280,7 @@ my_func 5, 6, 7, -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. +Karena tabel juga menggunakan koma sebagai pemisah, sintaks indentasi ini membantu agar nilai menjadi bagian dari daftar argumen, bukan bagian dari tabel. ```yuescript x = [ @@ -301,7 +301,7 @@ x = [ -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. +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. ```yuescript y = [ my_func 1, 2, 3, @@ -320,7 +320,7 @@ y = [ my_func 1, 2, 3, -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: +Hal yang sama juga dapat dilakukan pada pernyataan tingkat blok lainnya seperti kondisional. Kita bisa menggunakan tingkat indentasi untuk menentukan nilai milik pernyataan apa: ```yuescript if func 1, 2, 3, @@ -353,13 +353,13 @@ if func 1, 2, 3, -## Parameter Destructuring +## Destrukturisasi Parameter -YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: +YueScript kini mendukung destrukturisasi parameter fungsi ketika argumen berupa objek. Dua bentuk destrukturisasi literal tabel tersedia: -* **Curly-brace wrapped literals/object parameters**, allowing optional default values when fields are missing (e.g., `{:a, :b}`, `{a: a1 = 123}`). +* **Literal berkurung kurawal/parameter objek**, memungkinkan nilai default opsional ketika field hilang (misalnya, `{:a, :b}`, `{a: a1 = 123}`). -* **Unwrapped simple table syntax**, starting with a sequence of key-value or shorthand bindings and continuing until another expression terminates it (e.g., `:a, b: b1, :c`). This form extracts multiple fields from the same object. +* **Sintaks tabel sederhana tanpa pembungkus**, dimulai dengan urutan key-value atau binding singkat dan berlanjut sampai ekspresi lain menghentikannya (misalnya, `:a, b: b1, :c`). Bentuk ini mengekstrak beberapa field dari objek yang sama. ```yuescript f1 = (:a, :b, :c) -> @@ -390,9 +390,9 @@ f2 arg1, arg2 -## Prefixed Return Expression +## Ekspresi Return Berawalan -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: +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: ```yuescript findFirstEven = (list): nil -> @@ -415,7 +415,7 @@ findFirstEven = (list): nil -> -This is equivalent to: +Ini setara dengan: ```yuescript findFirstEven = (list) -> @@ -440,11 +440,11 @@ findFirstEven = (list) -> -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. +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. -## Named Varargs +## Varargs Bernama -You can use the `(...t) ->` syntax to automatically store varargs into a named table. This table will contain all passed arguments (including `nil` values), and the `n` field of the table will store the actual number of arguments passed (including `nil` values). +Anda dapat menggunakan sintaks `(...t) ->` untuk otomatis menyimpan varargs ke tabel bernama. Tabel ini berisi semua argumen yang diteruskan (termasuk nilai `nil`), dan field `n` pada tabel menyimpan jumlah argumen yang benar-benar diteruskan (termasuk nilai `nil`). ```yuescript f = (...t) -> @@ -457,7 +457,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Menangani kasus dengan nilai nil process = (...args) -> sum = 0 for i = 1, args.n @@ -480,7 +480,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Menangani kasus dengan nilai nil process = (...args) -> sum = 0 for i = 1, args.n diff --git a/doc/docs/id-id/doc/functions/function-stubs.md b/doc/docs/id-id/doc/functions/function-stubs.md index 57a8b0c..57ed5c1 100644 --- a/doc/docs/id-id/doc/functions/function-stubs.md +++ b/doc/docs/id-id/doc/functions/function-stubs.md @@ -1,10 +1,10 @@ -# Function Stubs +# Stub Fungsi -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. +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. -The function stub syntax is a shorthand for creating a new closure function that bundles both the object and function. This new function calls the wrapped function in the correct context of the object. +Sintaks stub fungsi adalah singkatan untuk membuat fungsi closure baru yang menggabungkan objek dan fungsi. Fungsi baru ini memanggil fungsi yang dibungkus dalam konteks objek yang benar. -Its syntax is the same as calling an instance method with the \ operator but with no argument list provided. +Sintaksnya sama seperti memanggil method instance dengan operator `\`, tetapi tanpa menyediakan daftar argumen. ```yuescript my_object = { @@ -16,12 +16,12 @@ run_callback = (func) -> print "running callback..." func! --- this will not work: --- the function has to no reference to my_object +-- ini tidak akan berfungsi: +-- fungsi tidak memiliki referensi ke my_object run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- sintaks stub fungsi +-- memungkinkan kita membundel objek ke fungsi baru run_callback my_object\write ``` @@ -36,12 +36,12 @@ run_callback = (func) -> print "running callback..." func! --- this will not work: --- the function has to no reference to my_object +-- ini tidak akan berfungsi: +-- fungsi tidak memiliki referensi ke my_object run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- sintaks stub fungsi +-- memungkinkan kita membundel objek ke fungsi baru run_callback my_object\write ``` diff --git a/doc/docs/id-id/doc/getting-started/installation.md b/doc/docs/id-id/doc/getting-started/installation.md index a93ddfd..2809cca 100644 --- a/doc/docs/id-id/doc/getting-started/installation.md +++ b/doc/docs/id-id/doc/getting-started/installation.md @@ -1,43 +1,43 @@ -# Installation +# Instalasi -## Lua Module +## Modul Lua -Install [luarocks](https://luarocks.org), a package manager for Lua modules. Then install it as a Lua module and executable with: +Instal [luarocks](https://luarocks.org), manajer paket untuk modul Lua. Lalu instal sebagai modul Lua dan executable dengan: ```shell luarocks install yuescript ``` -Or you can build `yue.so` file with: +Atau Anda dapat membangun file `yue.so` dengan: ```shell make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua ``` -Then get the binary file from path **bin/shared/yue.so**. +Lalu ambil file biner dari path **bin/shared/yue.so**. -## Build Binary Tool +## Membangun Tool Biner -Clone this repo, then build and install executable with: +Klon repo ini, lalu bangun dan instal executable dengan: ```shell make install ``` -Build YueScript tool without macro feature: +Bangun tool YueScript tanpa fitur macro: ```shell make install NO_MACRO=true ``` -Build YueScript tool without built-in Lua binary: +Bangun tool YueScript tanpa biner Lua bawaan: ```shell make install NO_LUA=true ``` -## Download Precompiled Binary +## Unduh Biner Pra-kompilasi -You can download precompiled binary files, including binary executable files compatible with different Lua versions and library files. +Anda dapat mengunduh file biner pra-kompilasi, termasuk file executable biner yang kompatibel dengan berbagai versi Lua dan file library. -Download precompiled binary files from [here](https://github.com/IppClub/YueScript/releases). +Unduh file biner pra-kompilasi dari [sini](https://github.com/IppClub/YueScript/releases). diff --git a/doc/docs/id-id/doc/getting-started/introduction.md b/doc/docs/id-id/doc/getting-started/introduction.md index a9a9389..c2fc236 100644 --- a/doc/docs/id-id/doc/getting-started/introduction.md +++ b/doc/docs/id-id/doc/getting-started/introduction.md @@ -1,10 +1,10 @@ -# Introduction +# Pendahuluan -YueScript is a dynamic language that compiles to Lua. And it's a [MoonScript](https://github.com/leafo/moonscript) dialect. The codes written in YueScript are expressive and extremely concise. And it is suitable for writing some changing application logic with more maintainable codes and runs in a Lua embeded environment such as games or website servers. +YueScript adalah bahasa dinamis yang dikompilasi ke Lua, dan merupakan dialek [MoonScript](https://github.com/leafo/moonscript). Kode yang ditulis dengan YueScript ekspresif dan sangat ringkas. YueScript cocok untuk menulis logika aplikasi yang sering berubah dengan kode yang lebih mudah dipelihara, serta berjalan di lingkungan embed Lua seperti game atau server situs web. -Yue (月) is the name of moon in Chinese and it's pronounced as [jyɛ]. +Yue (月) adalah kata untuk bulan dalam bahasa Tionghoa dan diucapkan sebagai [jyɛ]. -## An Overview of YueScript +## Ikhtisar YueScript ```yuescript -- import syntax @@ -48,7 +48,7 @@ with apple p .size, .color, . if .<>? -- js-like export syntax -export 🌛 = "月之脚本" +export 🌛 = "Skrip Bulan" ``` @@ -95,11 +95,11 @@ with apple p .size, .color, . if .<>? -- js-like export syntax -export 🌛 = "月之脚本" +export 🌛 = "Skrip Bulan" ``` -## About Dora SSR +## Tentang Dora SSR -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. \ No newline at end of file +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. diff --git a/doc/docs/id-id/doc/getting-started/usage.md b/doc/docs/id-id/doc/getting-started/usage.md index 45161c6..85cad07 100644 --- a/doc/docs/id-id/doc/getting-started/usage.md +++ b/doc/docs/id-id/doc/getting-started/usage.md @@ -1,20 +1,20 @@ -# Usage +# Penggunaan -## Lua Module +## Modul Lua -Use YueScript module in Lua: +Gunakan modul YueScript di Lua: -* **Case 1** +* **Kasus 1** - Require "your_yuescript_entry.yue" in Lua. + Require "your_yuescript_entry.yue" di Lua. ```Lua require("yue")("your_yuescript_entry") ``` - And this code still works when you compile "your_yuescript_entry.yue" to "your_yuescript_entry.lua" in the same path. In the rest YueScript files just use the normal **require** or **import**. The code line numbers in error messages will also be handled correctly. + Dan kode ini tetap bekerja ketika Anda mengompilasi "your_yuescript_entry.yue" menjadi "your_yuescript_entry.lua" di path yang sama. Pada file YueScript lainnya cukup gunakan **require** atau **import** biasa. Nomor baris pada pesan error juga akan ditangani dengan benar. -* **Case 2** +* **Kasus 2** - Require YueScript module and rewite message by hand. + Require modul YueScript dan tulis ulang pesan secara manual. ```lua local yue = require("yue") @@ -26,9 +26,9 @@ Use YueScript module in Lua: end) ``` -* **Case 3** +* **Kasus 3** - Use the YueScript compiler function in Lua. + Gunakan fungsi kompiler YueScript di Lua. ```lua local yue = require("yue") @@ -48,64 +48,65 @@ Use YueScript module in Lua: }) ``` -## YueScript Tool +## Tool YueScript -Use YueScript tool with: +Gunakan tool YueScript dengan: ```shell > yue -h -Usage: yue - [options] [] ... - yue -e [args...] - yue -w [] [options] - yue - - -Notes: - - '-' / '--' must be the first and only argument. - - '-o/--output' can not be used with multiple input files. - - '-w/--watch' can not be used with file input (directory only). - - with '-e/--execute', remaining tokens are treated as script args. - -Options: - -h, --help Show this help message and exit. - -e , --execute Execute a file or raw codes - -m, --minify Generate minified codes - -r, --rewrite Rewrite output to match original line numbers +Penggunaan: yue + [opsi] [] ... + yue -e [argumen...] + yue -w [] [opsi] + yue - + +Catatan: + - '-' / '--' harus menjadi argumen pertama dan satu-satunya. + - '-o/--output' tidak dapat digunakan dengan beberapa file input. + - '-w/--watch' tidak dapat digunakan dengan file input (khusus direktori). + - dengan '-e/--execute', token sisanya dianggap sebagai argumen skrip. + +Opsi: + -h, --help Tampilkan pesan bantuan ini dan keluar. + -e , --execute Eksekusi file atau kode mentah + -m, --minify Menghasilkan kode yang sudah diminimasi + -r, --rewrite Tulis ulang output agar sesuai dengan nomor baris asal -t , --output-to - Specify where to place compiled files - -o , --output Write output to file - -p, --print Write output to standard out - -b, --benchmark Dump compile time (doesn't write output) - -g, --globals Dump global variables used in NAME LINE COLUMN - -s, --spaces Use spaces in generated codes instead of tabs - -l, --line-numbers Write line numbers from source codes - -j, --no-implicit-return Disable implicit return at end of file - -c, --reserve-comments Reserve comments before statement from source codes + Tentukan lokasi untuk menaruh file hasil kompilasi + -o , --output Tulis output ke file + -p, --print Tulis output ke standar output + -b, --benchmark Tampilkan waktu kompilasi (tanpa menulis output) + -g, --globals Tampilkan variabel global yang digunakan dalam FORMAT NAMA BARIS KOLOM + -s, --spaces Pakai spasi di kode hasil kompilasi (bukan tab) + -l, --line-numbers Tulis nomor baris dari kode sumber + -j, --no-implicit-return Nonaktifkan return implisit di akhir file + -c, --reserve-comments Pertahankan komentar sebelum pernyataan dari kode sumber -w [], --watch [] - Watch changes and compile every file under directory - -v, --version Print version - - Read from standard in, print to standard out - (Must be first and only argument) - -- Same as '-' (kept for backward compatibility) - - --target Specify the Lua version that codes will be generated to - (version can only be 5.1 to 5.5) - --path Append an extra Lua search path string to package.path - --= Pass compiler option in key=value form (existing behavior) - - Execute without options to enter REPL, type symbol '$' - in a single line to start/stop multi-line mode + Pantau perubahan dan kompilasi setiap file di bawah direktori + -v, --version Tampilkan versi + - Baca dari standar input, tulis ke standar output + (harus menjadi argumen pertama dan satu-satunya) + -- Sama dengan '-', dipertahankan untuk kompatibilitas lama + + --target Tentukan versi Lua yang akan dihasilkan kodenya + (versi hanya bisa dari 5.1 sampai 5.5) + --path Tambahkan path pencarian Lua tambahan ke package.path + --= Kirim opsi kompilasi dalam bentuk key=value (perilaku standar) + + Jalankan tanpa opsi untuk masuk ke REPL, ketik simbol '$' + dalam satu baris untuk memulai/mengakhiri mode multi-baris ``` -Use cases: -Recursively compile every YueScript file with extension **.yue** under current path: **yue .** +Gunakan kasus: -Compile and save results to a target path: **yue -t /target/path/ .** +Kompilasi semua file YueScript dengan ekstensi **.yue** secara rekursif di bawah path saat ini: **yue .** -Compile and reserve debug info: **yue -l .** +Kompilasi dan simpan hasil ke path target: **yue -t /target/path/ .** -Compile and generate minified codes: **yue -m .** +Kompilasi dan pertahankan info debug: **yue -l .** -Execute raw codes: **yue -e 'print 123'** +Kompilasi dan hasilkan kode yang diminisasi: **yue -m .** -Execute a YueScript file: **yue -e main.yue** +Eksekusi kode mentah: **yue -e 'print 123'** + +Eksekusi file YueScript: **yue -e main.yue** diff --git a/doc/docs/id-id/doc/index.md b/doc/docs/id-id/doc/index.md index b7f609b..5df2cc3 100755 --- a/doc/docs/id-id/doc/index.md +++ b/doc/docs/id-id/doc/index.md @@ -1,11 +1,11 @@ --- -title: Reference +title: Referensi --- -# YueScript Documentation +# Dokumentasi YueScript logo -Welcome to the YueScript official documentation!
-Here you can find the language features, usage, reference examples and resources.
-Please select a chapter from the sidebar to start learning about YueScript. +Selamat datang di dokumentasi resmi YueScript!
+Di sini Anda dapat menemukan fitur bahasa, penggunaan, contoh referensi, dan sumber daya.
+Silakan pilih bab dari sidebar untuk mulai mempelajari YueScript. diff --git a/doc/docs/id-id/doc/language-basics/attributes.md b/doc/docs/id-id/doc/language-basics/attributes.md index e6fd5a7..5b92947 100644 --- a/doc/docs/id-id/doc/language-basics/attributes.md +++ b/doc/docs/id-id/doc/language-basics/attributes.md @@ -1,6 +1,6 @@ -# Attributes +# Atribut -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. +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. ```yuescript const a = 123 @@ -15,7 +15,7 @@ close _ = : -> print "Out of scope." -You can do desctructuring with variables attributed as constant. +Anda dapat melakukan destrukturisasi dengan variabel yang diberi atribut sebagai konstanta. ```yuescript const {:a, :b, c, d} = tb @@ -30,7 +30,7 @@ const {:a, :b, c, d} = tb -You can also declare a global variable to be `const`. +Anda juga bisa mendeklarasikan variabel global sebagai `const`. ```yuescript global const Constant = 123 diff --git a/doc/docs/id-id/doc/language-basics/comment.md b/doc/docs/id-id/doc/language-basics/comment.md index b67c97d..99f7b51 100644 --- a/doc/docs/id-id/doc/language-basics/comment.md +++ b/doc/docs/id-id/doc/language-basics/comment.md @@ -1,13 +1,13 @@ -# Comment +# Komentar ```yuescript --- I am a comment +-- Saya adalah komentar str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Ini komentar multi-baris. +Tidak masalah. +]] strA \ -- komentar 1 + .. strB \ -- komentar 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" @@ -15,13 +15,13 @@ func --[[port]] 3000, --[[ip]] "192.168.1.1" ```yue --- I am a comment +-- Saya adalah komentar str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Ini komentar multi-baris. +Tidak masalah. +]] strA \ -- komentar 1 + .. strB \ -- komentar 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" diff --git a/doc/docs/id-id/doc/language-basics/literals.md b/doc/docs/id-id/doc/language-basics/literals.md index e097c62..c17c310 100644 --- a/doc/docs/id-id/doc/language-basics/literals.md +++ b/doc/docs/id-id/doc/language-basics/literals.md @@ -1,15 +1,15 @@ -# Literals +# Literal -All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. +Semua literal primitif di Lua dapat digunakan. Ini berlaku untuk angka, string, boolean, dan **nil**. -Unlike Lua, Line breaks are allowed inside of single and double quote strings without an escape sequence: +Berbeda dengan Lua, pemisah baris diizinkan di dalam string bertanda kutip tunggal maupun ganda tanpa urutan escape: ```yuescript some_string = "Here is a string that has a line break in it." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. +-- Anda dapat mencampur ekspresi ke dalam literal string dengan sintaks #{}. +-- Interpolasi string hanya tersedia pada string dengan tanda kutip ganda. print "I am #{math.random! * 100}% sure." ``` @@ -18,16 +18,16 @@ print "I am #{math.random! * 100}% sure." some_string = "Here is a string that has a line break in it." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. +-- Anda dapat mencampur ekspresi ke dalam literal string dengan sintaks #{}. +-- Interpolasi string hanya tersedia pada string dengan tanda kutip ganda. print "I am #{math.random! * 100}% sure." ``` -## Number Literals +## Literal Angka -You can use underscores in a number literal to increase readability. +Anda bisa menggunakan garis bawah pada literal angka untuk meningkatkan keterbacaan. ```yuescript integer = 1_000_000 @@ -44,9 +44,9 @@ binary = 0B10011 -## YAML Multiline String +## String Multibaris YAML -The `|` prefix introduces a YAML-style multiline string literal: +Prefiks `|` memperkenalkan literal string multibaris bergaya YAML: ```yuescript str = | @@ -67,9 +67,9 @@ str = | -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)`. +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)`. -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. +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. ```yuescript fn = -> @@ -90,9 +90,9 @@ fn = -> -Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. +Indentasi internal dipertahankan relatif terhadap prefiks umum yang dihapus, sehingga struktur bertingkat tetap rapi. -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. +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. ```yuescript str = | diff --git a/doc/docs/id-id/doc/language-basics/operator.md b/doc/docs/id-id/doc/language-basics/operator.md index 9a2e89b..f3fe092 100644 --- a/doc/docs/id-id/doc/language-basics/operator.md +++ b/doc/docs/id-id/doc/language-basics/operator.md @@ -1,6 +1,6 @@ # Operator -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. +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. ```yuescript tb\func! if tb ~= nil @@ -15,9 +15,9 @@ tb::func! if tb != nil -## Chaining Comparisons +## Perbandingan Berantai -Comparisons can be arbitrarily chained: +Perbandingan bisa dirantai secara bebas: ```yuescript print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 @@ -40,7 +40,7 @@ print 1 <= a <= 10 -Note the evaluation behavior of chained comparisons: +Perhatikan perilaku evaluasi perbandingan berantai: ```yuescript v = (x) -> @@ -91,11 +91,11 @@ print v(1) > v(2) <= v(3) -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. +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. -## Table Appending +## Menambahkan ke Tabel -The **[] =** operator is used to append values to tables. +Operator **[] =** digunakan untuk menambahkan nilai ke tabel. ```yuescript tab = [] @@ -110,13 +110,13 @@ tab[] = "Value" -You can also use the spread operator `...` to append all elements from one list to another: +Anda juga bisa memakai operator spread `...` untuk menambahkan semua elemen dari satu list ke list lain: ```yuescript tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA sekarang [1, 2, 3, 4, 5, 6] ``` @@ -124,14 +124,14 @@ tbA[] = ...tbB tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA sekarang [1, 2, 3, 4, 5, 6] ``` -## Table Spreading +## Penyebaran Tabel -You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. +Anda bisa menggabungkan tabel array atau tabel hash menggunakan operator spread `...` sebelum ekspresi di literal tabel. ```yuescript parts = @@ -170,9 +170,9 @@ merge = {...a, ...b} -## Table Reversed Indexing +## Indeks Balik Tabel -You can use the **#** operator to get the last elements of a table. +Anda dapat menggunakan operator **#** untuk mendapatkan elemen terakhir dari tabel. ```yuescript last = data.items[#] @@ -191,11 +191,11 @@ data.items[#] = 1 ## Metatable -The **<>** operator can be used as a shortcut for metatable manipulation. +Operator **<>** dapat digunakan sebagai pintasan untuk manipulasi metatable. -### Metatable Creation +### Pembuatan Metatable -Create normal table with empty bracekets **<>** or metamethod key which is surrounded by **<>**. +Buat tabel normal dengan tanda kurung siku kosong **<>** atau kunci metamethod yang dikelilingi oleh **<>**. ```yuescript mt = {} @@ -203,7 +203,7 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- set field dengan variabel bernama sama b = :, value: 2 c = : mt.__add, value: 3 @@ -220,7 +220,7 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- set field dengan variabel bernama sama b = :, value: 2 c = : mt.__add, value: 3 @@ -232,12 +232,12 @@ close _ = : -> print "out of scope" -### Metatable Accessing +### Mengakses Metatable -Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. +Akses metatable dengan **<>**, nama metamethod yang dikelilingi **<>**, atau menulis ekspresi di dalam **<>**. ```yuescript --- create with metatable containing field "value" +-- dibuat dengan metatable yang berisi field "value" tb = <"value">: 123 tb. = tb.<> print tb.value @@ -248,7 +248,7 @@ print tb.item ```yue --- create with metatable containing field "value" +-- dibuat dengan metatable yang berisi field "value" tb = <"value">: 123 tb. = tb.<> print tb.value @@ -258,9 +258,9 @@ print tb.item -### Metatable Destructure +### Destrukturisasi Metatable -Destruct metatable with metamethod key surrounded by **<>**. +Destrukturisasi metatable dengan kunci metamethod yang dikelilingi **<>**. ```yuescript {item, :new, :, : getter} = tb @@ -275,9 +275,9 @@ print item, new, close, getter -## Existence +## Keberadaan -The **?** operator can be used in a variety of contexts to check for existence. +Operator **?** dapat digunakan dalam berbagai konteks untuk memeriksa keberadaan. ```yuescript func?! @@ -314,14 +314,14 @@ with? io.open "test.txt", "w" ## Piping -Instead of a series of nested function calls, you can pipe values with operator **|>**. +Sebagai ganti serangkaian pemanggilan fungsi bersarang, Anda bisa mengalirkan nilai dengan operator **|>**. ```yuescript "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder +1 |> print 2 -- sisipkan nilai pipe sebagai argumen pertama +2 |> print 1, _, 3 -- pipe dengan placeholder --- pipe expression in multiline +-- ekspresi pipe multi-baris readFile "example.txt" |> extract language, {} |> parse language @@ -333,9 +333,9 @@ readFile "example.txt" ```yue "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder --- pipe expression in multiline +1 |> print 2 -- sisipkan nilai pipe sebagai argumen pertama +2 |> print 1, _, 3 -- pipe dengan placeholder +-- ekspresi pipe multi-baris readFile "example.txt" |> extract language, {} |> parse language @@ -348,7 +348,7 @@ readFile "example.txt" ## Nil Coalescing -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. +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. ```yuescript local a, b, c, d a = b ?? c ?? d @@ -367,31 +367,31 @@ a ??= false -## Implicit Object +## Objek Implisit -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. +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. ```yuescript --- assignment with implicit object +-- assignment dengan objek implisit list = * 1 * 2 * 3 --- function call with implicit object +-- pemanggilan fungsi dengan objek implisit func * 1 * 2 * 3 --- return with implicit object +-- return dengan objek implisit f = -> return * 1 * 2 * 3 --- table with implicit object +-- tabel dengan objek implisit tb = name: "abc" @@ -416,26 +416,26 @@ tb = ```yue --- assignment with implicit object +-- assignment dengan objek implisit list = * 1 * 2 * 3 --- function call with implicit object +-- pemanggilan fungsi dengan objek implisit func * 1 * 2 * 3 --- return with implicit object +-- return dengan objek implisit f = -> return * 1 * 2 * 3 --- table with implicit object +-- tabel dengan objek implisit tb = name: "abc" diff --git a/doc/docs/id-id/doc/language-basics/whitespace.md b/doc/docs/id-id/doc/language-basics/whitespace.md index d742a2b..bdc124e 100644 --- a/doc/docs/id-id/doc/language-basics/whitespace.md +++ b/doc/docs/id-id/doc/language-basics/whitespace.md @@ -1,10 +1,10 @@ -# Whitespace +# Spasi Kosong -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. +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. -## Statement Separator +## Pemisah Pernyataan -A statement normally ends at a line break. You can also use a semicolon `;` to explicitly terminate a statement, which allows writing multiple statements on the same line: +Sebuah pernyataan biasanya berakhir pada pergantian baris. Anda juga bisa memakai titik koma `;` untuk mengakhiri pernyataan secara eksplisit, yang memungkinkan menulis beberapa pernyataan pada satu baris: ```yuescript a = 1; b = 2; print a + b @@ -17,9 +17,9 @@ a = 1; b = 2; print a + b -## Multiline Chaining +## Rantai Multibaris -You can write multi-line chaining function calls with a same indent. +Anda bisa menulis pemanggilan fungsi berantai multi-baris dengan indentasi yang sama. ```yuescript Rx.Observable diff --git a/doc/docs/id-id/doc/objects/object-oriented-programming.md b/doc/docs/id-id/doc/objects/object-oriented-programming.md index 6a8559e..96c19d7 100644 --- a/doc/docs/id-id/doc/objects/object-oriented-programming.md +++ b/doc/docs/id-id/doc/objects/object-oriented-programming.md @@ -1,8 +1,8 @@ -# Object Oriented Programming +# Pemrograman Berorientasi Objek -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. +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. -A simple class: +Kelas sederhana: ```yuescript class Inventory @@ -31,15 +31,15 @@ class Inventory -A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. +Kelas dideklarasikan dengan pernyataan `class` diikuti deklarasi mirip tabel di mana semua method dan properti dicantumkan. -The new property is special in that it will become the constructor. +Properti `new` bersifat khusus karena akan menjadi konstruktor. -Notice how all the methods in the class use the fat arrow function syntax. When calling methods on a instance, the instance itself is sent in as the first argument. The fat arrow handles the creation of a self argument. +Perhatikan bahwa semua method di kelas menggunakan sintaks fungsi panah tebal. Saat memanggil method pada instance, instance itu sendiri dikirim sebagai argumen pertama. Panah tebal menangani pembuatan argumen `self`. -The @ prefix on a variable name is shorthand for self.. @items becomes self.items. +Prefiks `@` pada nama variabel adalah singkatan untuk `self.`. `@items` menjadi `self.items`. -Creating an instance of the class is done by calling the name of the class as a function. +Membuat instance kelas dilakukan dengan memanggil nama kelas sebagai fungsi. ```yuescript inv = Inventory! @@ -56,11 +56,11 @@ inv\add_item "pants" -Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. +Karena instance kelas perlu dikirim ke method saat dipanggil, operator `\` digunakan. -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. +Semua properti kelas dibagikan di antara instance. Ini baik untuk fungsi, tetapi untuk jenis objek lain dapat menimbulkan hasil yang tidak diinginkan. -Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another: +Pertimbangkan contoh di bawah ini, properti `clothes` dibagikan di antara semua instance, sehingga perubahan di satu instance akan terlihat di instance lainnya: ```yuescript class Person @@ -74,7 +74,7 @@ b = Person! a\give_item "pants" b\give_item "shirt" --- will print both pants and shirt +-- akan mencetak pants dan shirt print item for item in *a.clothes ``` @@ -91,13 +91,13 @@ b = Person! a\give_item "pants" b\give_item "shirt" --- will print both pants and shirt +-- akan mencetak pants dan shirt print item for item in *a.clothes ``` -The proper way to avoid this problem is to create the mutable state of the object in the constructor: +Cara yang benar untuk menghindari masalah ini adalah membuat state yang dapat berubah di konstruktor: ```yuescript class Person @@ -114,9 +114,9 @@ class Person -## Inheritance +## Pewarisan -The extends keyword can be used in a class declaration to inherit the properties and methods from another class. +Kata kunci `extends` dapat digunakan dalam deklarasi kelas untuk mewarisi properti dan method dari kelas lain. ```yuescript class BackPack extends Inventory @@ -137,18 +137,18 @@ class BackPack extends Inventory -Here we extend our Inventory class, and limit the amount of items it can carry. +Di sini kita memperluas kelas Inventory, dan membatasi jumlah item yang bisa dibawa. -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. +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. -Whenever a class inherits from another, it sends a message to the parent class by calling the method __inherited on the parent class if it exists. The function receives two arguments, the class that is being inherited and the child class. +Setiap kali sebuah kelas mewarisi dari kelas lain, ia mengirim pesan ke kelas induk dengan memanggil method `__inherited` pada kelas induk jika ada. Fungsi menerima dua argumen, kelas yang diwarisi dan kelas anak. ```yuescript class Shelf @__inherited: (child) => print @__name, "was inherited by", child.__name --- will print: Shelf was inherited by Cupboard +-- akan mencetak: Shelf was inherited by Cupboard class Cupboard extends Shelf ``` @@ -158,7 +158,7 @@ class Shelf @__inherited: (child) => print @__name, "was inherited by", child.__name --- will print: Shelf was inherited by Cupboard +-- akan mencetak: Shelf was inherited by Cupboard class Cupboard extends Shelf ``` @@ -166,27 +166,27 @@ class Cupboard extends Shelf ## Super -**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. +**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. -When called as a function, it will call the function of the same name in the parent class. The current self will automatically be passed as the first argument. (As seen in the inheritance example above) +Ketika dipanggil sebagai fungsi, ia akan memanggil fungsi dengan nama yang sama di kelas induk. `self` saat ini akan otomatis dikirim sebagai argumen pertama. (Seperti pada contoh pewarisan di atas) -When super is used as a normal value, it is a reference to the parent class object. +Ketika `super` digunakan sebagai nilai normal, ia merupakan referensi ke objek kelas induk. -It can be accessed like any of object in order to retrieve values in the parent class that might have been shadowed by the child class. +Ia dapat diakses seperti objek biasa untuk mengambil nilai di kelas induk yang mungkin tertutup oleh kelas anak. -When the \ calling operator is used with super, self is inserted as the first argument instead of the value of super itself. When using . to retrieve a function, the raw function is returned. +Ketika operator pemanggilan `\` digunakan dengan `super`, `self` disisipkan sebagai argumen pertama alih-alih nilai `super` itu sendiri. Saat menggunakan `.` untuk mengambil fungsi, fungsi mentah dikembalikan. -A few examples of using super in different ways: +Beberapa contoh penggunaan `super` dengan cara berbeda: ```yuescript class MyClass extends ParentClass a_method: => - -- the following have the same effect: + -- berikut memiliki efek yang sama: super "hello", "world" super\a_method "hello", "world" super.a_method self, "hello", "world" - -- super as a value is equal to the parent class: + -- super sebagai nilai sama dengan kelas induk: assert super == ParentClass ``` @@ -194,28 +194,28 @@ class MyClass extends ParentClass ```yue class MyClass extends ParentClass a_method: => - -- the following have the same effect: + -- berikut memiliki efek yang sama: super "hello", "world" super\a_method "hello", "world" super.a_method self, "hello", "world" - -- super as a value is equal to the parent class: + -- super sebagai nilai sama dengan kelas induk: assert super == ParentClass ``` -**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. +**super** juga dapat digunakan di sisi kiri Function Stub. Perbedaan utamanya adalah, alih-alih fungsi hasil terikat pada nilai `super`, fungsi terikat pada `self`. -## Types +## Tipe -Every instance of a class carries its type with it. This is stored in the special __class property. This property holds the class object. The class object is what we call to build a new instance. We can also index the class object to retrieve class methods and properties. +Setiap instance kelas membawa tipenya sendiri. Ini disimpan di properti khusus `__class`. Properti ini memuat objek kelas. Objek kelas adalah yang kita panggil untuk membuat instance baru. Kita juga dapat mengindeks objek kelas untuk mengambil method dan properti kelas. ```yuescript b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- mencetak 10 ``` @@ -223,45 +223,45 @@ print BackPack.size -- prints 10 b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- mencetak 10 ``` -## Class Objects +## Objek Kelas -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. +Objek kelas adalah yang kita buat saat menggunakan pernyataan `class`. Objek kelas disimpan dalam variabel dengan nama yang sama dengan kelas. -The class object can be called like a function in order to create new instances. That's how we created instances of classes in the examples above. +Objek kelas dapat dipanggil seperti fungsi untuk membuat instance baru. Begitulah cara kita membuat instance kelas pada contoh di atas. -A class is made up of two tables. The class table itself, and the base table. The base is used as the metatable for all the instances. All properties listed in the class declaration are placed in the base. +Sebuah kelas terdiri dari dua tabel: tabel kelas itu sendiri dan tabel base. Base digunakan sebagai metatable untuk semua instance. Semua properti yang dicantumkan dalam deklarasi kelas ditempatkan di base. -The class object's metatable reads properties from the base if they don't exist in the class object. This means we can access functions and properties directly from the class. +Metatable objek kelas membaca properti dari base jika tidak ada di objek kelas. Ini berarti kita dapat mengakses fungsi dan properti langsung dari kelas. -It is important to note that assigning to the class object does not assign into the base, so it's not a valid way to add new methods to instances. Instead the base must explicitly be changed. See the __base field below. +Penting untuk dicatat bahwa assignment ke objek kelas tidak meng-assign ke base, sehingga itu bukan cara yang valid untuk menambahkan method baru ke instance. Sebagai gantinya, base harus diubah secara eksplisit. Lihat field `__base` di bawah. -The class object has a couple special properties: +Objek kelas memiliki beberapa properti khusus: -The name of the class as when it was declared is stored as a string in the __name field of the class object. +Nama kelas saat dideklarasikan disimpan sebagai string di field `__name` pada objek kelas. ```yuescript -print BackPack.__name -- prints Backpack +print BackPack.__name -- mencetak Backpack ``` ```yue -print BackPack.__name -- prints Backpack +print BackPack.__name -- mencetak Backpack ``` -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. +Objek base disimpan di `__base`. Kita dapat memodifikasi tabel ini untuk menambahkan fungsionalitas ke instance yang sudah dibuat maupun yang akan dibuat. -If the class extends from anything, the parent class object is stored in __parent. +Jika kelas memperluas kelas lain, objek kelas induk disimpan di `__parent`. -## Class Variables +## Variabel Kelas -We can create variables directly in the class object instead of in the base by using @ in the front of the property name in a class declaration. +Kita dapat membuat variabel langsung di objek kelas alih-alih di base dengan menggunakan `@` di depan nama properti pada deklarasi kelas. ```yuescript class Things @@ -269,7 +269,7 @@ class Things Things\some_func! --- class variables not visible in instances +-- variabel kelas tidak terlihat pada instance assert Things().some_func == nil ``` @@ -280,13 +280,13 @@ class Things Things\some_func! --- class variables not visible in instances +-- variabel kelas tidak terlihat pada instance assert Things().some_func == nil ``` -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. +Dalam ekspresi, kita dapat menggunakan `@@` untuk mengakses nilai yang disimpan di `__class` milik `self`. Jadi, `@@hello` adalah singkatan dari `self.__class.hello`. ```yuescript class Counter @@ -298,7 +298,7 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- mencetak 2 ``` @@ -312,12 +312,12 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- mencetak 2 ``` -The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. +Semantik pemanggilan `@@` mirip dengan `@`. Memanggil nama `@@` akan meneruskan kelas sebagai argumen pertama menggunakan sintaks kolon Lua. ```yuescript @@hello 1,2,3,4 @@ -330,11 +330,11 @@ The calling semantics of @@ are similar to @. Calling a @@ name will pass the cl -## Class Declaration Statements +## Pernyataan Deklarasi Kelas -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. +Di dalam badan deklarasi kelas, kita bisa memiliki ekspresi normal selain pasangan key/value. Dalam konteks ini, `self` sama dengan objek kelas. -Here is an alternative way to create a class variable compared to what's described above: +Berikut cara alternatif untuk membuat variabel kelas dibandingkan yang dijelaskan di atas: ```yuescript class Things @@ -349,9 +349,9 @@ class Things -These expressions are executed after all the properties have been added to the base. +Ekspresi ini dieksekusi setelah semua properti ditambahkan ke base. -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: +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: ```yuescript class MoreThings @@ -374,11 +374,11 @@ class MoreThings -## @ and @@ Values +## Nilai @ dan @@ -When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.__class. +Ketika `@` dan `@@` diprefiks di depan sebuah nama, masing-masing merepresentasikan nama tersebut yang diakses di `self` dan `self.__class`. -If they are used all by themselves, they are aliases for self and self.__class. +Jika digunakan sendirian, keduanya adalah alias untuk `self` dan `self.__class`. ```yuescript assert @ == self @@ -393,7 +393,7 @@ assert @@ == self.__class -For example, a quick way to create a new instance of the same class from an instance method using @@: +Contohnya, cara cepat untuk membuat instance baru dari kelas yang sama dari method instance menggunakan `@@`: ```yuescript some_instance_method = (...) => @@ ... @@ -406,15 +406,15 @@ some_instance_method = (...) => @@ ... -## Constructor Property Promotion +## Promosi Properti Konstruktor -To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: +Untuk mengurangi boilerplate saat mendefinisikan objek nilai sederhana, Anda dapat menulis kelas sederhana seperti: ```yuescript class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- Yang merupakan singkatan dari class Something new: (foo, bar, biz, baz) => @@ -429,7 +429,7 @@ class Something class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- Yang merupakan singkatan dari class Something new: (foo, bar, biz, baz) => @@ -441,7 +441,7 @@ class Something -You can also use this syntax for a common function to initialize a object's fields. +Anda juga bisa menggunakan sintaks ini untuk fungsi umum guna menginisialisasi field objek. ```yuescript new = (@fieldA, @fieldB) => @ @@ -458,9 +458,9 @@ print obj -## Class Expressions +## Ekspresi Kelas -The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. +Sintaks kelas juga bisa digunakan sebagai ekspresi yang dapat di-assign ke variabel atau di-return secara eksplisit. ```yuescript x = class Bucket @@ -477,9 +477,9 @@ x = class Bucket -## Anonymous classes +## Kelas Anonim -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. +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. ```yuescript BigBucket = class extends Bucket @@ -498,7 +498,7 @@ assert Bucket.__name == "BigBucket" -You can even leave off the body, meaning you can write a blank anonymous class like this: +Anda bahkan bisa menghilangkan badan kelas, artinya Anda bisa menulis kelas anonim kosong seperti ini: ```yuescript x = class @@ -511,9 +511,9 @@ x = class -## Class Mixing +## Pencampuran Kelas -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. +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. ```yuescript MyIndex = __index: var: 1 @@ -530,7 +530,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X bukan parent dari Y ``` @@ -549,7 +549,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X bukan parent dari Y ``` diff --git a/doc/docs/id-id/doc/objects/with-statement.md b/doc/docs/id-id/doc/objects/with-statement.md index 7786803..3c0a8a5 100644 --- a/doc/docs/id-id/doc/objects/with-statement.md +++ b/doc/docs/id-id/doc/objects/with-statement.md @@ -1,13 +1,12 @@ -# With Statement +# Pernyataan With +Pola umum saat membuat objek adalah memanggil serangkaian fungsi dan mengatur serangkaian properti segera setelah objek dibuat. -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. +Hal ini menyebabkan nama objek diulang berkali-kali di kode, menambah noise yang tidak perlu. Solusi umum untuk ini adalah meneruskan tabel sebagai argumen yang berisi kumpulan kunci dan nilai untuk ditimpa. Kekurangannya adalah konstruktor objek harus mendukung bentuk ini. -This results in repeating the name of the object multiple times in code, adding unnecessary noise. A common solution to this is to pass a table in as an argument which contains a collection of keys and values to overwrite. The downside to this is that the constructor of this object must support this form. +Blok `with` membantu mengatasi hal ini. Di dalam blok `with`, kita bisa menggunakan pernyataan khusus yang diawali dengan `.` atau `\` yang merepresentasikan operasi tersebut diterapkan pada objek yang sedang dipakai. -The with block helps to alleviate this. Within a with block we can use a special statements that begin with either . or \ which represent those operations applied to the object we are using with on. - -For example, we work with a newly created object: +Sebagai contoh, kita bekerja dengan objek yang baru dibuat: ```yuescript with Person! @@ -28,7 +27,7 @@ with Person! -The with statement can also be used as an expression which returns the value it has been giving access to. +Pernyataan `with` juga bisa digunakan sebagai ekspresi yang mengembalikan nilai yang diberi akses. ```yuescript file = with File "favorite_foods.txt" @@ -43,7 +42,7 @@ file = with File "favorite_foods.txt" -Or… +Atau… ```yuescript create_person = (name, relatives) -> @@ -66,9 +65,9 @@ me = create_person "Leaf", [dad, mother, sister] -In this usage, with can be seen as a special form of the K combinator. +Dalam penggunaan ini, `with` dapat dilihat sebagai bentuk khusus dari kombinator K. -The expression in the with statement can also be an assignment, if you want to give a name to the expression. +Ekspresi pada pernyataan `with` juga bisa berupa assignment jika Anda ingin memberi nama pada ekspresi tersebut. ```yuescript with str := "Hello" @@ -85,7 +84,7 @@ with str := "Hello" -You can access special keys with `[]` in a `with` statement. +Anda bisa mengakses kunci khusus dengan `[]` di dalam pernyataan `with`. ```yuescript with tb @@ -94,7 +93,7 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- menambahkan ke "tb" ``` @@ -105,12 +104,12 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- menambahkan ke "tb" ``` -`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. +`with?` adalah versi yang ditingkatkan dari sintaks `with`, yang memperkenalkan pengecekan keberadaan untuk mengakses objek yang mungkin nil secara aman tanpa pemeriksaan null eksplisit. ```yuescript with? obj diff --git a/doc/docs/id-id/doc/reference/license-mit.md b/doc/docs/id-id/doc/reference/license-mit.md index f1d5d60..5289f50 100644 --- a/doc/docs/id-id/doc/reference/license-mit.md +++ b/doc/docs/id-id/doc/reference/license-mit.md @@ -1,23 +1,22 @@ -# License: MIT +# Lisensi: MIT -Copyright (c) 2017-2026 Li Jin \ +Copyright (c) 2017-2026 Li Jin -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Izin dengan ini diberikan, tanpa biaya, kepada siapa pun yang memperoleh salinan +perangkat lunak ini beserta file dokumentasi terkait ("Perangkat Lunak"), untuk +berurusan dengan Perangkat Lunak tanpa pembatasan, termasuk tanpa batasan hak +untuk menggunakan, menyalin, memodifikasi, menggabungkan, menerbitkan, +mendistribusikan, mensublisensikan, dan/atau menjual salinan Perangkat Lunak, +dan untuk mengizinkan orang yang menerima Perangkat Lunak untuk melakukannya, +dengan syarat-syarat berikut: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Pemberitahuan hak cipta di atas dan pemberitahuan izin ini harus disertakan dalam +semua salinan atau bagian substansial dari Perangkat Lunak. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - +PERANGKAT LUNAK DISEDIAKAN "APA ADANYA", TANPA JAMINAN APA PUN, BAIK TERSURAT +MAUPUN TERSIRAT, TERMASUK NAMUN TIDAK TERBATAS PADA JAMINAN KELAYAKAN +DIPERDAGANGKAN, KESESUAIAN UNTUK TUJUAN TERTENTU, DAN TIDAK MELANGGAR HAK. +DALAM KEADAAN APA PUN, PENULIS ATAU PEMEGANG HAK CIPTA TIDAK BERTANGGUNG JAWAB +ATAS KLAIM, KERUSAKAN, ATAU KEWAJIBAN LAINNYA, BAIK DALAM TINDAKAN KONTRAK, +PERBUATAN MELAWAN HUKUM, ATAU LAINNYA, YANG TIMBUL DARI, DI LUAR, ATAU TERKAIT +DENGAN PERANGKAT LUNAK ATAU PENGGUNAAN ATAU URUSAN LAIN DALAM PERANGKAT LUNAK. diff --git a/doc/docs/id-id/doc/reference/the-yuescript-library.md b/doc/docs/id-id/doc/reference/the-yuescript-library.md index 3761755..0a398a5 100644 --- a/doc/docs/id-id/doc/reference/the-yuescript-library.md +++ b/doc/docs/id-id/doc/reference/the-yuescript-library.md @@ -1,20 +1,20 @@ -# The YueScript Library +# Pustaka YueScript -Access it by `local yue = require("yue")` in Lua. +Akses dengan `local yue = require("yue")` di Lua. ## yue -**Description:** +**Deskripsi:** -The YueScript language library. +Pustaka bahasa YueScript. ### version -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The YueScript version. +Versi YueScript. **Signature:** ```lua @@ -23,11 +23,11 @@ version: string ### dirsep -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The file separator for the current platform. +Pemisah file untuk platform saat ini. **Signature:** ```lua @@ -36,11 +36,11 @@ dirsep: string ### yue_compiled -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The compiled module code cache. +Cache kode modul yang telah dikompilasi. **Signature:** ```lua @@ -49,11 +49,11 @@ yue_compiled: {string: string} ### to_lua -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -The YueScript compiling function. It compiles the YueScript code to Lua code. +Fungsi kompilasi YueScript. Mengompilasi kode YueScript menjadi kode Lua. **Signature:** ```lua @@ -63,122 +63,122 @@ to_lua: function(code: string, config?: Config): --[[globals]] {{string, integer, integer}} | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| code | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| code | string | Kode YueScript. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| string \| nil | The compiled Lua code, or nil if the compilation failed. | -| string \| nil | The error message, or nil if the compilation succeeded. | -| {{string, integer, integer}} \| nil | The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. | +| string \| nil | Kode Lua hasil kompilasi, atau nil jika kompilasi gagal. | +| string \| nil | Pesan error, atau nil jika kompilasi berhasil. | +| {{string, integer, integer}} \| nil | Variabel global yang muncul dalam kode (dengan nama, baris, dan kolom), atau nil jika opsi kompiler `lint_global` bernilai false. | ### file_exist -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -The source file existence checking function. Can be overridden to customize the behavior. +Fungsi untuk memeriksa keberadaan file sumber. Dapat ditimpa untuk menyesuaikan perilaku. **Signature:** ```lua file_exist: function(filename: string): boolean ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | Nama file. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| boolean | Whether the file exists. | +| boolean | Apakah file ada. | ### read_file -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -The source file reading function. Can be overridden to customize the behavior. +Fungsi untuk membaca file sumber. Dapat ditimpa untuk menyesuaikan perilaku. **Signature:** ```lua read_file: function(filename: string): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | Nama file. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| string | The file content. | +| string | Isi file. | ### insert_loader -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Insert the YueScript loader to the package loaders (searchers). +Menyisipkan loader YueScript ke package loaders (searchers). **Signature:** ```lua insert_loader: function(pos?: integer): boolean ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| pos | integer | [Optional] The position to insert the loader. Default is 3. | +| pos | integer | [Opsional] Posisi untuk menyisipkan loader. Default adalah 3. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| boolean | Whether the loader is inserted successfully. It will fail if the loader is already inserted. | +| boolean | Apakah loader berhasil disisipkan. Akan gagal jika loader sudah disisipkan. | ### remove_loader -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Remove the YueScript loader from the package loaders (searchers). +Menghapus loader YueScript dari package loaders (searchers). **Signature:** ```lua remove_loader: function(): boolean ``` -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| boolean | Whether the loader is removed successfully. It will fail if the loader is not inserted. | +| boolean | Apakah loader berhasil dihapus. Akan gagal jika loader belum disisipkan. | ### loadstring -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a string into a function. +Memuat kode YueScript dari string menjadi fungsi. **Signature:** ```lua @@ -187,29 +187,29 @@ loadstring: function(input: string, chunkname: string, env: table, config?: Conf --[[error]] string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| input | string | Kode YueScript. | +| chunkname | string | Nama chunk kode. | +| env | table | Tabel environment. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Fungsi yang dimuat, atau nil jika pemuatan gagal. | +| string \| nil | Pesan error, atau nil jika pemuatan berhasil. | ### loadstring -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a string into a function. +Memuat kode YueScript dari string menjadi fungsi. **Signature:** ```lua @@ -218,28 +218,28 @@ loadstring: function(input: string, chunkname: string, config?: Config): --[[error]] string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| config | Config | [Optional] The compiler options. | +| input | string | Kode YueScript. | +| chunkname | string | Nama chunk kode. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Fungsi yang dimuat, atau nil jika pemuatan gagal. | +| string \| nil | Pesan error, atau nil jika pemuatan berhasil. | ### loadstring -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a string into a function. +Memuat kode YueScript dari string menjadi fungsi. **Signature:** ```lua @@ -248,27 +248,27 @@ loadstring: function(input: string, config?: Config): --[[error]] string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| input | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| input | string | Kode YueScript. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Fungsi yang dimuat, atau nil jika pemuatan gagal. | +| string \| nil | Pesan error, atau nil jika pemuatan berhasil. | ### loadfile -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a file into a function. +Memuat kode YueScript dari file menjadi fungsi. **Signature:** ```lua @@ -277,28 +277,28 @@ loadfile: function(filename: string, env: table, config?: Config): string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | Nama file. | +| env | table | Tabel environment. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Fungsi yang dimuat, atau nil jika pemuatan gagal. | +| string \| nil | Pesan error, atau nil jika pemuatan berhasil. | ### loadfile -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a file into a function. +Memuat kode YueScript dari file menjadi fungsi. **Signature:** ```lua @@ -307,178 +307,178 @@ loadfile: function(filename: string, config?: Config): string | nil ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | Nama file. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | Fungsi yang dimuat, atau nil jika pemuatan gagal. | +| string \| nil | Pesan error, atau nil jika pemuatan berhasil. | ### dofile -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a file into a function and executes it. +Memuat kode YueScript dari file menjadi fungsi dan mengeksekusinya. **Signature:** ```lua dofile: function(filename: string, env: table, config?: Config): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | Nama file. | +| env | table | Tabel environment. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Nilai return dari fungsi yang dimuat. | ### dofile -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads YueScript code from a file into a function and executes it. +Memuat kode YueScript dari file menjadi fungsi dan mengeksekusinya. **Signature:** ```lua dofile: function(filename: string, config?: Config): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | Nama file. | +| config | Config | [Opsional] Opsi kompiler. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Nilai return dari fungsi yang dimuat. | ### find_modulepath -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Resolves the YueScript module name to the file path. +Menguraikan nama modul YueScript menjadi path file. **Signature:** ```lua find_modulepath: function(name: string): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| name | string | The module name. | +| name | string | Nama modul. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| string | The file path. | +| string | Path file. | ### pcall -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Calls a function in protected mode. -Catches any errors and returns a status code and results or error object. -Rewrites the error line number to the original line number in the YueScript code when errors occur. +Memanggil fungsi dalam mode terlindungi. +Menangkap error apa pun dan mengembalikan kode status beserta hasil atau objek error. +Menulis ulang nomor baris error ke nomor baris asli di kode YueScript saat error terjadi. **Signature:** ```lua pcall: function(f: function, ...: any): boolean, any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| f | function | The function to call. | -| ... | any | Arguments to pass to the function. | +| f | function | Fungsi yang akan dipanggil. | +| ... | any | Argumen yang diteruskan ke fungsi. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| boolean, ... | Status code and function results or error object. | +| boolean, ... | Kode status dan hasil fungsi atau objek error. | ### require -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Loads a given module. Can be either a Lua module or a YueScript module. -Rewrites the error line number to the original line number in the YueScript code if the module is a YueScript module and loading fails. +Memuat modul tertentu. Bisa berupa modul Lua atau modul YueScript. +Menulis ulang nomor baris error ke nomor baris asli di kode YueScript jika modul adalah modul YueScript dan pemuatan gagal. **Signature:** ```lua require: function(name: string): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| modname | string | The name of the module to load. | +| modname | string | Nama modul yang akan dimuat. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| any | The value stored at package.loaded[modname] if the module is already loaded.Otherwise, tries to find a loader and returns the final value of package.loaded[modname] and a loader data as a second result. | +| any | Nilai yang disimpan di package.loaded[modname] jika modul sudah dimuat. Jika belum, mencoba mencari loader dan mengembalikan nilai akhir package.loaded[modname] serta data loader sebagai hasil kedua. | ### p -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Inspects the structures of the passed values and prints string representations. +Memeriksa struktur nilai yang diteruskan dan mencetak representasi string. **Signature:** ```lua p: function(...: any) ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| ... | any | The values to inspect. | +| ... | any | Nilai yang akan diperiksa. | ### options -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The current compiler options. +Opsi kompiler saat ini. **Signature:** ```lua @@ -487,62 +487,62 @@ options: Config.Options ### traceback -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -The traceback function that rewrites the stack trace line numbers to the original line numbers in the YueScript code. +Fungsi traceback yang menulis ulang nomor baris stack trace ke nomor baris asli di kode YueScript. **Signature:** ```lua traceback: function(message: string): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| message | string | The traceback message. | +| message | string | Pesan traceback. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| string | The rewritten traceback message. | +| string | Pesan traceback yang telah ditulis ulang. | ### is_ast -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Checks whether the code matches the specified AST. +Memeriksa apakah kode cocok dengan AST yang ditentukan. **Signature:** ```lua is_ast: function(astName: string, code: string): boolean ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| astName | string | The AST name. | -| code | string | The code. | +| astName | string | Nama AST. | +| code | string | Kode. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| boolean | Whether the code matches the AST. | +| boolean | Apakah kode cocok dengan AST. | ### AST -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The AST type definition with name, row, column and sub nodes. +Definisi tipe AST dengan nama, baris, kolom, dan sub-node. **Signature:** ```lua @@ -551,11 +551,11 @@ type AST = {string, integer, integer, any} ### to_ast -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Converts the code to the AST. +Mengonversi kode menjadi AST. **Signature:** ```lua @@ -564,88 +564,88 @@ to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveC --[[error]] nil | string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| code | string | The code. | -| flattenLevel | integer | [Optional] The flatten level. Higher level means more flattening. Default is 0. Maximum is 2. | -| astName | string | [Optional] The AST name. Default is "File". | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is false. | +| code | string | Kode. | +| flattenLevel | integer | [Opsional] Tingkat perataan. Semakin tinggi berarti semakin rata. Default 0. Maksimum 2. | +| astName | string | [Opsional] Nama AST. Default "File". | +| reserveComment | boolean | [Opsional] Apakah akan mempertahankan komentar asli. Default false. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| AST \| nil | The AST, or nil if the conversion failed. | -| string \| nil | The error message, or nil if the conversion succeeded. | +| AST \| nil | AST, atau nil jika konversi gagal. | +| string \| nil | Pesan error, atau nil jika konversi berhasil. | ### format -**Type:** Function. +**Tipe:** Function. -**Description:** +**Deskripsi:** -Formats the YueScript code. +Memformat kode YueScript. **Signature:** ```lua format: function(code: string, tabSize?: number, reserveComment?: boolean): string ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| code | string | The code. | -| tabSize | integer | [Optional] The tab size. Default is 4. | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is true. | +| code | string | Kode. | +| tabSize | integer | [Opsional] Ukuran tab. Default 4. | +| reserveComment | boolean | [Opsional] Apakah mempertahankan komentar asli. Default true. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| string | The formatted code. | +| string | Kode yang telah diformat. | ### __call -**Type:** Metamethod. +**Tipe:** Metamethod. -**Description:** +**Deskripsi:** -Requires the YueScript module. -Rewrites the error line number to the original line number in the YueScript code when loading fails. +Me-require modul YueScript. +Menulis ulang nomor baris error ke nomor baris asli di kode YueScript saat pemuatan gagal. **Signature:** ```lua metamethod __call: function(self: yue, module: string): any... ``` -**Parameters:** +**Parameter:** -| Parameter | Type | Description | +| Parameter | Tipe | Deskripsi | | --- | --- | --- | -| module | string | The module name. | +| module | string | Nama modul. | -**Returns:** +**Return:** -| Return Type | Description | +| Tipe Return | Deskripsi | | --- | --- | -| any | The module value. | +| any | Nilai modul. | ## Config -**Description:** +**Deskripsi:** -The compiler compile options. +Opsi kompilasi kompiler. ### lint_global -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler should collect the global variables appearing in the code. +Apakah kompiler harus mengumpulkan variabel global yang muncul dalam kode. **Signature:** ```lua @@ -654,11 +654,11 @@ lint_global: boolean ### implicit_return_root -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler should do an implicit return for the root code block. +Apakah kompiler harus melakukan return implisit untuk blok kode root. **Signature:** ```lua @@ -667,11 +667,11 @@ implicit_return_root: boolean ### reserve_line_number -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler should reserve the original line number in the compiled code. +Apakah kompiler harus mempertahankan nomor baris asli di kode hasil kompilasi. **Signature:** ```lua @@ -680,11 +680,11 @@ reserve_line_number: boolean ### reserve_comment -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler should reserve the original comments in the compiled code. +Apakah kompiler harus mempertahankan komentar asli di kode hasil kompilasi. **Signature:** ```lua @@ -693,11 +693,11 @@ reserve_comment: boolean ### space_over_tab -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler should use the space character instead of the tab character in the compiled code. +Apakah kompiler harus menggunakan karakter spasi alih-alih tab di kode hasil kompilasi. **Signature:** ```lua @@ -706,11 +706,11 @@ space_over_tab: boolean ### same_module -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler should treat the code to be compiled as the same currently being compiled module. For internal use only. +Apakah kompiler harus memperlakukan kode yang akan dikompilasi sebagai modul yang sama dengan modul yang sedang dikompilasi. Untuk penggunaan internal saja. **Signature:** ```lua @@ -719,11 +719,11 @@ same_module: boolean ### line_offset -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether the compiler error message should include the line number offset. For internal use only. +Apakah pesan error kompiler harus menyertakan offset nomor baris. Untuk penggunaan internal saja. **Signature:** ```lua @@ -732,11 +732,11 @@ line_offset: integer ### yue.Config.LuaTarget -**Type:** Enumeration. +**Tipe:** Enumeration. -**Description:** +**Deskripsi:** -The target Lua version enumeration. +Enumerasi versi Lua target. **Signature:** ```lua @@ -751,11 +751,11 @@ end ### options -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The extra options to be passed to the compilation function. +Opsi tambahan untuk diteruskan ke fungsi kompilasi. **Signature:** ```lua @@ -764,17 +764,17 @@ options: Options ## Options -**Description:** +**Deskripsi:** -The extra compiler options definition. +Definisi opsi kompiler tambahan. ### target -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The target Lua version for the compilation. +Versi Lua target untuk kompilasi. **Signature:** ```lua @@ -783,11 +783,11 @@ target: LuaTarget ### path -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -The extra module search path. +Path pencarian modul tambahan. **Signature:** ```lua @@ -796,11 +796,11 @@ path: string ### dump_locals -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether to dump the local variables in the traceback error message. Default is false. +Apakah akan menampilkan variabel local dalam pesan error traceback. Default false. **Signature:** ```lua @@ -809,11 +809,11 @@ dump_locals: boolean ### simplified -**Type:** Field. +**Tipe:** Field. -**Description:** +**Deskripsi:** -Whether to simplify the error message. Default is true. +Apakah akan menyederhanakan pesan error. Default true. **Signature:** ```lua diff --git a/doc/docs/id-id/index.md b/doc/docs/id-id/index.md index 016b688..c8b5fab 100644 --- a/doc/docs/id-id/index.md +++ b/doc/docs/id-id/index.md @@ -2,22 +2,22 @@ layout: home hero: name: YueScript - tagline: A language that compiles to Lua + tagline: Bahasa yang dikompilasi ke Lua image: src: /image/yuescript.svg alt: YueScript actions: - theme: brand - text: Quick Start → + text: Mulai Cepat → link: /doc/ features: - - title: Familiar Lua workflows - details: Write concise syntax that compiles to readable Lua, with predictable output. - - title: Modern language features - details: Pipe, pattern matching, slicing, and destructuring without giving up Lua interop. - - title: Rapid Iteration - details: Any feedback is welcome to help accelerate the language development and evolution! + - title: Alur kerja Lua yang familiar + details: Tulis sintaks ringkas yang dikompilasi ke Lua yang mudah dibaca, dengan output yang dapat diprediksi. + - title: Fitur bahasa modern + details: Pipe, pattern matching, slicing, dan destrukturisasi tanpa mengorbankan interoperabilitas Lua. + - title: Iterasi Cepat + details: Setiap masukan sangat diterima untuk membantu mempercepat pengembangan dan evolusi bahasa! footer: - message: MIT License. - copyright: Copyright © 2017-2026 Li Jin. All rights reserved. + message: Lisensi MIT. + copyright: Hak cipta © 2017-2026 Li Jin. Semua hak dilindungi. --- diff --git a/doc/docs/id-id/try/index.md b/doc/docs/id-id/try/index.md index 85a903b..c31dc1c 100755 --- a/doc/docs/id-id/try/index.md +++ b/doc/docs/id-id/try/index.md @@ -4,9 +4,9 @@ prev: false next: false --- -# YueScript Online Compiler +# Kompiler Online YueScript --- -Try YueScript in the browser with WASM. +Coba YueScript di browser dengan WASM. diff --git a/doc/docs/pt-br/doc/advanced/do.md b/doc/docs/pt-br/doc/advanced/do.md index 4990d6f..f13d8aa 100644 --- a/doc/docs/pt-br/doc/advanced/do.md +++ b/doc/docs/pt-br/doc/advanced/do.md @@ -1,12 +1,12 @@ # Do -When used as a statement, do works just like it does in Lua. +Quando usado como instrução, do funciona exatamente como no Lua. ```yuescript do var = "hello" print var -print var -- nil here +print var -- nil aqui ``` @@ -14,12 +14,12 @@ print var -- nil here do var = "hello" print var -print var -- nil here +print var -- nil aqui ``` -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. +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. ```yuescript counter = do diff --git a/doc/docs/pt-br/doc/advanced/line-decorators.md b/doc/docs/pt-br/doc/advanced/line-decorators.md index 292bc77..94d1004 100644 --- a/doc/docs/pt-br/doc/advanced/line-decorators.md +++ b/doc/docs/pt-br/doc/advanced/line-decorators.md @@ -1,6 +1,6 @@ -# Line Decorators +# Decoradores de linha -For convenience, the for loop and if statement can be applied to single statements at the end of the line: +Por conveniência, o loop for e a instrução if podem ser aplicados a instruções únicas no final da linha: ```yuescript print "hello world" if name == "Rob" @@ -13,7 +13,7 @@ print "hello world" if name == "Rob" -And with basic loops: +E com loops básicos: ```yuescript print "item: ", item for item in *items @@ -26,7 +26,7 @@ print "item: ", item for item in *items -And with while loops: +E com loops while: ```yuescript game\update! while game\isRunning! diff --git a/doc/docs/pt-br/doc/advanced/macro.md b/doc/docs/pt-br/doc/advanced/macro.md index 6d194c3..846d506 100644 --- a/doc/docs/pt-br/doc/advanced/macro.md +++ b/doc/docs/pt-br/doc/advanced/macro.md @@ -1,8 +1,8 @@ # Macro -## Common Usage +## Uso comum -Macro function is used for evaluating a string in the compile time and insert the generated codes into final compilation. +A função macro é usada para avaliar uma string em tempo de compilação e inserir os códigos gerados na compilação final. ```yuescript macro PI2 = -> math.pi * 2 @@ -27,7 +27,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- as expressões passadas são tratadas como strings macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -57,7 +57,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- as expressões passadas são tratadas como strings macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -65,9 +65,9 @@ if $and f1!, f2!, f3! -## Insert Raw Codes +## Inserir códigos brutos -A macro function can either return a YueScript string or a config table containing Lua codes. +Uma função macro pode retornar uma string YueScript ou uma tabela de configuração contendo códigos Lua. ```yuescript macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA @@ -85,9 +85,9 @@ macro lua = (code) -> { type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- os símbolos inicial e final da string bruta são aparados automaticamente $lua[==[ --- raw Lua codes insertion +-- inserção de códigos Lua brutos if cond then print("output") end @@ -112,9 +112,9 @@ macro lua = (code) -> { type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- os símbolos inicial e final da string bruta são aparados automaticamente $lua[==[ --- raw Lua codes insertion +-- inserção de códigos Lua brutos if cond then print("output") end @@ -123,38 +123,37 @@ end -## Export Macro +## Exportar macro -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. +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. ```yuescript --- file: utils.yue +-- arquivo: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" --- file main.yue +-- arquivo main.yue import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- símbolo para importar todas as macros + $foreach: $each -- renomear macro $foreach para $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ``` ```yue --- file: utils.yue +-- arquivo: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" --- file main.yue --- import function is not available in browser, try it in a real environment +-- arquivo main.yue --[[ import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- símbolo para importar todas as macros + $foreach: $each -- renomear macro $foreach para $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ]] @@ -162,25 +161,25 @@ import "utils" as { -## Builtin Macro +## Macro embutida -There are some builtin macros but you can override them by declaring macros with the same names. +Existem algumas macros embutidas, mas você pode sobrescrevê-las declarando macros com os mesmos nomes. ```yuescript -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- obtém string do nome do módulo atual +print $LINE -- obtém número 2 ``` ```yue -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- obtém string do nome do módulo atual +print $LINE -- obtém número 2 ``` -## Generating Macros with Macros +## Gerando macros com macros -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. +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. ```yuescript macro Enum = (...) -> @@ -222,9 +221,9 @@ print "Valid enum type:", $BodyType Static -## Argument Validation +## Validação de argumentos -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. +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. ```yuescript macro printNumAndStr = (num `Num, str `String) -> | @@ -249,7 +248,7 @@ $printNumAndStr 123, "hello" -If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. +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. ```yuescript macro printNumAndStr = (num, str) -> @@ -272,4 +271,4 @@ $printNumAndStr 123, "hello" -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). +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). diff --git a/doc/docs/pt-br/doc/advanced/module.md b/doc/docs/pt-br/doc/advanced/module.md index c955092..34fd106 100644 --- a/doc/docs/pt-br/doc/advanced/module.md +++ b/doc/docs/pt-br/doc/advanced/module.md @@ -1,28 +1,28 @@ -# Module +# Módulo ## Import -The import statement is a syntax sugar for requiring a module or help extracting items from an imported module. The imported items are const by default. +A instrução import é um açúcar sintático para requerer um módulo ou ajudar a extrair itens de um módulo importado. Os itens importados são const por padrão. ```yuescript --- used as table destructuring +-- usado como desestruturação de tabela do import insert, concat from table - -- report error when assigning to insert, concat + -- reporta erro ao atribuir a insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- atalho para require implícito import x, y, z from 'mymodule' - -- import with Python style + -- import com estilo Python from 'module' import a, b, c --- shortcut for requring a module +-- atalho para requerer um módulo do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- requerer módulo com aliasing ou desestruturação de tabela do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -31,24 +31,24 @@ do ```yue --- used as table destructuring +-- usado como desestruturação de tabela do import insert, concat from table - -- report error when assigning to insert, concat + -- reporta erro ao atribuir a insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- atalho para require implícito import x, y, z from 'mymodule' - -- import with Python style + -- import com estilo Python from 'module' import a, b, c --- shortcut for requring a module +-- atalho para requerer um módulo do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- requerer módulo com aliasing ou desestruturação de tabela do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -59,7 +59,7 @@ do ## Import Global -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. +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. ```yuescript do @@ -78,21 +78,21 @@ do -### Automatic Global Variable Import +### Importação automática de variável global -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. +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. -Names that are explicitly declared as globals in the same scope will not be imported, so you can still assign to them. +Nomes que foram explicitamente declarados como globais no mesmo escopo não serão importados, então você ainda pode atribuir a eles. ```yuescript do import global print "hello" math.random 3 - -- print = nil -- error: imported globals are const + -- print = nil -- erro: globais importados são const do - -- explicit global variable will not be imported + -- variável global explícita não será importada import global global FLAG print FLAG @@ -105,10 +105,10 @@ do import global print "hello" math.random 3 - -- print = nil -- error: imported globals are const + -- print = nil -- erro: globais importados são const do - -- explicit global variable will not be imported + -- variável global explícita não será importada import global global FLAG print FLAG @@ -119,11 +119,11 @@ do ## Export -The export statement offers a concise way to define modules. +A instrução export oferece uma forma concisa de definir módulos. -### Named Export +### Export nomeado -Named export will define a local variable as well as adding a field in the exported table. +Export nomeado definirá uma variável local e também adicionará um campo na tabela exportada. ```yuescript export a, b, c = 1, 2, 3 @@ -160,7 +160,7 @@ export class Something -Doing named export with destructuring. +Fazendo export nomeado com desestruturação. ```yuescript export :loadstring, to_lua: tolua = yue @@ -175,7 +175,7 @@ export {itemA: {:fieldA = 'default'}} = tb -Export named items from module without creating local variables. +Exportar itens nomeados do módulo sem criar variáveis locais. ```yuescript export.itemA = tb @@ -192,9 +192,9 @@ export["a-b-c"] = 123 -### Unnamed Export +### Export sem nome -Unnamed export will add the target item into the array part of the exported table. +Export sem nome adicionará o item alvo na parte array da tabela exportada. ```yuescript d, e, f = 3, 2, 1 @@ -225,9 +225,9 @@ export with tmp -### Default Export +### Export padrão -Using the **default** keyword in export statement to replace the exported table with any thing. +Usar a palavra-chave **default** na instrução export para substituir a tabela exportada por qualquer coisa. ```yuescript export default -> diff --git a/doc/docs/pt-br/doc/advanced/try.md b/doc/docs/pt-br/doc/advanced/try.md index 23c7877..fbb4e87 100644 --- a/doc/docs/pt-br/doc/advanced/try.md +++ b/doc/docs/pt-br/doc/advanced/try.md @@ -1,6 +1,6 @@ # Try -The syntax for Lua error handling in a common form. +A sintaxe para tratamento de erros do Lua em uma forma comum. ```yuescript try @@ -23,7 +23,7 @@ try print "trying" func 1, 2, 3 --- working with if assignment pattern +-- funcionando com padrão de atribuição em if if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -52,7 +52,7 @@ try print "trying" func 1, 2, 3 --- working with if assignment pattern +-- funcionando com padrão de atribuição em if if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -63,18 +63,18 @@ catch err ## Try? -`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. +`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. ```yuescript a, b, c = try? func! --- with nil coalescing operator +-- com operador de coalescência de nil a = (try? func!) ?? "default" --- as function argument +-- como argumento de função f try? func! --- with catch block +-- com bloco catch f try? print 123 func! @@ -87,13 +87,13 @@ catch e ```yue a, b, c = try? func! --- with nil coalescing operator +-- com operador de coalescência de nil a = (try? func!) ?? "default" --- as function argument +-- como argumento de função f try? func! --- with catch block +-- com bloco catch f try? print 123 func! diff --git a/doc/docs/pt-br/doc/assignment/assignment.md b/doc/docs/pt-br/doc/assignment/assignment.md index 4dac6f4..1da6bb0 100644 --- a/doc/docs/pt-br/doc/assignment/assignment.md +++ b/doc/docs/pt-br/doc/assignment/assignment.md @@ -1,25 +1,25 @@ -# Assignment +# Atribuição -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. +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**. ```yuescript hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- usa a variável existente ``` ```yue hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- usa a variável existente ``` -## Perform Update +## Atualização -You can perform update assignment with many binary operators. +Você pode realizar atribuição de atualização com muitos operadores binários. ```yuescript x = 1 x += 1 @@ -27,8 +27,8 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist -arg or= "default value" +s ..= "world" -- adiciona um novo local se a variável local não existir +arg or= "valor padrão" ``` @@ -39,15 +39,15 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist -arg or= "default value" +s ..= "world" -- adiciona um novo local se a variável local não existir +arg or= "valor padrão" ``` -## Chaining Assignment +## Atribuição encadeada -You can do chaining assignment to assign multiple items to hold the same value. +Você pode fazer atribuição encadeada para atribuir múltiplos itens ao mesmo valor. ```yuescript a = b = c = d = e = 0 x = y = z = f! @@ -61,12 +61,12 @@ x = y = z = f! -## Explicit Locals +## Locais explícitos ```yuescript do local a = 1 local * - print "forward declare all variables as locals" + print "declarar antecipadamente todas as variáveis como locais" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! @@ -74,7 +74,7 @@ do do local X = 1 local ^ - print "only forward declare upper case variables" + print "declarar antecipadamente apenas variáveis em maiúsculas" a = 1 B = 2 ``` @@ -84,7 +84,7 @@ do do local a = 1 local * - print "forward declare all variables as locals" + print "declarar antecipadamente todas as variáveis como locais" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! @@ -92,29 +92,29 @@ do do local X = 1 local ^ - print "only forward declare upper case variables" + print "declarar antecipadamente apenas variáveis em maiúsculas" a = 1 B = 2 ``` -## Explicit Globals +## Globais explícitos ```yuescript do global a = 1 global * - print "declare all variables as globals" + print "declarar todas as variáveis como globais" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ - print "only declare upper case variables as globals" + print "declarar apenas variáveis em maiúsculas como globais" a = 1 B = 2 - local Temp = "a local value" + local Temp = "um valor local" ``` @@ -122,17 +122,17 @@ do do global a = 1 global * - print "declare all variables as globals" + print "declarar todas as variáveis como globais" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ - print "only declare upper case variables as globals" + print "declarar apenas variáveis em maiúsculas como globais" a = 1 B = 2 - local Temp = "a local value" + local Temp = "um valor local" ``` diff --git a/doc/docs/pt-br/doc/assignment/destructuring-assignment.md b/doc/docs/pt-br/doc/assignment/destructuring-assignment.md index e7b8046..7692885 100644 --- a/doc/docs/pt-br/doc/assignment/destructuring-assignment.md +++ b/doc/docs/pt-br/doc/assignment/destructuring-assignment.md @@ -1,10 +1,10 @@ -# Destructuring Assignment +# Atribuição por desestruturação -Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. +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. -Typically when you see a table literal, {1,2,3}, it is on the right hand side of an assignment because it is a value. Destructuring assignment swaps the role of the table literal, and puts it on the left hand side of an assign statement. +Tipicamente, quando você vê um literal de tabela, {1,2,3}, ele está no lado direito de uma atribuição porque é um valor. A atribuição por desestruturação troca o papel do literal de tabela e o coloca no lado esquerdo de uma instrução de atribuição. -This is best explained with examples. Here is how you would unpack the first two values from a table: +Isso é melhor explicado com exemplos. Assim você extrairia os dois primeiros valores de uma tabela: ```yuescript thing = [1, 2] @@ -23,7 +23,7 @@ print a, b -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. +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. ```yuescript obj = { @@ -35,7 +35,7 @@ obj = { {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- OK fazer desestruturação simples sem chaves ``` @@ -49,12 +49,12 @@ obj = { {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- OK fazer desestruturação simples sem chaves ``` -This also works with nested data structures as well: +Isso também funciona com estruturas de dados aninhadas: ```yuescript obj2 = { @@ -85,7 +85,7 @@ print first, second, color -If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: +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: ```yuescript { @@ -108,7 +108,7 @@ If the destructuring statement is complicated, feel free to spread it out over a -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: +É 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 **:**: ```yuescript {:concat, :insert} = table @@ -121,7 +121,7 @@ It's common to extract values from at table and assign them the local variables -This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: +Isso é efetivamente o mesmo que import, mas podemos renomear campos que queremos extrair misturando a sintaxe: ```yuescript {:mix, :max, random: rand} = math @@ -134,20 +134,20 @@ This is effectively the same as import, but we can rename fields we want to extr -You can write default values while doing destructuring like: +Você pode escrever valores padrão ao fazer desestruturação: ```yuescript -{:name = "nameless", :job = "jobless"} = person +{:name = "sem nome", :job = "sem emprego"} = person ``` ```yue -{:name = "nameless", :job = "jobless"} = person +{:name = "sem nome", :job = "sem emprego"} = person ``` -You can use `_` as placeholder when doing a list destructuring: +Você pode usar `_` como placeholder ao fazer desestruturação de lista: ```yuescript [_, two, _, four] = items @@ -160,59 +160,59 @@ You can use `_` as placeholder when doing a list destructuring: -## Range Destructuring +## Desestruturação por intervalo -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. +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. ```yuescript orders = ["first", "second", "third", "fourth", "last"] [first, ...bulk, last] = orders -print first -- prints: first -print bulk -- prints: {"second", "third", "fourth"} -print last -- prints: last +print first -- imprime: first +print bulk -- imprime: {"second", "third", "fourth"} +print last -- imprime: last ``` ```yue orders = ["first", "second", "third", "fourth", "last"] [first, ...bulk, last] = orders -print first -- prints: first -print bulk -- prints: {"second", "third", "fourth"} -print last -- prints: last +print first -- imprime: first +print bulk -- imprime: {"second", "third", "fourth"} +print last -- imprime: last ``` -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: +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: ```yuescript --- Capture everything after first element +-- Capturar tudo após o primeiro elemento [first, ...rest] = orders --- Capture everything before last element +-- Capturar tudo antes do último elemento [...start, last] = orders --- Capture things except the middle elements +-- Capturar tudo exceto os elementos do meio [first, ..._, last] = orders ``` ```yue --- Capture everything after first element +-- Capturar tudo após o primeiro elemento [first, ...rest] = orders --- Capture everything before last element +-- Capturar tudo antes do último elemento [...start, last] = orders --- Capture things except the middle elements +-- Capturar tudo exceto os elementos do meio [first, ..._, last] = orders ``` -## Destructuring In Other Places +## Desestruturação em outros lugares -Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: +A desestruturação também pode aparecer em lugares onde uma atribuição ocorre implicitamente. Um exemplo disso é um loop for: ```yuescript tuples = [ @@ -237,4 +237,4 @@ for [left, right] in *tuples -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. +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. diff --git a/doc/docs/pt-br/doc/assignment/if-assignment.md b/doc/docs/pt-br/doc/assignment/if-assignment.md index 02984e8..84094ed 100644 --- a/doc/docs/pt-br/doc/assignment/if-assignment.md +++ b/doc/docs/pt-br/doc/assignment/if-assignment.md @@ -1,6 +1,6 @@ -# If Assignment +# Atribuição em if -`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. +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. ```yuescript if user := database.find_user "moon" @@ -17,55 +17,55 @@ if user := database.find_user "moon" ```yuescript if hello := os.getenv "hello" - print "You have hello", hello + print "Você tem hello", hello elseif world := os.getenv "world" - print "you have world", world + print "você tem world", world else - print "nothing :(" + print "nada :(" ``` ```yue if hello := os.getenv "hello" - print "You have hello", hello + print "Você tem hello", hello elseif world := os.getenv "world" - print "you have world", world + print "você tem world", world else - print "nothing :(" + print "nada :(" ``` -If assignment with multiple return values. Only the first value is getting checked, other values are scoped. +Atribuição em if com múltiplos valores de retorno. Apenas o primeiro valor é verificado, os outros valores estão no escopo. ```yuescript -if success, result := pcall -> "get result without problems" - print result -- variable result is scoped +if success, result := pcall -> "obter resultado sem problemas" + print result -- variável result está no escopo print "OK" ``` ```yue -if success, result := pcall -> "get result without problems" - print result -- variable result is scoped +if success, result := pcall -> "obter resultado sem problemas" + print result -- variável result está no escopo print "OK" ``` -## While Assignment +## Atribuição em while -You can also use if assignment in a while loop to get the value as the loop condition. +Você também pode usar atribuição em if em um loop while para obter o valor como condição do loop. ```yuescript while byte := stream\read_one! - -- do something with the byte + -- fazer algo com o byte print byte ``` ```yue while byte := stream\read_one! - -- do something with the byte + -- fazer algo com o byte print byte ``` diff --git a/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md b/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md index fb9b740..02d4162 100644 --- a/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md +++ b/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md @@ -1,11 +1,11 @@ -# The Using Clause; Controlling Destructive Assignment +# A cláusula Using; controlando atribuição destrutiva -While lexical scoping can be a great help in reducing the complexity of the code we write, things can get unwieldy as the code size increases. Consider the following snippet: +Embora o escopo léxico possa ser uma grande ajuda na redução da complexidade do código que escrevemos, as coisas podem ficar difíceis de gerenciar conforme o tamanho do código aumenta. Considere o seguinte trecho: ```yuescript i = 100 --- many lines of code... +-- muitas linhas de código... my_func = -> i = 10 @@ -15,14 +15,14 @@ my_func = -> my_func! -print i -- will print 0 +print i -- vai imprimir 0 ``` ```yue i = 100 --- many lines of code... +-- muitas linhas de código... my_func = -> i = 10 @@ -32,25 +32,25 @@ my_func = -> my_func! -print i -- will print 0 +print i -- vai imprimir 0 ``` -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. +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. -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. +Seria útil dizer quais variáveis do escopo envolvente pretendemos alterar, para evitar que alteremos outras por acidente. -The using keyword lets us do that. using nil makes sure that no closed variables are overwritten in assignment. The using clause is placed after the argument list in a function, or in place of it if there are no arguments. +A palavra-chave using nos permite fazer isso. using nil garante que nenhuma variável fechada seja sobrescrita na atribuição. A cláusula using é colocada após a lista de argumentos em uma função, ou no lugar dela se não houver argumentos. ```yuescript i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- uma nova variável local é criada aqui my_func! -print i -- prints 100, i is unaffected +print i -- imprime 100, i não é afetado ``` @@ -58,27 +58,27 @@ print i -- prints 100, i is unaffected i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- uma nova variável local é criada aqui my_func! -print i -- prints 100, i is unaffected +print i -- imprime 100, i não é afetado ``` -Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: +Múltiplos nomes podem ser separados por vírgulas. Os valores do closure ainda podem ser acessados, apenas não podem ser modificados: ```yuescript tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- uma nova variável local tmp é criada i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- estes foram atualizados ``` @@ -87,12 +87,12 @@ tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- uma nova variável local tmp é criada i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- estes foram atualizados ``` diff --git a/doc/docs/pt-br/doc/assignment/varargs-assignment.md b/doc/docs/pt-br/doc/assignment/varargs-assignment.md index 1d66680..0aab540 100644 --- a/doc/docs/pt-br/doc/assignment/varargs-assignment.md +++ b/doc/docs/pt-br/doc/assignment/varargs-assignment.md @@ -1,6 +1,6 @@ -# Varargs Assignment +# Atribuição de varargs -You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. +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. ```yuescript list = [1, 2, 3, 4, 5] diff --git a/doc/docs/pt-br/doc/control-flow/conditionals.md b/doc/docs/pt-br/doc/control-flow/conditionals.md index 5ba81cf..94e41ec 100644 --- a/doc/docs/pt-br/doc/control-flow/conditionals.md +++ b/doc/docs/pt-br/doc/control-flow/conditionals.md @@ -1,55 +1,55 @@ -# Conditionals +# Condicionais ```yuescript have_coins = false if have_coins - print "Got coins" + print "Tem moedas" else - print "No coins" + print "Sem moedas" ``` ```yue have_coins = false if have_coins - print "Got coins" + print "Tem moedas" else - print "No coins" + print "Sem moedas" ``` -A short syntax for single statements can also be used: +Uma sintaxe curta para instruções únicas também pode ser usada: ```yuescript have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Tem moedas" else print "Sem moedas" ``` ```yue have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Tem moedas" else print "Sem moedas" ``` -Because if statements can be used as expressions, this can also be written as: +Como instruções if podem ser usadas como expressões, isso também pode ser escrito como: ```yuescript have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Tem moedas" else "Sem moedas" ``` ```yue have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Tem moedas" else "Sem moedas" ``` -Conditionals can also be used in return statements and assignments: +Condicionais também podem ser usados em instruções de retorno e atribuições: ```yuescript is_tall = (name) -> @@ -59,11 +59,11 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Sou muito alto" else - "I am not so tall" + "Não sou tão alto" -print message -- prints: I am very tall +print message -- imprime: Sou muito alto ``` @@ -75,53 +75,53 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Sou muito alto" else - "I am not so tall" + "Não sou tão alto" -print message -- prints: I am very tall +print message -- imprime: Sou muito alto ``` -The opposite of if is unless: +O oposto de if é unless: ```yuescript unless os.date("%A") == "Monday" - print "it is not Monday!" + print "não é segunda-feira!" ``` ```yue unless os.date("%A") == "Monday" - print "it is not Monday!" + print "não é segunda-feira!" ``` ```yuescript -print "You're lucky!" unless math.random! > 0.1 +print "Você tem sorte!" unless math.random! > 0.1 ``` ```yue -print "You're lucky!" unless math.random! > 0.1 +print "Você tem sorte!" unless math.random! > 0.1 ``` -## In Expression +## Em expressão -You can write range checking code with an `in-expression`. +Você pode escrever código de verificação de intervalo com uma `in-expression`. ```yuescript a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "verificando igualdade com valores discretos" if a in list - print "checking if `a` is in a list" + print "verificando se `a` está na lista" ``` @@ -129,21 +129,10 @@ if a in list a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "verificando igualdade com valores discretos" if a in list - print "checking if `a` is in a list" -``` - - - -```yuescript -print "You're lucky!" unless math.random! > 0.1 -``` - - -```yue -print "You're lucky!" unless math.random! > 0.1 + print "verificando se `a` está na lista" ``` diff --git a/doc/docs/pt-br/doc/control-flow/continue.md b/doc/docs/pt-br/doc/control-flow/continue.md index b000765..8a3cdff 100644 --- a/doc/docs/pt-br/doc/control-flow/continue.md +++ b/doc/docs/pt-br/doc/control-flow/continue.md @@ -1,6 +1,6 @@ # Continue -A continue statement can be used to skip the current iteration in a loop. +Uma instrução continue pode ser usada para pular a iteração atual em um loop. ```yuescript i = 0 @@ -21,7 +21,7 @@ while i < 10 -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: +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: ```yuescript my_numbers = [1, 2, 3, 4, 5, 6] diff --git a/doc/docs/pt-br/doc/control-flow/for-loop.md b/doc/docs/pt-br/doc/control-flow/for-loop.md index cabcde5..dfd8285 100644 --- a/doc/docs/pt-br/doc/control-flow/for-loop.md +++ b/doc/docs/pt-br/doc/control-flow/for-loop.md @@ -1,12 +1,12 @@ -# For Loop +# Loop For -There are two for loop forms, just like in Lua. A numeric one and a generic one: +Existem duas formas de loop for, assim como no Lua. Uma numérica e uma genérica: ```yuescript for i = 10, 20 print i -for k = 1, 15, 2 -- an optional step provided +for k = 1, 15, 2 -- um passo opcional fornecido print k for key, value in pairs object @@ -18,7 +18,7 @@ for key, value in pairs object for i = 10, 20 print i -for k = 1, 15, 2 -- an optional step provided +for k = 1, 15, 2 -- um passo opcional fornecido print k for key, value in pairs object @@ -27,7 +27,7 @@ for key, value in pairs object -The slicing and **\*** operators can be used, just like with comprehensions: +Os operadores de slicing e **\*** podem ser usados, assim como com compreensões: ```yuescript for item in *items[2, 4] @@ -42,7 +42,7 @@ for item in *items[2, 4] -A shorter syntax is also available for all variations when the body is only a single line: +Uma sintaxe mais curta também está disponível para todas as variações quando o corpo é apenas uma linha: ```yuescript for item in *items do print item @@ -59,9 +59,9 @@ for j = 1, 10, 3 do print j -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. +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. -Doubling every even number: +Dobrando cada número par: ```yuescript doubled_evens = for i = 1, 20 @@ -82,9 +82,9 @@ doubled_evens = for i = 1, 20 -In addition, for loops support break with a return value, allowing the loop itself to be used as an expression that exits early with a meaningful result. +Além disso, os loops for suportam break com valor de retorno, permitindo que o próprio loop seja usado como expressão que sai antecipadamente com um resultado significativo. -For example, to find the first number greater than 10: +Por exemplo, para encontrar o primeiro número maior que 10: ```yuescript first_large = for n in *numbers @@ -99,18 +99,18 @@ first_large = for n in *numbers -This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. +Esta sintaxe de break-com-valor permite padrões concisos e expressivos de busca ou saída antecipada diretamente em expressões de loop. -You can also filter values by combining the for loop expression with the continue statement. +Você também pode filtrar valores combinando a expressão do loop for com a instrução continue. -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. +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. ```yuescript func_a = -> for i = 1, 10 do print i func_b = -> return for i = 1, 10 do i -print func_a! -- prints nil -print func_b! -- prints table object +print func_a! -- imprime nil +print func_b! -- imprime objeto table ``` @@ -118,10 +118,10 @@ print func_b! -- prints table object func_a = -> for i = 1, 10 do print i func_b = -> return for i = 1, 10 do i -print func_a! -- prints nil -print func_b! -- prints table object +print func_a! -- imprime nil +print func_b! -- imprime objeto table ``` -This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. +Isso é feito para evitar a criação desnecessária de tabelas para funções que não precisam retornar os resultados do loop. diff --git a/doc/docs/pt-br/doc/control-flow/switch.md b/doc/docs/pt-br/doc/control-flow/switch.md index f503a80..5c87327 100644 --- a/doc/docs/pt-br/doc/control-flow/switch.md +++ b/doc/docs/pt-br/doc/control-flow/switch.md @@ -1,33 +1,33 @@ # Switch -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. +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. ```yuescript switch name := "Dan" when "Robert" - print "You are Robert" + print "Você é Robert" when "Dan", "Daniel" - print "Your name, it's Dan" + print "Seu nome é Dan" else - print "I don't know about you with name #{name}" + print "Não sei quem você é com o nome #{name}" ``` ```yue switch name := "Dan" when "Robert" - print "You are Robert" + print "Você é Robert" when "Dan", "Daniel" - print "Your name, it's Dan" + print "Seu nome é Dan" else - print "I don't know about you with name #{name}" + print "Não sei quem você é com o nome #{name}" ``` -A switch when clause can match against multiple values by listing them out comma separated. +Uma cláusula when de um switch pode corresponder a múltiplos valores listando-os separados por vírgula. -Switches can be used as expressions as well, here we can assign the result of the switch to a variable: +Os switches também podem ser usados como expressões; aqui podemos atribuir o resultado do switch a uma variável: ```yuescript b = 1 @@ -37,7 +37,7 @@ next_number = switch b when 2 3 else - error "can't count that high!" + error "não consigo contar tão alto!" ``` @@ -49,66 +49,66 @@ next_number = switch b when 2 3 else - error "can't count that high!" + error "não consigo contar tão alto!" ``` -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. +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. ```yuescript msg = switch math.random(1, 5) - when 1 then "you are lucky" - when 2 then "you are almost lucky" - else "not so lucky" + when 1 then "você tem sorte" + when 2 then "você quase tem sorte" + else "não tão sortudo" ``` ```yue msg = switch math.random(1, 5) - when 1 then "you are lucky" - when 2 then "you are almost lucky" - else "not so lucky" + when 1 then "você tem sorte" + when 2 then "você quase tem sorte" + else "não tão sortudo" ``` -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. +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. ```yuescript switch math.random(1, 5) when 1 - print "you are lucky" -- two indents + print "você tem sorte" -- duas indentações else - print "not so lucky" + print "não tão sortudo" switch math.random(1, 5) when 1 - print "you are lucky" -- one indent + print "você tem sorte" -- uma indentação else - print "not so lucky" + print "não tão sortudo" ``` ```yue switch math.random(1, 5) when 1 - print "you are lucky" -- two indents + print "você tem sorte" -- duas indentações else - print "not so lucky" + print "não tão sortudo" switch math.random(1, 5) when 1 - print "you are lucky" -- one indent + print "você tem sorte" -- uma indentação else - print "not so lucky" + print "não tão sortudo" ``` -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. +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. -## Table Matching +## Correspondência de tabela -You can do table matching in a switch when clause, if the table can be destructured by a specific structure and get non-nil values. +Você pode fazer correspondência de tabela em uma cláusula when de switch, se a tabela puder ser desestruturada por uma estrutura específica e obter valores não-nil. ```yuescript items = @@ -122,7 +122,7 @@ for item in *items when :x, :y print "Vec2 #{x}, #{y}" when :width, :height - print "size #{width}, #{height}" + print "tamanho #{width}, #{height}" ``` @@ -138,39 +138,39 @@ for item in *items when :x, :y print "Vec2 #{x}, #{y}" when :width, :height - print "size #{width}, #{height}" + print "tamanho #{width}, #{height}" ``` -You can use default values to optionally destructure the table for some fields. +Você pode usar valores padrão para opcionalmente desestruturar a tabela para alguns campos. ```yuescript item = {} -{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') +{pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos') switch item when {pos: {:x = 50, :y = 200}} - print "Vec2 #{x}, #{y}" -- table destructuring will still pass + print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará ``` ```yue item = {} -{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') +{pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos') switch item when {pos: {:x = 50, :y = 200}} - print "Vec2 #{x}, #{y}" -- table destructuring will still pass + print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará ``` -You can also match against array elements, table fields, and even nested structures with array or table literals. +Você também pode corresponder contra elementos de array, campos de tabela, e até estruturas aninhadas com literais de array ou tabela. -Match against array elements. +Corresponder contra elementos de array. ```yuescript switch tb @@ -178,7 +178,7 @@ switch tb print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" - when [1, 2, b = 3] -- b has a default value + when [1, 2, b = 3] -- b tem valor padrão print "1, 2, #{b}" ``` @@ -189,63 +189,63 @@ switch tb print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" - when [1, 2, b = 3] -- b has a default value + when [1, 2, b = 3] -- b tem valor padrão print "1, 2, #{b}" ``` -Match against table fields with destructuring. +Corresponder contra campos de tabela com desestruturação. ```yuescript switch tb when success: true, :result - print "success", result + print "sucesso", result when success: false - print "failed", result + print "falhou", result else - print "invalid" + print "inválido" ``` ```yue switch tb when success: true, :result - print "success", result + print "sucesso", result when success: false - print "failed", result + print "falhou", result else - print "invalid" + print "inválido" ``` -Match against nested table structures. +Corresponder contra estruturas de tabela aninhadas. ```yuescript switch tb when data: {type: "success", :content} - print "success", content + print "sucesso", content when data: {type: "error", :content} - print "failed", content + print "erro", content else - print "invalid" + print "inválido" ``` ```yue switch tb when data: {type: "success", :content} - print "success", content + print "sucesso", content when data: {type: "error", :content} - print "failed", content + print "erro", content else - print "invalid" + print "inválido" ``` -Match against array of tables. +Corresponder contra array de tabelas. ```yuescript switch tb @@ -255,7 +255,7 @@ switch tb {a: 5, b: 6} fourth ] - print "matched", fourth + print "correspondido", fourth ``` @@ -267,20 +267,20 @@ switch tb {a: 5, b: 6} fourth ] - print "matched", fourth + print "correspondido", fourth ``` -Match against a list and capture a range of elements. +Corresponder contra uma lista e capturar um intervalo de elementos. ```yuescript segments = ["admin", "users", "logs", "view"] switch segments when [...groups, resource, action] - print "Group:", groups -- prints: {"admin", "users"} - print "Resource:", resource -- prints: "logs" - print "Action:", action -- prints: "view" + print "Grupo:", groups -- imprime: {"admin", "users"} + print "Recurso:", resource -- imprime: "logs" + print "Ação:", action -- imprime: "view" ``` @@ -288,9 +288,9 @@ switch segments segments = ["admin", "users", "logs", "view"] switch segments when [...groups, resource, action] - print "Group:", groups -- prints: {"admin", "users"} - print "Resource:", resource -- prints: "logs" - print "Action:", action -- prints: "view" + print "Grupo:", groups -- imprime: {"admin", "users"} + print "Recurso:", resource -- imprime: "logs" + print "Ação:", action -- imprime: "view" ``` diff --git a/doc/docs/pt-br/doc/control-flow/while-loop.md b/doc/docs/pt-br/doc/control-flow/while-loop.md index 502935e..f47f00c 100644 --- a/doc/docs/pt-br/doc/control-flow/while-loop.md +++ b/doc/docs/pt-br/doc/control-flow/while-loop.md @@ -1,6 +1,6 @@ -# While Loop +# Loop While -The while loop also comes in four variations: +O loop while também vem em quatro variações: ```yuescript i = 10 @@ -43,11 +43,11 @@ until running == false do my_function! -Like for loops, the while loop can also be used an expression. Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. +Como os loops for, o loop while também pode ser usado como expressão. Além disso, para uma função retornar o valor acumulado de um loop while, a instrução deve ser explicitamente retornada. -## Repeat Loop +## Loop Repeat -The repeat loop comes from Lua: +O loop repeat vem do Lua: ```yuescript i = 10 diff --git a/doc/docs/pt-br/doc/data-structures/comprehensions.md b/doc/docs/pt-br/doc/data-structures/comprehensions.md index 3a92167..1694813 100644 --- a/doc/docs/pt-br/doc/data-structures/comprehensions.md +++ b/doc/docs/pt-br/doc/data-structures/comprehensions.md @@ -1,10 +1,10 @@ -# Comprehensions +# Compreensões -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. +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. -## List Comprehensions +## Compreensões de lista -The following creates a copy of the items table but with all the values doubled. +O seguinte cria uma cópia da tabela items mas com todos os valores dobrados. ```yuescript items = [ 1, 2, 3, 4 ] @@ -19,7 +19,7 @@ doubled = [item * 2 for i, item in ipairs items] -The items included in the new table can be restricted with a when clause: +Os itens incluídos na nova tabela podem ser restringidos com uma cláusula when: ```yuescript slice = [item for i, item in ipairs items when i > 1 and i < 3] @@ -32,7 +32,7 @@ slice = [item for i, item in ipairs items when i > 1 and i < 3] -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: +Como é comum iterar sobre os valores de uma tabela indexada numericamente, um operador **\*** é introduzido. O exemplo doubled pode ser reescrito como: ```yuescript doubled = [item * 2 for item in *items] @@ -45,7 +45,7 @@ doubled = [item * 2 for item in *items] -In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: +Nas compreensões de lista, você também pode usar o operador spread `...` para achatar listas aninhadas, alcançando um efeito de flat map: ```yuescript data = @@ -53,7 +53,7 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat agora é [1, 2, 3, 4, 5, 6] ``` @@ -63,14 +63,14 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat agora é [1, 2, 3, 4, 5, 6] ``` -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. +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. -Using multiple for clauses is the same as using nested loops: +Usar múltiplas cláusulas for é o mesmo que usar loops aninhados: ```yuescript x_coords = [4, 5, 6, 7] @@ -91,7 +91,7 @@ for y in *y_coords] -Numeric for loops can also be used in comprehensions: +Loops for numéricos também podem ser usados em compreensões: ```yuescript evens = [i for i = 1, 100 when i % 2 == 0] @@ -104,11 +104,11 @@ evens = [i for i = 1, 100 when i % 2 == 0] -## Table Comprehensions +## Compreensões de tabela -The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. +A sintaxe para compreensões de tabela é muito semelhante, diferindo apenas por usar **{** e **}** e receber dois valores de cada iteração. -This example makes a copy of the tablething: +Este exemplo faz uma cópia da tabela thing: ```yuescript thing = { @@ -144,7 +144,7 @@ no_color = {k, v for k, v in pairs thing when k != "color"} -The **\*** operator is also supported. Here we create a square root look up table for a few numbers. +O operador **\*** também é suportado. Aqui criamos uma tabela de consulta de raiz quadrada para alguns números. ```yuescript numbers = [1, 2, 3, 4] @@ -159,9 +159,9 @@ sqrts = {i, math.sqrt i for i in *numbers} -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: +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: -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. +Neste exemplo convertemos um array de pares em uma tabela onde o primeiro item do par é a chave e o segundo é o valor. ```yuescript tuples = [ ["hello", "world"], ["foo", "bar"]] @@ -178,9 +178,9 @@ tbl = {unpack tuple for tuple in *tuples} ## Slicing -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. +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. -Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive: +Aqui podemos definir os limites mínimo e máximo, pegando todos os itens com índices entre 1 e 5 inclusive: ```yuescript slice = [item for item in *items[1, 5]] @@ -193,7 +193,7 @@ slice = [item for item in *items[1, 5]] -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: +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: ```yuescript slice = [item for item in *items[2,]] @@ -206,7 +206,7 @@ slice = [item for item in *items[2,]] -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, …) +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, …) ```yuescript slice = [item for item in *items[,,2]] @@ -219,22 +219,22 @@ slice = [item for item in *items[,,2]] -Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. +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. ```yuescript --- take the last 4 items +-- pegar os últimos 4 itens slice = [item for item in *items[-4,-1]] ``` ```yue --- take the last 4 items +-- pegar os últimos 4 itens slice = [item for item in *items[-4,-1]] ``` -The step size can also be negative, which means that the items are taken in reverse order. +O tamanho do passo também pode ser negativo, o que significa que os itens são tomados em ordem reversa. ```yuescript reverse_slice = [item for item in *items[-1,1,-1]] @@ -247,24 +247,24 @@ reverse_slice = [item for item in *items[-1,1,-1]] -### Slicing Expression +### Expressão de slicing -Slicing can also be used as an expression. This is useful for getting a sub-list of a table. +O slicing também pode ser usado como expressão. Isso é útil para obter uma sublista de uma tabela. ```yuescript --- take the 2nd and 4th items as a new list +-- pegar o 2º e 4º itens como nova lista sub_list = items[2, 4] --- take the last 4 items +-- pegar os últimos 4 itens last_four_items = items[-4, -1] ``` ```yue --- take the 2nd and 4th items as a new list +-- pegar o 2º e 4º itens como nova lista sub_list = items[2, 4] --- take the last 4 items +-- pegar os últimos 4 itens last_four_items = items[-4, -1] ``` diff --git a/doc/docs/pt-br/doc/data-structures/table-literals.md b/doc/docs/pt-br/doc/data-structures/table-literals.md index c1adcab..f0fbdc5 100644 --- a/doc/docs/pt-br/doc/data-structures/table-literals.md +++ b/doc/docs/pt-br/doc/data-structures/table-literals.md @@ -1,6 +1,6 @@ -# Table Literals +# Literais de tabela -Like in Lua, tables are delimited in curly braces. +Como no Lua, as tabelas são delimitadas por chaves. ```yuescript some_values = [1, 2, 3, 4] @@ -13,7 +13,7 @@ some_values = [1, 2, 3, 4] -Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). +Diferente do Lua, atribuir um valor a uma chave em uma tabela é feito com **:** (em vez de **=**). ```yuescript some_values = { @@ -34,7 +34,7 @@ some_values = { -The curly braces can be left off if a single table of key value pairs is being assigned. +As chaves podem ser omitidas se uma única tabela de pares chave-valor está sendo atribuída. ```yuescript profile = @@ -53,7 +53,7 @@ profile = -Newlines can be used to delimit values instead of a comma (or both): +Quebras de linha podem ser usadas para delimitar valores em vez de vírgula (ou ambos): ```yuescript values = { @@ -76,7 +76,7 @@ values = { -When creating a single line table literal, the curly braces can also be left off: +Ao criar um literal de tabela em uma única linha, as chaves também podem ser omitidas: ```yuescript my_function dance: "Tango", partner: "none" @@ -93,7 +93,7 @@ y = type: "dog", legs: 4, tails: 1 -The keys of a table literal can be language keywords without being escaped: +As chaves de um literal de tabela podem ser palavras-chave da linguagem sem precisar escapar: ```yuescript tbl = { @@ -112,7 +112,7 @@ tbl = { -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: +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: ```yuescript hair = "golden" @@ -133,7 +133,7 @@ print_table :hair, :height -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. +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. ```yuescript t = { @@ -152,7 +152,7 @@ t = { -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. +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. ```yuescript some_values = [1, 2, 3, 4] diff --git a/doc/docs/pt-br/doc/functions/backcalls.md b/doc/docs/pt-br/doc/functions/backcalls.md index e34331e..924c10a 100644 --- a/doc/docs/pt-br/doc/functions/backcalls.md +++ b/doc/docs/pt-br/doc/functions/backcalls.md @@ -1,6 +1,6 @@ # Backcalls -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. +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. ```yuescript x <- f @@ -15,7 +15,7 @@ print "hello" .. x -Fat arrow functions are also available. +Funções seta "fat" também estão disponíveis. ```yuescript <= f @@ -30,7 +30,7 @@ print @value -You can specify a placeholder for where you want the backcall function to go as a parameter. +Você pode especificar um placeholder para onde deseja que a função backcall vá como parâmetro. ```yuescript (x) <- map _, [1, 2, 3] @@ -45,7 +45,7 @@ x * 2 -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. +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. ```yuescript result, msg = do diff --git a/doc/docs/pt-br/doc/functions/function-literals.md b/doc/docs/pt-br/doc/functions/function-literals.md index 316e07c..e63888f 100644 --- a/doc/docs/pt-br/doc/functions/function-literals.md +++ b/doc/docs/pt-br/doc/functions/function-literals.md @@ -1,21 +1,21 @@ -# Function Literals +# Literais de função -All functions are created using a function expression. A simple function is denoted using the arrow: **->**. +Todas as funções são criadas usando uma expressão de função. Uma função simples é denotada usando a seta: **->**. ```yuescript my_function = -> -my_function() -- call the empty function +my_function() -- chama a função vazia ``` ```yue my_function = -> -my_function() -- call the empty function +my_function() -- chama a função vazia ``` -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: +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: ```yuescript func_a = -> print "hello world" @@ -36,7 +36,7 @@ func_b = -> -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. +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. ```yuescript func_a! @@ -51,7 +51,7 @@ func_b() -Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: +Funções com argumentos podem ser criadas precedendo a seta com uma lista de nomes de argumentos entre parênteses: ```yuescript sum = (x, y) -> print "sum", x + y @@ -64,7 +64,7 @@ sum = (x, y) -> print "sum", x + y -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. +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. ```yuescript sum 10, 20 @@ -83,7 +83,7 @@ a b c "a", "b", "c" -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. +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. ```yuescript print "x:", sum(10, 20), "y:", sum(30, 40) @@ -96,9 +96,9 @@ print "x:", sum(10, 20), "y:", sum(30, 40) -There must not be any space between the opening parenthesis and the function. +Não deve haver espaço entre o parêntese de abertura e a função. -Functions will coerce the last statement in their body into a return statement, this is called implicit return: +As funções convertem a última instrução em seu corpo em uma instrução de retorno, isso é chamado de retorno implícito: ```yuescript sum = (x, y) -> x + y @@ -113,7 +113,7 @@ print "The sum is ", sum 10, 20 -And if you need to explicitly return, you can use the return keyword: +E se você precisar retornar explicitamente, pode usar a palavra-chave return: ```yuescript sum = (x, y) -> return x + y @@ -126,7 +126,7 @@ sum = (x, y) -> return x + y -Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: +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: ```yuescript mystery = (x, y) -> x + y, x - y @@ -141,9 +141,9 @@ a, b = mystery 10, 20 -## Fat Arrows +## Setas fat -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. +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. ```yuescript func = (num) => @value + num @@ -156,9 +156,9 @@ func = (num) => @value + num -## Argument Defaults +## Valores padrão de argumentos -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. +É 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. ```yuescript my_function = (name = "something", height = 100) -> @@ -175,7 +175,7 @@ my_function = (name = "something", height = 100) -> -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. +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. ```yuescript some_args = (x = 100, y = x + 1000) -> @@ -190,11 +190,11 @@ some_args = (x = 100, y = x + 1000) -> -## Considerations +## Considerações -Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. +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. -The minus sign plays two roles, a unary negation operator and a binary subtraction operator. Consider how the following examples compile: +O sinal de menos desempenha dois papéis: um operador de negação unário e um operador de subtração binário. Considere como os seguintes exemplos compilam: ```yuescript a = x - 10 @@ -213,11 +213,11 @@ d = x- z -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. +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. -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. +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. -Where there is a space following a variable and a string literal, the function call acts as show above. The string literal belongs to any following expressions (if they exist), which serves as the argument list. +Quando há um espaço após uma variável e um literal de string, a chamada de função age como mostrado acima. O literal de string pertence a quaisquer expressões seguintes (se existirem), que servem como lista de argumentos. ```yuescript x = func"hello" + 100 @@ -232,11 +232,11 @@ y = func "hello" + 100 -## Multi-line arguments +## Argumentos multilinha -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. +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. -If an argument list is to be continued onto the next line, the current line must end in a comma. And the following line must be indented more than the current indentation. Once indented, all other argument lines must be at the same level of indentation to be part of the argument list +Se uma lista de argumentos for continuada na próxima linha, a linha atual deve terminar em vírgula. E a linha seguinte deve estar mais indentada que a indentação atual. Uma vez indentada, todas as outras linhas de argumentos devem estar no mesmo nível de indentação para fazer parte da lista de argumentos. ```yuescript my_func 5, 4, 3, @@ -261,7 +261,7 @@ cool_func 1, 2, -This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. +Este tipo de invocação pode ser aninhado. O nível de indentação é usado para determinar a qual função os argumentos pertencem. ```yuescript my_func 5, 6, 7, @@ -280,7 +280,7 @@ my_func 5, 6, 7, -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. +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. ```yuescript x = [ @@ -301,7 +301,7 @@ x = [ -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. +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. ```yuescript y = [ my_func 1, 2, 3, @@ -320,7 +320,7 @@ y = [ my_func 1, 2, 3, -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: +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: ```yuescript if func 1, 2, 3, @@ -353,13 +353,13 @@ if func 1, 2, 3, -## Parameter Destructuring +## Desestruturação de parâmetros -YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: +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: -* **Curly-brace wrapped literals/object parameters**, allowing optional default values when fields are missing (e.g., `{:a, :b}`, `{a: a1 = 123}`). +* **Literais/parâmetros de objeto envolvidos em chaves**, permitindo valores padrão opcionais quando os campos estão ausentes (ex.: `{:a, :b}`, `{a: a1 = 123}`). -* **Unwrapped simple table syntax**, starting with a sequence of key-value or shorthand bindings and continuing until another expression terminates it (e.g., `:a, b: b1, :c`). This form extracts multiple fields from the same object. +* **Sintaxe de tabela simples não envolvida**, começando com uma sequência de ligações chave-valor ou abreviadas e continuando até outra expressão terminá-la (ex.: `:a, b: b1, :c`). Esta forma extrai múltiplos campos do mesmo objeto. ```yuescript f1 = (:a, :b, :c) -> @@ -390,9 +390,9 @@ f2 arg1, arg2 -## Prefixed Return Expression +## Expressão de retorno prefixada -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: +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: ```yuescript findFirstEven = (list): nil -> @@ -415,7 +415,7 @@ findFirstEven = (list): nil -> -This is equivalent to: +Isso é equivalente a: ```yuescript findFirstEven = (list) -> @@ -440,16 +440,16 @@ findFirstEven = (list) -> -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. +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. -## Named Varargs +## Varargs nomeados -You can use the `(...t) ->` syntax to automatically store varargs into a named table. This table will contain all passed arguments (including `nil` values), and the `n` field of the table will store the actual number of arguments passed (including `nil` values). +Você pode usar a sintaxe `(...t) ->` para armazenar automaticamente varargs em uma tabela nomeada. Esta tabela conterá todos os argumentos passados (incluindo valores `nil`), e o campo `n` da tabela armazenará o número real de argumentos passados (incluindo valores `nil`). ```yuescript f = (...t) -> - print "argument count:", t.n - print "table length:", #t + print "contagem de argumentos:", t.n + print "comprimento da tabela:", #t for i = 1, t.n print t[i] @@ -457,7 +457,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Tratando casos com valores nil process = (...args) -> sum = 0 for i = 1, args.n @@ -471,8 +471,8 @@ process 1, nil, 3, nil, 5 ```yue f = (...t) -> - print "argument count:", t.n - print "table length:", #t + print "contagem de argumentos:", t.n + print "comprimento da tabela:", #t for i = 1, t.n print t[i] @@ -480,7 +480,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Tratando casos com valores nil process = (...args) -> sum = 0 for i = 1, args.n diff --git a/doc/docs/pt-br/doc/functions/function-stubs.md b/doc/docs/pt-br/doc/functions/function-stubs.md index 57a8b0c..d13f8ed 100644 --- a/doc/docs/pt-br/doc/functions/function-stubs.md +++ b/doc/docs/pt-br/doc/functions/function-stubs.md @@ -1,10 +1,10 @@ -# Function Stubs +# Stubs de função -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. +É 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. -The function stub syntax is a shorthand for creating a new closure function that bundles both the object and function. This new function calls the wrapped function in the correct context of the object. +A sintaxe de function stub é uma forma abreviada de criar uma nova função closure que empacota tanto o objeto quanto a função. Esta nova função chama a função empacotada no contexto correto do objeto. -Its syntax is the same as calling an instance method with the \ operator but with no argument list provided. +Sua sintaxe é a mesma que chamar um método de instância com o operador \, mas sem lista de argumentos fornecida. ```yuescript my_object = { @@ -16,12 +16,12 @@ run_callback = (func) -> print "running callback..." func! --- this will not work: --- the function has to no reference to my_object +-- isso não funcionará: +-- a função não tem referência a my_object run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- sintaxe de function stub +-- nos permite empacotar o objeto em uma nova função run_callback my_object\write ``` @@ -36,12 +36,12 @@ run_callback = (func) -> print "running callback..." func! --- this will not work: --- the function has to no reference to my_object +-- isso não funcionará: +-- a função não tem referência a my_object run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- sintaxe de function stub +-- nos permite empacotar o objeto em uma nova função run_callback my_object\write ``` diff --git a/doc/docs/pt-br/doc/getting-started/installation.md b/doc/docs/pt-br/doc/getting-started/installation.md index a93ddfd..c5ee875 100644 --- a/doc/docs/pt-br/doc/getting-started/installation.md +++ b/doc/docs/pt-br/doc/getting-started/installation.md @@ -1,43 +1,43 @@ -# Installation +# Instalação -## Lua Module +## Módulo Lua -Install [luarocks](https://luarocks.org), a package manager for Lua modules. Then install it as a Lua module and executable with: +Instale o [luarocks](https://luarocks.org), um gerenciador de pacotes para módulos Lua. Em seguida, instale-o como módulo Lua e executável com: ```shell luarocks install yuescript ``` -Or you can build `yue.so` file with: +Ou você pode compilar o arquivo `yue.so` com: ```shell make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua ``` -Then get the binary file from path **bin/shared/yue.so**. +Depois, obtenha o arquivo binário no caminho **bin/shared/yue.so**. -## Build Binary Tool +## Compilar ferramenta binária -Clone this repo, then build and install executable with: +Clone este repositório e compile e instale o executável com: ```shell make install ``` -Build YueScript tool without macro feature: +Compilar a ferramenta YueScript sem o recurso de macro: ```shell make install NO_MACRO=true ``` -Build YueScript tool without built-in Lua binary: +Compilar a ferramenta YueScript sem o binário Lua embutido: ```shell make install NO_LUA=true ``` -## Download Precompiled Binary +## Baixar binário pré-compilado -You can download precompiled binary files, including binary executable files compatible with different Lua versions and library files. +Você pode baixar arquivos binários pré-compilados, incluindo executáveis compatíveis com diferentes versões do Lua e arquivos de biblioteca. -Download precompiled binary files from [here](https://github.com/IppClub/YueScript/releases). +Baixe os arquivos binários pré-compilados [aqui](https://github.com/IppClub/YueScript/releases). diff --git a/doc/docs/pt-br/doc/getting-started/introduction.md b/doc/docs/pt-br/doc/getting-started/introduction.md index a9a9389..8c3f30a 100644 --- a/doc/docs/pt-br/doc/getting-started/introduction.md +++ b/doc/docs/pt-br/doc/getting-started/introduction.md @@ -1,16 +1,16 @@ -# Introduction +# Introdução -YueScript is a dynamic language that compiles to Lua. And it's a [MoonScript](https://github.com/leafo/moonscript) dialect. The codes written in YueScript are expressive and extremely concise. And it is suitable for writing some changing application logic with more maintainable codes and runs in a Lua embeded environment such as games or website servers. +YueScript é uma linguagem dinâmica que compila para Lua. É um dialeto do [MoonScript](https://github.com/leafo/moonscript). O código escrito em YueScript é expressivo e extremamente conciso. É adequado para escrever lógica de aplicação variável com código mais manutenível e roda em ambientes Lua embutidos, como jogos ou servidores web. -Yue (月) is the name of moon in Chinese and it's pronounced as [jyɛ]. +Yue (月) é o nome da lua em chinês e é pronunciado como [jyɛ]. -## An Overview of YueScript +## Uma visão geral do YueScript ```yuescript --- import syntax +-- sintaxe de importação import p, to_lua from "yue" --- object literals +-- literais de objeto inventory = equipment: - "sword" @@ -21,7 +21,7 @@ inventory = - name: "bread" count: 3 --- list comprehension +-- compreensão de lista map = (arr, action) -> [action item for item in *arr] @@ -31,14 +31,14 @@ filter = (arr, cond) -> reduce = (arr, init, action): init -> init = action init, item for item in *arr --- pipe operator +-- operador pipe [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print --- metatable manipulation +-- manipulação de metatable apple = size: 15 : @@ -47,17 +47,17 @@ apple = with apple p .size, .color, . if .<>? --- js-like export syntax -export 🌛 = "月之脚本" +-- sintaxe de exportação estilo js +export 🌛 = "Script da Lua" ``` ```yue --- import syntax +-- sintaxe de importação import p, to_lua from "yue" --- object literals +-- literais de objeto inventory = equipment: - "sword" @@ -68,7 +68,7 @@ inventory = - name: "bread" count: 3 --- list comprehension +-- compreensão de lista map = (arr, action) -> [action item for item in *arr] @@ -78,14 +78,14 @@ filter = (arr, cond) -> reduce = (arr, init, action): init -> init = action init, item for item in *arr --- pipe operator +-- operador pipe [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print --- metatable manipulation +-- manipulação de metatable apple = size: 15 : @@ -94,12 +94,12 @@ apple = with apple p .size, .color, . if .<>? --- js-like export syntax -export 🌛 = "月之脚本" +-- sintaxe de exportação estilo js +export 🌛 = "Script da Lua" ``` -## About Dora SSR +## Sobre o Dora SSR -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. \ No newline at end of file +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. diff --git a/doc/docs/pt-br/doc/getting-started/usage.md b/doc/docs/pt-br/doc/getting-started/usage.md index 45161c6..7653838 100644 --- a/doc/docs/pt-br/doc/getting-started/usage.md +++ b/doc/docs/pt-br/doc/getting-started/usage.md @@ -1,20 +1,20 @@ -# Usage +# Uso -## Lua Module +## Módulo Lua -Use YueScript module in Lua: +Use o módulo YueScript em Lua: -* **Case 1** +* **Caso 1** - Require "your_yuescript_entry.yue" in Lua. + Use require em "your_yuescript_entry.yue" no Lua. ```Lua require("yue")("your_yuescript_entry") ``` - And this code still works when you compile "your_yuescript_entry.yue" to "your_yuescript_entry.lua" in the same path. In the rest YueScript files just use the normal **require** or **import**. The code line numbers in error messages will also be handled correctly. + E esse código continua funcionando quando você compila "your_yuescript_entry.yue" para "your_yuescript_entry.lua" no mesmo caminho. Nos demais arquivos YueScript, use normalmente o **require** ou **import**. Os números de linha nas mensagens de erro também serão tratados corretamente. -* **Case 2** +* **Caso 2** - Require YueScript module and rewite message by hand. + Requerer o módulo YueScript e reescrever a mensagem manualmente. ```lua local yue = require("yue") @@ -26,9 +26,9 @@ Use YueScript module in Lua: end) ``` -* **Case 3** +* **Caso 3** - Use the YueScript compiler function in Lua. + Usar a função compiladora do YueScript em Lua. ```lua local yue = require("yue") @@ -48,9 +48,9 @@ Use YueScript module in Lua: }) ``` -## YueScript Tool +## Ferramenta YueScript -Use YueScript tool with: +Use a ferramenta YueScript com: ```shell > yue -h @@ -60,52 +60,53 @@ Usage: yue yue -w [] [options] yue - -Notes: - - '-' / '--' must be the first and only argument. - - '-o/--output' can not be used with multiple input files. - - '-w/--watch' can not be used with file input (directory only). - - with '-e/--execute', remaining tokens are treated as script args. - -Options: - -h, --help Show this help message and exit. - -e , --execute Execute a file or raw codes - -m, --minify Generate minified codes - -r, --rewrite Rewrite output to match original line numbers +Notas: + - '-' / '--' deve ser o primeiro e único argumento. + - '-o/--output' não pode ser usado com múltiplos arquivos de entrada. + - '-w/--watch' não pode ser usado com entrada de arquivo (apenas diretório). + - com '-e/--execute', os tokens restantes são tratados como argumentos do script. + +Opções: + -h, --help Mostrar esta mensagem de ajuda e sair. + -e , --execute Executar um arquivo ou código bruto + -m, --minify Gerar código minificado + -r, --rewrite Reescrever saída para corresponder aos números de linha originais -t , --output-to - Specify where to place compiled files - -o , --output Write output to file - -p, --print Write output to standard out - -b, --benchmark Dump compile time (doesn't write output) - -g, --globals Dump global variables used in NAME LINE COLUMN - -s, --spaces Use spaces in generated codes instead of tabs - -l, --line-numbers Write line numbers from source codes - -j, --no-implicit-return Disable implicit return at end of file - -c, --reserve-comments Reserve comments before statement from source codes + Especificar onde colocar os arquivos compilados + -o , --output Escrever saída em arquivo + -p, --print Escrever saída na saída padrão + -b, --benchmark Mostrar tempo de compilação (não grava saída) + -g, --globals Listar variáveis globais usadas em NOME LINHA COLUNA + -s, --spaces Usar espaços no código gerado em vez de tabulações + -l, --line-numbers Escrever números de linha do código fonte + -j, --no-implicit-return Desabilitar retorno implícito no final do arquivo + -c, --reserve-comments Preservar comentários antes de instruções do código fonte -w [], --watch [] - Watch changes and compile every file under directory - -v, --version Print version - - Read from standard in, print to standard out - (Must be first and only argument) - -- Same as '-' (kept for backward compatibility) - - --target Specify the Lua version that codes will be generated to - (version can only be 5.1 to 5.5) - --path Append an extra Lua search path string to package.path - --= Pass compiler option in key=value form (existing behavior) - - Execute without options to enter REPL, type symbol '$' - in a single line to start/stop multi-line mode + Observar alterações e compilar cada arquivo no diretório + -v, --version Imprimir versão + - Ler da entrada padrão, imprimir na saída padrão + (Deve ser o primeiro e único argumento) + -- Igual a '-' (mantido para compatibilidade retroativa) + + --target Especificar a versão do Lua para a qual o código será gerado + (a versão pode ser apenas 5.1 a 5.5) + --path Adicionar um caminho de busca Lua extra ao package.path + --= Passar opção do compilador no formato key=value (comportamento existente) + + Execute sem opções para entrar no REPL, digite o símbolo '$' + em uma única linha para iniciar/parar o modo multilinha ``` -Use cases: -Recursively compile every YueScript file with extension **.yue** under current path: **yue .** +Casos de uso: -Compile and save results to a target path: **yue -t /target/path/ .** +Compilar recursivamente todos os arquivos YueScript com extensão **.yue** no caminho atual: **yue .** -Compile and reserve debug info: **yue -l .** +Compilar e salvar resultados em um caminho de destino: **yue -t /target/path/ .** -Compile and generate minified codes: **yue -m .** +Compilar e preservar informações de debug: **yue -l .** -Execute raw codes: **yue -e 'print 123'** +Compilar e gerar código minificado: **yue -m .** -Execute a YueScript file: **yue -e main.yue** +Executar código bruto: **yue -e 'print 123'** + +Executar um arquivo YueScript: **yue -e main.yue** diff --git a/doc/docs/pt-br/doc/language-basics/attributes.md b/doc/docs/pt-br/doc/language-basics/attributes.md index e6fd5a7..8e27f21 100644 --- a/doc/docs/pt-br/doc/language-basics/attributes.md +++ b/doc/docs/pt-br/doc/language-basics/attributes.md @@ -1,21 +1,21 @@ -# Attributes +# Atributos -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. +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. ```yuescript const a = 123 -close _ = : -> print "Out of scope." +close _ = : -> print "Fora do escopo." ``` ```yue const a = 123 -close _ = : -> print "Out of scope." +close _ = : -> print "Fora do escopo." ``` -You can do desctructuring with variables attributed as constant. +Você pode fazer desestruturação com variáveis atribuídas como constante. ```yuescript const {:a, :b, c, d} = tb @@ -30,7 +30,7 @@ const {:a, :b, c, d} = tb -You can also declare a global variable to be `const`. +Você também pode declarar uma variável global como `const`. ```yuescript global const Constant = 123 diff --git a/doc/docs/pt-br/doc/language-basics/comment.md b/doc/docs/pt-br/doc/language-basics/comment.md index b67c97d..ed3102d 100644 --- a/doc/docs/pt-br/doc/language-basics/comment.md +++ b/doc/docs/pt-br/doc/language-basics/comment.md @@ -1,13 +1,13 @@ -# Comment +# Comentário ```yuescript --- I am a comment +-- Eu sou um comentário str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Este é um comentário multilinha. +Está OK. +]] strA \ -- comentário 1 + .. strB \ -- comentário 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" @@ -15,13 +15,13 @@ func --[[port]] 3000, --[[ip]] "192.168.1.1" ```yue --- I am a comment +-- Eu sou um comentário str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Este é um comentário multilinha. +Está OK. +]] strA \ -- comentário 1 + .. strB \ -- comentário 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" diff --git a/doc/docs/pt-br/doc/language-basics/literals.md b/doc/docs/pt-br/doc/language-basics/literals.md index e097c62..b32b73a 100644 --- a/doc/docs/pt-br/doc/language-basics/literals.md +++ b/doc/docs/pt-br/doc/language-basics/literals.md @@ -1,33 +1,33 @@ -# Literals +# Literais -All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. +Todos os literais primitivos do Lua podem ser usados. Isso se aplica a números, strings, booleanos e **nil**. -Unlike Lua, Line breaks are allowed inside of single and double quote strings without an escape sequence: +Diferente do Lua, quebras de linha são permitidas dentro de strings com aspas simples e duplas sem sequência de escape: ```yuescript -some_string = "Here is a string - that has a line break in it." +some_string = "Aqui está uma string + que tem uma quebra de linha." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. -print "I am #{math.random! * 100}% sure." +-- Você pode misturar expressões em literais de string usando a sintaxe #{}. +-- Interpolação de string está disponível apenas em strings com aspas duplas. +print "Tenho #{math.random! * 100}% de certeza." ``` ```yue -some_string = "Here is a string - that has a line break in it." +some_string = "Aqui está uma string + que tem uma quebra de linha." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. -print "I am #{math.random! * 100}% sure." +-- Você pode misturar expressões em literais de string usando a sintaxe #{}. +-- Interpolação de string está disponível apenas em strings com aspas duplas. +print "Tenho #{math.random! * 100}% de certeza." ``` -## Number Literals +## Literais numéricos -You can use underscores in a number literal to increase readability. +Você pode usar underscores em um literal numérico para aumentar a legibilidade. ```yuescript integer = 1_000_000 @@ -44,9 +44,9 @@ binary = 0B10011 -## YAML Multiline String +## String multilinha estilo YAML -The `|` prefix introduces a YAML-style multiline string literal: +O prefixo `|` introduz um literal de string multilinha no estilo YAML: ```yuescript str = | @@ -67,9 +67,9 @@ str = | -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)`. +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)`. -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. +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. ```yuescript fn = -> @@ -90,21 +90,21 @@ fn = -> -Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. +A indentação interna é preservada em relação ao prefixo comum removido, permitindo estruturas aninhadas limpas. -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. +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. ```yuescript str = | path: "C:\Program Files\App" - note: 'He said: "#{Hello}!"' + note: 'Ele disse: "#{Hello}!"' ``` ```yue str = | path: "C:\Program Files\App" - note: 'He said: "#{Hello}!"' + note: 'Ele disse: "#{Hello}!"' ``` diff --git a/doc/docs/pt-br/doc/language-basics/operator.md b/doc/docs/pt-br/doc/language-basics/operator.md index 9a2e89b..aba9c50 100644 --- a/doc/docs/pt-br/doc/language-basics/operator.md +++ b/doc/docs/pt-br/doc/language-basics/operator.md @@ -1,6 +1,6 @@ -# Operator +# Operador -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. +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. ```yuescript tb\func! if tb ~= nil @@ -15,32 +15,32 @@ tb::func! if tb != nil -## Chaining Comparisons +## Comparações encadeadas -Comparisons can be arbitrarily chained: +Comparações podem ser encadeadas arbitrariamente: ```yuescript print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 --- output: true +-- saída: true a = 5 print 1 <= a <= 10 --- output: true +-- saída: true ``` ```yue print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 --- output: true +-- saída: true a = 5 print 1 <= a <= 10 --- output: true +-- saída: true ``` -Note the evaluation behavior of chained comparisons: +Observe o comportamento de avaliação das comparações encadeadas: ```yuescript v = (x) -> @@ -49,7 +49,7 @@ v = (x) -> print v(1) < v(2) <= v(3) --[[ - output: + saída: 2 1 3 @@ -58,7 +58,7 @@ print v(1) < v(2) <= v(3) print v(1) > v(2) <= v(3) --[[ - output: + saída: 2 1 false @@ -73,7 +73,7 @@ v = (x) -> print v(1) < v(2) <= v(3) --[[ - output: + saída: 2 1 3 @@ -82,7 +82,7 @@ print v(1) < v(2) <= v(3) print v(1) > v(2) <= v(3) --[[ - output: + saída: 2 1 false @@ -91,11 +91,11 @@ print v(1) > v(2) <= v(3) -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. +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. -## Table Appending +## Anexar à tabela -The **[] =** operator is used to append values to tables. +O operador **[] =** é usado para anexar valores a tabelas. ```yuescript tab = [] @@ -110,13 +110,13 @@ tab[] = "Value" -You can also use the spread operator `...` to append all elements from one list to another: +Você também pode usar o operador spread `...` para anexar todos os elementos de uma lista a outra: ```yuescript tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA agora é [1, 2, 3, 4, 5, 6] ``` @@ -124,14 +124,14 @@ tbA[] = ...tbB tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA agora é [1, 2, 3, 4, 5, 6] ``` -## Table Spreading +## Spread de tabela -You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. +Você pode concatenar tabelas de array ou tabelas hash usando o operador spread `...` antes de expressões em literais de tabela. ```yuescript parts = @@ -170,9 +170,9 @@ merge = {...a, ...b} -## Table Reversed Indexing +## Indexação reversa de tabela -You can use the **#** operator to get the last elements of a table. +Você pode usar o operador **#** para obter os últimos elementos de uma tabela. ```yuescript last = data.items[#] @@ -191,11 +191,11 @@ data.items[#] = 1 ## Metatable -The **<>** operator can be used as a shortcut for metatable manipulation. +O operador **<>** pode ser usado como atalho para manipulação de metatable. -### Metatable Creation +### Criação de metatable -Create normal table with empty bracekets **<>** or metamethod key which is surrounded by **<>**. +Crie tabela normal com chaves vazias **<>** ou chave de metamétodo cercada por **<>**. ```yuescript mt = {} @@ -203,14 +203,14 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- definir campo com variável de mesmo nome b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value -close _ = : -> print "out of scope" +close _ = : -> print "fora do escopo" ``` @@ -220,24 +220,24 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- definir campo com variável de mesmo nome b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value -close _ = : -> print "out of scope" +close _ = : -> print "fora do escopo" ``` -### Metatable Accessing +### Acesso à metatable -Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. +Acesse a metatable com **<>** ou nome do metamétodo cercado por **<>** ou escrevendo alguma expressão em **<>**. ```yuescript --- create with metatable containing field "value" +-- criar com metatable contendo campo "value" tb = <"value">: 123 tb. = tb.<> print tb.value @@ -248,7 +248,7 @@ print tb.item ```yue --- create with metatable containing field "value" +-- criar com metatable contendo campo "value" tb = <"value">: 123 tb. = tb.<> print tb.value @@ -258,9 +258,9 @@ print tb.item -### Metatable Destructure +### Desestruturação de metatable -Destruct metatable with metamethod key surrounded by **<>**. +Desestruture a metatable com chave de metamétodo cercada por **<>**. ```yuescript {item, :new, :, : getter} = tb @@ -275,9 +275,9 @@ print item, new, close, getter -## Existence +## Existência -The **?** operator can be used in a variety of contexts to check for existence. +O operador **?** pode ser usado em diversos contextos para verificar existência. ```yuescript func?! @@ -312,16 +312,16 @@ with? io.open "test.txt", "w" -## Piping +## Pipe -Instead of a series of nested function calls, you can pipe values with operator **|>**. +Em vez de uma série de chamadas de função aninhadas, você pode encaminhar valores com o operador **|>**. ```yuescript "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder +1 |> print 2 -- insere o item do pipe como primeiro argumento +2 |> print 1, _, 3 -- pipe com um placeholder --- pipe expression in multiline +-- expressão pipe em multilinha readFile "example.txt" |> extract language, {} |> parse language @@ -333,9 +333,9 @@ readFile "example.txt" ```yue "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder --- pipe expression in multiline +1 |> print 2 -- insere o item do pipe como primeiro argumento +2 |> print 1, _, 3 -- pipe com um placeholder +-- expressão pipe em multilinha readFile "example.txt" |> extract language, {} |> parse language @@ -346,9 +346,9 @@ readFile "example.txt" -## Nil Coalescing +## Coalescência de nil -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. +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. ```yuescript local a, b, c, d a = b ?? c ?? d @@ -367,31 +367,31 @@ a ??= false -## Implicit Object +## Objeto implícito -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. +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. ```yuescript --- assignment with implicit object +-- atribuição com objeto implícito list = * 1 * 2 * 3 --- function call with implicit object +-- chamada de função com objeto implícito func * 1 * 2 * 3 --- return with implicit object +-- retorno com objeto implícito f = -> return * 1 * 2 * 3 --- table with implicit object +-- tabela com objeto implícito tb = name: "abc" @@ -416,26 +416,26 @@ tb = ```yue --- assignment with implicit object +-- atribuição com objeto implícito list = * 1 * 2 * 3 --- function call with implicit object +-- chamada de função com objeto implícito func * 1 * 2 * 3 --- return with implicit object +-- retorno com objeto implícito f = -> return * 1 * 2 * 3 --- table with implicit object +-- tabela com objeto implícito tb = name: "abc" diff --git a/doc/docs/pt-br/doc/language-basics/whitespace.md b/doc/docs/pt-br/doc/language-basics/whitespace.md index d742a2b..df844f9 100644 --- a/doc/docs/pt-br/doc/language-basics/whitespace.md +++ b/doc/docs/pt-br/doc/language-basics/whitespace.md @@ -1,10 +1,10 @@ -# Whitespace +# Espaço em branco -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. +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. -## Statement Separator +## Separador de instrução -A statement normally ends at a line break. You can also use a semicolon `;` to explicitly terminate a statement, which allows writing multiple statements on the same line: +Uma instrução normalmente termina em uma quebra de linha. Você também pode usar ponto e vírgula `;` para terminar explicitamente uma instrução, o que permite escrever múltiplas instruções na mesma linha: ```yuescript a = 1; b = 2; print a + b @@ -17,9 +17,9 @@ a = 1; b = 2; print a + b -## Multiline Chaining +## Encadeamento multilinha -You can write multi-line chaining function calls with a same indent. +Você pode escrever chamadas de função encadeadas em múltiplas linhas com a mesma indentação. ```yuescript Rx.Observable diff --git a/doc/docs/pt-br/doc/objects/object-oriented-programming.md b/doc/docs/pt-br/doc/objects/object-oriented-programming.md index 6a8559e..3d5f061 100644 --- a/doc/docs/pt-br/doc/objects/object-oriented-programming.md +++ b/doc/docs/pt-br/doc/objects/object-oriented-programming.md @@ -1,8 +1,8 @@ -# Object Oriented Programming +# Programação orientada a objetos -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. +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. -A simple class: +Uma classe simples: ```yuescript class Inventory @@ -31,15 +31,15 @@ class Inventory -A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. +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. -The new property is special in that it will become the constructor. +A propriedade new é especial pois se tornará o construtor. -Notice how all the methods in the class use the fat arrow function syntax. When calling methods on a instance, the instance itself is sent in as the first argument. The fat arrow handles the creation of a self argument. +Observe como todos os métodos da classe usam a sintaxe de função seta fat. Ao chamar métodos em uma instância, a própria instância é enviada como primeiro argumento. A seta fat cuida da criação do argumento self. -The @ prefix on a variable name is shorthand for self.. @items becomes self.items. +O prefixo @ em um nome de variável é abreviação para self.. @items torna-se self.items. -Creating an instance of the class is done by calling the name of the class as a function. +Criar uma instância da classe é feito chamando o nome da classe como uma função. ```yuescript inv = Inventory! @@ -56,11 +56,11 @@ inv\add_item "pants" -Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. +Como a instância da classe precisa ser enviada aos métodos quando são chamados, o operador \ é usado. -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. +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. -Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another: +Considere o exemplo abaixo, a propriedade clothes é compartilhada entre todas as instâncias, então modificações nela em uma instância aparecerão em outra: ```yuescript class Person @@ -74,7 +74,7 @@ b = Person! a\give_item "pants" b\give_item "shirt" --- will print both pants and shirt +-- vai imprimir tanto pants quanto shirt print item for item in *a.clothes ``` @@ -91,13 +91,13 @@ b = Person! a\give_item "pants" b\give_item "shirt" --- will print both pants and shirt +-- vai imprimir tanto pants quanto shirt print item for item in *a.clothes ``` -The proper way to avoid this problem is to create the mutable state of the object in the constructor: +A forma correta de evitar esse problema é criar o estado mutável do objeto no construtor: ```yuescript class Person @@ -114,9 +114,9 @@ class Person -## Inheritance +## Herança -The extends keyword can be used in a class declaration to inherit the properties and methods from another class. +A palavra-chave extends pode ser usada em uma declaração de classe para herdar as propriedades e métodos de outra classe. ```yuescript class BackPack extends Inventory @@ -137,18 +137,18 @@ class BackPack extends Inventory -Here we extend our Inventory class, and limit the amount of items it can carry. +Aqui estendemos nossa classe Inventory e limitamos a quantidade de itens que ela pode carregar. -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. +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. -Whenever a class inherits from another, it sends a message to the parent class by calling the method __inherited on the parent class if it exists. The function receives two arguments, the class that is being inherited and the child class. +Sempre que uma classe herda de outra, ela envia uma mensagem à classe pai chamando o método __inherited na classe pai se ele existir. A função recebe dois argumentos: a classe que está sendo herdada e a classe filha. ```yuescript class Shelf @__inherited: (child) => print @__name, "was inherited by", child.__name --- will print: Shelf was inherited by Cupboard +-- vai imprimir: Shelf was inherited by Cupboard class Cupboard extends Shelf ``` @@ -158,7 +158,7 @@ class Shelf @__inherited: (child) => print @__name, "was inherited by", child.__name --- will print: Shelf was inherited by Cupboard +-- vai imprimir: Shelf was inherited by Cupboard class Cupboard extends Shelf ``` @@ -166,27 +166,27 @@ class Cupboard extends Shelf ## Super -**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. +**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. -When called as a function, it will call the function of the same name in the parent class. The current self will automatically be passed as the first argument. (As seen in the inheritance example above) +Quando chamado como função, chamará a função de mesmo nome na classe pai. O self atual será automaticamente passado como primeiro argumento. (Como visto no exemplo de herança acima) -When super is used as a normal value, it is a reference to the parent class object. +Quando super é usado como valor normal, é uma referência ao objeto da classe pai. -It can be accessed like any of object in order to retrieve values in the parent class that might have been shadowed by the child class. +Pode ser acessado como qualquer objeto para recuperar valores na classe pai que possam ter sido sombreados pela classe filha. -When the \ calling operator is used with super, self is inserted as the first argument instead of the value of super itself. When using . to retrieve a function, the raw function is returned. +Quando o operador de chamada \ é usado com super, self é inserido como primeiro argumento em vez do valor do próprio super. Ao usar . para recuperar uma função, a função bruta é retornada. -A few examples of using super in different ways: +Alguns exemplos de uso de super de diferentes formas: ```yuescript class MyClass extends ParentClass a_method: => - -- the following have the same effect: + -- os seguintes têm o mesmo efeito: super "hello", "world" super\a_method "hello", "world" super.a_method self, "hello", "world" - -- super as a value is equal to the parent class: + -- super como valor é igual à classe pai: assert super == ParentClass ``` @@ -194,28 +194,28 @@ class MyClass extends ParentClass ```yue class MyClass extends ParentClass a_method: => - -- the following have the same effect: + -- os seguintes têm o mesmo efeito: super "hello", "world" super\a_method "hello", "world" super.a_method self, "hello", "world" - -- super as a value is equal to the parent class: + -- super como valor é igual à classe pai: assert super == ParentClass ``` -**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. +**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. -## Types +## Tipos -Every instance of a class carries its type with it. This is stored in the special __class property. This property holds the class object. The class object is what we call to build a new instance. We can also index the class object to retrieve class methods and properties. +Cada instância de uma classe carrega seu tipo consigo. Isso é armazenado na propriedade especial __class. Esta propriedade contém o objeto da classe. O objeto da classe é o que chamamos para construir uma nova instância. Também podemos indexar o objeto da classe para recuperar métodos e propriedades da classe. ```yuescript b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- imprime 10 ``` @@ -223,45 +223,45 @@ print BackPack.size -- prints 10 b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- imprime 10 ``` -## Class Objects +## Objetos de classe -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. +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. -The class object can be called like a function in order to create new instances. That's how we created instances of classes in the examples above. +O objeto da classe pode ser chamado como uma função para criar novas instâncias. É assim que criamos instâncias de classes nos exemplos acima. -A class is made up of two tables. The class table itself, and the base table. The base is used as the metatable for all the instances. All properties listed in the class declaration are placed in the base. +Uma classe é composta por duas tabelas. A própria tabela da classe e a tabela base. A base é usada como metatable para todas as instâncias. Todas as propriedades listadas na declaração da classe são colocadas na base. -The class object's metatable reads properties from the base if they don't exist in the class object. This means we can access functions and properties directly from the class. +A metatable do objeto da classe lê propriedades da base se não existirem no objeto da classe. Isso significa que podemos acessar funções e propriedades diretamente da classe. -It is important to note that assigning to the class object does not assign into the base, so it's not a valid way to add new methods to instances. Instead the base must explicitly be changed. See the __base field below. +É importante notar que atribuir ao objeto da classe não atribui à base, então não é uma forma válida de adicionar novos métodos às instâncias. Em vez disso, a base deve ser alterada explicitamente. Veja o campo __base abaixo. -The class object has a couple special properties: +O objeto da classe tem algumas propriedades especiais: -The name of the class as when it was declared is stored as a string in the __name field of the class object. +O nome da classe quando foi declarada é armazenado como string no campo __name do objeto da classe. ```yuescript -print BackPack.__name -- prints Backpack +print BackPack.__name -- imprime Backpack ``` ```yue -print BackPack.__name -- prints Backpack +print BackPack.__name -- imprime Backpack ``` -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. +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. -If the class extends from anything, the parent class object is stored in __parent. +Se a classe estende de algo, o objeto da classe pai é armazenado em __parent. -## Class Variables +## Variáveis de classe -We can create variables directly in the class object instead of in the base by using @ in the front of the property name in a class declaration. +Podemos criar variáveis diretamente no objeto da classe em vez da base usando @ na frente do nome da propriedade em uma declaração de classe. ```yuescript class Things @@ -269,7 +269,7 @@ class Things Things\some_func! --- class variables not visible in instances +-- variáveis de classe não visíveis em instâncias assert Things().some_func == nil ``` @@ -280,13 +280,13 @@ class Things Things\some_func! --- class variables not visible in instances +-- variáveis de classe não visíveis em instâncias assert Things().some_func == nil ``` -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. +Em expressões, podemos usar @@ para acessar um valor armazenado no __class de self. Assim, @@hello é abreviação para self.__class.hello. ```yuescript class Counter @@ -298,7 +298,7 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- imprime 2 ``` @@ -312,12 +312,12 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- imprime 2 ``` -The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. +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. ```yuescript @@hello 1,2,3,4 @@ -330,11 +330,11 @@ The calling semantics of @@ are similar to @. Calling a @@ name will pass the cl -## Class Declaration Statements +## Instruções de declaração de classe -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. +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. -Here is an alternative way to create a class variable compared to what's described above: +Aqui está uma forma alternativa de criar variável de classe comparada ao descrito acima: ```yuescript class Things @@ -349,9 +349,9 @@ class Things -These expressions are executed after all the properties have been added to the base. +Estas expressões são executadas após todas as propriedades terem sido adicionadas à base. -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: +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: ```yuescript class MoreThings @@ -374,11 +374,11 @@ class MoreThings -## @ and @@ Values +## Valores @ e @@ -When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.__class. +Quando @ e @@ são prefixados na frente de um nome, eles representam, respectivamente, esse nome acessado em self e self.__class. -If they are used all by themselves, they are aliases for self and self.__class. +Se forem usados sozinhos, são aliases para self e self.__class. ```yuescript assert @ == self @@ -393,7 +393,7 @@ assert @@ == self.__class -For example, a quick way to create a new instance of the same class from an instance method using @@: +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 @@: ```yuescript some_instance_method = (...) => @@ ... @@ -406,15 +406,15 @@ some_instance_method = (...) => @@ ... -## Constructor Property Promotion +## Promoção de propriedade no construtor -To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: +Para reduzir o código repetitivo na definição de objetos de valor simples. Você pode escrever uma classe simples como: ```yuescript class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- O que é abreviação para class Something new: (foo, bar, biz, baz) => @@ -429,7 +429,7 @@ class Something class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- O que é abreviação para class Something new: (foo, bar, biz, baz) => @@ -441,7 +441,7 @@ class Something -You can also use this syntax for a common function to initialize a object's fields. +Você também pode usar esta sintaxe para uma função comum para inicializar os campos de um objeto. ```yuescript new = (@fieldA, @fieldB) => @ @@ -458,9 +458,9 @@ print obj -## Class Expressions +## Expressões de classe -The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. +A sintaxe de classe também pode ser usada como expressão que pode ser atribuída a uma variável ou retornada explicitamente. ```yuescript x = class Bucket @@ -477,9 +477,9 @@ x = class Bucket -## Anonymous classes +## Classes anônimas -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. +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. ```yuescript BigBucket = class extends Bucket @@ -498,7 +498,7 @@ assert Bucket.__name == "BigBucket" -You can even leave off the body, meaning you can write a blank anonymous class like this: +Você pode até omitir o corpo, significando que pode escrever uma classe anônima em branco assim: ```yuescript x = class @@ -511,9 +511,9 @@ x = class -## Class Mixing +## Mistura de classes -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. +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. ```yuescript MyIndex = __index: var: 1 @@ -530,7 +530,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X não é pai de Y ``` @@ -549,7 +549,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X não é pai de Y ``` diff --git a/doc/docs/pt-br/doc/objects/with-statement.md b/doc/docs/pt-br/doc/objects/with-statement.md index 7786803..6495d09 100644 --- a/doc/docs/pt-br/doc/objects/with-statement.md +++ b/doc/docs/pt-br/doc/objects/with-statement.md @@ -1,13 +1,12 @@ -# With Statement +# Instrução With +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. -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. +Isso resulta em repetir o nome do objeto várias vezes no código, adicionando ruído desnecessário. Uma solução comum para isso é passar uma tabela como argumento que contém uma coleção de chaves e valores para sobrescrever. O inconveniente é que o construtor desse objeto deve suportar essa forma. -This results in repeating the name of the object multiple times in code, adding unnecessary noise. A common solution to this is to pass a table in as an argument which contains a collection of keys and values to overwrite. The downside to this is that the constructor of this object must support this form. +O bloco with ajuda a aliviar isso. Dentro de um bloco with podemos usar instruções especiais que começam com . ou \ que representam essas operações aplicadas ao objeto com o qual estamos usando with. -The with block helps to alleviate this. Within a with block we can use a special statements that begin with either . or \ which represent those operations applied to the object we are using with on. - -For example, we work with a newly created object: +Por exemplo, trabalhamos com um objeto recém-criado: ```yuescript with Person! @@ -28,7 +27,7 @@ with Person! -The with statement can also be used as an expression which returns the value it has been giving access to. +A instrução with também pode ser usada como expressão que retorna o valor ao qual foi dado acesso. ```yuescript file = with File "favorite_foods.txt" @@ -43,7 +42,7 @@ file = with File "favorite_foods.txt" -Or… +Ou… ```yuescript create_person = (name, relatives) -> @@ -66,9 +65,9 @@ me = create_person "Leaf", [dad, mother, sister] -In this usage, with can be seen as a special form of the K combinator. +Neste uso, with pode ser visto como uma forma especial do combinador K. -The expression in the with statement can also be an assignment, if you want to give a name to the expression. +A expressão na instrução with também pode ser uma atribuição, se você quiser dar um nome à expressão. ```yuescript with str := "Hello" @@ -85,7 +84,7 @@ with str := "Hello" -You can access special keys with `[]` in a `with` statement. +Você pode acessar chaves especiais com `[]` em uma instrução `with`. ```yuescript with tb @@ -94,7 +93,7 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- anexando a "tb" ``` @@ -105,12 +104,12 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- anexando a "tb" ``` -`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. +`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. ```yuescript with? obj diff --git a/doc/docs/pt-br/doc/reference/license-mit.md b/doc/docs/pt-br/doc/reference/license-mit.md index f1d5d60..0e00e90 100644 --- a/doc/docs/pt-br/doc/reference/license-mit.md +++ b/doc/docs/pt-br/doc/reference/license-mit.md @@ -1,23 +1,21 @@ -# License: MIT +# Licença: MIT Copyright (c) 2017-2026 Li Jin \ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +A permissão é concedida, gratuitamente, a qualquer pessoa que obtenha uma cópia +deste software e dos arquivos de documentação associados (o "Software"), para negociar +o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, +modificar, mesclar, publicar, distribuir, sublicenciar e/ou vender +cópias do Software, e permitir que pessoas a quem o Software seja fornecido o façam, +sujeito às seguintes condições: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +O aviso de direitos autorais acima e este aviso de permissão devem ser incluídos em todas as +cópias ou partes substanciais do Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - +O SOFTWARE É FORNECIDO "NO ESTADO EM QUE SE ENCONTRA", SEM GARANTIA DE QUALQUER TIPO, +EXPRESSA OU IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO, +ADEQUAÇÃO A UM DETERMINADO FIM E NÃO VIOLAÇÃO. EM NENHUMA HIPÓTESE OS AUTORES OU +DETENTORES DOS DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUAISQUER REIVINDICAÇÕES, +DANOS OU OUTRAS RESPONSABILIDADES, SEJA EM UMA AÇÃO DE CONTRATO, ATO ILÍCITO OU OUTRA, +DECORRENTES DE, FORA DE OU RELACIONADAS COM O SOFTWARE OU O USO OU OUTRAS NEGOCIAÇÕES +NO SOFTWARE. diff --git a/doc/docs/pt-br/doc/reference/the-yuescript-library.md b/doc/docs/pt-br/doc/reference/the-yuescript-library.md index 3761755..2a65ffb 100644 --- a/doc/docs/pt-br/doc/reference/the-yuescript-library.md +++ b/doc/docs/pt-br/doc/reference/the-yuescript-library.md @@ -1,61 +1,61 @@ -# The YueScript Library +# A biblioteca YueScript -Access it by `local yue = require("yue")` in Lua. +Acesse com `local yue = require("yue")` no Lua. ## yue -**Description:** +**Descrição:** -The YueScript language library. +A biblioteca da linguagem YueScript. ### version -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The YueScript version. +A versão do YueScript. -**Signature:** +**Assinatura:** ```lua version: string ``` ### dirsep -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The file separator for the current platform. +O separador de arquivos da plataforma atual. -**Signature:** +**Assinatura:** ```lua dirsep: string ``` ### yue_compiled -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The compiled module code cache. +O cache de código de módulo compilado. -**Signature:** +**Assinatura:** ```lua yue_compiled: {string: string} ``` ### to_lua -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The YueScript compiling function. It compiles the YueScript code to Lua code. +A função de compilação do YueScript. Compila o código YueScript para código Lua. -**Signature:** +**Assinatura:** ```lua to_lua: function(code: string, config?: Config): --[[codes]] string | nil, @@ -63,682 +63,682 @@ to_lua: function(code: string, config?: Config): --[[globals]] {{string, integer, integer}} | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| code | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| code | string | O código YueScript. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string \| nil | The compiled Lua code, or nil if the compilation failed. | -| string \| nil | The error message, or nil if the compilation succeeded. | -| {{string, integer, integer}} \| nil | The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. | +| string \| nil | O código Lua compilado, ou nil se a compilação falhou. | +| string \| nil | A mensagem de erro, ou nil se a compilação foi bem-sucedida. | +| {{string, integer, integer}} \| nil | As variáveis globais que aparecem no código (com nome, linha e coluna), ou nil se a opção do compilador `lint_global` for false. | ### file_exist -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The source file existence checking function. Can be overridden to customize the behavior. +Função de verificação de existência do arquivo fonte. Pode ser sobrescrita para personalizar o comportamento. -**Signature:** +**Assinatura:** ```lua file_exist: function(filename: string): boolean ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | O nome do arquivo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the file exists. | +| boolean | Se o arquivo existe. | ### read_file -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The source file reading function. Can be overridden to customize the behavior. +Função de leitura do arquivo fonte. Pode ser sobrescrita para personalizar o comportamento. -**Signature:** +**Assinatura:** ```lua read_file: function(filename: string): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | O nome do arquivo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The file content. | +| string | O conteúdo do arquivo. | ### insert_loader -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Insert the YueScript loader to the package loaders (searchers). +Insere o carregador YueScript nos carregadores de pacote (searchers). -**Signature:** +**Assinatura:** ```lua insert_loader: function(pos?: integer): boolean ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| pos | integer | [Optional] The position to insert the loader. Default is 3. | +| pos | integer | [Opcional] A posição para inserir o carregador. Padrão é 3. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the loader is inserted successfully. It will fail if the loader is already inserted. | +| boolean | Se o carregador foi inserido com sucesso. Falhará se o carregador já estiver inserido. | ### remove_loader -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Remove the YueScript loader from the package loaders (searchers). +Remove o carregador YueScript dos carregadores de pacote (searchers). -**Signature:** +**Assinatura:** ```lua remove_loader: function(): boolean ``` -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the loader is removed successfully. It will fail if the loader is not inserted. | +| boolean | Se o carregador foi removido com sucesso. Falhará se o carregador não estiver inserido. | ### loadstring -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a string into a function. +Carrega código YueScript de uma string em uma função. -**Signature:** +**Assinatura:** ```lua loadstring: function(input: string, chunkname: string, env: table, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| input | string | O código YueScript. | +| chunkname | string | O nome do chunk de código. | +| env | table | A tabela de ambiente. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadstring -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a string into a function. +Carrega código YueScript de uma string em uma função. -**Signature:** +**Assinatura:** ```lua loadstring: function(input: string, chunkname: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| config | Config | [Optional] The compiler options. | +| input | string | O código YueScript. | +| chunkname | string | O nome do chunk de código. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadstring -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a string into a function. +Carrega código YueScript de uma string em uma função. -**Signature:** +**Assinatura:** ```lua loadstring: function(input: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| input | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| input | string | O código YueScript. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadfile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function. +Carrega código YueScript de um arquivo em uma função. -**Signature:** +**Assinatura:** ```lua loadfile: function(filename: string, env: table, config?: Config): nil | function(...: any): (any...), string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| env | table | A tabela de ambiente. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadfile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function. +Carrega código YueScript de um arquivo em uma função. -**Signature:** +**Assinatura:** ```lua loadfile: function(filename: string, config?: Config): nil | function(...: any): (any...), string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### dofile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function and executes it. +Carrega código YueScript de um arquivo em uma função e o executa. -**Signature:** +**Assinatura:** ```lua dofile: function(filename: string, env: table, config?: Config): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| env | table | A tabela de ambiente. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Os valores de retorno da função carregada. | ### dofile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function and executes it. +Carrega código YueScript de um arquivo em uma função e o executa. -**Signature:** +**Assinatura:** ```lua dofile: function(filename: string, config?: Config): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Os valores de retorno da função carregada. | ### find_modulepath -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Resolves the YueScript module name to the file path. +Resolve o nome do módulo YueScript para o caminho do arquivo. -**Signature:** +**Assinatura:** ```lua find_modulepath: function(name: string): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| name | string | The module name. | +| name | string | O nome do módulo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The file path. | +| string | O caminho do arquivo. | ### pcall -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Calls a function in protected mode. -Catches any errors and returns a status code and results or error object. -Rewrites the error line number to the original line number in the YueScript code when errors occur. +Chama uma função em modo protegido. +Captura quaisquer erros e retorna um código de status e resultados ou objeto de erro. +Reescreve o número da linha do erro para o número da linha original no código YueScript quando ocorrem erros. -**Signature:** +**Assinatura:** ```lua pcall: function(f: function, ...: any): boolean, any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| f | function | The function to call. | -| ... | any | Arguments to pass to the function. | +| f | function | A função a chamar. | +| ... | any | Argumentos a passar para a função. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean, ... | Status code and function results or error object. | +| boolean, ... | Código de status e resultados da função ou objeto de erro. | ### require -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads a given module. Can be either a Lua module or a YueScript module. -Rewrites the error line number to the original line number in the YueScript code if the module is a YueScript module and loading fails. +Carrega um módulo dado. Pode ser um módulo Lua ou um módulo YueScript. +Reescreve o número da linha do erro para o número da linha original no código YueScript se o módulo for um módulo YueScript e o carregamento falhar. -**Signature:** +**Assinatura:** ```lua require: function(name: string): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| modname | string | The name of the module to load. | +| modname | string | O nome do módulo a carregar. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any | The value stored at package.loaded[modname] if the module is already loaded.Otherwise, tries to find a loader and returns the final value of package.loaded[modname] and a loader data as a second result. | +| any | O valor armazenado em package.loaded[modname] se o módulo já estiver carregado. Caso contrário, tenta encontrar um carregador e retorna o valor final de package.loaded[modname] e os dados do carregador como segundo resultado. | ### p -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Inspects the structures of the passed values and prints string representations. +Inspeciona as estruturas dos valores passados e imprime representações em string. -**Signature:** +**Assinatura:** ```lua p: function(...: any) ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| ... | any | The values to inspect. | +| ... | any | Os valores a inspecionar. | ### options -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The current compiler options. +As opções atuais do compilador. -**Signature:** +**Assinatura:** ```lua options: Config.Options ``` ### traceback -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The traceback function that rewrites the stack trace line numbers to the original line numbers in the YueScript code. +A função traceback que reescreve os números das linhas do stack trace para os números das linhas originais no código YueScript. -**Signature:** +**Assinatura:** ```lua traceback: function(message: string): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| message | string | The traceback message. | +| message | string | A mensagem de traceback. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The rewritten traceback message. | +| string | A mensagem de traceback reescrita. | ### is_ast -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Checks whether the code matches the specified AST. +Verifica se o código corresponde ao AST especificado. -**Signature:** +**Assinatura:** ```lua is_ast: function(astName: string, code: string): boolean ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| astName | string | The AST name. | -| code | string | The code. | +| astName | string | O nome do AST. | +| code | string | O código. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the code matches the AST. | +| boolean | Se o código corresponde ao AST. | ### AST -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The AST type definition with name, row, column and sub nodes. +A definição do tipo AST com nome, linha, coluna e subnós. -**Signature:** +**Assinatura:** ```lua type AST = {string, integer, integer, any} ``` ### to_ast -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Converts the code to the AST. +Converte o código para o AST. -**Signature:** +**Assinatura:** ```lua to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveComment?: boolean): --[[AST]] AST | nil, --[[error]] nil | string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| code | string | The code. | -| flattenLevel | integer | [Optional] The flatten level. Higher level means more flattening. Default is 0. Maximum is 2. | -| astName | string | [Optional] The AST name. Default is "File". | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is false. | +| code | string | O código. | +| flattenLevel | integer | [Opcional] O nível de achatamento. Nível mais alto significa mais achatamento. Padrão é 0. Máximo é 2. | +| astName | string | [Opcional] O nome do AST. Padrão é "File". | +| reserveComment | boolean | [Opcional] Se deve preservar os comentários originais. Padrão é false. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| AST \| nil | The AST, or nil if the conversion failed. | -| string \| nil | The error message, or nil if the conversion succeeded. | +| AST \| nil | O AST, ou nil se a conversão falhou. | +| string \| nil | A mensagem de erro, ou nil se a conversão foi bem-sucedida. | ### format -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Formats the YueScript code. +Formata o código YueScript. -**Signature:** +**Assinatura:** ```lua format: function(code: string, tabSize?: number, reserveComment?: boolean): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| code | string | The code. | -| tabSize | integer | [Optional] The tab size. Default is 4. | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is true. | +| code | string | O código. | +| tabSize | integer | [Opcional] O tamanho da tabulação. Padrão é 4. | +| reserveComment | boolean | [Opcional] Se deve preservar os comentários originais. Padrão é true. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The formatted code. | +| string | O código formatado. | ### __call -**Type:** Metamethod. +**Tipo:** Metamétodo. -**Description:** +**Descrição:** -Requires the YueScript module. -Rewrites the error line number to the original line number in the YueScript code when loading fails. +Requer o módulo YueScript. +Reescreve o número da linha do erro para o número da linha original no código YueScript quando o carregamento falha. -**Signature:** +**Assinatura:** ```lua metamethod __call: function(self: yue, module: string): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| module | string | The module name. | +| module | string | O nome do módulo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any | The module value. | +| any | O valor do módulo. | ## Config -**Description:** +**Descrição:** -The compiler compile options. +As opções de compilação do compilador. ### lint_global -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should collect the global variables appearing in the code. +Se o compilador deve coletar as variáveis globais que aparecem no código. -**Signature:** +**Assinatura:** ```lua lint_global: boolean ``` ### implicit_return_root -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should do an implicit return for the root code block. +Se o compilador deve fazer retorno implícito para o bloco de código raiz. -**Signature:** +**Assinatura:** ```lua implicit_return_root: boolean ``` ### reserve_line_number -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should reserve the original line number in the compiled code. +Se o compilador deve preservar o número da linha original no código compilado. -**Signature:** +**Assinatura:** ```lua reserve_line_number: boolean ``` ### reserve_comment -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should reserve the original comments in the compiled code. +Se o compilador deve preservar os comentários originais no código compilado. -**Signature:** +**Assinatura:** ```lua reserve_comment: boolean ``` ### space_over_tab -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should use the space character instead of the tab character in the compiled code. +Se o compilador deve usar o caractere de espaço em vez do caractere de tabulação no código compilado. -**Signature:** +**Assinatura:** ```lua space_over_tab: boolean ``` ### same_module -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should treat the code to be compiled as the same currently being compiled module. For internal use only. +Se o compilador deve tratar o código a ser compilado como o mesmo módulo que está sendo compilado atualmente. Apenas para uso interno. -**Signature:** +**Assinatura:** ```lua same_module: boolean ``` ### line_offset -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler error message should include the line number offset. For internal use only. +Se a mensagem de erro do compilador deve incluir o deslocamento do número da linha. Apenas para uso interno. -**Signature:** +**Assinatura:** ```lua line_offset: integer ``` ### yue.Config.LuaTarget -**Type:** Enumeration. +**Tipo:** Enumeração. -**Description:** +**Descrição:** -The target Lua version enumeration. +A enumeração da versão alvo do Lua. -**Signature:** +**Assinatura:** ```lua enum LuaTarget "5.1" @@ -751,71 +751,71 @@ end ### options -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The extra options to be passed to the compilation function. +As opções extras a serem passadas para a função de compilação. -**Signature:** +**Assinatura:** ```lua options: Options ``` ## Options -**Description:** +**Descrição:** -The extra compiler options definition. +A definição das opções extras do compilador. ### target -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The target Lua version for the compilation. +A versão alvo do Lua para a compilação. -**Signature:** +**Assinatura:** ```lua target: LuaTarget ``` ### path -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The extra module search path. +O caminho de busca de módulo extra. -**Signature:** +**Assinatura:** ```lua path: string ``` ### dump_locals -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether to dump the local variables in the traceback error message. Default is false. +Se deve incluir as variáveis locais na mensagem de erro do traceback. Padrão é false. -**Signature:** +**Assinatura:** ```lua dump_locals: boolean ``` ### simplified -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether to simplify the error message. Default is true. +Se deve simplificar a mensagem de erro. Padrão é true. -**Signature:** +**Assinatura:** ```lua simplified: boolean ``` diff --git a/doc/docs/zh/doc/control-flow/conditionals.md b/doc/docs/zh/doc/control-flow/conditionals.md index e4b217a..ba77f40 100644 --- a/doc/docs/zh/doc/control-flow/conditionals.md +++ b/doc/docs/zh/doc/control-flow/conditionals.md @@ -137,14 +137,3 @@ if a in list ``` - -```yuescript -print "你很幸运!" unless math.random! > 0.1 -``` - - -```yue -print "你很幸运!" unless math.random! > 0.1 -``` - - diff --git a/doc/docs/zh/doc/reference/license-mit.md b/doc/docs/zh/doc/reference/license-mit.md index 1a07518..24b5b15 100644 --- a/doc/docs/zh/doc/reference/license-mit.md +++ b/doc/docs/zh/doc/reference/license-mit.md @@ -5,5 +5,3 @@ 特此免费授予任何获得本软件副本和相关文档文件(下称“软件”)的人不受限制地处置该软件的权利,包括不受限制地使用、复制、修改、合并、发布、分发、转授许可和/或出售该软件副本,以及再授权被配发了本软件的人如上的权利,须在下列条件下: 上述版权声明和本许可声明应包含在该软件的所有副本或实质成分中。 本软件是“如此”提供的,没有任何形式的明示或暗示的保证,包括但不限于对适销性、特定用途的适用性和不侵权的保证。在任何情况下,作者或版权持有人都不对任何索赔、损害或其他责任负责,无论这些追责来自合同、侵权或其它行为中,还是产生于、源于或有关于本软件以及本软件的使用或其它处置。 - - -- cgit v1.2.3-55-g6feb