aboutsummaryrefslogtreecommitdiff
path: root/doc/docs/pt-br
diff options
context:
space:
mode:
authorLi Jin <dragon-fly@qq.com>2026-02-06 11:54:32 +0800
committerLi Jin <dragon-fly@qq.com>2026-02-06 11:54:32 +0800
commit1f83d504bc344ffd3c8b4120b3865fd6c11a9e2d (patch)
tree1d5c39eadcbe086d2a592ac76c8f1d288adfbe9d /doc/docs/pt-br
parentaa3ecc7badfb39cb9167fb95c9a678257c1d9954 (diff)
downloadyuescript-1f83d504bc344ffd3c8b4120b3865fd6c11a9e2d.tar.gz
yuescript-1f83d504bc344ffd3c8b4120b3865fd6c11a9e2d.tar.bz2
yuescript-1f83d504bc344ffd3c8b4120b3865fd6c11a9e2d.zip
Updated docs.v0.32.9
Diffstat (limited to 'doc/docs/pt-br')
-rw-r--r--doc/docs/pt-br/doc/advanced/do.md8
-rw-r--r--doc/docs/pt-br/doc/advanced/line-decorators.md8
-rw-r--r--doc/docs/pt-br/doc/advanced/macro.md65
-rw-r--r--doc/docs/pt-br/doc/advanced/module.md62
-rw-r--r--doc/docs/pt-br/doc/advanced/try.md20
-rw-r--r--doc/docs/pt-br/doc/assignment/assignment.md48
-rw-r--r--doc/docs/pt-br/doc/assignment/destructuring-assignment.md66
-rw-r--r--doc/docs/pt-br/doc/assignment/if-assignment.md34
-rw-r--r--doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md36
-rw-r--r--doc/docs/pt-br/doc/assignment/varargs-assignment.md4
-rw-r--r--doc/docs/pt-br/doc/control-flow/conditionals.md69
-rw-r--r--doc/docs/pt-br/doc/control-flow/continue.md4
-rw-r--r--doc/docs/pt-br/doc/control-flow/for-loop.md36
-rw-r--r--doc/docs/pt-br/doc/control-flow/switch.md130
-rw-r--r--doc/docs/pt-br/doc/control-flow/while-loop.md10
-rw-r--r--doc/docs/pt-br/doc/data-structures/comprehensions.md64
-rw-r--r--doc/docs/pt-br/doc/data-structures/table-literals.md20
-rw-r--r--doc/docs/pt-br/doc/functions/backcalls.md8
-rw-r--r--doc/docs/pt-br/doc/functions/function-literals.md94
-rw-r--r--doc/docs/pt-br/doc/functions/function-stubs.md24
-rw-r--r--doc/docs/pt-br/doc/getting-started/installation.md24
-rw-r--r--doc/docs/pt-br/doc/getting-started/introduction.md40
-rw-r--r--doc/docs/pt-br/doc/getting-started/usage.md105
-rw-r--r--doc/docs/pt-br/doc/language-basics/attributes.md12
-rw-r--r--doc/docs/pt-br/doc/language-basics/comment.md22
-rw-r--r--doc/docs/pt-br/doc/language-basics/literals.md46
-rw-r--r--doc/docs/pt-br/doc/language-basics/operator.md116
-rw-r--r--doc/docs/pt-br/doc/language-basics/whitespace.md12
-rw-r--r--doc/docs/pt-br/doc/objects/object-oriented-programming.md158
-rw-r--r--doc/docs/pt-br/doc/objects/with-statement.md27
-rw-r--r--doc/docs/pt-br/doc/reference/license-mit.md34
-rw-r--r--doc/docs/pt-br/doc/reference/the-yuescript-library.md632
32 files changed, 1012 insertions, 1026 deletions
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 @@
1# Do 1# Do
2 2
3When used as a statement, do works just like it does in Lua. 3Quando usado como instrução, do funciona exatamente como no Lua.
4 4
5```yuescript 5```yuescript
6do 6do
7 var = "hello" 7 var = "hello"
8 print var 8 print var
9print var -- nil here 9print var -- nil aqui
10``` 10```
11<YueDisplay> 11<YueDisplay>
12 12
@@ -14,12 +14,12 @@ print var -- nil here
14do 14do
15 var = "hello" 15 var = "hello"
16 print var 16 print var
17print var -- nil here 17print var -- nil aqui
18``` 18```
19 19
20</YueDisplay> 20</YueDisplay>
21 21
22YueScript'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. 22O **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.
23 23
24```yuescript 24```yuescript
25counter = do 25counter = 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 @@
1# Line Decorators 1# Decoradores de linha
2 2
3For convenience, the for loop and if statement can be applied to single statements at the end of the line: 3Por conveniência, o loop for e a instrução if podem ser aplicados a instruções únicas no final da linha:
4 4
5```yuescript 5```yuescript
6print "hello world" if name == "Rob" 6print "hello world" if name == "Rob"
@@ -13,7 +13,7 @@ print "hello world" if name == "Rob"
13 13
14</YueDisplay> 14</YueDisplay>
15 15
16And with basic loops: 16E com loops básicos:
17 17
18```yuescript 18```yuescript
19print "item: ", item for item in *items 19print "item: ", item for item in *items
@@ -26,7 +26,7 @@ print "item: ", item for item in *items
26 26
27</YueDisplay> 27</YueDisplay>
28 28
29And with while loops: 29E com loops while:
30 30
31```yuescript 31```yuescript
32game\update! while game\isRunning! 32game\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 @@
1# Macro 1# Macro
2 2
3## Common Usage 3## Uso comum
4 4
5Macro function is used for evaluating a string in the compile time and insert the generated codes into final compilation. 5A função macro é usada para avaliar uma string em tempo de compilação e inserir os códigos gerados na compilação final.
6 6
7```yuescript 7```yuescript
8macro PI2 = -> math.pi * 2 8macro PI2 = -> math.pi * 2
@@ -27,7 +27,7 @@ $asserts item ~= nil
27$config false 27$config false
28value = $assert item 28value = $assert item
29 29
30-- the passed expressions are treated as strings 30-- as expressões passadas são tratadas como strings
31macro and = (...) -> "#{ table.concat {...}, ' and ' }" 31macro and = (...) -> "#{ table.concat {...}, ' and ' }"
32if $and f1!, f2!, f3! 32if $and f1!, f2!, f3!
33 print "OK" 33 print "OK"
@@ -57,7 +57,7 @@ $asserts item ~= nil
57$config false 57$config false
58value = $assert item 58value = $assert item
59 59
60-- the passed expressions are treated as strings 60-- as expressões passadas são tratadas como strings
61macro and = (...) -> "#{ table.concat {...}, ' and ' }" 61macro and = (...) -> "#{ table.concat {...}, ' and ' }"
62if $and f1!, f2!, f3! 62if $and f1!, f2!, f3!
63 print "OK" 63 print "OK"
@@ -65,9 +65,9 @@ if $and f1!, f2!, f3!
65 65
66</YueDisplay> 66</YueDisplay>
67 67
68## Insert Raw Codes 68## Inserir códigos brutos
69 69
70A macro function can either return a YueScript string or a config table containing Lua codes. 70Uma função macro pode retornar uma string YueScript ou uma tabela de configuração contendo códigos Lua.
71```yuescript 71```yuescript
72macro yueFunc = (var) -> "local #{var} = ->" 72macro yueFunc = (var) -> "local #{var} = ->"
73$yueFunc funcA 73$yueFunc funcA
@@ -85,9 +85,9 @@ macro lua = (code) -> {
85 type: "lua" 85 type: "lua"
86} 86}
87 87
88-- the raw string leading and ending symbols are auto trimed 88-- os símbolos inicial e final da string bruta são aparados automaticamente
89$lua[==[ 89$lua[==[
90-- raw Lua codes insertion 90-- inserção de códigos Lua brutos
91if cond then 91if cond then
92 print("output") 92 print("output")
93end 93end
@@ -112,9 +112,9 @@ macro lua = (code) -> {
112 type: "lua" 112 type: "lua"
113} 113}
114 114
115-- the raw string leading and ending symbols are auto trimed 115-- os símbolos inicial e final da string bruta são aparados automaticamente
116$lua[==[ 116$lua[==[
117-- raw Lua codes insertion 117-- inserção de códigos Lua brutos
118if cond then 118if cond then
119 print("output") 119 print("output")
120end 120end
@@ -123,38 +123,37 @@ end
123 123
124</YueDisplay> 124</YueDisplay>
125 125
126## Export Macro 126## Exportar macro
127 127
128Macro 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. 128Funçõ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.
129```yuescript 129```yuescript
130-- file: utils.yue 130-- arquivo: utils.yue
131export macro map = (items, action) -> "[#{action} for _ in *#{items}]" 131export macro map = (items, action) -> "[#{action} for _ in *#{items}]"
132export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" 132export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]"
133export macro foreach = (items, action) -> "for _ in *#{items} 133export macro foreach = (items, action) -> "for _ in *#{items}
134 #{action}" 134 #{action}"
135 135
136-- file main.yue 136-- arquivo main.yue
137import "utils" as { 137import "utils" as {
138 $, -- symbol to import all macros 138 $, -- símbolo para importar todas as macros
139 $foreach: $each -- rename macro $foreach to $each 139 $foreach: $each -- renomear macro $foreach para $each
140} 140}
141[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ 141[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _
142``` 142```
143<YueDisplay> 143<YueDisplay>
144 144
145```yue 145```yue
146-- file: utils.yue 146-- arquivo: utils.yue
147export macro map = (items, action) -> "[#{action} for _ in *#{items}]" 147export macro map = (items, action) -> "[#{action} for _ in *#{items}]"
148export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" 148export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]"
149export macro foreach = (items, action) -> "for _ in *#{items} 149export macro foreach = (items, action) -> "for _ in *#{items}
150 #{action}" 150 #{action}"
151 151
152-- file main.yue 152-- arquivo main.yue
153-- import function is not available in browser, try it in a real environment
154--[[ 153--[[
155import "utils" as { 154import "utils" as {
156 $, -- symbol to import all macros 155 $, -- símbolo para importar todas as macros
157 $foreach: $each -- rename macro $foreach to $each 156 $foreach: $each -- renomear macro $foreach para $each
158} 157}
159[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ 158[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _
160]] 159]]
@@ -162,25 +161,25 @@ import "utils" as {
162 161
163</YueDisplay> 162</YueDisplay>
164 163
165## Builtin Macro 164## Macro embutida
166 165
167There are some builtin macros but you can override them by declaring macros with the same names. 166Existem algumas macros embutidas, mas você pode sobrescrevê-las declarando macros com os mesmos nomes.
168```yuescript 167```yuescript
169print $FILE -- get string of current module name 168print $FILE -- obtém string do nome dodulo atual
170print $LINE -- get number 2 169print $LINE -- obtém número 2
171``` 170```
172<YueDisplay> 171<YueDisplay>
173 172
174```yue 173```yue
175print $FILE -- get string of current module name 174print $FILE -- obtém string do nome dodulo atual
176print $LINE -- get number 2 175print $LINE -- obtém número 2
177``` 176```
178 177
179</YueDisplay> 178</YueDisplay>
180 179
181## Generating Macros with Macros 180## Gerando macros com macros
182 181
183In 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. 182No 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.
184 183
185```yuescript 184```yuescript
186macro Enum = (...) -> 185macro Enum = (...) ->
@@ -222,9 +221,9 @@ print "Valid enum type:", $BodyType Static
222 221
223</YueDisplay> 222</YueDisplay>
224 223
225## Argument Validation 224## Validação de argumentos
226 225
227You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time. 226Você 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.
228 227
229```yuescript 228```yuescript
230macro printNumAndStr = (num `Num, str `String) -> | 229macro printNumAndStr = (num `Num, str `String) -> |
@@ -249,7 +248,7 @@ $printNumAndStr 123, "hello"
249 248
250</YueDisplay> 249</YueDisplay>
251 250
252If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. 251Se 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.
253 252
254```yuescript 253```yuescript
255macro printNumAndStr = (num, str) -> 254macro printNumAndStr = (num, str) ->
@@ -272,4 +271,4 @@ $printNumAndStr 123, "hello"
272 271
273</YueDisplay> 272</YueDisplay>
274 273
275For 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). 274Para 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 @@
1# Module 1# Módulo
2 2
3## Import 3## Import
4 4
5The 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. 5A 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.
6 6
7```yuescript 7```yuescript
8-- used as table destructuring 8-- usado como desestruturação de tabela
9do 9do
10 import insert, concat from table 10 import insert, concat from table
11 -- report error when assigning to insert, concat 11 -- reporta erro ao atribuir a insert, concat
12 import C, Ct, Cmt from require "lpeg" 12 import C, Ct, Cmt from require "lpeg"
13 -- shortcut for implicit requiring 13 -- atalho para require implícito
14 import x, y, z from 'mymodule' 14 import x, y, z from 'mymodule'
15 -- import with Python style 15 -- import com estilo Python
16 from 'module' import a, b, c 16 from 'module' import a, b, c
17 17
18-- shortcut for requring a module 18-- atalho para requerer um módulo
19do 19do
20 import 'module' 20 import 'module'
21 import 'module_x' 21 import 'module_x'
22 import "d-a-s-h-e-s" 22 import "d-a-s-h-e-s"
23 import "module.part" 23 import "module.part"
24 24
25-- requring module with aliasing or table destructuring 25-- requerer módulo com aliasing ou desestruturação de tabela
26do 26do
27 import "player" as PlayerModule 27 import "player" as PlayerModule
28 import "lpeg" as :C, :Ct, :Cmt 28 import "lpeg" as :C, :Ct, :Cmt
@@ -31,24 +31,24 @@ do
31<YueDisplay> 31<YueDisplay>
32 32
33```yue 33```yue
34-- used as table destructuring 34-- usado como desestruturação de tabela
35do 35do
36 import insert, concat from table 36 import insert, concat from table
37 -- report error when assigning to insert, concat 37 -- reporta erro ao atribuir a insert, concat
38 import C, Ct, Cmt from require "lpeg" 38 import C, Ct, Cmt from require "lpeg"
39 -- shortcut for implicit requiring 39 -- atalho para require implícito
40 import x, y, z from 'mymodule' 40 import x, y, z from 'mymodule'
41 -- import with Python style 41 -- import com estilo Python
42 from 'module' import a, b, c 42 from 'module' import a, b, c
43 43
44-- shortcut for requring a module 44-- atalho para requerer um módulo
45do 45do
46 import 'module' 46 import 'module'
47 import 'module_x' 47 import 'module_x'
48 import "d-a-s-h-e-s" 48 import "d-a-s-h-e-s"
49 import "module.part" 49 import "module.part"
50 50
51-- requring module with aliasing or table destructuring 51-- requerer módulo com aliasing ou desestruturação de tabela
52do 52do
53 import "player" as PlayerModule 53 import "player" as PlayerModule
54 import "lpeg" as :C, :Ct, :Cmt 54 import "lpeg" as :C, :Ct, :Cmt
@@ -59,7 +59,7 @@ do
59 59
60## Import Global 60## Import Global
61 61
62You 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. 62Você 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.
63 63
64```yuescript 64```yuescript
65do 65do
@@ -78,21 +78,21 @@ do
78 78
79</YueDisplay> 79</YueDisplay>
80 80
81### Automatic Global Variable Import 81### Importação automática de variável global
82 82
83You 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. 83Você 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.
84 84
85Names that are explicitly declared as globals in the same scope will not be imported, so you can still assign to them. 85Nomes que foram explicitamente declarados como globais no mesmo escopo não serão importados, então você ainda pode atribuir a eles.
86 86
87```yuescript 87```yuescript
88do 88do
89 import global 89 import global
90 print "hello" 90 print "hello"
91 math.random 3 91 math.random 3
92 -- print = nil -- error: imported globals are const 92 -- print = nil -- erro: globais importados são const
93 93
94do 94do
95 -- explicit global variable will not be imported 95 -- variável global explícita não se importada
96 import global 96 import global
97 global FLAG 97 global FLAG
98 print FLAG 98 print FLAG
@@ -105,10 +105,10 @@ do
105 import global 105 import global
106 print "hello" 106 print "hello"
107 math.random 3 107 math.random 3
108 -- print = nil -- error: imported globals are const 108 -- print = nil -- erro: globais importados são const
109 109
110do 110do
111 -- explicit global variable will not be imported 111 -- variável global explícita não se importada
112 import global 112 import global
113 global FLAG 113 global FLAG
114 print FLAG 114 print FLAG
@@ -119,11 +119,11 @@ do
119 119
120## Export 120## Export
121 121
122The export statement offers a concise way to define modules. 122A instrução export oferece uma forma concisa de definir módulos.
123 123
124### Named Export 124### Export nomeado
125 125
126Named export will define a local variable as well as adding a field in the exported table. 126Export nomeado definirá uma variável local e também adiciona um campo na tabela exportada.
127 127
128```yuescript 128```yuescript
129export a, b, c = 1, 2, 3 129export a, b, c = 1, 2, 3
@@ -160,7 +160,7 @@ export class Something
160 160
161</YueDisplay> 161</YueDisplay>
162 162
163Doing named export with destructuring. 163Fazendo export nomeado com desestruturação.
164 164
165```yuescript 165```yuescript
166export :loadstring, to_lua: tolua = yue 166export :loadstring, to_lua: tolua = yue
@@ -175,7 +175,7 @@ export {itemA: {:fieldA = 'default'}} = tb
175 175
176</YueDisplay> 176</YueDisplay>
177 177
178Export named items from module without creating local variables. 178Exportar itens nomeados dodulo sem criar variáveis locais.
179 179
180```yuescript 180```yuescript
181export.itemA = tb 181export.itemA = tb
@@ -192,9 +192,9 @@ export["a-b-c"] = 123
192 192
193</YueDisplay> 193</YueDisplay>
194 194
195### Unnamed Export 195### Export sem nome
196 196
197Unnamed export will add the target item into the array part of the exported table. 197Export sem nome adicionará o item alvo na parte array da tabela exportada.
198 198
199```yuescript 199```yuescript
200d, e, f = 3, 2, 1 200d, e, f = 3, 2, 1
@@ -225,9 +225,9 @@ export with tmp
225 225
226</YueDisplay> 226</YueDisplay>
227 227
228### Default Export 228### Export padrão
229 229
230Using the **default** keyword in export statement to replace the exported table with any thing. 230Usar a palavra-chave **default** na instrução export para substituir a tabela exportada por qualquer coisa.
231 231
232```yuescript 232```yuescript
233export default -> 233export 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 @@
1# Try 1# Try
2 2
3The syntax for Lua error handling in a common form. 3A sintaxe para tratamento de erros do Lua em uma forma comum.
4 4
5```yuescript 5```yuescript
6try 6try
@@ -23,7 +23,7 @@ try
23 print "trying" 23 print "trying"
24 func 1, 2, 3 24 func 1, 2, 3
25 25
26-- working with if assignment pattern 26-- funcionando com padrão de atribuição em if
27if success, result := try func 1, 2, 3 27if success, result := try func 1, 2, 3
28catch err 28catch err
29 print yue.traceback err 29 print yue.traceback err
@@ -52,7 +52,7 @@ try
52 print "trying" 52 print "trying"
53 func 1, 2, 3 53 func 1, 2, 3
54 54
55-- working with if assignment pattern 55-- funcionando com padrão de atribuição em if
56if success, result := try func 1, 2, 3 56if success, result := try func 1, 2, 3
57catch err 57catch err
58 print yue.traceback err 58 print yue.traceback err
@@ -63,18 +63,18 @@ catch err
63 63
64## Try? 64## Try?
65 65
66`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. 66`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.
67 67
68```yuescript 68```yuescript
69a, b, c = try? func! 69a, b, c = try? func!
70 70
71-- with nil coalescing operator 71-- com operador de coalescência de nil
72a = (try? func!) ?? "default" 72a = (try? func!) ?? "default"
73 73
74-- as function argument 74-- como argumento de função
75f try? func! 75f try? func!
76 76
77-- with catch block 77-- com bloco catch
78f try? 78f try?
79 print 123 79 print 123
80 func! 80 func!
@@ -87,13 +87,13 @@ catch e
87```yue 87```yue
88a, b, c = try? func! 88a, b, c = try? func!
89 89
90-- with nil coalescing operator 90-- com operador de coalescência de nil
91a = (try? func!) ?? "default" 91a = (try? func!) ?? "default"
92 92
93-- as function argument 93-- como argumento de função
94f try? func! 94f try? func!
95 95
96-- with catch block 96-- com bloco catch
97f try? 97f try?
98 print 123 98 print 123
99 func! 99 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 @@
1# Assignment 1# Atribuição
2 2
3The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement. 3A 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**.
4 4
5```yuescript 5```yuescript
6hello = "world" 6hello = "world"
7a, b, c = 1, 2, 3 7a, b, c = 1, 2, 3
8hello = 123 -- uses the existing variable 8hello = 123 -- usa a variável existente
9``` 9```
10<YueDisplay> 10<YueDisplay>
11 11
12```yue 12```yue
13hello = "world" 13hello = "world"
14a, b, c = 1, 2, 3 14a, b, c = 1, 2, 3
15hello = 123 -- uses the existing variable 15hello = 123 -- usa a variável existente
16``` 16```
17 17
18</YueDisplay> 18</YueDisplay>
19 19
20## Perform Update 20## Atualização
21 21
22You can perform update assignment with many binary operators. 22Você pode realizar atribuição de atualização com muitos operadores binários.
23```yuescript 23```yuescript
24x = 1 24x = 1
25x += 1 25x += 1
@@ -27,8 +27,8 @@ x -= 1
27x *= 10 27x *= 10
28x /= 10 28x /= 10
29x %= 10 29x %= 10
30s ..= "world" -- will add a new local if local variable is not exist 30s ..= "world" -- adiciona um novo local se a variável local não existir
31arg or= "default value" 31arg or= "valor padrão"
32``` 32```
33<YueDisplay> 33<YueDisplay>
34 34
@@ -39,15 +39,15 @@ x -= 1
39x *= 10 39x *= 10
40x /= 10 40x /= 10
41x %= 10 41x %= 10
42s ..= "world" -- will add a new local if local variable is not exist 42s ..= "world" -- adiciona um novo local se a variável local não existir
43arg or= "default value" 43arg or= "valor padrão"
44``` 44```
45 45
46</YueDisplay> 46</YueDisplay>
47 47
48## Chaining Assignment 48## Atribuição encadeada
49 49
50You can do chaining assignment to assign multiple items to hold the same value. 50Você pode fazer atribuição encadeada para atribuir múltiplos itens ao mesmo valor.
51```yuescript 51```yuescript
52a = b = c = d = e = 0 52a = b = c = d = e = 0
53x = y = z = f! 53x = y = z = f!
@@ -61,12 +61,12 @@ x = y = z = f!
61 61
62</YueDisplay> 62</YueDisplay>
63 63
64## Explicit Locals 64## Locais explícitos
65```yuescript 65```yuescript
66do 66do
67 local a = 1 67 local a = 1
68 local * 68 local *
69 print "forward declare all variables as locals" 69 print "declarar antecipadamente todas as variáveis como locais"
70 x = -> 1 + y + z 70 x = -> 1 + y + z
71 y, z = 2, 3 71 y, z = 2, 3
72 global instance = Item\new! 72 global instance = Item\new!
@@ -74,7 +74,7 @@ do
74do 74do
75 local X = 1 75 local X = 1
76 local ^ 76 local ^
77 print "only forward declare upper case variables" 77 print "declarar antecipadamente apenas variáveis em maiúsculas"
78 a = 1 78 a = 1
79 B = 2 79 B = 2
80``` 80```
@@ -84,7 +84,7 @@ do
84do 84do
85 local a = 1 85 local a = 1
86 local * 86 local *
87 print "forward declare all variables as locals" 87 print "declarar antecipadamente todas as variáveis como locais"
88 x = -> 1 + y + z 88 x = -> 1 + y + z
89 y, z = 2, 3 89 y, z = 2, 3
90 global instance = Item\new! 90 global instance = Item\new!
@@ -92,29 +92,29 @@ do
92do 92do
93 local X = 1 93 local X = 1
94 local ^ 94 local ^
95 print "only forward declare upper case variables" 95 print "declarar antecipadamente apenas variáveis em maiúsculas"
96 a = 1 96 a = 1
97 B = 2 97 B = 2
98``` 98```
99 99
100</YueDisplay> 100</YueDisplay>
101 101
102## Explicit Globals 102## Globais explícitos
103```yuescript 103```yuescript
104do 104do
105 global a = 1 105 global a = 1
106 global * 106 global *
107 print "declare all variables as globals" 107 print "declarar todas as variáveis como globais"
108 x = -> 1 + y + z 108 x = -> 1 + y + z
109 y, z = 2, 3 109 y, z = 2, 3
110 110
111do 111do
112 global X = 1 112 global X = 1
113 global ^ 113 global ^
114 print "only declare upper case variables as globals" 114 print "declarar apenas variáveis em masculas como globais"
115 a = 1 115 a = 1
116 B = 2 116 B = 2
117 local Temp = "a local value" 117 local Temp = "um valor local"
118``` 118```
119<YueDisplay> 119<YueDisplay>
120 120
@@ -122,17 +122,17 @@ do
122do 122do
123 global a = 1 123 global a = 1
124 global * 124 global *
125 print "declare all variables as globals" 125 print "declarar todas as variáveis como globais"
126 x = -> 1 + y + z 126 x = -> 1 + y + z
127 y, z = 2, 3 127 y, z = 2, 3
128 128
129do 129do
130 global X = 1 130 global X = 1
131 global ^ 131 global ^
132 print "only declare upper case variables as globals" 132 print "declarar apenas variáveis em masculas como globais"
133 a = 1 133 a = 1
134 B = 2 134 B = 2
135 local Temp = "a local value" 135 local Temp = "um valor local"
136``` 136```
137 137
138</YueDisplay> 138</YueDisplay>
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 @@
1# Destructuring Assignment 1# Atribuição por desestruturação
2 2
3Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. 3A 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.
4 4
5Typically 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. 5Tipicamente, 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.
6 6
7This is best explained with examples. Here is how you would unpack the first two values from a table: 7Isso é melhor explicado com exemplos. Assim vo extrairia os dois primeiros valores de uma tabela:
8 8
9```yuescript 9```yuescript
10thing = [1, 2] 10thing = [1, 2]
@@ -23,7 +23,7 @@ print a, b
23 23
24</YueDisplay> 24</YueDisplay>
25 25
26In 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. 26No 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.
27 27
28```yuescript 28```yuescript
29obj = { 29obj = {
@@ -35,7 +35,7 @@ obj = {
35{hello: hello, day: the_day} = obj 35{hello: hello, day: the_day} = obj
36print hello, the_day 36print hello, the_day
37 37
38:day = obj -- OK to do simple destructuring without braces 38:day = obj -- OK fazer desestruturação simples sem chaves
39``` 39```
40<YueDisplay> 40<YueDisplay>
41 41
@@ -49,12 +49,12 @@ obj = {
49{hello: hello, day: the_day} = obj 49{hello: hello, day: the_day} = obj
50print hello, the_day 50print hello, the_day
51 51
52:day = obj -- OK to do simple destructuring without braces 52:day = obj -- OK fazer desestruturação simples sem chaves
53``` 53```
54 54
55</YueDisplay> 55</YueDisplay>
56 56
57This also works with nested data structures as well: 57Isso também funciona com estruturas de dados aninhadas:
58 58
59```yuescript 59```yuescript
60obj2 = { 60obj2 = {
@@ -85,7 +85,7 @@ print first, second, color
85 85
86</YueDisplay> 86</YueDisplay>
87 87
88If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: 88Se a instrução de desestruturação for complicada, sinta-se à vontade para espalhá-la em várias linhas. Um exemplo um pouco mais complicado:
89 89
90```yuescript 90```yuescript
91{ 91{
@@ -108,7 +108,7 @@ If the destructuring statement is complicated, feel free to spread it out over a
108 108
109</YueDisplay> 109</YueDisplay>
110 110
111It'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: 111É 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 **:**:
112 112
113```yuescript 113```yuescript
114{:concat, :insert} = table 114{:concat, :insert} = table
@@ -121,7 +121,7 @@ It's common to extract values from at table and assign them the local variables
121 121
122</YueDisplay> 122</YueDisplay>
123 123
124This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: 124Isso é efetivamente o mesmo que import, mas podemos renomear campos que queremos extrair misturando a sintaxe:
125 125
126```yuescript 126```yuescript
127{:mix, :max, random: rand} = math 127{: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
134 134
135</YueDisplay> 135</YueDisplay>
136 136
137You can write default values while doing destructuring like: 137Você pode escrever valores pado ao fazer desestruturação:
138 138
139```yuescript 139```yuescript
140{:name = "nameless", :job = "jobless"} = person 140{:name = "sem nome", :job = "sem emprego"} = person
141``` 141```
142<YueDisplay> 142<YueDisplay>
143 143
144```yue 144```yue
145{:name = "nameless", :job = "jobless"} = person 145{:name = "sem nome", :job = "sem emprego"} = person
146``` 146```
147 147
148</YueDisplay> 148</YueDisplay>
149 149
150You can use `_` as placeholder when doing a list destructuring: 150Você pode usar `_` como placeholder ao fazer desestruturação de lista:
151 151
152```yuescript 152```yuescript
153[_, two, _, four] = items 153[_, two, _, four] = items
@@ -160,59 +160,59 @@ You can use `_` as placeholder when doing a list destructuring:
160 160
161</YueDisplay> 161</YueDisplay>
162 162
163## Range Destructuring 163## Desestruturação por intervalo
164 164
165You 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. 165Você 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.
166 166
167```yuescript 167```yuescript
168orders = ["first", "second", "third", "fourth", "last"] 168orders = ["first", "second", "third", "fourth", "last"]
169[first, ...bulk, last] = orders 169[first, ...bulk, last] = orders
170print first -- prints: first 170print first -- imprime: first
171print bulk -- prints: {"second", "third", "fourth"} 171print bulk -- imprime: {"second", "third", "fourth"}
172print last -- prints: last 172print last -- imprime: last
173``` 173```
174<YueDisplay> 174<YueDisplay>
175 175
176```yue 176```yue
177orders = ["first", "second", "third", "fourth", "last"] 177orders = ["first", "second", "third", "fourth", "last"]
178[first, ...bulk, last] = orders 178[first, ...bulk, last] = orders
179print first -- prints: first 179print first -- imprime: first
180print bulk -- prints: {"second", "third", "fourth"} 180print bulk -- imprime: {"second", "third", "fourth"}
181print last -- prints: last 181print last -- imprime: last
182``` 182```
183 183
184</YueDisplay> 184</YueDisplay>
185 185
186The 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: 186O 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:
187 187
188```yuescript 188```yuescript
189-- Capture everything after first element 189-- Capturar tudo após o primeiro elemento
190[first, ...rest] = orders 190[first, ...rest] = orders
191 191
192-- Capture everything before last element 192-- Capturar tudo antes do último elemento
193[...start, last] = orders 193[...start, last] = orders
194 194
195-- Capture things except the middle elements 195-- Capturar tudo exceto os elementos do meio
196[first, ..._, last] = orders 196[first, ..._, last] = orders
197``` 197```
198<YueDisplay> 198<YueDisplay>
199 199
200```yue 200```yue
201-- Capture everything after first element 201-- Capturar tudo após o primeiro elemento
202[first, ...rest] = orders 202[first, ...rest] = orders
203 203
204-- Capture everything before last element 204-- Capturar tudo antes do último elemento
205[...start, last] = orders 205[...start, last] = orders
206 206
207-- Capture things except the middle elements 207-- Capturar tudo exceto os elementos do meio
208[first, ..._, last] = orders 208[first, ..._, last] = orders
209``` 209```
210 210
211</YueDisplay> 211</YueDisplay>
212 212
213## Destructuring In Other Places 213## Desestruturação em outros lugares
214 214
215Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: 215A desestruturação também pode aparecer em lugares onde uma atribuição ocorre implicitamente. Um exemplo disso é um loop for:
216 216
217```yuescript 217```yuescript
218tuples = [ 218tuples = [
@@ -237,4 +237,4 @@ for [left, right] in *tuples
237 237
238</YueDisplay> 238</YueDisplay>
239 239
240We 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. 240Sabemos 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 @@
1# If Assignment 1# Atribuição em if
2 2
3`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. 3Os 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.
4 4
5```yuescript 5```yuescript
6if user := database.find_user "moon" 6if user := database.find_user "moon"
@@ -17,55 +17,55 @@ if user := database.find_user "moon"
17 17
18```yuescript 18```yuescript
19if hello := os.getenv "hello" 19if hello := os.getenv "hello"
20 print "You have hello", hello 20 print "Vo tem hello", hello
21elseif world := os.getenv "world" 21elseif world := os.getenv "world"
22 print "you have world", world 22 print "vo tem world", world
23else 23else
24 print "nothing :(" 24 print "nada :("
25``` 25```
26<YueDisplay> 26<YueDisplay>
27 27
28```yue 28```yue
29if hello := os.getenv "hello" 29if hello := os.getenv "hello"
30 print "You have hello", hello 30 print "Vo tem hello", hello
31elseif world := os.getenv "world" 31elseif world := os.getenv "world"
32 print "you have world", world 32 print "vo tem world", world
33else 33else
34 print "nothing :(" 34 print "nada :("
35``` 35```
36 36
37</YueDisplay> 37</YueDisplay>
38 38
39If assignment with multiple return values. Only the first value is getting checked, other values are scoped. 39Atribuição em if com múltiplos valores de retorno. Apenas o primeiro valor é verificado, os outros valores estão no escopo.
40```yuescript 40```yuescript
41if success, result := pcall -> "get result without problems" 41if success, result := pcall -> "obter resultado sem problemas"
42 print result -- variable result is scoped 42 print result -- variável result es no escopo
43print "OK" 43print "OK"
44``` 44```
45<YueDisplay> 45<YueDisplay>
46 46
47```yue 47```yue
48if success, result := pcall -> "get result without problems" 48if success, result := pcall -> "obter resultado sem problemas"
49 print result -- variable result is scoped 49 print result -- variável result es no escopo
50print "OK" 50print "OK"
51``` 51```
52 52
53</YueDisplay> 53</YueDisplay>
54 54
55## While Assignment 55## Atribuição em while
56 56
57You can also use if assignment in a while loop to get the value as the loop condition. 57Você também pode usar atribuição em if em um loop while para obter o valor como condição do loop.
58 58
59```yuescript 59```yuescript
60while byte := stream\read_one! 60while byte := stream\read_one!
61 -- do something with the byte 61 -- fazer algo com o byte
62 print byte 62 print byte
63``` 63```
64<YueDisplay> 64<YueDisplay>
65 65
66```yue 66```yue
67while byte := stream\read_one! 67while byte := stream\read_one!
68 -- do something with the byte 68 -- fazer algo com o byte
69 print byte 69 print byte
70``` 70```
71 71
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 @@
1# The Using Clause; Controlling Destructive Assignment 1# A cláusula Using; controlando atribuição destrutiva
2 2
3While 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: 3Embora 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:
4 4
5```yuescript 5```yuescript
6i = 100 6i = 100
7 7
8-- many lines of code... 8-- muitas linhas de código...
9 9
10my_func = -> 10my_func = ->
11 i = 10 11 i = 10
@@ -15,14 +15,14 @@ my_func = ->
15 15
16my_func! 16my_func!
17 17
18print i -- will print 0 18print i -- vai imprimir 0
19``` 19```
20<YueDisplay> 20<YueDisplay>
21 21
22```yue 22```yue
23i = 100 23i = 100
24 24
25-- many lines of code... 25-- muitas linhas de código...
26 26
27my_func = -> 27my_func = ->
28 i = 10 28 i = 10
@@ -32,25 +32,25 @@ my_func = ->
32 32
33my_func! 33my_func!
34 34
35print i -- will print 0 35print i -- vai imprimir 0
36``` 36```
37 37
38</YueDisplay> 38</YueDisplay>
39 39
40In 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. 40Em 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.
41 41
42It 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. 42Seria útil dizer quais variáveis do escopo envolvente pretendemos alterar, para evitar que alteremos outras por acidente.
43 43
44The 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. 44A 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.
45 45
46```yuescript 46```yuescript
47i = 100 47i = 100
48 48
49my_func = (using nil) -> 49my_func = (using nil) ->
50 i = "hello" -- a new local variable is created here 50 i = "hello" -- uma nova variável local é criada aqui
51 51
52my_func! 52my_func!
53print i -- prints 100, i is unaffected 53print i -- imprime 100, i não é afetado
54``` 54```
55<YueDisplay> 55<YueDisplay>
56 56
@@ -58,27 +58,27 @@ print i -- prints 100, i is unaffected
58i = 100 58i = 100
59 59
60my_func = (using nil) -> 60my_func = (using nil) ->
61 i = "hello" -- a new local variable is created here 61 i = "hello" -- uma nova variável local é criada aqui
62 62
63my_func! 63my_func!
64print i -- prints 100, i is unaffected 64print i -- imprime 100, i não é afetado
65``` 65```
66 66
67</YueDisplay> 67</YueDisplay>
68 68
69Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: 69Múltiplos nomes podem ser separados por vírgulas. Os valores do closure ainda podem ser acessados, apenas não podem ser modificados:
70 70
71```yuescript 71```yuescript
72tmp = 1213 72tmp = 1213
73i, k = 100, 50 73i, k = 100, 50
74 74
75my_func = (add using k, i) -> 75my_func = (add using k, i) ->
76 tmp = tmp + add -- a new local tmp is created 76 tmp = tmp + add -- uma nova variável local tmp é criada
77 i += tmp 77 i += tmp
78 k += tmp 78 k += tmp
79 79
80my_func(22) 80my_func(22)
81print i, k -- these have been updated 81print i, k -- estes foram atualizados
82``` 82```
83<YueDisplay> 83<YueDisplay>
84 84
@@ -87,12 +87,12 @@ tmp = 1213
87i, k = 100, 50 87i, k = 100, 50
88 88
89my_func = (add using k, i) -> 89my_func = (add using k, i) ->
90 tmp = tmp + add -- a new local tmp is created 90 tmp = tmp + add -- uma nova variável local tmp é criada
91 i += tmp 91 i += tmp
92 k += tmp 92 k += tmp
93 93
94my_func(22) 94my_func(22)
95print i, k -- these have been updated 95print i, k -- estes foram atualizados
96``` 96```
97 97
98</YueDisplay> 98</YueDisplay>
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 @@
1# Varargs Assignment 1# Atribuição de varargs
2 2
3You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. 3Você pode atribuir os resultados retornados de uma função a um símbolo varargs `...`. E então acessar seu conteúdo da forma Lua.
4 4
5```yuescript 5```yuescript
6list = [1, 2, 3, 4, 5] 6list = [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 @@
1# Conditionals 1# Condicionais
2 2
3```yuescript 3```yuescript
4have_coins = false 4have_coins = false
5if have_coins 5if have_coins
6 print "Got coins" 6 print "Tem moedas"
7else 7else
8 print "No coins" 8 print "Sem moedas"
9``` 9```
10<YueDisplay> 10<YueDisplay>
11 11
12```yue 12```yue
13have_coins = false 13have_coins = false
14if have_coins 14if have_coins
15 print "Got coins" 15 print "Tem moedas"
16else 16else
17 print "No coins" 17 print "Sem moedas"
18``` 18```
19 19
20</YueDisplay> 20</YueDisplay>
21 21
22A short syntax for single statements can also be used: 22Uma sintaxe curta para instruções únicas também pode ser usada:
23 23
24```yuescript 24```yuescript
25have_coins = false 25have_coins = false
26if have_coins then print "Got coins" else print "No coins" 26if have_coins then print "Tem moedas" else print "Sem moedas"
27``` 27```
28<YueDisplay> 28<YueDisplay>
29 29
30```yue 30```yue
31have_coins = false 31have_coins = false
32if have_coins then print "Got coins" else print "No coins" 32if have_coins then print "Tem moedas" else print "Sem moedas"
33``` 33```
34 34
35</YueDisplay> 35</YueDisplay>
36 36
37Because if statements can be used as expressions, this can also be written as: 37Como instruções if podem ser usadas como expressões, isso também pode ser escrito como:
38 38
39```yuescript 39```yuescript
40have_coins = false 40have_coins = false
41print if have_coins then "Got coins" else "No coins" 41print if have_coins then "Tem moedas" else "Sem moedas"
42``` 42```
43<YueDisplay> 43<YueDisplay>
44 44
45```yue 45```yue
46have_coins = false 46have_coins = false
47print if have_coins then "Got coins" else "No coins" 47print if have_coins then "Tem moedas" else "Sem moedas"
48``` 48```
49 49
50</YueDisplay> 50</YueDisplay>
51 51
52Conditionals can also be used in return statements and assignments: 52Condicionais também podem ser usados em instruções de retorno e atribuições:
53 53
54```yuescript 54```yuescript
55is_tall = (name) -> 55is_tall = (name) ->
@@ -59,11 +59,11 @@ is_tall = (name) ->
59 false 59 false
60 60
61message = if is_tall "Rob" 61message = if is_tall "Rob"
62 "I am very tall" 62 "Sou muito alto"
63else 63else
64 "I am not so tall" 64 "o sou tão alto"
65 65
66print message -- prints: I am very tall 66print message -- imprime: Sou muito alto
67``` 67```
68<YueDisplay> 68<YueDisplay>
69 69
@@ -75,53 +75,53 @@ is_tall = (name) ->
75 false 75 false
76 76
77message = if is_tall "Rob" 77message = if is_tall "Rob"
78 "I am very tall" 78 "Sou muito alto"
79else 79else
80 "I am not so tall" 80 "o sou tão alto"
81 81
82print message -- prints: I am very tall 82print message -- imprime: Sou muito alto
83``` 83```
84 84
85</YueDisplay> 85</YueDisplay>
86 86
87The opposite of if is unless: 87O oposto de if é unless:
88 88
89```yuescript 89```yuescript
90unless os.date("%A") == "Monday" 90unless os.date("%A") == "Monday"
91 print "it is not Monday!" 91 print "não é segunda-feira!"
92``` 92```
93<YueDisplay> 93<YueDisplay>
94 94
95```yue 95```yue
96unless os.date("%A") == "Monday" 96unless os.date("%A") == "Monday"
97 print "it is not Monday!" 97 print "não é segunda-feira!"
98``` 98```
99 99
100</YueDisplay> 100</YueDisplay>
101 101
102```yuescript 102```yuescript
103print "You're lucky!" unless math.random! > 0.1 103print "Você tem sorte!" unless math.random! > 0.1
104``` 104```
105<YueDisplay> 105<YueDisplay>
106 106
107```yue 107```yue
108print "You're lucky!" unless math.random! > 0.1 108print "Você tem sorte!" unless math.random! > 0.1
109``` 109```
110 110
111</YueDisplay> 111</YueDisplay>
112 112
113## In Expression 113## Em expressão
114 114
115You can write range checking code with an `in-expression`. 115Você pode escrever código de verificação de intervalo com uma `in-expression`.
116 116
117```yuescript 117```yuescript
118a = 5 118a = 5
119 119
120if a in [1, 3, 5, 7] 120if a in [1, 3, 5, 7]
121 print "checking equality with discrete values" 121 print "verificando igualdade com valores discretos"
122 122
123if a in list 123if a in list
124 print "checking if `a` is in a list" 124 print "verificando se `a` es na lista"
125``` 125```
126<YueDisplay> 126<YueDisplay>
127 127
@@ -129,21 +129,10 @@ if a in list
129a = 5 129a = 5
130 130
131if a in [1, 3, 5, 7] 131if a in [1, 3, 5, 7]
132 print "checking equality with discrete values" 132 print "verificando igualdade com valores discretos"
133 133
134if a in list 134if a in list
135 print "checking if `a` is in a list" 135 print "verificando se `a` está na lista"
136```
137
138</YueDisplay>
139
140```yuescript
141print "You're lucky!" unless math.random! > 0.1
142```
143<YueDisplay>
144
145```yue
146print "You're lucky!" unless math.random! > 0.1
147``` 136```
148 137
149</YueDisplay> 138</YueDisplay>
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 @@
1# Continue 1# Continue
2 2
3A continue statement can be used to skip the current iteration in a loop. 3Uma instrução continue pode ser usada para pular a iteração atual em um loop.
4 4
5```yuescript 5```yuescript
6i = 0 6i = 0
@@ -21,7 +21,7 @@ while i < 10
21 21
22</YueDisplay> 22</YueDisplay>
23 23
24continue 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: 24continue 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:
25 25
26```yuescript 26```yuescript
27my_numbers = [1, 2, 3, 4, 5, 6] 27my_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 @@
1# For Loop 1# Loop For
2 2
3There are two for loop forms, just like in Lua. A numeric one and a generic one: 3Existem duas formas de loop for, assim como no Lua. Uma numérica e uma genérica:
4 4
5```yuescript 5```yuescript
6for i = 10, 20 6for i = 10, 20
7 print i 7 print i
8 8
9for k = 1, 15, 2 -- an optional step provided 9for k = 1, 15, 2 -- um passo opcional fornecido
10 print k 10 print k
11 11
12for key, value in pairs object 12for key, value in pairs object
@@ -18,7 +18,7 @@ for key, value in pairs object
18for i = 10, 20 18for i = 10, 20
19 print i 19 print i
20 20
21for k = 1, 15, 2 -- an optional step provided 21for k = 1, 15, 2 -- um passo opcional fornecido
22 print k 22 print k
23 23
24for key, value in pairs object 24for key, value in pairs object
@@ -27,7 +27,7 @@ for key, value in pairs object
27 27
28</YueDisplay> 28</YueDisplay>
29 29
30The slicing and **\*** operators can be used, just like with comprehensions: 30Os operadores de slicing e **\*** podem ser usados, assim como com compreensões:
31 31
32```yuescript 32```yuescript
33for item in *items[2, 4] 33for item in *items[2, 4]
@@ -42,7 +42,7 @@ for item in *items[2, 4]
42 42
43</YueDisplay> 43</YueDisplay>
44 44
45A shorter syntax is also available for all variations when the body is only a single line: 45Uma sintaxe mais curta também está disponível para todas as variações quando o corpo é apenas uma linha:
46 46
47```yuescript 47```yuescript
48for item in *items do print item 48for item in *items do print item
@@ -59,9 +59,9 @@ for j = 1, 10, 3 do print j
59 59
60</YueDisplay> 60</YueDisplay>
61 61
62A 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. 62Um 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.
63 63
64Doubling every even number: 64Dobrando cada número par:
65 65
66```yuescript 66```yuescript
67doubled_evens = for i = 1, 20 67doubled_evens = for i = 1, 20
@@ -82,9 +82,9 @@ doubled_evens = for i = 1, 20
82 82
83</YueDisplay> 83</YueDisplay>
84 84
85In 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. 85Alé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.
86 86
87For example, to find the first number greater than 10: 87Por exemplo, para encontrar o primeiro número maior que 10:
88 88
89```yuescript 89```yuescript
90first_large = for n in *numbers 90first_large = for n in *numbers
@@ -99,18 +99,18 @@ first_large = for n in *numbers
99 99
100</YueDisplay> 100</YueDisplay>
101 101
102This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. 102Esta sintaxe de break-com-valor permite padrões concisos e expressivos de busca ou saída antecipada diretamente em expressões de loop.
103 103
104You can also filter values by combining the for loop expression with the continue statement. 104Você também pode filtrar valores combinando a expressão do loop for com a instrução continue.
105 105
106For 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. 106Loops 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.
107 107
108```yuescript 108```yuescript
109func_a = -> for i = 1, 10 do print i 109func_a = -> for i = 1, 10 do print i
110func_b = -> return for i = 1, 10 do i 110func_b = -> return for i = 1, 10 do i
111 111
112print func_a! -- prints nil 112print func_a! -- imprime nil
113print func_b! -- prints table object 113print func_b! -- imprime objeto table
114``` 114```
115<YueDisplay> 115<YueDisplay>
116 116
@@ -118,10 +118,10 @@ print func_b! -- prints table object
118func_a = -> for i = 1, 10 do print i 118func_a = -> for i = 1, 10 do print i
119func_b = -> return for i = 1, 10 do i 119func_b = -> return for i = 1, 10 do i
120 120
121print func_a! -- prints nil 121print func_a! -- imprime nil
122print func_b! -- prints table object 122print func_b! -- imprime objeto table
123``` 123```
124 124
125</YueDisplay> 125</YueDisplay>
126 126
127This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. 127Isso é 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 @@
1# Switch 1# Switch
2 2
3The 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. 3A 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.
4 4
5```yuescript 5```yuescript
6switch name := "Dan" 6switch name := "Dan"
7 when "Robert" 7 when "Robert"
8 print "You are Robert" 8 print "Vo é Robert"
9 when "Dan", "Daniel" 9 when "Dan", "Daniel"
10 print "Your name, it's Dan" 10 print "Seu nome é Dan"
11 else 11 else
12 print "I don't know about you with name #{name}" 12 print "o sei quem vo é com o nome #{name}"
13``` 13```
14<YueDisplay> 14<YueDisplay>
15 15
16```yue 16```yue
17switch name := "Dan" 17switch name := "Dan"
18 when "Robert" 18 when "Robert"
19 print "You are Robert" 19 print "Vo é Robert"
20 when "Dan", "Daniel" 20 when "Dan", "Daniel"
21 print "Your name, it's Dan" 21 print "Seu nome é Dan"
22 else 22 else
23 print "I don't know about you with name #{name}" 23 print "o sei quem vo é com o nome #{name}"
24``` 24```
25 25
26</YueDisplay> 26</YueDisplay>
27 27
28A switch when clause can match against multiple values by listing them out comma separated. 28Uma cláusula when de um switch pode corresponder a múltiplos valores listando-os separados por vírgula.
29 29
30Switches can be used as expressions as well, here we can assign the result of the switch to a variable: 30Os switches também podem ser usados como expressões; aqui podemos atribuir o resultado do switch a uma variável:
31 31
32```yuescript 32```yuescript
33b = 1 33b = 1
@@ -37,7 +37,7 @@ next_number = switch b
37 when 2 37 when 2
38 3 38 3
39 else 39 else
40 error "can't count that high!" 40 error "não consigo contar tão alto!"
41``` 41```
42<YueDisplay> 42<YueDisplay>
43 43
@@ -49,66 +49,66 @@ next_number = switch b
49 when 2 49 when 2
50 3 50 3
51 else 51 else
52 error "can't count that high!" 52 error "não consigo contar tão alto!"
53``` 53```
54 54
55</YueDisplay> 55</YueDisplay>
56 56
57We 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. 57Podemos 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.
58 58
59```yuescript 59```yuescript
60msg = switch math.random(1, 5) 60msg = switch math.random(1, 5)
61 when 1 then "you are lucky" 61 when 1 then "vo tem sorte"
62 when 2 then "you are almost lucky" 62 when 2 then "vo quase tem sorte"
63 else "not so lucky" 63 else "não tão sortudo"
64``` 64```
65<YueDisplay> 65<YueDisplay>
66 66
67```yue 67```yue
68msg = switch math.random(1, 5) 68msg = switch math.random(1, 5)
69 when 1 then "you are lucky" 69 when 1 then "vo tem sorte"
70 when 2 then "you are almost lucky" 70 when 2 then "vo quase tem sorte"
71 else "not so lucky" 71 else "não tão sortudo"
72``` 72```
73 73
74</YueDisplay> 74</YueDisplay>
75 75
76If 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. 76Se 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.
77 77
78```yuescript 78```yuescript
79switch math.random(1, 5) 79switch math.random(1, 5)
80 when 1 80 when 1
81 print "you are lucky" -- two indents 81 print "vo tem sorte" -- duas indentações
82 else 82 else
83 print "not so lucky" 83 print "não tão sortudo"
84 84
85switch math.random(1, 5) when 1 85switch math.random(1, 5) when 1
86 print "you are lucky" -- one indent 86 print "vo tem sorte" -- uma indentação
87else 87else
88 print "not so lucky" 88 print "não tão sortudo"
89``` 89```
90<YueDisplay> 90<YueDisplay>
91 91
92```yue 92```yue
93switch math.random(1, 5) 93switch math.random(1, 5)
94 when 1 94 when 1
95 print "you are lucky" -- two indents 95 print "vo tem sorte" -- duas indentações
96 else 96 else
97 print "not so lucky" 97 print "não tão sortudo"
98 98
99switch math.random(1, 5) when 1 99switch math.random(1, 5) when 1
100 print "you are lucky" -- one indent 100 print "vo tem sorte" -- uma indentação
101else 101else
102 print "not so lucky" 102 print "não tão sortudo"
103``` 103```
104 104
105</YueDisplay> 105</YueDisplay>
106 106
107It 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. 107Vale 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.
108 108
109## Table Matching 109## Correspondência de tabela
110 110
111You can do table matching in a switch when clause, if the table can be destructured by a specific structure and get non-nil values. 111Você 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.
112 112
113```yuescript 113```yuescript
114items = 114items =
@@ -122,7 +122,7 @@ for item in *items
122 when :x, :y 122 when :x, :y
123 print "Vec2 #{x}, #{y}" 123 print "Vec2 #{x}, #{y}"
124 when :width, :height 124 when :width, :height
125 print "size #{width}, #{height}" 125 print "tamanho #{width}, #{height}"
126``` 126```
127<YueDisplay> 127<YueDisplay>
128 128
@@ -138,39 +138,39 @@ for item in *items
138 when :x, :y 138 when :x, :y
139 print "Vec2 #{x}, #{y}" 139 print "Vec2 #{x}, #{y}"
140 when :width, :height 140 when :width, :height
141 print "size #{width}, #{height}" 141 print "tamanho #{width}, #{height}"
142``` 142```
143 143
144</YueDisplay> 144</YueDisplay>
145 145
146You can use default values to optionally destructure the table for some fields. 146Você pode usar valores padrão para opcionalmente desestruturar a tabela para alguns campos.
147 147
148```yuescript 148```yuescript
149item = {} 149item = {}
150 150
151{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') 151{pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos')
152 152
153switch item 153switch item
154 when {pos: {:x = 50, :y = 200}} 154 when {pos: {:x = 50, :y = 200}}
155 print "Vec2 #{x}, #{y}" -- table destructuring will still pass 155 print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará
156``` 156```
157<YueDisplay> 157<YueDisplay>
158 158
159```yue 159```yue
160item = {} 160item = {}
161 161
162{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') 162{pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos')
163 163
164switch item 164switch item
165 when {pos: {:x = 50, :y = 200}} 165 when {pos: {:x = 50, :y = 200}}
166 print "Vec2 #{x}, #{y}" -- table destructuring will still pass 166 print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará
167``` 167```
168 168
169</YueDisplay> 169</YueDisplay>
170 170
171You can also match against array elements, table fields, and even nested structures with array or table literals. 171Você também pode corresponder contra elementos de array, campos de tabela, e até estruturas aninhadas com literais de array ou tabela.
172 172
173Match against array elements. 173Corresponder contra elementos de array.
174 174
175```yuescript 175```yuescript
176switch tb 176switch tb
@@ -178,7 +178,7 @@ switch tb
178 print "1, 2, 3" 178 print "1, 2, 3"
179 when [1, b, 3] 179 when [1, b, 3]
180 print "1, #{b}, 3" 180 print "1, #{b}, 3"
181 when [1, 2, b = 3] -- b has a default value 181 when [1, 2, b = 3] -- b tem valor padrão
182 print "1, 2, #{b}" 182 print "1, 2, #{b}"
183``` 183```
184<YueDisplay> 184<YueDisplay>
@@ -189,63 +189,63 @@ switch tb
189 print "1, 2, 3" 189 print "1, 2, 3"
190 when [1, b, 3] 190 when [1, b, 3]
191 print "1, #{b}, 3" 191 print "1, #{b}, 3"
192 when [1, 2, b = 3] -- b has a default value 192 when [1, 2, b = 3] -- b tem valor padrão
193 print "1, 2, #{b}" 193 print "1, 2, #{b}"
194``` 194```
195 195
196</YueDisplay> 196</YueDisplay>
197 197
198Match against table fields with destructuring. 198Corresponder contra campos de tabela com desestruturação.
199 199
200```yuescript 200```yuescript
201switch tb 201switch tb
202 when success: true, :result 202 when success: true, :result
203 print "success", result 203 print "sucesso", result
204 when success: false 204 when success: false
205 print "failed", result 205 print "falhou", result
206 else 206 else
207 print "invalid" 207 print "inválido"
208``` 208```
209<YueDisplay> 209<YueDisplay>
210 210
211```yue 211```yue
212switch tb 212switch tb
213 when success: true, :result 213 when success: true, :result
214 print "success", result 214 print "sucesso", result
215 when success: false 215 when success: false
216 print "failed", result 216 print "falhou", result
217 else 217 else
218 print "invalid" 218 print "inválido"
219``` 219```
220 220
221</YueDisplay> 221</YueDisplay>
222 222
223Match against nested table structures. 223Corresponder contra estruturas de tabela aninhadas.
224 224
225```yuescript 225```yuescript
226switch tb 226switch tb
227 when data: {type: "success", :content} 227 when data: {type: "success", :content}
228 print "success", content 228 print "sucesso", content
229 when data: {type: "error", :content} 229 when data: {type: "error", :content}
230 print "failed", content 230 print "erro", content
231 else 231 else
232 print "invalid" 232 print "inválido"
233``` 233```
234<YueDisplay> 234<YueDisplay>
235 235
236```yue 236```yue
237switch tb 237switch tb
238 when data: {type: "success", :content} 238 when data: {type: "success", :content}
239 print "success", content 239 print "sucesso", content
240 when data: {type: "error", :content} 240 when data: {type: "error", :content}
241 print "failed", content 241 print "erro", content
242 else 242 else
243 print "invalid" 243 print "inválido"
244``` 244```
245 245
246</YueDisplay> 246</YueDisplay>
247 247
248Match against array of tables. 248Corresponder contra array de tabelas.
249 249
250```yuescript 250```yuescript
251switch tb 251switch tb
@@ -255,7 +255,7 @@ switch tb
255 {a: 5, b: 6} 255 {a: 5, b: 6}
256 fourth 256 fourth
257 ] 257 ]
258 print "matched", fourth 258 print "correspondido", fourth
259``` 259```
260<YueDisplay> 260<YueDisplay>
261 261
@@ -267,20 +267,20 @@ switch tb
267 {a: 5, b: 6} 267 {a: 5, b: 6}
268 fourth 268 fourth
269 ] 269 ]
270 print "matched", fourth 270 print "correspondido", fourth
271``` 271```
272 272
273</YueDisplay> 273</YueDisplay>
274 274
275Match against a list and capture a range of elements. 275Corresponder contra uma lista e capturar um intervalo de elementos.
276 276
277```yuescript 277```yuescript
278segments = ["admin", "users", "logs", "view"] 278segments = ["admin", "users", "logs", "view"]
279switch segments 279switch segments
280 when [...groups, resource, action] 280 when [...groups, resource, action]
281 print "Group:", groups -- prints: {"admin", "users"} 281 print "Grupo:", groups -- imprime: {"admin", "users"}
282 print "Resource:", resource -- prints: "logs" 282 print "Recurso:", resource -- imprime: "logs"
283 print "Action:", action -- prints: "view" 283 print "Ação:", action -- imprime: "view"
284``` 284```
285<YueDisplay> 285<YueDisplay>
286 286
@@ -288,9 +288,9 @@ switch segments
288segments = ["admin", "users", "logs", "view"] 288segments = ["admin", "users", "logs", "view"]
289switch segments 289switch segments
290 when [...groups, resource, action] 290 when [...groups, resource, action]
291 print "Group:", groups -- prints: {"admin", "users"} 291 print "Grupo:", groups -- imprime: {"admin", "users"}
292 print "Resource:", resource -- prints: "logs" 292 print "Recurso:", resource -- imprime: "logs"
293 print "Action:", action -- prints: "view" 293 print "Ação:", action -- imprime: "view"
294``` 294```
295 295
296</YueDisplay> 296</YueDisplay>
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 @@
1# While Loop 1# Loop While
2 2
3The while loop also comes in four variations: 3O loop while também vem em quatro variações:
4 4
5```yuescript 5```yuescript
6i = 10 6i = 10
@@ -43,11 +43,11 @@ until running == false do my_function!
43 43
44</YueDisplay> 44</YueDisplay>
45 45
46Like 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. 46Como 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.
47 47
48## Repeat Loop 48## Loop Repeat
49 49
50The repeat loop comes from Lua: 50O loop repeat vem do Lua:
51 51
52```yuescript 52```yuescript
53i = 10 53i = 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 @@
1# Comprehensions 1# Compreensões
2 2
3Comprehensions 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. 3As 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.
4 4
5## List Comprehensions 5## Compreensões de lista
6 6
7The following creates a copy of the items table but with all the values doubled. 7O seguinte cria uma cópia da tabela items mas com todos os valores dobrados.
8 8
9```yuescript 9```yuescript
10items = [ 1, 2, 3, 4 ] 10items = [ 1, 2, 3, 4 ]
@@ -19,7 +19,7 @@ doubled = [item * 2 for i, item in ipairs items]
19 19
20</YueDisplay> 20</YueDisplay>
21 21
22The items included in the new table can be restricted with a when clause: 22Os itens incluídos na nova tabela podem ser restringidos com uma cláusula when:
23 23
24```yuescript 24```yuescript
25slice = [item for i, item in ipairs items when i > 1 and i < 3] 25slice = [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]
32 32
33</YueDisplay> 33</YueDisplay>
34 34
35Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as: 35Como é comum iterar sobre os valores de uma tabela indexada numericamente, um operador **\*** é introduzido. O exemplo doubled pode ser reescrito como:
36 36
37```yuescript 37```yuescript
38doubled = [item * 2 for item in *items] 38doubled = [item * 2 for item in *items]
@@ -45,7 +45,7 @@ doubled = [item * 2 for item in *items]
45 45
46</YueDisplay> 46</YueDisplay>
47 47
48In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: 48Nas compreensões de lista, você também pode usar o operador spread `...` para achatar listas aninhadas, alcançando um efeito de flat map:
49 49
50```yuescript 50```yuescript
51data = 51data =
@@ -53,7 +53,7 @@ data =
53 b: [4, 5, 6] 53 b: [4, 5, 6]
54 54
55flat = [...v for k,v in pairs data] 55flat = [...v for k,v in pairs data]
56-- flat is now [1, 2, 3, 4, 5, 6] 56-- flat agora é [1, 2, 3, 4, 5, 6]
57``` 57```
58<YueDisplay> 58<YueDisplay>
59 59
@@ -63,14 +63,14 @@ data =
63 b: [4, 5, 6] 63 b: [4, 5, 6]
64 64
65flat = [...v for k,v in pairs data] 65flat = [...v for k,v in pairs data]
66-- flat is now [1, 2, 3, 4, 5, 6] 66-- flat agora é [1, 2, 3, 4, 5, 6]
67``` 67```
68 68
69</YueDisplay> 69</YueDisplay>
70 70
71The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause. 71As 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.
72 72
73Using multiple for clauses is the same as using nested loops: 73Usar múltiplas cláusulas for é o mesmo que usar loops aninhados:
74 74
75```yuescript 75```yuescript
76x_coords = [4, 5, 6, 7] 76x_coords = [4, 5, 6, 7]
@@ -91,7 +91,7 @@ for y in *y_coords]
91 91
92</YueDisplay> 92</YueDisplay>
93 93
94Numeric for loops can also be used in comprehensions: 94Loops for numéricos também podem ser usados em compreensões:
95 95
96```yuescript 96```yuescript
97evens = [i for i = 1, 100 when i % 2 == 0] 97evens = [i for i = 1, 100 when i % 2 == 0]
@@ -104,11 +104,11 @@ evens = [i for i = 1, 100 when i % 2 == 0]
104 104
105</YueDisplay> 105</YueDisplay>
106 106
107## Table Comprehensions 107## Compreensões de tabela
108 108
109The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. 109A sintaxe para compreensões de tabela é muito semelhante, diferindo apenas por usar **{** e **}** e receber dois valores de cada iteração.
110 110
111This example makes a copy of the tablething: 111Este exemplo faz uma cópia da tabela thing:
112 112
113```yuescript 113```yuescript
114thing = { 114thing = {
@@ -144,7 +144,7 @@ no_color = {k, v for k, v in pairs thing when k != "color"}
144 144
145</YueDisplay> 145</YueDisplay>
146 146
147The **\*** operator is also supported. Here we create a square root look up table for a few numbers. 147O operador **\*** também é suportado. Aqui criamos uma tabela de consulta de raiz quadrada para alguns números.
148 148
149```yuescript 149```yuescript
150numbers = [1, 2, 3, 4] 150numbers = [1, 2, 3, 4]
@@ -159,9 +159,9 @@ sqrts = {i, math.sqrt i for i in *numbers}
159 159
160</YueDisplay> 160</YueDisplay>
161 161
162The 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: 162A 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:
163 163
164In 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. 164Neste exemplo convertemos um array de pares em uma tabela onde o primeiro item do par é a chave e o segundo é o valor.
165 165
166```yuescript 166```yuescript
167tuples = [ ["hello", "world"], ["foo", "bar"]] 167tuples = [ ["hello", "world"], ["foo", "bar"]]
@@ -178,9 +178,9 @@ tbl = {unpack tuple for tuple in *tuples}
178 178
179## Slicing 179## Slicing
180 180
181A 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. 181Uma 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.
182 182
183Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive: 183Aqui podemos definir os limites mínimo e máximo, pegando todos os itens com índices entre 1 e 5 inclusive:
184 184
185```yuescript 185```yuescript
186slice = [item for item in *items[1, 5]] 186slice = [item for item in *items[1, 5]]
@@ -193,7 +193,7 @@ slice = [item for item in *items[1, 5]]
193 193
194</YueDisplay> 194</YueDisplay>
195 195
196Any 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: 196Qualquer 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:
197 197
198```yuescript 198```yuescript
199slice = [item for item in *items[2,]] 199slice = [item for item in *items[2,]]
@@ -206,7 +206,7 @@ slice = [item for item in *items[2,]]
206 206
207</YueDisplay> 207</YueDisplay>
208 208
209If 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, …) 209Se 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, …)
210 210
211```yuescript 211```yuescript
212slice = [item for item in *items[,,2]] 212slice = [item for item in *items[,,2]]
@@ -219,22 +219,22 @@ slice = [item for item in *items[,,2]]
219 219
220</YueDisplay> 220</YueDisplay>
221 221
222Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. 222Tanto 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.
223 223
224```yuescript 224```yuescript
225-- take the last 4 items 225-- pegar os últimos 4 itens
226slice = [item for item in *items[-4,-1]] 226slice = [item for item in *items[-4,-1]]
227``` 227```
228<YueDisplay> 228<YueDisplay>
229 229
230```yue 230```yue
231-- take the last 4 items 231-- pegar os últimos 4 itens
232slice = [item for item in *items[-4,-1]] 232slice = [item for item in *items[-4,-1]]
233``` 233```
234 234
235</YueDisplay> 235</YueDisplay>
236 236
237The step size can also be negative, which means that the items are taken in reverse order. 237O tamanho do passo também pode ser negativo, o que significa que os itens são tomados em ordem reversa.
238 238
239```yuescript 239```yuescript
240reverse_slice = [item for item in *items[-1,1,-1]] 240reverse_slice = [item for item in *items[-1,1,-1]]
@@ -247,24 +247,24 @@ reverse_slice = [item for item in *items[-1,1,-1]]
247 247
248</YueDisplay> 248</YueDisplay>
249 249
250### Slicing Expression 250### Expressão de slicing
251 251
252Slicing can also be used as an expression. This is useful for getting a sub-list of a table. 252O slicing também pode ser usado como expressão. Isso é útil para obter uma sublista de uma tabela.
253 253
254```yuescript 254```yuescript
255-- take the 2nd and 4th items as a new list 255-- pegar o 2º e 4º itens como nova lista
256sub_list = items[2, 4] 256sub_list = items[2, 4]
257 257
258-- take the last 4 items 258-- pegar os últimos 4 itens
259last_four_items = items[-4, -1] 259last_four_items = items[-4, -1]
260``` 260```
261<YueDisplay> 261<YueDisplay>
262 262
263```yue 263```yue
264-- take the 2nd and 4th items as a new list 264-- pegar o 2º e 4º itens como nova lista
265sub_list = items[2, 4] 265sub_list = items[2, 4]
266 266
267-- take the last 4 items 267-- pegar os últimos 4 itens
268last_four_items = items[-4, -1] 268last_four_items = items[-4, -1]
269``` 269```
270 270
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 @@
1# Table Literals 1# Literais de tabela
2 2
3Like in Lua, tables are delimited in curly braces. 3Como no Lua, as tabelas são delimitadas por chaves.
4 4
5```yuescript 5```yuescript
6some_values = [1, 2, 3, 4] 6some_values = [1, 2, 3, 4]
@@ -13,7 +13,7 @@ some_values = [1, 2, 3, 4]
13 13
14</YueDisplay> 14</YueDisplay>
15 15
16Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). 16Diferente do Lua, atribuir um valor a uma chave em uma tabela é feito com **:** (em vez de **=**).
17 17
18```yuescript 18```yuescript
19some_values = { 19some_values = {
@@ -34,7 +34,7 @@ some_values = {
34 34
35</YueDisplay> 35</YueDisplay>
36 36
37The curly braces can be left off if a single table of key value pairs is being assigned. 37As chaves podem ser omitidas se uma única tabela de pares chave-valor es sendo atribuída.
38 38
39```yuescript 39```yuescript
40profile = 40profile =
@@ -53,7 +53,7 @@ profile =
53 53
54</YueDisplay> 54</YueDisplay>
55 55
56Newlines can be used to delimit values instead of a comma (or both): 56Quebras de linha podem ser usadas para delimitar valores em vez de vírgula (ou ambos):
57 57
58```yuescript 58```yuescript
59values = { 59values = {
@@ -76,7 +76,7 @@ values = {
76 76
77</YueDisplay> 77</YueDisplay>
78 78
79When creating a single line table literal, the curly braces can also be left off: 79Ao criar um literal de tabela em uma única linha, as chaves também podem ser omitidas:
80 80
81```yuescript 81```yuescript
82my_function dance: "Tango", partner: "none" 82my_function dance: "Tango", partner: "none"
@@ -93,7 +93,7 @@ y = type: "dog", legs: 4, tails: 1
93 93
94</YueDisplay> 94</YueDisplay>
95 95
96The keys of a table literal can be language keywords without being escaped: 96As chaves de um literal de tabela podem ser palavras-chave da linguagem sem precisar escapar:
97 97
98```yuescript 98```yuescript
99tbl = { 99tbl = {
@@ -112,7 +112,7 @@ tbl = {
112 112
113</YueDisplay> 113</YueDisplay>
114 114
115If 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: 115Se 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:
116 116
117```yuescript 117```yuescript
118hair = "golden" 118hair = "golden"
@@ -133,7 +133,7 @@ print_table :hair, :height
133 133
134</YueDisplay> 134</YueDisplay>
135 135
136If 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. 136Se 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.
137 137
138```yuescript 138```yuescript
139t = { 139t = {
@@ -152,7 +152,7 @@ t = {
152 152
153</YueDisplay> 153</YueDisplay>
154 154
155Lua 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. 155As 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.
156 156
157```yuescript 157```yuescript
158some_values = [1, 2, 3, 4] 158some_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 @@
1# Backcalls 1# Backcalls
2 2
3Backcalls 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. 3Backcalls 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.
4 4
5```yuescript 5```yuescript
6x <- f 6x <- f
@@ -15,7 +15,7 @@ print "hello" .. x
15 15
16</YueDisplay> 16</YueDisplay>
17 17
18Fat arrow functions are also available. 18Funções seta "fat" também eso disponíveis.
19 19
20```yuescript 20```yuescript
21<= f 21<= f
@@ -30,7 +30,7 @@ print @value
30 30
31</YueDisplay> 31</YueDisplay>
32 32
33You can specify a placeholder for where you want the backcall function to go as a parameter. 33Você pode especificar um placeholder para onde deseja que a função backcall como parâmetro.
34 34
35```yuescript 35```yuescript
36(x) <- map _, [1, 2, 3] 36(x) <- map _, [1, 2, 3]
@@ -45,7 +45,7 @@ x * 2
45 45
46</YueDisplay> 46</YueDisplay>
47 47
48If 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. 48Se 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.
49 49
50```yuescript 50```yuescript
51result, msg = do 51result, 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 @@
1# Function Literals 1# Literais de função
2 2
3All functions are created using a function expression. A simple function is denoted using the arrow: **->**. 3Todas as funções são criadas usando uma expressão de função. Uma função simples é denotada usando a seta: **->**.
4 4
5```yuescript 5```yuescript
6my_function = -> 6my_function = ->
7my_function() -- call the empty function 7my_function() -- chama a função vazia
8``` 8```
9<YueDisplay> 9<YueDisplay>
10 10
11```yue 11```yue
12my_function = -> 12my_function = ->
13my_function() -- call the empty function 13my_function() -- chama a função vazia
14``` 14```
15 15
16</YueDisplay> 16</YueDisplay>
17 17
18The 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: 18O 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:
19 19
20```yuescript 20```yuescript
21func_a = -> print "hello world" 21func_a = -> print "hello world"
@@ -36,7 +36,7 @@ func_b = ->
36 36
37</YueDisplay> 37</YueDisplay>
38 38
39If 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. 39Se 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.
40 40
41```yuescript 41```yuescript
42func_a! 42func_a!
@@ -51,7 +51,7 @@ func_b()
51 51
52</YueDisplay> 52</YueDisplay>
53 53
54Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: 54Funções com argumentos podem ser criadas precedendo a seta com uma lista de nomes de argumentos entre parênteses:
55 55
56```yuescript 56```yuescript
57sum = (x, y) -> print "sum", x + y 57sum = (x, y) -> print "sum", x + y
@@ -64,7 +64,7 @@ sum = (x, y) -> print "sum", x + y
64 64
65</YueDisplay> 65</YueDisplay>
66 66
67Functions 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. 67Funçõ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.
68 68
69```yuescript 69```yuescript
70sum 10, 20 70sum 10, 20
@@ -83,7 +83,7 @@ a b c "a", "b", "c"
83 83
84</YueDisplay> 84</YueDisplay>
85 85
86In 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. 86Para 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.
87 87
88```yuescript 88```yuescript
89print "x:", sum(10, 20), "y:", sum(30, 40) 89print "x:", sum(10, 20), "y:", sum(30, 40)
@@ -96,9 +96,9 @@ print "x:", sum(10, 20), "y:", sum(30, 40)
96 96
97</YueDisplay> 97</YueDisplay>
98 98
99There must not be any space between the opening parenthesis and the function. 99o deve haver espaço entre o parêntese de abertura e a função.
100 100
101Functions will coerce the last statement in their body into a return statement, this is called implicit return: 101As funções convertem a última instrução em seu corpo em uma instrução de retorno, isso é chamado de retorno implícito:
102 102
103```yuescript 103```yuescript
104sum = (x, y) -> x + y 104sum = (x, y) -> x + y
@@ -113,7 +113,7 @@ print "The sum is ", sum 10, 20
113 113
114</YueDisplay> 114</YueDisplay>
115 115
116And if you need to explicitly return, you can use the return keyword: 116E se vo precisar retornar explicitamente, pode usar a palavra-chave return:
117 117
118```yuescript 118```yuescript
119sum = (x, y) -> return x + y 119sum = (x, y) -> return x + y
@@ -126,7 +126,7 @@ sum = (x, y) -> return x + y
126 126
127</YueDisplay> 127</YueDisplay>
128 128
129Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: 129Assim 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:
130 130
131```yuescript 131```yuescript
132mystery = (x, y) -> x + y, x - y 132mystery = (x, y) -> x + y, x - y
@@ -141,9 +141,9 @@ a, b = mystery 10, 20
141 141
142</YueDisplay> 142</YueDisplay>
143 143
144## Fat Arrows 144## Setas fat
145 145
146Because 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. 146Como é 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.
147 147
148```yuescript 148```yuescript
149func = (num) => @value + num 149func = (num) => @value + num
@@ -156,9 +156,9 @@ func = (num) => @value + num
156 156
157</YueDisplay> 157</YueDisplay>
158 158
159## Argument Defaults 159## Valores padrão de argumentos
160 160
161It 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. 161É 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.
162 162
163```yuescript 163```yuescript
164my_function = (name = "something", height = 100) -> 164my_function = (name = "something", height = 100) ->
@@ -175,7 +175,7 @@ my_function = (name = "something", height = 100) ->
175 175
176</YueDisplay> 176</YueDisplay>
177 177
178An 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. 178Uma 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.
179 179
180```yuescript 180```yuescript
181some_args = (x = 100, y = x + 1000) -> 181some_args = (x = 100, y = x + 1000) ->
@@ -190,11 +190,11 @@ some_args = (x = 100, y = x + 1000) ->
190 190
191</YueDisplay> 191</YueDisplay>
192 192
193## Considerations 193## Considerações
194 194
195Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. 195Devido à 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.
196 196
197The minus sign plays two roles, a unary negation operator and a binary subtraction operator. Consider how the following examples compile: 197O 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:
198 198
199```yuescript 199```yuescript
200a = x - 10 200a = x - 10
@@ -213,11 +213,11 @@ d = x- z
213 213
214</YueDisplay> 214</YueDisplay>
215 215
216The 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. 216A 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.
217 217
218When 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. 218Quando 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.
219 219
220Where 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. 220Quando 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.
221 221
222```yuescript 222```yuescript
223x = func"hello" + 100 223x = func"hello" + 100
@@ -232,11 +232,11 @@ y = func "hello" + 100
232 232
233</YueDisplay> 233</YueDisplay>
234 234
235## Multi-line arguments 235## Argumentos multilinha
236 236
237When 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. 237Ao 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.
238 238
239If 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 239Se 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.
240 240
241```yuescript 241```yuescript
242my_func 5, 4, 3, 242my_func 5, 4, 3,
@@ -261,7 +261,7 @@ cool_func 1, 2,
261 261
262</YueDisplay> 262</YueDisplay>
263 263
264This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. 264Este tipo de invocação pode ser aninhado. O nível de indentação é usado para determinar a qual função os argumentos pertencem.
265 265
266```yuescript 266```yuescript
267my_func 5, 6, 7, 267my_func 5, 6, 7,
@@ -280,7 +280,7 @@ my_func 5, 6, 7,
280 280
281</YueDisplay> 281</YueDisplay>
282 282
283Because 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. 283Como 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.
284 284
285```yuescript 285```yuescript
286x = [ 286x = [
@@ -301,7 +301,7 @@ x = [
301 301
302</YueDisplay> 302</YueDisplay>
303 303
304Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on. 304Embora 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.
305 305
306```yuescript 306```yuescript
307y = [ my_func 1, 2, 3, 307y = [ my_func 1, 2, 3,
@@ -320,7 +320,7 @@ y = [ my_func 1, 2, 3,
320 320
321</YueDisplay> 321</YueDisplay>
322 322
323The 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: 323A 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:
324 324
325```yuescript 325```yuescript
326if func 1, 2, 3, 326if func 1, 2, 3,
@@ -353,13 +353,13 @@ if func 1, 2, 3,
353 353
354</YueDisplay> 354</YueDisplay>
355 355
356## Parameter Destructuring 356## Desestruturação de parâmetros
357 357
358YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: 358YueScript 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:
359 359
360* **Curly-brace wrapped literals/object parameters**, allowing optional default values when fields are missing (e.g., `{:a, :b}`, `{a: a1 = 123}`). 360* **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}`).
361 361
362* **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. 362* **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.
363 363
364```yuescript 364```yuescript
365f1 = (:a, :b, :c) -> 365f1 = (:a, :b, :c) ->
@@ -390,9 +390,9 @@ f2 arg1, arg2
390 390
391</YueDisplay> 391</YueDisplay>
392 392
393## Prefixed Return Expression 393## Expressão de retorno prefixada
394 394
395When 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: 395Ao 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:
396 396
397```yuescript 397```yuescript
398findFirstEven = (list): nil -> 398findFirstEven = (list): nil ->
@@ -415,7 +415,7 @@ findFirstEven = (list): nil ->
415 415
416</YueDisplay> 416</YueDisplay>
417 417
418This is equivalent to: 418Isso é equivalente a:
419 419
420```yuescript 420```yuescript
421findFirstEven = (list) -> 421findFirstEven = (list) ->
@@ -440,16 +440,16 @@ findFirstEven = (list) ->
440 440
441</YueDisplay> 441</YueDisplay>
442 442
443The 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. 443A ú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.
444 444
445## Named Varargs 445## Varargs nomeados
446 446
447You 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). 447Você 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`).
448 448
449```yuescript 449```yuescript
450f = (...t) -> 450f = (...t) ->
451 print "argument count:", t.n 451 print "contagem de argumentos:", t.n
452 print "table length:", #t 452 print "comprimento da tabela:", #t
453 for i = 1, t.n 453 for i = 1, t.n
454 print t[i] 454 print t[i]
455 455
@@ -457,7 +457,7 @@ f 1, 2, 3
457f "a", "b", "c", "d" 457f "a", "b", "c", "d"
458f! 458f!
459 459
460-- Handling cases with nil values 460-- Tratando casos com valores nil
461process = (...args) -> 461process = (...args) ->
462 sum = 0 462 sum = 0
463 for i = 1, args.n 463 for i = 1, args.n
@@ -471,8 +471,8 @@ process 1, nil, 3, nil, 5
471 471
472```yue 472```yue
473f = (...t) -> 473f = (...t) ->
474 print "argument count:", t.n 474 print "contagem de argumentos:", t.n
475 print "table length:", #t 475 print "comprimento da tabela:", #t
476 for i = 1, t.n 476 for i = 1, t.n
477 print t[i] 477 print t[i]
478 478
@@ -480,7 +480,7 @@ f 1, 2, 3
480f "a", "b", "c", "d" 480f "a", "b", "c", "d"
481f! 481f!
482 482
483-- Handling cases with nil values 483-- Tratando casos com valores nil
484process = (...args) -> 484process = (...args) ->
485 sum = 0 485 sum = 0
486 for i = 1, args.n 486 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 @@
1# Function Stubs 1# Stubs de função
2 2
3It 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. 3É 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.
4 4
5The 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. 5A 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.
6 6
7Its syntax is the same as calling an instance method with the \ operator but with no argument list provided. 7Sua sintaxe é a mesma que chamar um método de instância com o operador \, mas sem lista de argumentos fornecida.
8 8
9```yuescript 9```yuescript
10my_object = { 10my_object = {
@@ -16,12 +16,12 @@ run_callback = (func) ->
16 print "running callback..." 16 print "running callback..."
17 func! 17 func!
18 18
19-- this will not work: 19-- isso não funcionará:
20-- the function has to no reference to my_object 20-- a função não tem referência a my_object
21run_callback my_object.write 21run_callback my_object.write
22 22
23-- function stub syntax 23-- sintaxe de function stub
24-- lets us bundle the object into a new function 24-- nos permite empacotar o objeto em uma nova função
25run_callback my_object\write 25run_callback my_object\write
26``` 26```
27<YueDisplay> 27<YueDisplay>
@@ -36,12 +36,12 @@ run_callback = (func) ->
36 print "running callback..." 36 print "running callback..."
37 func! 37 func!
38 38
39-- this will not work: 39-- isso não funcionará:
40-- the function has to no reference to my_object 40-- a função não tem referência a my_object
41run_callback my_object.write 41run_callback my_object.write
42 42
43-- function stub syntax 43-- sintaxe de function stub
44-- lets us bundle the object into a new function 44-- nos permite empacotar o objeto em uma nova função
45run_callback my_object\write 45run_callback my_object\write
46``` 46```
47 47
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 @@
1# Installation 1# Instalação
2 2
3## Lua Module 3## Módulo Lua
4 4
5Install [luarocks](https://luarocks.org), a package manager for Lua modules. Then install it as a Lua module and executable with: 5Instale 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:
6 6
7```shell 7```shell
8luarocks install yuescript 8luarocks install yuescript
9``` 9```
10 10
11Or you can build `yue.so` file with: 11Ou vo pode compilar o arquivo `yue.so` com:
12 12
13```shell 13```shell
14make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua 14make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua
15``` 15```
16 16
17Then get the binary file from path **bin/shared/yue.so**. 17Depois, obtenha o arquivo binário no caminho **bin/shared/yue.so**.
18 18
19## Build Binary Tool 19## Compilar ferramenta binária
20 20
21Clone this repo, then build and install executable with: 21Clone este repositório e compile e instale o executável com:
22 22
23```shell 23```shell
24make install 24make install
25``` 25```
26 26
27Build YueScript tool without macro feature: 27Compilar a ferramenta YueScript sem o recurso de macro:
28 28
29```shell 29```shell
30make install NO_MACRO=true 30make install NO_MACRO=true
31``` 31```
32 32
33Build YueScript tool without built-in Lua binary: 33Compilar a ferramenta YueScript sem o binário Lua embutido:
34 34
35```shell 35```shell
36make install NO_LUA=true 36make install NO_LUA=true
37``` 37```
38 38
39## Download Precompiled Binary 39## Baixar binário pré-compilado
40 40
41You can download precompiled binary files, including binary executable files compatible with different Lua versions and library files. 41Você pode baixar arquivos binários pré-compilados, incluindo executáveis compatíveis com diferentes versões do Lua e arquivos de biblioteca.
42 42
43Download precompiled binary files from [here](https://github.com/IppClub/YueScript/releases). 43Baixe 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 @@
1# Introduction 1# Introdução
2 2
3YueScript 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. 3YueScript é 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.
4 4
5Yue (月) is the name of moon in Chinese and it's pronounced as [jyɛ]. 5Yue (月) é o nome da lua em chinês e é pronunciado como [jyɛ].
6 6
7## An Overview of YueScript 7## Uma visão geral do YueScript
8 8
9```yuescript 9```yuescript
10-- import syntax 10-- sintaxe de importação
11import p, to_lua from "yue" 11import p, to_lua from "yue"
12 12
13-- object literals 13-- literais de objeto
14inventory = 14inventory =
15 equipment: 15 equipment:
16 - "sword" 16 - "sword"
@@ -21,7 +21,7 @@ inventory =
21 - name: "bread" 21 - name: "bread"
22 count: 3 22 count: 3
23 23
24-- list comprehension 24-- compreensão de lista
25map = (arr, action) -> 25map = (arr, action) ->
26 [action item for item in *arr] 26 [action item for item in *arr]
27 27
@@ -31,14 +31,14 @@ filter = (arr, cond) ->
31reduce = (arr, init, action): init -> 31reduce = (arr, init, action): init ->
32 init = action init, item for item in *arr 32 init = action init, item for item in *arr
33 33
34-- pipe operator 34-- operador pipe
35[1, 2, 3] 35[1, 2, 3]
36 |> map (x) -> x * 2 36 |> map (x) -> x * 2
37 |> filter (x) -> x > 4 37 |> filter (x) -> x > 4
38 |> reduce 0, (a, b) -> a + b 38 |> reduce 0, (a, b) -> a + b
39 |> print 39 |> print
40 40
41-- metatable manipulation 41-- manipulação de metatable
42apple = 42apple =
43 size: 15 43 size: 15
44 <index>: 44 <index>:
@@ -47,17 +47,17 @@ apple =
47with apple 47with apple
48 p .size, .color, .<index> if .<>? 48 p .size, .color, .<index> if .<>?
49 49
50-- js-like export syntax 50-- sintaxe de exportação estilo js
51export 🌛 = "月之脚本" 51export 🌛 = "Script da Lua"
52``` 52```
53 53
54<YueDisplay> 54<YueDisplay>
55 55
56```yue 56```yue
57-- import syntax 57-- sintaxe de importação
58import p, to_lua from "yue" 58import p, to_lua from "yue"
59 59
60-- object literals 60-- literais de objeto
61inventory = 61inventory =
62 equipment: 62 equipment:
63 - "sword" 63 - "sword"
@@ -68,7 +68,7 @@ inventory =
68 - name: "bread" 68 - name: "bread"
69 count: 3 69 count: 3
70 70
71-- list comprehension 71-- compreensão de lista
72map = (arr, action) -> 72map = (arr, action) ->
73 [action item for item in *arr] 73 [action item for item in *arr]
74 74
@@ -78,14 +78,14 @@ filter = (arr, cond) ->
78reduce = (arr, init, action): init -> 78reduce = (arr, init, action): init ->
79 init = action init, item for item in *arr 79 init = action init, item for item in *arr
80 80
81-- pipe operator 81-- operador pipe
82[1, 2, 3] 82[1, 2, 3]
83 |> map (x) -> x * 2 83 |> map (x) -> x * 2
84 |> filter (x) -> x > 4 84 |> filter (x) -> x > 4
85 |> reduce 0, (a, b) -> a + b 85 |> reduce 0, (a, b) -> a + b
86 |> print 86 |> print
87 87
88-- metatable manipulation 88-- manipulação de metatable
89apple = 89apple =
90 size: 15 90 size: 15
91 <index>: 91 <index>:
@@ -94,12 +94,12 @@ apple =
94with apple 94with apple
95 p .size, .color, .<index> if .<>? 95 p .size, .color, .<index> if .<>?
96 96
97-- js-like export syntax 97-- sintaxe de exportação estilo js
98export 🌛 = "月之脚本" 98export 🌛 = "Script da Lua"
99``` 99```
100 100
101</YueDisplay> 101</YueDisplay>
102 102
103## About Dora SSR 103## Sobre o Dora SSR
104 104
105YueScript 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 105O 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 @@
1# Usage 1# Uso
2 2
3## Lua Module 3## Módulo Lua
4 4
5Use YueScript module in Lua: 5Use o módulo YueScript em Lua:
6 6
7* **Case 1** 7* **Caso 1**
8 8
9 Require "your_yuescript_entry.yue" in Lua. 9 Use require em "your_yuescript_entry.yue" no Lua.
10 ```Lua 10 ```Lua
11 require("yue")("your_yuescript_entry") 11 require("yue")("your_yuescript_entry")
12 ``` 12 ```
13 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. 13 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.
14 14
15* **Case 2** 15* **Caso 2**
16 16
17 Require YueScript module and rewite message by hand. 17 Requerer o módulo YueScript e reescrever a mensagem manualmente.
18 18
19 ```lua 19 ```lua
20 local yue = require("yue") 20 local yue = require("yue")
@@ -26,9 +26,9 @@ Use YueScript module in Lua:
26 end) 26 end)
27 ``` 27 ```
28 28
29* **Case 3** 29* **Caso 3**
30 30
31 Use the YueScript compiler function in Lua. 31 Usar a função compiladora do YueScript em Lua.
32 32
33 ```lua 33 ```lua
34 local yue = require("yue") 34 local yue = require("yue")
@@ -48,9 +48,9 @@ Use YueScript module in Lua:
48 }) 48 })
49 ``` 49 ```
50 50
51## YueScript Tool 51## Ferramenta YueScript
52 52
53Use YueScript tool with: 53Use a ferramenta YueScript com:
54 54
55```shell 55```shell
56> yue -h 56> yue -h
@@ -60,52 +60,53 @@ Usage: yue
60 yue -w [<directory>] [options] 60 yue -w [<directory>] [options]
61 yue - 61 yue -
62 62
63Notes: 63Notas:
64 - '-' / '--' must be the first and only argument. 64 - '-' / '--' deve ser o primeiro e único argumento.
65 - '-o/--output' can not be used with multiple input files. 65 - '-o/--output' não pode ser usado com múltiplos arquivos de entrada.
66 - '-w/--watch' can not be used with file input (directory only). 66 - '-w/--watch' não pode ser usado com entrada de arquivo (apenas diretório).
67 - with '-e/--execute', remaining tokens are treated as script args. 67 - com '-e/--execute', os tokens restantes são tratados como argumentos do script.
68 68
69Options: 69Opções:
70 -h, --help Show this help message and exit. 70 -h, --help Mostrar esta mensagem de ajuda e sair.
71 -e <str>, --execute <str> Execute a file or raw codes 71 -e <str>, --execute <str> Executar um arquivo ou código bruto
72 -m, --minify Generate minified codes 72 -m, --minify Gerar código minificado
73 -r, --rewrite Rewrite output to match original line numbers 73 -r, --rewrite Reescrever saída para corresponder aos meros de linha originais
74 -t <output_to>, --output-to <output_to> 74 -t <output_to>, --output-to <output_to>
75 Specify where to place compiled files 75 Especificar onde colocar os arquivos compilados
76 -o <file>, --output <file> Write output to file 76 -o <file>, --output <file> Escrever saída em arquivo
77 -p, --print Write output to standard out 77 -p, --print Escrever saída na saída padrão
78 -b, --benchmark Dump compile time (doesn't write output) 78 -b, --benchmark Mostrar tempo de compilação (não grava saída)
79 -g, --globals Dump global variables used in NAME LINE COLUMN 79 -g, --globals Listar variáveis globais usadas em NOME LINHA COLUNA
80 -s, --spaces Use spaces in generated codes instead of tabs 80 -s, --spaces Usar espaços no código gerado em vez de tabulações
81 -l, --line-numbers Write line numbers from source codes 81 -l, --line-numbers Escrever números de linha do código fonte
82 -j, --no-implicit-return Disable implicit return at end of file 82 -j, --no-implicit-return Desabilitar retorno implícito no final do arquivo
83 -c, --reserve-comments Reserve comments before statement from source codes 83 -c, --reserve-comments Preservar comentários antes de instruções dodigo fonte
84 -w [<dir>], --watch [<dir>] 84 -w [<dir>], --watch [<dir>]
85 Watch changes and compile every file under directory 85 Observar alterações e compilar cada arquivo no diretório
86 -v, --version Print version 86 -v, --version Imprimir versão
87 - Read from standard in, print to standard out 87 - Ler da entrada padrão, imprimir na saída padrão
88 (Must be first and only argument) 88 (Deve ser o primeiro e único argumento)
89 -- Same as '-' (kept for backward compatibility) 89 -- Igual a '-' (mantido para compatibilidade retroativa)
90 90
91 --target <version> Specify the Lua version that codes will be generated to 91 --target <version> Especificar a versão do Lua para a qual o código se gerado
92 (version can only be 5.1 to 5.5) 92 (a versão pode ser apenas 5.1 a 5.5)
93 --path <path_str> Append an extra Lua search path string to package.path 93 --path <path_str> Adicionar um caminho de busca Lua extra ao package.path
94 --<key>=<value> Pass compiler option in key=value form (existing behavior) 94 --<key>=<value> Passar opção do compilador no formato key=value (comportamento existente)
95 95
96 Execute without options to enter REPL, type symbol '$' 96 Execute sem opções para entrar no REPL, digite o símbolo '$'
97 in a single line to start/stop multi-line mode 97 em uma única linha para iniciar/parar o modo multilinha
98``` 98```
99Use cases:
100 99
101Recursively compile every YueScript file with extension **.yue** under current path: **yue .** 100Casos de uso:
102 101
103Compile and save results to a target path: **yue -t /target/path/ .** 102Compilar recursivamente todos os arquivos YueScript com extensão **.yue** no caminho atual: **yue .**
104 103
105Compile and reserve debug info: **yue -l .** 104Compilar e salvar resultados em um caminho de destino: **yue -t /target/path/ .**
106 105
107Compile and generate minified codes: **yue -m .** 106Compilar e preservar informações de debug: **yue -l .**
108 107
109Execute raw codes: **yue -e 'print 123'** 108Compilar e gerar código minificado: **yue -m .**
110 109
111Execute a YueScript file: **yue -e main.yue** 110Executar código bruto: **yue -e 'print 123'**
111
112Executar 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 @@
1# Attributes 1# Atributos
2 2
3Syntax 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. 3Suporte 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.
4 4
5```yuescript 5```yuescript
6const a = 123 6const a = 123
7close _ = <close>: -> print "Out of scope." 7close _ = <close>: -> print "Fora do escopo."
8``` 8```
9<YueDisplay> 9<YueDisplay>
10 10
11```yue 11```yue
12const a = 123 12const a = 123
13close _ = <close>: -> print "Out of scope." 13close _ = <close>: -> print "Fora do escopo."
14``` 14```
15 15
16</YueDisplay> 16</YueDisplay>
17 17
18You can do desctructuring with variables attributed as constant. 18Você pode fazer desestruturação com variáveis atribuídas como constante.
19 19
20```yuescript 20```yuescript
21const {:a, :b, c, d} = tb 21const {:a, :b, c, d} = tb
@@ -30,7 +30,7 @@ const {:a, :b, c, d} = tb
30 30
31</YueDisplay> 31</YueDisplay>
32 32
33You can also declare a global variable to be `const`. 33Você também pode declarar uma variável global como `const`.
34 34
35```yuescript 35```yuescript
36global const Constant = 123 36global 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 @@
1# Comment 1# Comentário
2 2
3```yuescript 3```yuescript
4-- I am a comment 4-- Eu sou um comentário
5 5
6str = --[[ 6str = --[[
7This is a multi-line comment. 7Este é um comentário multilinha.
8It's OK. 8Es OK.
9]] strA \ -- comment 1 9]] strA \ -- comentário 1
10 .. strB \ -- comment 2 10 .. strB \ -- comentário 2
11 .. strC 11 .. strC
12 12
13func --[[port]] 3000, --[[ip]] "192.168.1.1" 13func --[[port]] 3000, --[[ip]] "192.168.1.1"
@@ -15,13 +15,13 @@ func --[[port]] 3000, --[[ip]] "192.168.1.1"
15<YueDisplay> 15<YueDisplay>
16 16
17```yue 17```yue
18-- I am a comment 18-- Eu sou um comentário
19 19
20str = --[[ 20str = --[[
21This is a multi-line comment. 21Este é um comentário multilinha.
22It's OK. 22Es OK.
23]] strA \ -- comment 1 23]] strA \ -- comentário 1
24 .. strB \ -- comment 2 24 .. strB \ -- comentário 2
25 .. strC 25 .. strC
26 26
27func --[[port]] 3000, --[[ip]] "192.168.1.1" 27func --[[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 @@
1# Literals 1# Literais
2 2
3All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. 3Todos os literais primitivos do Lua podem ser usados. Isso se aplica a números, strings, booleanos e **nil**.
4 4
5Unlike Lua, Line breaks are allowed inside of single and double quote strings without an escape sequence: 5Diferente do Lua, quebras de linha o permitidas dentro de strings com aspas simples e duplas sem sequência de escape:
6 6
7```yuescript 7```yuescript
8some_string = "Here is a string 8some_string = "Aqui es uma string
9 that has a line break in it." 9 que tem uma quebra de linha."
10 10
11-- You can mix expressions into string literals using #{} syntax. 11-- Você pode misturar expressões em literais de string usando a sintaxe #{}.
12-- String interpolation is only available in double quoted strings. 12-- Interpolação de string es disponível apenas em strings com aspas duplas.
13print "I am #{math.random! * 100}% sure." 13print "Tenho #{math.random! * 100}% de certeza."
14``` 14```
15<YueDisplay> 15<YueDisplay>
16 16
17```yue 17```yue
18some_string = "Here is a string 18some_string = "Aqui es uma string
19 that has a line break in it." 19 que tem uma quebra de linha."
20 20
21-- You can mix expressions into string literals using #{} syntax. 21-- Você pode misturar expressões em literais de string usando a sintaxe #{}.
22-- String interpolation is only available in double quoted strings. 22-- Interpolação de string es disponível apenas em strings com aspas duplas.
23print "I am #{math.random! * 100}% sure." 23print "Tenho #{math.random! * 100}% de certeza."
24``` 24```
25 25
26</YueDisplay> 26</YueDisplay>
27 27
28## Number Literals 28## Literais numéricos
29 29
30You can use underscores in a number literal to increase readability. 30Você pode usar underscores em um literal numérico para aumentar a legibilidade.
31 31
32```yuescript 32```yuescript
33integer = 1_000_000 33integer = 1_000_000
@@ -44,9 +44,9 @@ binary = 0B10011
44 44
45</YueDisplay> 45</YueDisplay>
46 46
47## YAML Multiline String 47## String multilinha estilo YAML
48 48
49The `|` prefix introduces a YAML-style multiline string literal: 49O prefixo `|` introduz um literal de string multilinha no estilo YAML:
50 50
51```yuescript 51```yuescript
52str = | 52str = |
@@ -67,9 +67,9 @@ str = |
67 67
68</YueDisplay> 68</YueDisplay>
69 69
70This 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)`. 70Isso 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)`.
71 71
72YAML 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. 72A 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.
73 73
74```yuescript 74```yuescript
75fn = -> 75fn = ->
@@ -90,21 +90,21 @@ fn = ->
90 90
91</YueDisplay> 91</YueDisplay>
92 92
93Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. 93A indentação interna é preservada em relação ao prefixo comum removido, permitindo estruturas aninhadas limpas.
94 94
95All 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. 95Todos 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.
96 96
97```yuescript 97```yuescript
98str = | 98str = |
99 path: "C:\Program Files\App" 99 path: "C:\Program Files\App"
100 note: 'He said: "#{Hello}!"' 100 note: 'Ele disse: "#{Hello}!"'
101``` 101```
102<YueDisplay> 102<YueDisplay>
103 103
104```yue 104```yue
105str = | 105str = |
106 path: "C:\Program Files\App" 106 path: "C:\Program Files\App"
107 note: 'He said: "#{Hello}!"' 107 note: 'Ele disse: "#{Hello}!"'
108``` 108```
109 109
110</YueDisplay> 110</YueDisplay>
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 @@
1# Operator 1# Operador
2 2
3All 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. 3Todos 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.
4 4
5```yuescript 5```yuescript
6tb\func! if tb ~= nil 6tb\func! if tb ~= nil
@@ -15,32 +15,32 @@ tb::func! if tb != nil
15 15
16</YueDisplay> 16</YueDisplay>
17 17
18## Chaining Comparisons 18## Comparações encadeadas
19 19
20Comparisons can be arbitrarily chained: 20Comparações podem ser encadeadas arbitrariamente:
21 21
22```yuescript 22```yuescript
23print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 23print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
24-- output: true 24-- saída: true
25 25
26a = 5 26a = 5
27print 1 <= a <= 10 27print 1 <= a <= 10
28-- output: true 28-- saída: true
29``` 29```
30<YueDisplay> 30<YueDisplay>
31 31
32```yue 32```yue
33print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 33print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
34-- output: true 34-- saída: true
35 35
36a = 5 36a = 5
37print 1 <= a <= 10 37print 1 <= a <= 10
38-- output: true 38-- saída: true
39``` 39```
40 40
41</YueDisplay> 41</YueDisplay>
42 42
43Note the evaluation behavior of chained comparisons: 43Observe o comportamento de avaliação das comparações encadeadas:
44 44
45```yuescript 45```yuescript
46v = (x) -> 46v = (x) ->
@@ -49,7 +49,7 @@ v = (x) ->
49 49
50print v(1) < v(2) <= v(3) 50print v(1) < v(2) <= v(3)
51--[[ 51--[[
52 output: 52 saída:
53 2 53 2
54 1 54 1
55 3 55 3
@@ -58,7 +58,7 @@ print v(1) < v(2) <= v(3)
58 58
59print v(1) > v(2) <= v(3) 59print v(1) > v(2) <= v(3)
60--[[ 60--[[
61 output: 61 saída:
62 2 62 2
63 1 63 1
64 false 64 false
@@ -73,7 +73,7 @@ v = (x) ->
73 73
74print v(1) < v(2) <= v(3) 74print v(1) < v(2) <= v(3)
75--[[ 75--[[
76 output: 76 saída:
77 2 77 2
78 1 78 1
79 3 79 3
@@ -82,7 +82,7 @@ print v(1) < v(2) <= v(3)
82 82
83print v(1) > v(2) <= v(3) 83print v(1) > v(2) <= v(3)
84--[[ 84--[[
85 output: 85 saída:
86 2 86 2
87 1 87 1
88 false 88 false
@@ -91,11 +91,11 @@ print v(1) > v(2) <= v(3)
91 91
92</YueDisplay> 92</YueDisplay>
93 93
94The 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. 94A 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.
95 95
96## Table Appending 96## Anexar à tabela
97 97
98The **[] =** operator is used to append values to tables. 98O operador **[] =** é usado para anexar valores a tabelas.
99 99
100```yuescript 100```yuescript
101tab = [] 101tab = []
@@ -110,13 +110,13 @@ tab[] = "Value"
110 110
111</YueDisplay> 111</YueDisplay>
112 112
113You can also use the spread operator `...` to append all elements from one list to another: 113Você também pode usar o operador spread `...` para anexar todos os elementos de uma lista a outra:
114 114
115```yuescript 115```yuescript
116tbA = [1, 2, 3] 116tbA = [1, 2, 3]
117tbB = [4, 5, 6] 117tbB = [4, 5, 6]
118tbA[] = ...tbB 118tbA[] = ...tbB
119-- tbA is now [1, 2, 3, 4, 5, 6] 119-- tbA agora é [1, 2, 3, 4, 5, 6]
120``` 120```
121<YueDisplay> 121<YueDisplay>
122 122
@@ -124,14 +124,14 @@ tbA[] = ...tbB
124tbA = [1, 2, 3] 124tbA = [1, 2, 3]
125tbB = [4, 5, 6] 125tbB = [4, 5, 6]
126tbA[] = ...tbB 126tbA[] = ...tbB
127-- tbA is now [1, 2, 3, 4, 5, 6] 127-- tbA agora é [1, 2, 3, 4, 5, 6]
128``` 128```
129 129
130</YueDisplay> 130</YueDisplay>
131 131
132## Table Spreading 132## Spread de tabela
133 133
134You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. 134Você pode concatenar tabelas de array ou tabelas hash usando o operador spread `...` antes de expressões em literais de tabela.
135 135
136```yuescript 136```yuescript
137parts = 137parts =
@@ -170,9 +170,9 @@ merge = {...a, ...b}
170 170
171</YueDisplay> 171</YueDisplay>
172 172
173## Table Reversed Indexing 173## Indexação reversa de tabela
174 174
175You can use the **#** operator to get the last elements of a table. 175Você pode usar o operador **#** para obter os últimos elementos de uma tabela.
176 176
177```yuescript 177```yuescript
178last = data.items[#] 178last = data.items[#]
@@ -191,11 +191,11 @@ data.items[#] = 1
191 191
192## Metatable 192## Metatable
193 193
194The **<>** operator can be used as a shortcut for metatable manipulation. 194O operador **<>** pode ser usado como atalho para manipulação de metatable.
195 195
196### Metatable Creation 196### Criação de metatable
197 197
198Create normal table with empty bracekets **<>** or metamethod key which is surrounded by **<>**. 198Crie tabela normal com chaves vazias **<>** ou chave de metamétodo cercada por **<>**.
199 199
200```yuescript 200```yuescript
201mt = {} 201mt = {}
@@ -203,14 +203,14 @@ add = (right) => <>: mt, value: @value + right.value
203mt.__add = add 203mt.__add = add
204 204
205a = <>: mt, value: 1 205a = <>: mt, value: 1
206 -- set field with variable of the same name 206 -- definir campo com variável de mesmo nome
207b = :<add>, value: 2 207b = :<add>, value: 2
208c = <add>: mt.__add, value: 3 208c = <add>: mt.__add, value: 3
209 209
210d = a + b + c 210d = a + b + c
211print d.value 211print d.value
212 212
213close _ = <close>: -> print "out of scope" 213close _ = <close>: -> print "fora do escopo"
214``` 214```
215<YueDisplay> 215<YueDisplay>
216 216
@@ -220,24 +220,24 @@ add = (right) => <>: mt, value: @value + right.value
220mt.__add = add 220mt.__add = add
221 221
222a = <>: mt, value: 1 222a = <>: mt, value: 1
223 -- set field with variable of the same name 223 -- definir campo com variável de mesmo nome
224b = :<add>, value: 2 224b = :<add>, value: 2
225c = <add>: mt.__add, value: 3 225c = <add>: mt.__add, value: 3
226 226
227d = a + b + c 227d = a + b + c
228print d.value 228print d.value
229 229
230close _ = <close>: -> print "out of scope" 230close _ = <close>: -> print "fora do escopo"
231``` 231```
232 232
233</YueDisplay> 233</YueDisplay>
234 234
235### Metatable Accessing 235### Acesso à metatable
236 236
237Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. 237Acesse a metatable com **<>** ou nome do metamétodo cercado por **<>** ou escrevendo alguma expressão em **<>**.
238 238
239```yuescript 239```yuescript
240-- create with metatable containing field "value" 240-- criar com metatable contendo campo "value"
241tb = <"value">: 123 241tb = <"value">: 123
242tb.<index> = tb.<> 242tb.<index> = tb.<>
243print tb.value 243print tb.value
@@ -248,7 +248,7 @@ print tb.item
248<YueDisplay> 248<YueDisplay>
249 249
250```yue 250```yue
251-- create with metatable containing field "value" 251-- criar com metatable contendo campo "value"
252tb = <"value">: 123 252tb = <"value">: 123
253tb.<index> = tb.<> 253tb.<index> = tb.<>
254print tb.value 254print tb.value
@@ -258,9 +258,9 @@ print tb.item
258 258
259</YueDisplay> 259</YueDisplay>
260 260
261### Metatable Destructure 261### Desestruturação de metatable
262 262
263Destruct metatable with metamethod key surrounded by **<>**. 263Desestruture a metatable com chave de metamétodo cercada por **<>**.
264 264
265```yuescript 265```yuescript
266{item, :new, :<close>, <index>: getter} = tb 266{item, :new, :<close>, <index>: getter} = tb
@@ -275,9 +275,9 @@ print item, new, close, getter
275 275
276</YueDisplay> 276</YueDisplay>
277 277
278## Existence 278## Existência
279 279
280The **?** operator can be used in a variety of contexts to check for existence. 280O operador **?** pode ser usado em diversos contextos para verificar existência.
281 281
282```yuescript 282```yuescript
283func?! 283func?!
@@ -312,16 +312,16 @@ with? io.open "test.txt", "w"
312 312
313</YueDisplay> 313</YueDisplay>
314 314
315## Piping 315## Pipe
316 316
317Instead of a series of nested function calls, you can pipe values with operator **|>**. 317Em vez de uma série de chamadas de função aninhadas, você pode encaminhar valores com o operador **|>**.
318 318
319```yuescript 319```yuescript
320"hello" |> print 320"hello" |> print
3211 |> print 2 -- insert pipe item as the first argument 3211 |> print 2 -- insere o item do pipe como primeiro argumento
3222 |> print 1, _, 3 -- pipe with a placeholder 3222 |> print 1, _, 3 -- pipe com um placeholder
323 323
324-- pipe expression in multiline 324-- expressão pipe em multilinha
325readFile "example.txt" 325readFile "example.txt"
326 |> extract language, {} 326 |> extract language, {}
327 |> parse language 327 |> parse language
@@ -333,9 +333,9 @@ readFile "example.txt"
333 333
334```yue 334```yue
335"hello" |> print 335"hello" |> print
3361 |> print 2 -- insert pipe item as the first argument 3361 |> print 2 -- insere o item do pipe como primeiro argumento
3372 |> print 1, _, 3 -- pipe with a placeholder 3372 |> print 1, _, 3 -- pipe com um placeholder
338-- pipe expression in multiline 338-- expressão pipe em multilinha
339readFile "example.txt" 339readFile "example.txt"
340 |> extract language, {} 340 |> extract language, {}
341 |> parse language 341 |> parse language
@@ -346,9 +346,9 @@ readFile "example.txt"
346 346
347</YueDisplay> 347</YueDisplay>
348 348
349## Nil Coalescing 349## Coalescência de nil
350 350
351The 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. 351O 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.
352```yuescript 352```yuescript
353local a, b, c, d 353local a, b, c, d
354a = b ?? c ?? d 354a = b ?? c ?? d
@@ -367,31 +367,31 @@ a ??= false
367 367
368</YueDisplay> 368</YueDisplay>
369 369
370## Implicit Object 370## Objeto implícito
371 371
372You 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. 372Você 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.
373 373
374```yuescript 374```yuescript
375-- assignment with implicit object 375-- atribuição com objeto implícito
376list = 376list =
377 * 1 377 * 1
378 * 2 378 * 2
379 * 3 379 * 3
380 380
381-- function call with implicit object 381-- chamada de função com objeto implícito
382func 382func
383 * 1 383 * 1
384 * 2 384 * 2
385 * 3 385 * 3
386 386
387-- return with implicit object 387-- retorno com objeto implícito
388f = -> 388f = ->
389 return 389 return
390 * 1 390 * 1
391 * 2 391 * 2
392 * 3 392 * 3
393 393
394-- table with implicit object 394-- tabela com objeto implícito
395tb = 395tb =
396 name: "abc" 396 name: "abc"
397 397
@@ -416,26 +416,26 @@ tb =
416<YueDisplay> 416<YueDisplay>
417 417
418```yue 418```yue
419-- assignment with implicit object 419-- atribuição com objeto implícito
420list = 420list =
421 * 1 421 * 1
422 * 2 422 * 2
423 * 3 423 * 3
424 424
425-- function call with implicit object 425-- chamada de função com objeto implícito
426func 426func
427 * 1 427 * 1
428 * 2 428 * 2
429 * 3 429 * 3
430 430
431-- return with implicit object 431-- retorno com objeto implícito
432f = -> 432f = ->
433 return 433 return
434 * 1 434 * 1
435 * 2 435 * 2
436 * 3 436 * 3
437 437
438-- table with implicit object 438-- tabela com objeto implícito
439tb = 439tb =
440 name: "abc" 440 name: "abc"
441 441
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 @@
1# Whitespace 1# Espaço em branco
2 2
3YueScript 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. 3YueScript é 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.
4 4
5## Statement Separator 5## Separador de instrução
6 6
7A 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: 7Uma 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:
8 8
9```yuescript 9```yuescript
10a = 1; b = 2; print a + b 10a = 1; b = 2; print a + b
@@ -17,9 +17,9 @@ a = 1; b = 2; print a + b
17 17
18</YueDisplay> 18</YueDisplay>
19 19
20## Multiline Chaining 20## Encadeamento multilinha
21 21
22You can write multi-line chaining function calls with a same indent. 22Você pode escrever chamadas de função encadeadas em múltiplas linhas com a mesma indentação.
23 23
24```yuescript 24```yuescript
25Rx.Observable 25Rx.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 @@
1# Object Oriented Programming 1# Programação orientada a objetos
2 2
3In 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. 3Nestes 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.
4 4
5A simple class: 5Uma classe simples:
6 6
7```yuescript 7```yuescript
8class Inventory 8class Inventory
@@ -31,15 +31,15 @@ class Inventory
31 31
32</YueDisplay> 32</YueDisplay>
33 33
34A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. 34Uma 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.
35 35
36The new property is special in that it will become the constructor. 36A propriedade new é especial pois se tornará o construtor.
37 37
38Notice 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. 38Observe 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.
39 39
40The @ prefix on a variable name is shorthand for self.. @items becomes self.items. 40O prefixo @ em um nome de variável é abreviação para self.. @items torna-se self.items.
41 41
42Creating an instance of the class is done by calling the name of the class as a function. 42Criar uma instância da classe é feito chamando o nome da classe como uma função.
43 43
44```yuescript 44```yuescript
45inv = Inventory! 45inv = Inventory!
@@ -56,11 +56,11 @@ inv\add_item "pants"
56 56
57</YueDisplay> 57</YueDisplay>
58 58
59Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. 59Como a instância da classe precisa ser enviada aos métodos quando são chamados, o operador \ é usado.
60 60
61All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur. 61Todas 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.
62 62
63Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another: 63Considere 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:
64 64
65```yuescript 65```yuescript
66class Person 66class Person
@@ -74,7 +74,7 @@ b = Person!
74a\give_item "pants" 74a\give_item "pants"
75b\give_item "shirt" 75b\give_item "shirt"
76 76
77-- will print both pants and shirt 77-- vai imprimir tanto pants quanto shirt
78print item for item in *a.clothes 78print item for item in *a.clothes
79``` 79```
80<YueDisplay> 80<YueDisplay>
@@ -91,13 +91,13 @@ b = Person!
91a\give_item "pants" 91a\give_item "pants"
92b\give_item "shirt" 92b\give_item "shirt"
93 93
94-- will print both pants and shirt 94-- vai imprimir tanto pants quanto shirt
95print item for item in *a.clothes 95print item for item in *a.clothes
96``` 96```
97 97
98</YueDisplay> 98</YueDisplay>
99 99
100The proper way to avoid this problem is to create the mutable state of the object in the constructor: 100A forma correta de evitar esse problema é criar o estado mutável do objeto no construtor:
101 101
102```yuescript 102```yuescript
103class Person 103class Person
@@ -114,9 +114,9 @@ class Person
114 114
115</YueDisplay> 115</YueDisplay>
116 116
117## Inheritance 117## Herança
118 118
119The extends keyword can be used in a class declaration to inherit the properties and methods from another class. 119A palavra-chave extends pode ser usada em uma declaração de classe para herdar as propriedades etodos de outra classe.
120 120
121```yuescript 121```yuescript
122class BackPack extends Inventory 122class BackPack extends Inventory
@@ -137,18 +137,18 @@ class BackPack extends Inventory
137 137
138</YueDisplay> 138</YueDisplay>
139 139
140Here we extend our Inventory class, and limit the amount of items it can carry. 140Aqui estendemos nossa classe Inventory e limitamos a quantidade de itens que ela pode carregar.
141 141
142In 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. 142Neste 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.
143 143
144Whenever 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. 144Sempre 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.
145 145
146```yuescript 146```yuescript
147class Shelf 147class Shelf
148 @__inherited: (child) => 148 @__inherited: (child) =>
149 print @__name, "was inherited by", child.__name 149 print @__name, "was inherited by", child.__name
150 150
151-- will print: Shelf was inherited by Cupboard 151-- vai imprimir: Shelf was inherited by Cupboard
152class Cupboard extends Shelf 152class Cupboard extends Shelf
153``` 153```
154<YueDisplay> 154<YueDisplay>
@@ -158,7 +158,7 @@ class Shelf
158 @__inherited: (child) => 158 @__inherited: (child) =>
159 print @__name, "was inherited by", child.__name 159 print @__name, "was inherited by", child.__name
160 160
161-- will print: Shelf was inherited by Cupboard 161-- vai imprimir: Shelf was inherited by Cupboard
162class Cupboard extends Shelf 162class Cupboard extends Shelf
163``` 163```
164 164
@@ -166,27 +166,27 @@ class Cupboard extends Shelf
166 166
167## Super 167## Super
168 168
169**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. 169**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.
170 170
171When 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) 171Quando 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)
172 172
173When super is used as a normal value, it is a reference to the parent class object. 173Quando super é usado como valor normal, é uma referência ao objeto da classe pai.
174 174
175It 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. 175Pode ser acessado como qualquer objeto para recuperar valores na classe pai que possam ter sido sombreados pela classe filha.
176 176
177When 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. 177Quando 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.
178 178
179A few examples of using super in different ways: 179Alguns exemplos de uso de super de diferentes formas:
180 180
181```yuescript 181```yuescript
182class MyClass extends ParentClass 182class MyClass extends ParentClass
183 a_method: => 183 a_method: =>
184 -- the following have the same effect: 184 -- os seguintes têm o mesmo efeito:
185 super "hello", "world" 185 super "hello", "world"
186 super\a_method "hello", "world" 186 super\a_method "hello", "world"
187 super.a_method self, "hello", "world" 187 super.a_method self, "hello", "world"
188 188
189 -- super as a value is equal to the parent class: 189 -- super como valor é igual à classe pai:
190 assert super == ParentClass 190 assert super == ParentClass
191``` 191```
192<YueDisplay> 192<YueDisplay>
@@ -194,28 +194,28 @@ class MyClass extends ParentClass
194```yue 194```yue
195class MyClass extends ParentClass 195class MyClass extends ParentClass
196 a_method: => 196 a_method: =>
197 -- the following have the same effect: 197 -- os seguintes têm o mesmo efeito:
198 super "hello", "world" 198 super "hello", "world"
199 super\a_method "hello", "world" 199 super\a_method "hello", "world"
200 super.a_method self, "hello", "world" 200 super.a_method self, "hello", "world"
201 201
202 -- super as a value is equal to the parent class: 202 -- super como valor é igual à classe pai:
203 assert super == ParentClass 203 assert super == ParentClass
204``` 204```
205 205
206</YueDisplay> 206</YueDisplay>
207 207
208**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. 208**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.
209 209
210## Types 210## Tipos
211 211
212Every 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. 212Cada 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.
213 213
214```yuescript 214```yuescript
215b = BackPack! 215b = BackPack!
216assert b.__class == BackPack 216assert b.__class == BackPack
217 217
218print BackPack.size -- prints 10 218print BackPack.size -- imprime 10
219``` 219```
220<YueDisplay> 220<YueDisplay>
221 221
@@ -223,45 +223,45 @@ print BackPack.size -- prints 10
223b = BackPack! 223b = BackPack!
224assert b.__class == BackPack 224assert b.__class == BackPack
225 225
226print BackPack.size -- prints 10 226print BackPack.size -- imprime 10
227``` 227```
228 228
229</YueDisplay> 229</YueDisplay>
230 230
231## Class Objects 231## Objetos de classe
232 232
233The 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. 233O 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.
234 234
235The 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. 235O 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.
236 236
237A 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. 237Uma 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.
238 238
239The 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. 239A 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.
240 240
241It 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. 241É 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.
242 242
243The class object has a couple special properties: 243O objeto da classe tem algumas propriedades especiais:
244 244
245The name of the class as when it was declared is stored as a string in the __name field of the class object. 245O nome da classe quando foi declarada é armazenado como string no campo __name do objeto da classe.
246 246
247```yuescript 247```yuescript
248print BackPack.__name -- prints Backpack 248print BackPack.__name -- imprime Backpack
249``` 249```
250<YueDisplay> 250<YueDisplay>
251 251
252```yue 252```yue
253print BackPack.__name -- prints Backpack 253print BackPack.__name -- imprime Backpack
254``` 254```
255 255
256</YueDisplay> 256</YueDisplay>
257 257
258The 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. 258O 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.
259 259
260If the class extends from anything, the parent class object is stored in __parent. 260Se a classe estende de algo, o objeto da classe pai é armazenado em __parent.
261 261
262## Class Variables 262## Variáveis de classe
263 263
264We 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. 264Podemos 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.
265 265
266```yuescript 266```yuescript
267class Things 267class Things
@@ -269,7 +269,7 @@ class Things
269 269
270Things\some_func! 270Things\some_func!
271 271
272-- class variables not visible in instances 272-- variáveis de classe não visíveis em instâncias
273assert Things().some_func == nil 273assert Things().some_func == nil
274``` 274```
275<YueDisplay> 275<YueDisplay>
@@ -280,13 +280,13 @@ class Things
280 280
281Things\some_func! 281Things\some_func!
282 282
283-- class variables not visible in instances 283-- variáveis de classe não visíveis em instâncias
284assert Things().some_func == nil 284assert Things().some_func == nil
285``` 285```
286 286
287</YueDisplay> 287</YueDisplay>
288 288
289In expressions, we can use @@ to access a value that is stored in the __class of self. Thus, @@hello is shorthand for self.__class.hello. 289Em expressões, podemos usar @@ para acessar um valor armazenado no __class de self. Assim, @@hello é abreviação para self.__class.hello.
290 290
291```yuescript 291```yuescript
292class Counter 292class Counter
@@ -298,7 +298,7 @@ class Counter
298Counter! 298Counter!
299Counter! 299Counter!
300 300
301print Counter.count -- prints 2 301print Counter.count -- imprime 2
302``` 302```
303<YueDisplay> 303<YueDisplay>
304 304
@@ -312,12 +312,12 @@ class Counter
312Counter! 312Counter!
313Counter! 313Counter!
314 314
315print Counter.count -- prints 2 315print Counter.count -- imprime 2
316``` 316```
317 317
318</YueDisplay> 318</YueDisplay>
319 319
320The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. 320A semântica de chamada de @@ é semelhante a @. Chamar um nome @@ passará a classe como primeiro argumento usando a sintaxe de dois pontos do Lua.
321 321
322```yuescript 322```yuescript
323@@hello 1,2,3,4 323@@hello 1,2,3,4
@@ -330,11 +330,11 @@ The calling semantics of @@ are similar to @. Calling a @@ name will pass the cl
330 330
331</YueDisplay> 331</YueDisplay>
332 332
333## Class Declaration Statements 333## Instruções de declaração de classe
334 334
335In 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. 335No 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.
336 336
337Here is an alternative way to create a class variable compared to what's described above: 337Aqui es uma forma alternativa de criar variável de classe comparada ao descrito acima:
338 338
339```yuescript 339```yuescript
340class Things 340class Things
@@ -349,9 +349,9 @@ class Things
349 349
350</YueDisplay> 350</YueDisplay>
351 351
352These expressions are executed after all the properties have been added to the base. 352Estas expressões são executadas após todas as propriedades terem sido adicionadas à base.
353 353
354All 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: 354Todas 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:
355 355
356```yuescript 356```yuescript
357class MoreThings 357class MoreThings
@@ -374,11 +374,11 @@ class MoreThings
374 374
375</YueDisplay> 375</YueDisplay>
376 376
377## @ and @@ Values 377## Valores @ e @@
378 378
379When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.__class. 379Quando @ e @@ são prefixados na frente de um nome, eles representam, respectivamente, esse nome acessado em self e self.__class.
380 380
381If they are used all by themselves, they are aliases for self and self.__class. 381Se forem usados sozinhos, são aliases para self e self.__class.
382 382
383```yuescript 383```yuescript
384assert @ == self 384assert @ == self
@@ -393,7 +393,7 @@ assert @@ == self.__class
393 393
394</YueDisplay> 394</YueDisplay>
395 395
396For example, a quick way to create a new instance of the same class from an instance method using @@: 396Por exemplo, uma forma rápida de criar uma nova instância da mesma classe a partir de um método de instância usando @@:
397 397
398```yuescript 398```yuescript
399some_instance_method = (...) => @@ ... 399some_instance_method = (...) => @@ ...
@@ -406,15 +406,15 @@ some_instance_method = (...) => @@ ...
406 406
407</YueDisplay> 407</YueDisplay>
408 408
409## Constructor Property Promotion 409## Promoção de propriedade no construtor
410 410
411To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: 411Para reduzir o código repetitivo na definição de objetos de valor simples. Você pode escrever uma classe simples como:
412 412
413```yuescript 413```yuescript
414class Something 414class Something
415 new: (@foo, @bar, @@biz, @@baz) => 415 new: (@foo, @bar, @@biz, @@baz) =>
416 416
417-- Which is short for 417-- O que é abreviação para
418 418
419class Something 419class Something
420 new: (foo, bar, biz, baz) => 420 new: (foo, bar, biz, baz) =>
@@ -429,7 +429,7 @@ class Something
429class Something 429class Something
430 new: (@foo, @bar, @@biz, @@baz) => 430 new: (@foo, @bar, @@biz, @@baz) =>
431 431
432-- Which is short for 432-- O que é abreviação para
433 433
434class Something 434class Something
435 new: (foo, bar, biz, baz) => 435 new: (foo, bar, biz, baz) =>
@@ -441,7 +441,7 @@ class Something
441 441
442</YueDisplay> 442</YueDisplay>
443 443
444You can also use this syntax for a common function to initialize a object's fields. 444Você também pode usar esta sintaxe para uma função comum para inicializar os campos de um objeto.
445 445
446```yuescript 446```yuescript
447new = (@fieldA, @fieldB) => @ 447new = (@fieldA, @fieldB) => @
@@ -458,9 +458,9 @@ print obj
458 458
459</YueDisplay> 459</YueDisplay>
460 460
461## Class Expressions 461## Expressões de classe
462 462
463The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. 463A sintaxe de classe também pode ser usada como expressão que pode ser atribuída a uma variável ou retornada explicitamente.
464 464
465```yuescript 465```yuescript
466x = class Bucket 466x = class Bucket
@@ -477,9 +477,9 @@ x = class Bucket
477 477
478</YueDisplay> 478</YueDisplay>
479 479
480## Anonymous classes 480## Classes anônimas
481 481
482The 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. 482O 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.
483 483
484```yuescript 484```yuescript
485BigBucket = class extends Bucket 485BigBucket = class extends Bucket
@@ -498,7 +498,7 @@ assert Bucket.__name == "BigBucket"
498 498
499</YueDisplay> 499</YueDisplay>
500 500
501You can even leave off the body, meaning you can write a blank anonymous class like this: 501Você pode a omitir o corpo, significando que pode escrever uma classe anônima em branco assim:
502 502
503```yuescript 503```yuescript
504x = class 504x = class
@@ -511,9 +511,9 @@ x = class
511 511
512</YueDisplay> 512</YueDisplay>
513 513
514## Class Mixing 514## Mistura de classes
515 515
516You 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. 516Você 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.
517 517
518```yuescript 518```yuescript
519MyIndex = __index: var: 1 519MyIndex = __index: var: 1
@@ -530,7 +530,7 @@ class Y using X
530y = Y! 530y = Y!
531y\func! 531y\func!
532 532
533assert y.__class.__parent ~= X -- X is not parent of Y 533assert y.__class.__parent ~= X -- X não é pai de Y
534``` 534```
535<YueDisplay> 535<YueDisplay>
536 536
@@ -549,7 +549,7 @@ class Y using X
549y = Y! 549y = Y!
550y\func! 550y\func!
551 551
552assert y.__class.__parent ~= X -- X is not parent of Y 552assert y.__class.__parent ~= X -- X não é pai de Y
553``` 553```
554 554
555</YueDisplay> 555</YueDisplay>
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 @@
1# With Statement 1# Instrução With
2 2
3Um 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.
3 4
4A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it. 5Isso 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.
5 6
6This 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. 7O 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.
7 8
8The 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. 9Por exemplo, trabalhamos com um objeto recém-criado:
9
10For example, we work with a newly created object:
11 10
12```yuescript 11```yuescript
13with Person! 12with Person!
@@ -28,7 +27,7 @@ with Person!
28 27
29</YueDisplay> 28</YueDisplay>
30 29
31The with statement can also be used as an expression which returns the value it has been giving access to. 30A instrução with também pode ser usada como expressão que retorna o valor ao qual foi dado acesso.
32 31
33```yuescript 32```yuescript
34file = with File "favorite_foods.txt" 33file = with File "favorite_foods.txt"
@@ -43,7 +42,7 @@ file = with File "favorite_foods.txt"
43 42
44</YueDisplay> 43</YueDisplay>
45 44
46Or 45Ou
47 46
48```yuescript 47```yuescript
49create_person = (name, relatives) -> 48create_person = (name, relatives) ->
@@ -66,9 +65,9 @@ me = create_person "Leaf", [dad, mother, sister]
66 65
67</YueDisplay> 66</YueDisplay>
68 67
69In this usage, with can be seen as a special form of the K combinator. 68Neste uso, with pode ser visto como uma forma especial do combinador K.
70 69
71The expression in the with statement can also be an assignment, if you want to give a name to the expression. 70A expressão na instrução with também pode ser uma atribuição, se vo quiser dar um nome à expressão.
72 71
73```yuescript 72```yuescript
74with str := "Hello" 73with str := "Hello"
@@ -85,7 +84,7 @@ with str := "Hello"
85 84
86</YueDisplay> 85</YueDisplay>
87 86
88You can access special keys with `[]` in a `with` statement. 87Você pode acessar chaves especiais com `[]` em uma instrução `with`.
89 88
90```yuescript 89```yuescript
91with tb 90with tb
@@ -94,7 +93,7 @@ with tb
94 with [abc] 93 with [abc]
95 [3] = [2]\func! 94 [3] = [2]\func!
96 ["key-name"] = value 95 ["key-name"] = value
97 [] = "abc" -- appending to "tb" 96 [] = "abc" -- anexando a "tb"
98``` 97```
99<YueDisplay> 98<YueDisplay>
100 99
@@ -105,12 +104,12 @@ with tb
105 with [abc] 104 with [abc]
106 [3] = [2]\func! 105 [3] = [2]\func!
107 ["key-name"] = value 106 ["key-name"] = value
108 [] = "abc" -- appending to "tb" 107 [] = "abc" -- anexando a "tb"
109``` 108```
110 109
111</YueDisplay> 110</YueDisplay>
112 111
113`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. 112`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.
114 113
115```yuescript 114```yuescript
116with? obj 115with? 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 @@
1# License: MIT 1# Licença: MIT
2 2
3Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\> 3Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\>
4 4
5Permission is hereby granted, free of charge, to any person obtaining a copy 5A permissão é concedida, gratuitamente, a qualquer pessoa que obtenha uma cópia
6of this software and associated documentation files (the "Software"), to deal 6deste software e dos arquivos de documentação associados (o "Software"), para negociar
7in the Software without restriction, including without limitation the rights 7o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar,
8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8modificar, mesclar, publicar, distribuir, sublicenciar e/ou vender
9copies of the Software, and to permit persons to whom the Software is 9cópias do Software, e permitir que pessoas a quem o Software seja fornecido o façam,
10furnished to do so, subject to the following conditions: 10sujeito às seguintes condições:
11 11
12The above copyright notice and this permission notice shall be included in all 12O aviso de direitos autorais acima e este aviso de permissão devem ser incluídos em todas as
13copies or substantial portions of the Software. 13cópias ou partes substanciais do Software.
14 14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15O SOFTWARE É FORNECIDO "NO ESTADO EM QUE SE ENCONTRA", SEM GARANTIA DE QUALQUER TIPO,
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16EXPRESSA OU IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17ADEQUAÇÃO A UM DETERMINADO FIM E NÃO VIOLAÇÃO. EM NENHUMA HIPÓTESE OS AUTORES OU
18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18DETENTORES DOS DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUAISQUER REIVINDICAÇÕES,
19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19DANOS OU OUTRAS RESPONSABILIDADES, SEJA EM UMA AÇÃO DE CONTRATO, ATO ILÍCITO OU OUTRA,
20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20DECORRENTES DE, FORA DE OU RELACIONADAS COM O SOFTWARE OU O USO OU OUTRAS NEGOCIAÇÕES
21SOFTWARE. 21NO SOFTWARE.
22
23<CompilerModal />
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 @@
1# The YueScript Library 1# A biblioteca YueScript
2 2
3Access it by `local yue = require("yue")` in Lua. 3Acesse com `local yue = require("yue")` no Lua.
4 4
5## yue 5## yue
6 6
7**Description:** 7**Descrição:**
8 8
9The YueScript language library. 9A biblioteca da linguagem YueScript.
10 10
11### version 11### version
12 12
13**Type:** Field. 13**Tipo:** Campo.
14 14
15**Description:** 15**Descrição:**
16 16
17The YueScript version. 17A versão do YueScript.
18 18
19**Signature:** 19**Assinatura:**
20```lua 20```lua
21version: string 21version: string
22``` 22```
23 23
24### dirsep 24### dirsep
25 25
26**Type:** Field. 26**Tipo:** Campo.
27 27
28**Description:** 28**Descrição:**
29 29
30The file separator for the current platform. 30O separador de arquivos da plataforma atual.
31 31
32**Signature:** 32**Assinatura:**
33```lua 33```lua
34dirsep: string 34dirsep: string
35``` 35```
36 36
37### yue_compiled 37### yue_compiled
38 38
39**Type:** Field. 39**Tipo:** Campo.
40 40
41**Description:** 41**Descrição:**
42 42
43The compiled module code cache. 43O cache de código de módulo compilado.
44 44
45**Signature:** 45**Assinatura:**
46```lua 46```lua
47yue_compiled: {string: string} 47yue_compiled: {string: string}
48``` 48```
49 49
50### to_lua 50### to_lua
51 51
52**Type:** Function. 52**Tipo:** Função.
53 53
54**Description:** 54**Descrição:**
55 55
56The YueScript compiling function. It compiles the YueScript code to Lua code. 56A função de compilação do YueScript. Compila o código YueScript para código Lua.
57 57
58**Signature:** 58**Assinatura:**
59```lua 59```lua
60to_lua: function(code: string, config?: Config): 60to_lua: function(code: string, config?: Config):
61 --[[codes]] string | nil, 61 --[[codes]] string | nil,
@@ -63,682 +63,682 @@ to_lua: function(code: string, config?: Config):
63 --[[globals]] {{string, integer, integer}} | nil 63 --[[globals]] {{string, integer, integer}} | nil
64``` 64```
65 65
66**Parameters:** 66**Parâmetros:**
67 67
68| Parameter | Type | Description | 68| Parâmetro | Tipo | Descrição |
69| --- | --- | --- | 69| --- | --- | --- |
70| code | string | The YueScript code. | 70| code | string | O código YueScript. |
71| config | Config | [Optional] The compiler options. | 71| config | Config | [Opcional] As opções do compilador. |
72 72
73**Returns:** 73**Retorna:**
74 74
75| Return Type | Description | 75| Tipo de Retorno | Descrição |
76| --- | --- | 76| --- | --- |
77| string \| nil | The compiled Lua code, or nil if the compilation failed. | 77| string \| nil | O código Lua compilado, ou nil se a compilação falhou. |
78| string \| nil | The error message, or nil if the compilation succeeded. | 78| string \| nil | A mensagem de erro, ou nil se a compilação foi bem-sucedida. |
79| {{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. | 79| {{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. |
80 80
81### file_exist 81### file_exist
82 82
83**Type:** Function. 83**Tipo:** Função.
84 84
85**Description:** 85**Descrição:**
86 86
87The source file existence checking function. Can be overridden to customize the behavior. 87Função de verificação de existência do arquivo fonte. Pode ser sobrescrita para personalizar o comportamento.
88 88
89**Signature:** 89**Assinatura:**
90```lua 90```lua
91file_exist: function(filename: string): boolean 91file_exist: function(filename: string): boolean
92``` 92```
93 93
94**Parameters:** 94**Parâmetros:**
95 95
96| Parameter | Type | Description | 96| Parâmetro | Tipo | Descrição |
97| --- | --- | --- | 97| --- | --- | --- |
98| filename | string | The file name. | 98| filename | string | O nome do arquivo. |
99 99
100**Returns:** 100**Retorna:**
101 101
102| Return Type | Description | 102| Tipo de Retorno | Descrição |
103| --- | --- | 103| --- | --- |
104| boolean | Whether the file exists. | 104| boolean | Se o arquivo existe. |
105 105
106### read_file 106### read_file
107 107
108**Type:** Function. 108**Tipo:** Função.
109 109
110**Description:** 110**Descrição:**
111 111
112The source file reading function. Can be overridden to customize the behavior. 112Função de leitura do arquivo fonte. Pode ser sobrescrita para personalizar o comportamento.
113 113
114**Signature:** 114**Assinatura:**
115```lua 115```lua
116read_file: function(filename: string): string 116read_file: function(filename: string): string
117``` 117```
118 118
119**Parameters:** 119**Parâmetros:**
120 120
121| Parameter | Type | Description | 121| Parâmetro | Tipo | Descrição |
122| --- | --- | --- | 122| --- | --- | --- |
123| filename | string | The file name. | 123| filename | string | O nome do arquivo. |
124 124
125**Returns:** 125**Retorna:**
126 126
127| Return Type | Description | 127| Tipo de Retorno | Descrição |
128| --- | --- | 128| --- | --- |
129| string | The file content. | 129| string | O conteúdo do arquivo. |
130 130
131### insert_loader 131### insert_loader
132 132
133**Type:** Function. 133**Tipo:** Função.
134 134
135**Description:** 135**Descrição:**
136 136
137Insert the YueScript loader to the package loaders (searchers). 137Insere o carregador YueScript nos carregadores de pacote (searchers).
138 138
139**Signature:** 139**Assinatura:**
140```lua 140```lua
141insert_loader: function(pos?: integer): boolean 141insert_loader: function(pos?: integer): boolean
142``` 142```
143 143
144**Parameters:** 144**Parâmetros:**
145 145
146| Parameter | Type | Description | 146| Parâmetro | Tipo | Descrição |
147| --- | --- | --- | 147| --- | --- | --- |
148| pos | integer | [Optional] The position to insert the loader. Default is 3. | 148| pos | integer | [Opcional] A posição para inserir o carregador. Padrão é 3. |
149 149
150**Returns:** 150**Retorna:**
151 151
152| Return Type | Description | 152| Tipo de Retorno | Descrição |
153| --- | --- | 153| --- | --- |
154| boolean | Whether the loader is inserted successfully. It will fail if the loader is already inserted. | 154| boolean | Se o carregador foi inserido com sucesso. Falhará se o carregador já estiver inserido. |
155 155
156### remove_loader 156### remove_loader
157 157
158**Type:** Function. 158**Tipo:** Função.
159 159
160**Description:** 160**Descrição:**
161 161
162Remove the YueScript loader from the package loaders (searchers). 162Remove o carregador YueScript dos carregadores de pacote (searchers).
163 163
164**Signature:** 164**Assinatura:**
165```lua 165```lua
166remove_loader: function(): boolean 166remove_loader: function(): boolean
167``` 167```
168 168
169**Returns:** 169**Retorna:**
170 170
171| Return Type | Description | 171| Tipo de Retorno | Descrição |
172| --- | --- | 172| --- | --- |
173| boolean | Whether the loader is removed successfully. It will fail if the loader is not inserted. | 173| boolean | Se o carregador foi removido com sucesso. Falhará se o carregador não estiver inserido. |
174 174
175### loadstring 175### loadstring
176 176
177**Type:** Function. 177**Tipo:** Função.
178 178
179**Description:** 179**Descrição:**
180 180
181Loads YueScript code from a string into a function. 181Carrega código YueScript de uma string em uma função.
182 182
183**Signature:** 183**Assinatura:**
184```lua 184```lua
185loadstring: function(input: string, chunkname: string, env: table, config?: Config): 185loadstring: function(input: string, chunkname: string, env: table, config?: Config):
186 --[[loaded function]] nil | function(...: any): (any...), 186 --[[loaded function]] nil | function(...: any): (any...),
187 --[[error]] string | nil 187 --[[error]] string | nil
188``` 188```
189 189
190**Parameters:** 190**Parâmetros:**
191 191
192| Parameter | Type | Description | 192| Parâmetro | Tipo | Descrição |
193| --- | --- | --- | 193| --- | --- | --- |
194| input | string | The YueScript code. | 194| input | string | O código YueScript. |
195| chunkname | string | The name of the code chunk. | 195| chunkname | string | O nome do chunk de código. |
196| env | table | The environment table. | 196| env | table | A tabela de ambiente. |
197| config | Config | [Optional] The compiler options. | 197| config | Config | [Opcional] As opções do compilador. |
198 198
199**Returns:** 199**Retorna:**
200 200
201| Return Type | Description | 201| Tipo de Retorno | Descrição |
202| --- | --- | 202| --- | --- |
203| function \| nil | The loaded function, or nil if the loading failed. | 203| function \| nil | A função carregada, ou nil se o carregamento falhou. |
204| string \| nil | The error message, or nil if the loading succeeded. | 204| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. |
205 205
206### loadstring 206### loadstring
207 207
208**Type:** Function. 208**Tipo:** Função.
209 209
210**Description:** 210**Descrição:**
211 211
212Loads YueScript code from a string into a function. 212Carrega código YueScript de uma string em uma função.
213 213
214**Signature:** 214**Assinatura:**
215```lua 215```lua
216loadstring: function(input: string, chunkname: string, config?: Config): 216loadstring: function(input: string, chunkname: string, config?: Config):
217 --[[loaded function]] nil | function(...: any): (any...), 217 --[[loaded function]] nil | function(...: any): (any...),
218 --[[error]] string | nil 218 --[[error]] string | nil
219``` 219```
220 220
221**Parameters:** 221**Parâmetros:**
222 222
223| Parameter | Type | Description | 223| Parâmetro | Tipo | Descrição |
224| --- | --- | --- | 224| --- | --- | --- |
225| input | string | The YueScript code. | 225| input | string | O código YueScript. |
226| chunkname | string | The name of the code chunk. | 226| chunkname | string | O nome do chunk de código. |
227| config | Config | [Optional] The compiler options. | 227| config | Config | [Opcional] As opções do compilador. |
228 228
229**Returns:** 229**Retorna:**
230 230
231| Return Type | Description | 231| Tipo de Retorno | Descrição |
232| --- | --- | 232| --- | --- |
233| function \| nil | The loaded function, or nil if the loading failed. | 233| function \| nil | A função carregada, ou nil se o carregamento falhou. |
234| string \| nil | The error message, or nil if the loading succeeded. | 234| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. |
235 235
236### loadstring 236### loadstring
237 237
238**Type:** Function. 238**Tipo:** Função.
239 239
240**Description:** 240**Descrição:**
241 241
242Loads YueScript code from a string into a function. 242Carrega código YueScript de uma string em uma função.
243 243
244**Signature:** 244**Assinatura:**
245```lua 245```lua
246loadstring: function(input: string, config?: Config): 246loadstring: function(input: string, config?: Config):
247 --[[loaded function]] nil | function(...: any): (any...), 247 --[[loaded function]] nil | function(...: any): (any...),
248 --[[error]] string | nil 248 --[[error]] string | nil
249``` 249```
250 250
251**Parameters:** 251**Parâmetros:**
252 252
253| Parameter | Type | Description | 253| Parâmetro | Tipo | Descrição |
254| --- | --- | --- | 254| --- | --- | --- |
255| input | string | The YueScript code. | 255| input | string | O código YueScript. |
256| config | Config | [Optional] The compiler options. | 256| config | Config | [Opcional] As opções do compilador. |
257 257
258**Returns:** 258**Retorna:**
259 259
260| Return Type | Description | 260| Tipo de Retorno | Descrição |
261| --- | --- | 261| --- | --- |
262| function \| nil | The loaded function, or nil if the loading failed. | 262| function \| nil | A função carregada, ou nil se o carregamento falhou. |
263| string \| nil | The error message, or nil if the loading succeeded. | 263| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. |
264 264
265### loadfile 265### loadfile
266 266
267**Type:** Function. 267**Tipo:** Função.
268 268
269**Description:** 269**Descrição:**
270 270
271Loads YueScript code from a file into a function. 271Carrega código YueScript de um arquivo em uma função.
272 272
273**Signature:** 273**Assinatura:**
274```lua 274```lua
275loadfile: function(filename: string, env: table, config?: Config): 275loadfile: function(filename: string, env: table, config?: Config):
276 nil | function(...: any): (any...), 276 nil | function(...: any): (any...),
277 string | nil 277 string | nil
278``` 278```
279 279
280**Parameters:** 280**Parâmetros:**
281 281
282| Parameter | Type | Description | 282| Parâmetro | Tipo | Descrição |
283| --- | --- | --- | 283| --- | --- | --- |
284| filename | string | The file name. | 284| filename | string | O nome do arquivo. |
285| env | table | The environment table. | 285| env | table | A tabela de ambiente. |
286| config | Config | [Optional] The compiler options. | 286| config | Config | [Opcional] As opções do compilador. |
287 287
288**Returns:** 288**Retorna:**
289 289
290| Return Type | Description | 290| Tipo de Retorno | Descrição |
291| --- | --- | 291| --- | --- |
292| function \| nil | The loaded function, or nil if the loading failed. | 292| function \| nil | A função carregada, ou nil se o carregamento falhou. |
293| string \| nil | The error message, or nil if the loading succeeded. | 293| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. |
294 294
295### loadfile 295### loadfile
296 296
297**Type:** Function. 297**Tipo:** Função.
298 298
299**Description:** 299**Descrição:**
300 300
301Loads YueScript code from a file into a function. 301Carrega código YueScript de um arquivo em uma função.
302 302
303**Signature:** 303**Assinatura:**
304```lua 304```lua
305loadfile: function(filename: string, config?: Config): 305loadfile: function(filename: string, config?: Config):
306 nil | function(...: any): (any...), 306 nil | function(...: any): (any...),
307 string | nil 307 string | nil
308``` 308```
309 309
310**Parameters:** 310**Parâmetros:**
311 311
312| Parameter | Type | Description | 312| Parâmetro | Tipo | Descrição |
313| --- | --- | --- | 313| --- | --- | --- |
314| filename | string | The file name. | 314| filename | string | O nome do arquivo. |
315| config | Config | [Optional] The compiler options. | 315| config | Config | [Opcional] As opções do compilador. |
316 316
317**Returns:** 317**Retorna:**
318 318
319| Return Type | Description | 319| Tipo de Retorno | Descrição |
320| --- | --- | 320| --- | --- |
321| function \| nil | The loaded function, or nil if the loading failed. | 321| function \| nil | A função carregada, ou nil se o carregamento falhou. |
322| string \| nil | The error message, or nil if the loading succeeded. | 322| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. |
323 323
324### dofile 324### dofile
325 325
326**Type:** Function. 326**Tipo:** Função.
327 327
328**Description:** 328**Descrição:**
329 329
330Loads YueScript code from a file into a function and executes it. 330Carrega código YueScript de um arquivo em uma função e o executa.
331 331
332**Signature:** 332**Assinatura:**
333```lua 333```lua
334dofile: function(filename: string, env: table, config?: Config): any... 334dofile: function(filename: string, env: table, config?: Config): any...
335``` 335```
336 336
337**Parameters:** 337**Parâmetros:**
338 338
339| Parameter | Type | Description | 339| Parâmetro | Tipo | Descrição |
340| --- | --- | --- | 340| --- | --- | --- |
341| filename | string | The file name. | 341| filename | string | O nome do arquivo. |
342| env | table | The environment table. | 342| env | table | A tabela de ambiente. |
343| config | Config | [Optional] The compiler options. | 343| config | Config | [Opcional] As opções do compilador. |
344 344
345**Returns:** 345**Retorna:**
346 346
347| Return Type | Description | 347| Tipo de Retorno | Descrição |
348| --- | --- | 348| --- | --- |
349| any... | The return values of the loaded function. | 349| any... | Os valores de retorno da função carregada. |
350 350
351### dofile 351### dofile
352 352
353**Type:** Function. 353**Tipo:** Função.
354 354
355**Description:** 355**Descrição:**
356 356
357Loads YueScript code from a file into a function and executes it. 357Carrega código YueScript de um arquivo em uma função e o executa.
358 358
359**Signature:** 359**Assinatura:**
360```lua 360```lua
361dofile: function(filename: string, config?: Config): any... 361dofile: function(filename: string, config?: Config): any...
362``` 362```
363 363
364**Parameters:** 364**Parâmetros:**
365 365
366| Parameter | Type | Description | 366| Parâmetro | Tipo | Descrição |
367| --- | --- | --- | 367| --- | --- | --- |
368| filename | string | The file name. | 368| filename | string | O nome do arquivo. |
369| config | Config | [Optional] The compiler options. | 369| config | Config | [Opcional] As opções do compilador. |
370 370
371**Returns:** 371**Retorna:**
372 372
373| Return Type | Description | 373| Tipo de Retorno | Descrição |
374| --- | --- | 374| --- | --- |
375| any... | The return values of the loaded function. | 375| any... | Os valores de retorno da função carregada. |
376 376
377### find_modulepath 377### find_modulepath
378 378
379**Type:** Function. 379**Tipo:** Função.
380 380
381**Description:** 381**Descrição:**
382 382
383Resolves the YueScript module name to the file path. 383Resolve o nome do módulo YueScript para o caminho do arquivo.
384 384
385**Signature:** 385**Assinatura:**
386```lua 386```lua
387find_modulepath: function(name: string): string 387find_modulepath: function(name: string): string
388``` 388```
389 389
390**Parameters:** 390**Parâmetros:**
391 391
392| Parameter | Type | Description | 392| Parâmetro | Tipo | Descrição |
393| --- | --- | --- | 393| --- | --- | --- |
394| name | string | The module name. | 394| name | string | O nome dodulo. |
395 395
396**Returns:** 396**Retorna:**
397 397
398| Return Type | Description | 398| Tipo de Retorno | Descrição |
399| --- | --- | 399| --- | --- |
400| string | The file path. | 400| string | O caminho do arquivo. |
401 401
402### pcall 402### pcall
403 403
404**Type:** Function. 404**Tipo:** Função.
405 405
406**Description:** 406**Descrição:**
407 407
408Calls a function in protected mode. 408Chama uma função em modo protegido.
409Catches any errors and returns a status code and results or error object. 409Captura quaisquer erros e retorna um código de status e resultados ou objeto de erro.
410Rewrites the error line number to the original line number in the YueScript code when errors occur. 410Reescreve o número da linha do erro para o número da linha original no código YueScript quando ocorrem erros.
411 411
412**Signature:** 412**Assinatura:**
413```lua 413```lua
414pcall: function(f: function, ...: any): boolean, any... 414pcall: function(f: function, ...: any): boolean, any...
415``` 415```
416 416
417**Parameters:** 417**Parâmetros:**
418 418
419| Parameter | Type | Description | 419| Parâmetro | Tipo | Descrição |
420| --- | --- | --- | 420| --- | --- | --- |
421| f | function | The function to call. | 421| f | function | A função a chamar. |
422| ... | any | Arguments to pass to the function. | 422| ... | any | Argumentos a passar para a função. |
423 423
424**Returns:** 424**Retorna:**
425 425
426| Return Type | Description | 426| Tipo de Retorno | Descrição |
427| --- | --- | 427| --- | --- |
428| boolean, ... | Status code and function results or error object. | 428| boolean, ... | Código de status e resultados da função ou objeto de erro. |
429 429
430### require 430### require
431 431
432**Type:** Function. 432**Tipo:** Função.
433 433
434**Description:** 434**Descrição:**
435 435
436Loads a given module. Can be either a Lua module or a YueScript module. 436Carrega um módulo dado. Pode ser um módulo Lua ou um módulo YueScript.
437Rewrites the error line number to the original line number in the YueScript code if the module is a YueScript module and loading fails. 437Reescreve 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.
438 438
439**Signature:** 439**Assinatura:**
440```lua 440```lua
441require: function(name: string): any... 441require: function(name: string): any...
442``` 442```
443 443
444**Parameters:** 444**Parâmetros:**
445 445
446| Parameter | Type | Description | 446| Parâmetro | Tipo | Descrição |
447| --- | --- | --- | 447| --- | --- | --- |
448| modname | string | The name of the module to load. | 448| modname | string | O nome do módulo a carregar. |
449 449
450**Returns:** 450**Retorna:**
451 451
452| Return Type | Description | 452| Tipo de Retorno | Descrição |
453| --- | --- | 453| --- | --- |
454| 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. | 454| 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. |
455 455
456### p 456### p
457 457
458**Type:** Function. 458**Tipo:** Função.
459 459
460**Description:** 460**Descrição:**
461 461
462Inspects the structures of the passed values and prints string representations. 462Inspeciona as estruturas dos valores passados e imprime representações em string.
463 463
464**Signature:** 464**Assinatura:**
465```lua 465```lua
466p: function(...: any) 466p: function(...: any)
467``` 467```
468 468
469**Parameters:** 469**Parâmetros:**
470 470
471| Parameter | Type | Description | 471| Parâmetro | Tipo | Descrição |
472| --- | --- | --- | 472| --- | --- | --- |
473| ... | any | The values to inspect. | 473| ... | any | Os valores a inspecionar. |
474 474
475### options 475### options
476 476
477**Type:** Field. 477**Tipo:** Campo.
478 478
479**Description:** 479**Descrição:**
480 480
481The current compiler options. 481As opções atuais do compilador.
482 482
483**Signature:** 483**Assinatura:**
484```lua 484```lua
485options: Config.Options 485options: Config.Options
486``` 486```
487 487
488### traceback 488### traceback
489 489
490**Type:** Function. 490**Tipo:** Função.
491 491
492**Description:** 492**Descrição:**
493 493
494The traceback function that rewrites the stack trace line numbers to the original line numbers in the YueScript code. 494A função traceback que reescreve os números das linhas do stack trace para os números das linhas originais no código YueScript.
495 495
496**Signature:** 496**Assinatura:**
497```lua 497```lua
498traceback: function(message: string): string 498traceback: function(message: string): string
499``` 499```
500 500
501**Parameters:** 501**Parâmetros:**
502 502
503| Parameter | Type | Description | 503| Parâmetro | Tipo | Descrição |
504| --- | --- | --- | 504| --- | --- | --- |
505| message | string | The traceback message. | 505| message | string | A mensagem de traceback. |
506 506
507**Returns:** 507**Retorna:**
508 508
509| Return Type | Description | 509| Tipo de Retorno | Descrição |
510| --- | --- | 510| --- | --- |
511| string | The rewritten traceback message. | 511| string | A mensagem de traceback reescrita. |
512 512
513### is_ast 513### is_ast
514 514
515**Type:** Function. 515**Tipo:** Função.
516 516
517**Description:** 517**Descrição:**
518 518
519Checks whether the code matches the specified AST. 519Verifica se o código corresponde ao AST especificado.
520 520
521**Signature:** 521**Assinatura:**
522```lua 522```lua
523is_ast: function(astName: string, code: string): boolean 523is_ast: function(astName: string, code: string): boolean
524``` 524```
525 525
526**Parameters:** 526**Parâmetros:**
527 527
528| Parameter | Type | Description | 528| Parâmetro | Tipo | Descrição |
529| --- | --- | --- | 529| --- | --- | --- |
530| astName | string | The AST name. | 530| astName | string | O nome do AST. |
531| code | string | The code. | 531| code | string | O código. |
532 532
533**Returns:** 533**Retorna:**
534 534
535| Return Type | Description | 535| Tipo de Retorno | Descrição |
536| --- | --- | 536| --- | --- |
537| boolean | Whether the code matches the AST. | 537| boolean | Se o código corresponde ao AST. |
538 538
539### AST 539### AST
540 540
541**Type:** Field. 541**Tipo:** Campo.
542 542
543**Description:** 543**Descrição:**
544 544
545The AST type definition with name, row, column and sub nodes. 545A definição do tipo AST com nome, linha, coluna e subnós.
546 546
547**Signature:** 547**Assinatura:**
548```lua 548```lua
549type AST = {string, integer, integer, any} 549type AST = {string, integer, integer, any}
550``` 550```
551 551
552### to_ast 552### to_ast
553 553
554**Type:** Function. 554**Tipo:** Função.
555 555
556**Description:** 556**Descrição:**
557 557
558Converts the code to the AST. 558Converte o código para o AST.
559 559
560**Signature:** 560**Assinatura:**
561```lua 561```lua
562to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveComment?: boolean): 562to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveComment?: boolean):
563 --[[AST]] AST | nil, 563 --[[AST]] AST | nil,
564 --[[error]] nil | string 564 --[[error]] nil | string
565``` 565```
566 566
567**Parameters:** 567**Parâmetros:**
568 568
569| Parameter | Type | Description | 569| Parâmetro | Tipo | Descrição |
570| --- | --- | --- | 570| --- | --- | --- |
571| code | string | The code. | 571| code | string | O código. |
572| flattenLevel | integer | [Optional] The flatten level. Higher level means more flattening. Default is 0. Maximum is 2. | 572| flattenLevel | integer | [Opcional] O nível de achatamento. Nível mais alto significa mais achatamento. Padrão é 0. Máximo é 2. |
573| astName | string | [Optional] The AST name. Default is "File". | 573| astName | string | [Opcional] O nome do AST. Padrão é "File". |
574| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is false. | 574| reserveComment | boolean | [Opcional] Se deve preservar os comentários originais. Padrão é false. |
575 575
576**Returns:** 576**Retorna:**
577 577
578| Return Type | Description | 578| Tipo de Retorno | Descrição |
579| --- | --- | 579| --- | --- |
580| AST \| nil | The AST, or nil if the conversion failed. | 580| AST \| nil | O AST, ou nil se a conversão falhou. |
581| string \| nil | The error message, or nil if the conversion succeeded. | 581| string \| nil | A mensagem de erro, ou nil se a conversão foi bem-sucedida. |
582 582
583### format 583### format
584 584
585**Type:** Function. 585**Tipo:** Função.
586 586
587**Description:** 587**Descrição:**
588 588
589Formats the YueScript code. 589Formata o código YueScript.
590 590
591**Signature:** 591**Assinatura:**
592```lua 592```lua
593format: function(code: string, tabSize?: number, reserveComment?: boolean): string 593format: function(code: string, tabSize?: number, reserveComment?: boolean): string
594``` 594```
595 595
596**Parameters:** 596**Parâmetros:**
597 597
598| Parameter | Type | Description | 598| Parâmetro | Tipo | Descrição |
599| --- | --- | --- | 599| --- | --- | --- |
600| code | string | The code. | 600| code | string | O código. |
601| tabSize | integer | [Optional] The tab size. Default is 4. | 601| tabSize | integer | [Opcional] O tamanho da tabulação. Padrão é 4. |
602| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is true. | 602| reserveComment | boolean | [Opcional] Se deve preservar os comentários originais. Padrão é true. |
603 603
604**Returns:** 604**Retorna:**
605 605
606| Return Type | Description | 606| Tipo de Retorno | Descrição |
607| --- | --- | 607| --- | --- |
608| string | The formatted code. | 608| string | O código formatado. |
609 609
610### __call 610### __call
611 611
612**Type:** Metamethod. 612**Tipo:** Metamétodo.
613 613
614**Description:** 614**Descrição:**
615 615
616Requires the YueScript module. 616Requer o módulo YueScript.
617Rewrites the error line number to the original line number in the YueScript code when loading fails. 617Reescreve o número da linha do erro para o número da linha original no código YueScript quando o carregamento falha.
618 618
619**Signature:** 619**Assinatura:**
620```lua 620```lua
621metamethod __call: function(self: yue, module: string): any... 621metamethod __call: function(self: yue, module: string): any...
622``` 622```
623 623
624**Parameters:** 624**Parâmetros:**
625 625
626| Parameter | Type | Description | 626| Parâmetro | Tipo | Descrição |
627| --- | --- | --- | 627| --- | --- | --- |
628| module | string | The module name. | 628| module | string | O nome dodulo. |
629 629
630**Returns:** 630**Retorna:**
631 631
632| Return Type | Description | 632| Tipo de Retorno | Descrição |
633| --- | --- | 633| --- | --- |
634| any | The module value. | 634| any | O valor do módulo. |
635 635
636## Config 636## Config
637 637
638**Description:** 638**Descrição:**
639 639
640The compiler compile options. 640As opções de compilação do compilador.
641 641
642### lint_global 642### lint_global
643 643
644**Type:** Field. 644**Tipo:** Campo.
645 645
646**Description:** 646**Descrição:**
647 647
648Whether the compiler should collect the global variables appearing in the code. 648Se o compilador deve coletar as variáveis globais que aparecem no código.
649 649
650**Signature:** 650**Assinatura:**
651```lua 651```lua
652lint_global: boolean 652lint_global: boolean
653``` 653```
654 654
655### implicit_return_root 655### implicit_return_root
656 656
657**Type:** Field. 657**Tipo:** Campo.
658 658
659**Description:** 659**Descrição:**
660 660
661Whether the compiler should do an implicit return for the root code block. 661Se o compilador deve fazer retorno implícito para o bloco de código raiz.
662 662
663**Signature:** 663**Assinatura:**
664```lua 664```lua
665implicit_return_root: boolean 665implicit_return_root: boolean
666``` 666```
667 667
668### reserve_line_number 668### reserve_line_number
669 669
670**Type:** Field. 670**Tipo:** Campo.
671 671
672**Description:** 672**Descrição:**
673 673
674Whether the compiler should reserve the original line number in the compiled code. 674Se o compilador deve preservar o número da linha original no código compilado.
675 675
676**Signature:** 676**Assinatura:**
677```lua 677```lua
678reserve_line_number: boolean 678reserve_line_number: boolean
679``` 679```
680 680
681### reserve_comment 681### reserve_comment
682 682
683**Type:** Field. 683**Tipo:** Campo.
684 684
685**Description:** 685**Descrição:**
686 686
687Whether the compiler should reserve the original comments in the compiled code. 687Se o compilador deve preservar os comentários originais no código compilado.
688 688
689**Signature:** 689**Assinatura:**
690```lua 690```lua
691reserve_comment: boolean 691reserve_comment: boolean
692``` 692```
693 693
694### space_over_tab 694### space_over_tab
695 695
696**Type:** Field. 696**Tipo:** Campo.
697 697
698**Description:** 698**Descrição:**
699 699
700Whether the compiler should use the space character instead of the tab character in the compiled code. 700Se o compilador deve usar o caractere de espaço em vez do caractere de tabulação no código compilado.
701 701
702**Signature:** 702**Assinatura:**
703```lua 703```lua
704space_over_tab: boolean 704space_over_tab: boolean
705``` 705```
706 706
707### same_module 707### same_module
708 708
709**Type:** Field. 709**Tipo:** Campo.
710 710
711**Description:** 711**Descrição:**
712 712
713Whether the compiler should treat the code to be compiled as the same currently being compiled module. For internal use only. 713Se o compilador deve tratar o código a ser compilado como o mesmo módulo que está sendo compilado atualmente. Apenas para uso interno.
714 714
715**Signature:** 715**Assinatura:**
716```lua 716```lua
717same_module: boolean 717same_module: boolean
718``` 718```
719 719
720### line_offset 720### line_offset
721 721
722**Type:** Field. 722**Tipo:** Campo.
723 723
724**Description:** 724**Descrição:**
725 725
726Whether the compiler error message should include the line number offset. For internal use only. 726Se a mensagem de erro do compilador deve incluir o deslocamento do número da linha. Apenas para uso interno.
727 727
728**Signature:** 728**Assinatura:**
729```lua 729```lua
730line_offset: integer 730line_offset: integer
731``` 731```
732 732
733### yue.Config.LuaTarget 733### yue.Config.LuaTarget
734 734
735**Type:** Enumeration. 735**Tipo:** Enumeração.
736 736
737**Description:** 737**Descrição:**
738 738
739The target Lua version enumeration. 739A enumeração da versão alvo do Lua.
740 740
741**Signature:** 741**Assinatura:**
742```lua 742```lua
743enum LuaTarget 743enum LuaTarget
744 "5.1" 744 "5.1"
@@ -751,71 +751,71 @@ end
751 751
752### options 752### options
753 753
754**Type:** Field. 754**Tipo:** Campo.
755 755
756**Description:** 756**Descrição:**
757 757
758The extra options to be passed to the compilation function. 758As opções extras a serem passadas para a função de compilação.
759 759
760**Signature:** 760**Assinatura:**
761```lua 761```lua
762options: Options 762options: Options
763``` 763```
764 764
765## Options 765## Options
766 766
767**Description:** 767**Descrição:**
768 768
769The extra compiler options definition. 769A definição das opções extras do compilador.
770 770
771### target 771### target
772 772
773**Type:** Field. 773**Tipo:** Campo.
774 774
775**Description:** 775**Descrição:**
776 776
777The target Lua version for the compilation. 777A versão alvo do Lua para a compilação.
778 778
779**Signature:** 779**Assinatura:**
780```lua 780```lua
781target: LuaTarget 781target: LuaTarget
782``` 782```
783 783
784### path 784### path
785 785
786**Type:** Field. 786**Tipo:** Campo.
787 787
788**Description:** 788**Descrição:**
789 789
790The extra module search path. 790O caminho de busca de módulo extra.
791 791
792**Signature:** 792**Assinatura:**
793```lua 793```lua
794path: string 794path: string
795``` 795```
796 796
797### dump_locals 797### dump_locals
798 798
799**Type:** Field. 799**Tipo:** Campo.
800 800
801**Description:** 801**Descrição:**
802 802
803Whether to dump the local variables in the traceback error message. Default is false. 803Se deve incluir as variáveis locais na mensagem de erro do traceback. Padrão é false.
804 804
805**Signature:** 805**Assinatura:**
806```lua 806```lua
807dump_locals: boolean 807dump_locals: boolean
808``` 808```
809 809
810### simplified 810### simplified
811 811
812**Type:** Field. 812**Tipo:** Campo.
813 813
814**Description:** 814**Descrição:**
815 815
816Whether to simplify the error message. Default is true. 816Se deve simplificar a mensagem de erro. Padrão é true.
817 817
818**Signature:** 818**Assinatura:**
819```lua 819```lua
820simplified: boolean 820simplified: boolean
821``` 821```