From 1f83d504bc344ffd3c8b4120b3865fd6c11a9e2d Mon Sep 17 00:00:00 2001 From: Li Jin Date: Fri, 6 Feb 2026 11:54:32 +0800 Subject: Updated docs. --- doc/docs/pt-br/doc/advanced/do.md | 8 +- doc/docs/pt-br/doc/advanced/line-decorators.md | 8 +- doc/docs/pt-br/doc/advanced/macro.md | 65 ++- doc/docs/pt-br/doc/advanced/module.md | 62 +- doc/docs/pt-br/doc/advanced/try.md | 20 +- doc/docs/pt-br/doc/assignment/assignment.md | 48 +- .../doc/assignment/destructuring-assignment.md | 66 +-- doc/docs/pt-br/doc/assignment/if-assignment.md | 34 +- ...ng-clause-controlling-destructive-assignment.md | 36 +- .../pt-br/doc/assignment/varargs-assignment.md | 4 +- doc/docs/pt-br/doc/control-flow/conditionals.md | 69 +-- doc/docs/pt-br/doc/control-flow/continue.md | 4 +- doc/docs/pt-br/doc/control-flow/for-loop.md | 36 +- doc/docs/pt-br/doc/control-flow/switch.md | 130 ++--- doc/docs/pt-br/doc/control-flow/while-loop.md | 10 +- .../pt-br/doc/data-structures/comprehensions.md | 64 +-- .../pt-br/doc/data-structures/table-literals.md | 20 +- doc/docs/pt-br/doc/functions/backcalls.md | 8 +- doc/docs/pt-br/doc/functions/function-literals.md | 94 +-- doc/docs/pt-br/doc/functions/function-stubs.md | 24 +- doc/docs/pt-br/doc/getting-started/installation.md | 24 +- doc/docs/pt-br/doc/getting-started/introduction.md | 40 +- doc/docs/pt-br/doc/getting-started/usage.md | 105 ++-- doc/docs/pt-br/doc/language-basics/attributes.md | 12 +- doc/docs/pt-br/doc/language-basics/comment.md | 22 +- doc/docs/pt-br/doc/language-basics/literals.md | 46 +- doc/docs/pt-br/doc/language-basics/operator.md | 116 ++-- doc/docs/pt-br/doc/language-basics/whitespace.md | 12 +- .../doc/objects/object-oriented-programming.md | 158 +++--- doc/docs/pt-br/doc/objects/with-statement.md | 27 +- doc/docs/pt-br/doc/reference/license-mit.md | 34 +- .../pt-br/doc/reference/the-yuescript-library.md | 632 ++++++++++----------- 32 files changed, 1012 insertions(+), 1026 deletions(-) (limited to 'doc/docs/pt-br') diff --git a/doc/docs/pt-br/doc/advanced/do.md b/doc/docs/pt-br/doc/advanced/do.md index 4990d6f..f13d8aa 100644 --- a/doc/docs/pt-br/doc/advanced/do.md +++ b/doc/docs/pt-br/doc/advanced/do.md @@ -1,12 +1,12 @@ # Do -When used as a statement, do works just like it does in Lua. +Quando usado como instrução, do funciona exatamente como no Lua. ```yuescript do var = "hello" print var -print var -- nil here +print var -- nil aqui ``` @@ -14,12 +14,12 @@ print var -- nil here do var = "hello" print var -print var -- nil here +print var -- nil aqui ``` -YueScript's **do** can also be used an expression . Allowing you to combine multiple lines into one. The result of the do expression is the last statement in its body. +O **do** do YueScript também pode ser usado como expressão. Permitindo combinar múltiplas linhas em uma. O resultado da expressão do é a última instrução em seu corpo. ```yuescript counter = do diff --git a/doc/docs/pt-br/doc/advanced/line-decorators.md b/doc/docs/pt-br/doc/advanced/line-decorators.md index 292bc77..94d1004 100644 --- a/doc/docs/pt-br/doc/advanced/line-decorators.md +++ b/doc/docs/pt-br/doc/advanced/line-decorators.md @@ -1,6 +1,6 @@ -# Line Decorators +# Decoradores de linha -For convenience, the for loop and if statement can be applied to single statements at the end of the line: +Por conveniência, o loop for e a instrução if podem ser aplicados a instruções únicas no final da linha: ```yuescript print "hello world" if name == "Rob" @@ -13,7 +13,7 @@ print "hello world" if name == "Rob" -And with basic loops: +E com loops básicos: ```yuescript print "item: ", item for item in *items @@ -26,7 +26,7 @@ print "item: ", item for item in *items -And with while loops: +E com loops while: ```yuescript game\update! while game\isRunning! diff --git a/doc/docs/pt-br/doc/advanced/macro.md b/doc/docs/pt-br/doc/advanced/macro.md index 6d194c3..846d506 100644 --- a/doc/docs/pt-br/doc/advanced/macro.md +++ b/doc/docs/pt-br/doc/advanced/macro.md @@ -1,8 +1,8 @@ # Macro -## Common Usage +## Uso comum -Macro function is used for evaluating a string in the compile time and insert the generated codes into final compilation. +A função macro é usada para avaliar uma string em tempo de compilação e inserir os códigos gerados na compilação final. ```yuescript macro PI2 = -> math.pi * 2 @@ -27,7 +27,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- as expressões passadas são tratadas como strings macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -57,7 +57,7 @@ $asserts item ~= nil $config false value = $assert item --- the passed expressions are treated as strings +-- as expressões passadas são tratadas como strings macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" @@ -65,9 +65,9 @@ if $and f1!, f2!, f3! -## Insert Raw Codes +## Inserir códigos brutos -A macro function can either return a YueScript string or a config table containing Lua codes. +Uma função macro pode retornar uma string YueScript ou uma tabela de configuração contendo códigos Lua. ```yuescript macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA @@ -85,9 +85,9 @@ macro lua = (code) -> { type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- os símbolos inicial e final da string bruta são aparados automaticamente $lua[==[ --- raw Lua codes insertion +-- inserção de códigos Lua brutos if cond then print("output") end @@ -112,9 +112,9 @@ macro lua = (code) -> { type: "lua" } --- the raw string leading and ending symbols are auto trimed +-- os símbolos inicial e final da string bruta são aparados automaticamente $lua[==[ --- raw Lua codes insertion +-- inserção de códigos Lua brutos if cond then print("output") end @@ -123,38 +123,37 @@ end -## Export Macro +## Exportar macro -Macro functions can be exported from a module and get imported in another module. You have to put export macro functions in a single file to be used, and only macro definition, macro importing and macro expansion in place can be put into the macro exporting module. +Funções macro podem ser exportadas de um módulo e importadas em outro módulo. Você deve colocar funções export macro em um único arquivo para uso, e apenas definição de macro, importação de macro e expansão de macro inline podem ser colocadas no módulo exportador de macro. ```yuescript --- file: utils.yue +-- arquivo: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" --- file main.yue +-- arquivo main.yue import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- símbolo para importar todas as macros + $foreach: $each -- renomear macro $foreach para $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ``` ```yue --- file: utils.yue +-- arquivo: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" --- file main.yue --- import function is not available in browser, try it in a real environment +-- arquivo main.yue --[[ import "utils" as { - $, -- symbol to import all macros - $foreach: $each -- rename macro $foreach to $each + $, -- símbolo para importar todas as macros + $foreach: $each -- renomear macro $foreach para $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ]] @@ -162,25 +161,25 @@ import "utils" as { -## Builtin Macro +## Macro embutida -There are some builtin macros but you can override them by declaring macros with the same names. +Existem algumas macros embutidas, mas você pode sobrescrevê-las declarando macros com os mesmos nomes. ```yuescript -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- obtém string do nome do módulo atual +print $LINE -- obtém número 2 ``` ```yue -print $FILE -- get string of current module name -print $LINE -- get number 2 +print $FILE -- obtém string do nome do módulo atual +print $LINE -- obtém número 2 ``` -## Generating Macros with Macros +## Gerando macros com macros -In YueScript, macro functions allow you to generate code at compile time. By nesting macro functions, you can create more complex generation patterns. This feature enables you to define a macro function that generates another macro function, allowing for more dynamic code generation. +No YueScript, as funções macro permitem que você gere código em tempo de compilação. Aninhando funções macro, você pode criar padrões de geração mais complexos. Este recurso permite que você defina uma função macro que gera outra função macro, permitindo geração de código mais dinâmica. ```yuescript macro Enum = (...) -> @@ -222,9 +221,9 @@ print "Valid enum type:", $BodyType Static -## Argument Validation +## Validação de argumentos -You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time. +Você pode declarar os tipos de nós AST esperados na lista de argumentos e verificar se os argumentos da macro recebidos atendem às expectativas em tempo de compilação. ```yuescript macro printNumAndStr = (num `Num, str `String) -> | @@ -249,7 +248,7 @@ $printNumAndStr 123, "hello" -If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. +Se você precisar de verificação de argumentos mais flexível, pode usar a função macro embutida `$is_ast` para verificar manualmente no lugar apropriado. ```yuescript macro printNumAndStr = (num, str) -> @@ -272,4 +271,4 @@ $printNumAndStr 123, "hello" -For more details about available AST nodes, please refer to the uppercased definitions in [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). +Para mais detalhes sobre os nós AST disponíveis, consulte as definições em maiúsculas em [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). diff --git a/doc/docs/pt-br/doc/advanced/module.md b/doc/docs/pt-br/doc/advanced/module.md index c955092..34fd106 100644 --- a/doc/docs/pt-br/doc/advanced/module.md +++ b/doc/docs/pt-br/doc/advanced/module.md @@ -1,28 +1,28 @@ -# Module +# Módulo ## Import -The import statement is a syntax sugar for requiring a module or help extracting items from an imported module. The imported items are const by default. +A instrução import é um açúcar sintático para requerer um módulo ou ajudar a extrair itens de um módulo importado. Os itens importados são const por padrão. ```yuescript --- used as table destructuring +-- usado como desestruturação de tabela do import insert, concat from table - -- report error when assigning to insert, concat + -- reporta erro ao atribuir a insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- atalho para require implícito import x, y, z from 'mymodule' - -- import with Python style + -- import com estilo Python from 'module' import a, b, c --- shortcut for requring a module +-- atalho para requerer um módulo do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- requerer módulo com aliasing ou desestruturação de tabela do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -31,24 +31,24 @@ do ```yue --- used as table destructuring +-- usado como desestruturação de tabela do import insert, concat from table - -- report error when assigning to insert, concat + -- reporta erro ao atribuir a insert, concat import C, Ct, Cmt from require "lpeg" - -- shortcut for implicit requiring + -- atalho para require implícito import x, y, z from 'mymodule' - -- import with Python style + -- import com estilo Python from 'module' import a, b, c --- shortcut for requring a module +-- atalho para requerer um módulo do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" --- requring module with aliasing or table destructuring +-- requerer módulo com aliasing ou desestruturação de tabela do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt @@ -59,7 +59,7 @@ do ## Import Global -You can import specific globals into local variables with `import`. When importing a chain of global variable accessings, the last field will be assigned to the local variable. +Você pode importar globais específicos para variáveis locais com `import`. Ao importar uma cadeia de acessos a variáveis globais, o último campo será atribuído à variável local. ```yuescript do @@ -78,21 +78,21 @@ do -### Automatic Global Variable Import +### Importação automática de variável global -You can place `import global` at the top of a block to automatically import all names that have not been explicitly declared or assigned in the current scope as globals. These implicit imports are treated as local consts that reference the corresponding globals at the position of the statement. +Você pode colocar `import global` no topo de um bloco para importar automaticamente todos os nomes que não foram explicitamente declarados ou atribuídos no escopo atual como globais. Essas importações implícitas são tratadas como consts locais que referenciam os globais correspondentes na posição da instrução. -Names that are explicitly declared as globals in the same scope will not be imported, so you can still assign to them. +Nomes que foram explicitamente declarados como globais no mesmo escopo não serão importados, então você ainda pode atribuir a eles. ```yuescript do import global print "hello" math.random 3 - -- print = nil -- error: imported globals are const + -- print = nil -- erro: globais importados são const do - -- explicit global variable will not be imported + -- variável global explícita não será importada import global global FLAG print FLAG @@ -105,10 +105,10 @@ do import global print "hello" math.random 3 - -- print = nil -- error: imported globals are const + -- print = nil -- erro: globais importados são const do - -- explicit global variable will not be imported + -- variável global explícita não será importada import global global FLAG print FLAG @@ -119,11 +119,11 @@ do ## Export -The export statement offers a concise way to define modules. +A instrução export oferece uma forma concisa de definir módulos. -### Named Export +### Export nomeado -Named export will define a local variable as well as adding a field in the exported table. +Export nomeado definirá uma variável local e também adicionará um campo na tabela exportada. ```yuescript export a, b, c = 1, 2, 3 @@ -160,7 +160,7 @@ export class Something -Doing named export with destructuring. +Fazendo export nomeado com desestruturação. ```yuescript export :loadstring, to_lua: tolua = yue @@ -175,7 +175,7 @@ export {itemA: {:fieldA = 'default'}} = tb -Export named items from module without creating local variables. +Exportar itens nomeados do módulo sem criar variáveis locais. ```yuescript export.itemA = tb @@ -192,9 +192,9 @@ export["a-b-c"] = 123 -### Unnamed Export +### Export sem nome -Unnamed export will add the target item into the array part of the exported table. +Export sem nome adicionará o item alvo na parte array da tabela exportada. ```yuescript d, e, f = 3, 2, 1 @@ -225,9 +225,9 @@ export with tmp -### Default Export +### Export padrão -Using the **default** keyword in export statement to replace the exported table with any thing. +Usar a palavra-chave **default** na instrução export para substituir a tabela exportada por qualquer coisa. ```yuescript export default -> diff --git a/doc/docs/pt-br/doc/advanced/try.md b/doc/docs/pt-br/doc/advanced/try.md index 23c7877..fbb4e87 100644 --- a/doc/docs/pt-br/doc/advanced/try.md +++ b/doc/docs/pt-br/doc/advanced/try.md @@ -1,6 +1,6 @@ # Try -The syntax for Lua error handling in a common form. +A sintaxe para tratamento de erros do Lua em uma forma comum. ```yuescript try @@ -23,7 +23,7 @@ try print "trying" func 1, 2, 3 --- working with if assignment pattern +-- funcionando com padrão de atribuição em if if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -52,7 +52,7 @@ try print "trying" func 1, 2, 3 --- working with if assignment pattern +-- funcionando com padrão de atribuição em if if success, result := try func 1, 2, 3 catch err print yue.traceback err @@ -63,18 +63,18 @@ catch err ## Try? -`try?` is a simplified use for error handling syntax that omit the boolean status from the `try` statement, and it will return the result from the try block when success, return nil instead of error object otherwise. +`try?` é um uso simplificado para sintaxe de tratamento de erros que omite o status booleano da instrução `try`, e retornará o resultado do bloco try quando tiver sucesso, retornando nil em vez do objeto de erro caso contrário. ```yuescript a, b, c = try? func! --- with nil coalescing operator +-- com operador de coalescência de nil a = (try? func!) ?? "default" --- as function argument +-- como argumento de função f try? func! --- with catch block +-- com bloco catch f try? print 123 func! @@ -87,13 +87,13 @@ catch e ```yue a, b, c = try? func! --- with nil coalescing operator +-- com operador de coalescência de nil a = (try? func!) ?? "default" --- as function argument +-- como argumento de função f try? func! --- with catch block +-- com bloco catch f try? print 123 func! diff --git a/doc/docs/pt-br/doc/assignment/assignment.md b/doc/docs/pt-br/doc/assignment/assignment.md index 4dac6f4..1da6bb0 100644 --- a/doc/docs/pt-br/doc/assignment/assignment.md +++ b/doc/docs/pt-br/doc/assignment/assignment.md @@ -1,25 +1,25 @@ -# Assignment +# Atribuição -The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement. +A variável é tipada dinamicamente e é definida como local por padrão. Mas você pode alterar o escopo da declaração pelas instruções **local** e **global**. ```yuescript hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- usa a variável existente ``` ```yue hello = "world" a, b, c = 1, 2, 3 -hello = 123 -- uses the existing variable +hello = 123 -- usa a variável existente ``` -## Perform Update +## Atualização -You can perform update assignment with many binary operators. +Você pode realizar atribuição de atualização com muitos operadores binários. ```yuescript x = 1 x += 1 @@ -27,8 +27,8 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist -arg or= "default value" +s ..= "world" -- adiciona um novo local se a variável local não existir +arg or= "valor padrão" ``` @@ -39,15 +39,15 @@ x -= 1 x *= 10 x /= 10 x %= 10 -s ..= "world" -- will add a new local if local variable is not exist -arg or= "default value" +s ..= "world" -- adiciona um novo local se a variável local não existir +arg or= "valor padrão" ``` -## Chaining Assignment +## Atribuição encadeada -You can do chaining assignment to assign multiple items to hold the same value. +Você pode fazer atribuição encadeada para atribuir múltiplos itens ao mesmo valor. ```yuescript a = b = c = d = e = 0 x = y = z = f! @@ -61,12 +61,12 @@ x = y = z = f! -## Explicit Locals +## Locais explícitos ```yuescript do local a = 1 local * - print "forward declare all variables as locals" + print "declarar antecipadamente todas as variáveis como locais" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! @@ -74,7 +74,7 @@ do do local X = 1 local ^ - print "only forward declare upper case variables" + print "declarar antecipadamente apenas variáveis em maiúsculas" a = 1 B = 2 ``` @@ -84,7 +84,7 @@ do do local a = 1 local * - print "forward declare all variables as locals" + print "declarar antecipadamente todas as variáveis como locais" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! @@ -92,29 +92,29 @@ do do local X = 1 local ^ - print "only forward declare upper case variables" + print "declarar antecipadamente apenas variáveis em maiúsculas" a = 1 B = 2 ``` -## Explicit Globals +## Globais explícitos ```yuescript do global a = 1 global * - print "declare all variables as globals" + print "declarar todas as variáveis como globais" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ - print "only declare upper case variables as globals" + print "declarar apenas variáveis em maiúsculas como globais" a = 1 B = 2 - local Temp = "a local value" + local Temp = "um valor local" ``` @@ -122,17 +122,17 @@ do do global a = 1 global * - print "declare all variables as globals" + print "declarar todas as variáveis como globais" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ - print "only declare upper case variables as globals" + print "declarar apenas variáveis em maiúsculas como globais" a = 1 B = 2 - local Temp = "a local value" + local Temp = "um valor local" ``` diff --git a/doc/docs/pt-br/doc/assignment/destructuring-assignment.md b/doc/docs/pt-br/doc/assignment/destructuring-assignment.md index e7b8046..7692885 100644 --- a/doc/docs/pt-br/doc/assignment/destructuring-assignment.md +++ b/doc/docs/pt-br/doc/assignment/destructuring-assignment.md @@ -1,10 +1,10 @@ -# Destructuring Assignment +# Atribuição por desestruturação -Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. +A atribuição por desestruturação é uma forma de extrair rapidamente valores de uma tabela por seu nome ou posição em tabelas baseadas em array. -Typically when you see a table literal, {1,2,3}, it is on the right hand side of an assignment because it is a value. Destructuring assignment swaps the role of the table literal, and puts it on the left hand side of an assign statement. +Tipicamente, quando você vê um literal de tabela, {1,2,3}, ele está no lado direito de uma atribuição porque é um valor. A atribuição por desestruturação troca o papel do literal de tabela e o coloca no lado esquerdo de uma instrução de atribuição. -This is best explained with examples. Here is how you would unpack the first two values from a table: +Isso é melhor explicado com exemplos. Assim você extrairia os dois primeiros valores de uma tabela: ```yuescript thing = [1, 2] @@ -23,7 +23,7 @@ print a, b -In the destructuring table literal, the key represents the key to read from the right hand side, and the value represents the name the read value will be assigned to. +No literal de tabela de desestruturação, a chave representa a chave para ler do lado direito, e o valor representa o nome ao qual o valor lido será atribuído. ```yuescript obj = { @@ -35,7 +35,7 @@ obj = { {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- OK fazer desestruturação simples sem chaves ``` @@ -49,12 +49,12 @@ obj = { {hello: hello, day: the_day} = obj print hello, the_day -:day = obj -- OK to do simple destructuring without braces +:day = obj -- OK fazer desestruturação simples sem chaves ``` -This also works with nested data structures as well: +Isso também funciona com estruturas de dados aninhadas: ```yuescript obj2 = { @@ -85,7 +85,7 @@ print first, second, color -If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: +Se a instrução de desestruturação for complicada, sinta-se à vontade para espalhá-la em várias linhas. Um exemplo um pouco mais complicado: ```yuescript { @@ -108,7 +108,7 @@ If the destructuring statement is complicated, feel free to spread it out over a -It's common to extract values from at table and assign them the local variables that have the same name as the key. In order to avoid repetition we can use the **:** prefix operator: +É comum extrair valores de uma tabela e atribuí-los a variáveis locais que têm o mesmo nome da chave. Para evitar repetição, podemos usar o operador de prefixo **:**: ```yuescript {:concat, :insert} = table @@ -121,7 +121,7 @@ It's common to extract values from at table and assign them the local variables -This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: +Isso é efetivamente o mesmo que import, mas podemos renomear campos que queremos extrair misturando a sintaxe: ```yuescript {:mix, :max, random: rand} = math @@ -134,20 +134,20 @@ This is effectively the same as import, but we can rename fields we want to extr -You can write default values while doing destructuring like: +Você pode escrever valores padrão ao fazer desestruturação: ```yuescript -{:name = "nameless", :job = "jobless"} = person +{:name = "sem nome", :job = "sem emprego"} = person ``` ```yue -{:name = "nameless", :job = "jobless"} = person +{:name = "sem nome", :job = "sem emprego"} = person ``` -You can use `_` as placeholder when doing a list destructuring: +Você pode usar `_` como placeholder ao fazer desestruturação de lista: ```yuescript [_, two, _, four] = items @@ -160,59 +160,59 @@ You can use `_` as placeholder when doing a list destructuring: -## Range Destructuring +## Desestruturação por intervalo -You can use the spread operator `...` in list destructuring to capture a range of values. This is useful when you want to extract specific elements from the beginning and end of a list while collecting the rest in between. +Você pode usar o operador spread `...` na desestruturação de lista para capturar um intervalo de valores. Isso é útil quando você quer extrair elementos específicos do início e do fim de uma lista enquanto coleta o restante entre eles. ```yuescript orders = ["first", "second", "third", "fourth", "last"] [first, ...bulk, last] = orders -print first -- prints: first -print bulk -- prints: {"second", "third", "fourth"} -print last -- prints: last +print first -- imprime: first +print bulk -- imprime: {"second", "third", "fourth"} +print last -- imprime: last ``` ```yue orders = ["first", "second", "third", "fourth", "last"] [first, ...bulk, last] = orders -print first -- prints: first -print bulk -- prints: {"second", "third", "fourth"} -print last -- prints: last +print first -- imprime: first +print bulk -- imprime: {"second", "third", "fourth"} +print last -- imprime: last ``` -The spread operator can be used in different positions to capture different ranges, and you can use `_` as a placeholder for the values you don't want to capture: +O operador spread pode ser usado em diferentes posições para capturar diferentes intervalos, e você pode usar `_` como placeholder para os valores que não quer capturar: ```yuescript --- Capture everything after first element +-- Capturar tudo após o primeiro elemento [first, ...rest] = orders --- Capture everything before last element +-- Capturar tudo antes do último elemento [...start, last] = orders --- Capture things except the middle elements +-- Capturar tudo exceto os elementos do meio [first, ..._, last] = orders ``` ```yue --- Capture everything after first element +-- Capturar tudo após o primeiro elemento [first, ...rest] = orders --- Capture everything before last element +-- Capturar tudo antes do último elemento [...start, last] = orders --- Capture things except the middle elements +-- Capturar tudo exceto os elementos do meio [first, ..._, last] = orders ``` -## Destructuring In Other Places +## Desestruturação em outros lugares -Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: +A desestruturação também pode aparecer em lugares onde uma atribuição ocorre implicitamente. Um exemplo disso é um loop for: ```yuescript tuples = [ @@ -237,4 +237,4 @@ for [left, right] in *tuples -We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure. +Sabemos que cada elemento na tabela array é uma tupla de dois itens, então podemos desempacotá-lo diretamente na cláusula de nomes da instrução for usando desestruturação. diff --git a/doc/docs/pt-br/doc/assignment/if-assignment.md b/doc/docs/pt-br/doc/assignment/if-assignment.md index 02984e8..84094ed 100644 --- a/doc/docs/pt-br/doc/assignment/if-assignment.md +++ b/doc/docs/pt-br/doc/assignment/if-assignment.md @@ -1,6 +1,6 @@ -# If Assignment +# Atribuição em if -`if` and `elseif` blocks can take an assignment in place of a conditional expression. Upon evaluating the conditional, the assignment will take place and the value that was assigned to will be used as the conditional expression. The assigned variable is only in scope for the body of the conditional, meaning it is never available if the value is not truthy. And you have to use "the walrus operator" `:=` instead of `=` to do assignment. +Os blocos `if` e `elseif` podem receber uma atribuição no lugar de uma expressão condicional. Ao avaliar o condicional, a atribuição será realizada e o valor que foi atribuído será usado como expressão condicional. A variável atribuída está no escopo apenas para o corpo do condicional, ou seja, nunca está disponível se o valor não for truthy. E você precisa usar o "operador walrus" `:=` em vez de `=` para fazer a atribuição. ```yuescript if user := database.find_user "moon" @@ -17,55 +17,55 @@ if user := database.find_user "moon" ```yuescript if hello := os.getenv "hello" - print "You have hello", hello + print "Você tem hello", hello elseif world := os.getenv "world" - print "you have world", world + print "você tem world", world else - print "nothing :(" + print "nada :(" ``` ```yue if hello := os.getenv "hello" - print "You have hello", hello + print "Você tem hello", hello elseif world := os.getenv "world" - print "you have world", world + print "você tem world", world else - print "nothing :(" + print "nada :(" ``` -If assignment with multiple return values. Only the first value is getting checked, other values are scoped. +Atribuição em if com múltiplos valores de retorno. Apenas o primeiro valor é verificado, os outros valores estão no escopo. ```yuescript -if success, result := pcall -> "get result without problems" - print result -- variable result is scoped +if success, result := pcall -> "obter resultado sem problemas" + print result -- variável result está no escopo print "OK" ``` ```yue -if success, result := pcall -> "get result without problems" - print result -- variable result is scoped +if success, result := pcall -> "obter resultado sem problemas" + print result -- variável result está no escopo print "OK" ``` -## While Assignment +## Atribuição em while -You can also use if assignment in a while loop to get the value as the loop condition. +Você também pode usar atribuição em if em um loop while para obter o valor como condição do loop. ```yuescript while byte := stream\read_one! - -- do something with the byte + -- fazer algo com o byte print byte ``` ```yue while byte := stream\read_one! - -- do something with the byte + -- fazer algo com o byte print byte ``` diff --git a/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md b/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md index fb9b740..02d4162 100644 --- a/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md +++ b/doc/docs/pt-br/doc/assignment/the-using-clause-controlling-destructive-assignment.md @@ -1,11 +1,11 @@ -# The Using Clause; Controlling Destructive Assignment +# A cláusula Using; controlando atribuição destrutiva -While lexical scoping can be a great help in reducing the complexity of the code we write, things can get unwieldy as the code size increases. Consider the following snippet: +Embora o escopo léxico possa ser uma grande ajuda na redução da complexidade do código que escrevemos, as coisas podem ficar difíceis de gerenciar conforme o tamanho do código aumenta. Considere o seguinte trecho: ```yuescript i = 100 --- many lines of code... +-- muitas linhas de código... my_func = -> i = 10 @@ -15,14 +15,14 @@ my_func = -> my_func! -print i -- will print 0 +print i -- vai imprimir 0 ``` ```yue i = 100 --- many lines of code... +-- muitas linhas de código... my_func = -> i = 10 @@ -32,25 +32,25 @@ my_func = -> my_func! -print i -- will print 0 +print i -- vai imprimir 0 ``` -In my_func, we've overwritten the value of i mistakenly. In this example it is quite obvious, but consider a large, or foreign code base where it isn't clear what names have already been declared. +Em my_func, sobrescrevemos o valor de i por engano. Neste exemplo é bem óbvio, mas considere uma base de código grande ou estrangeira onde não está claro quais nomes já foram declarados. -It would be helpful to say which variables from the enclosing scope we intend on change, in order to prevent us from changing others by accident. +Seria útil dizer quais variáveis do escopo envolvente pretendemos alterar, para evitar que alteremos outras por acidente. -The using keyword lets us do that. using nil makes sure that no closed variables are overwritten in assignment. The using clause is placed after the argument list in a function, or in place of it if there are no arguments. +A palavra-chave using nos permite fazer isso. using nil garante que nenhuma variável fechada seja sobrescrita na atribuição. A cláusula using é colocada após a lista de argumentos em uma função, ou no lugar dela se não houver argumentos. ```yuescript i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- uma nova variável local é criada aqui my_func! -print i -- prints 100, i is unaffected +print i -- imprime 100, i não é afetado ``` @@ -58,27 +58,27 @@ print i -- prints 100, i is unaffected i = 100 my_func = (using nil) -> - i = "hello" -- a new local variable is created here + i = "hello" -- uma nova variável local é criada aqui my_func! -print i -- prints 100, i is unaffected +print i -- imprime 100, i não é afetado ``` -Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: +Múltiplos nomes podem ser separados por vírgulas. Os valores do closure ainda podem ser acessados, apenas não podem ser modificados: ```yuescript tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- uma nova variável local tmp é criada i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- estes foram atualizados ``` @@ -87,12 +87,12 @@ tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> - tmp = tmp + add -- a new local tmp is created + tmp = tmp + add -- uma nova variável local tmp é criada i += tmp k += tmp my_func(22) -print i, k -- these have been updated +print i, k -- estes foram atualizados ``` diff --git a/doc/docs/pt-br/doc/assignment/varargs-assignment.md b/doc/docs/pt-br/doc/assignment/varargs-assignment.md index 1d66680..0aab540 100644 --- a/doc/docs/pt-br/doc/assignment/varargs-assignment.md +++ b/doc/docs/pt-br/doc/assignment/varargs-assignment.md @@ -1,6 +1,6 @@ -# Varargs Assignment +# Atribuição de varargs -You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. +Você pode atribuir os resultados retornados de uma função a um símbolo varargs `...`. E então acessar seu conteúdo da forma Lua. ```yuescript list = [1, 2, 3, 4, 5] diff --git a/doc/docs/pt-br/doc/control-flow/conditionals.md b/doc/docs/pt-br/doc/control-flow/conditionals.md index 5ba81cf..94e41ec 100644 --- a/doc/docs/pt-br/doc/control-flow/conditionals.md +++ b/doc/docs/pt-br/doc/control-flow/conditionals.md @@ -1,55 +1,55 @@ -# Conditionals +# Condicionais ```yuescript have_coins = false if have_coins - print "Got coins" + print "Tem moedas" else - print "No coins" + print "Sem moedas" ``` ```yue have_coins = false if have_coins - print "Got coins" + print "Tem moedas" else - print "No coins" + print "Sem moedas" ``` -A short syntax for single statements can also be used: +Uma sintaxe curta para instruções únicas também pode ser usada: ```yuescript have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Tem moedas" else print "Sem moedas" ``` ```yue have_coins = false -if have_coins then print "Got coins" else print "No coins" +if have_coins then print "Tem moedas" else print "Sem moedas" ``` -Because if statements can be used as expressions, this can also be written as: +Como instruções if podem ser usadas como expressões, isso também pode ser escrito como: ```yuescript have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Tem moedas" else "Sem moedas" ``` ```yue have_coins = false -print if have_coins then "Got coins" else "No coins" +print if have_coins then "Tem moedas" else "Sem moedas" ``` -Conditionals can also be used in return statements and assignments: +Condicionais também podem ser usados em instruções de retorno e atribuições: ```yuescript is_tall = (name) -> @@ -59,11 +59,11 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Sou muito alto" else - "I am not so tall" + "Não sou tão alto" -print message -- prints: I am very tall +print message -- imprime: Sou muito alto ``` @@ -75,53 +75,53 @@ is_tall = (name) -> false message = if is_tall "Rob" - "I am very tall" + "Sou muito alto" else - "I am not so tall" + "Não sou tão alto" -print message -- prints: I am very tall +print message -- imprime: Sou muito alto ``` -The opposite of if is unless: +O oposto de if é unless: ```yuescript unless os.date("%A") == "Monday" - print "it is not Monday!" + print "não é segunda-feira!" ``` ```yue unless os.date("%A") == "Monday" - print "it is not Monday!" + print "não é segunda-feira!" ``` ```yuescript -print "You're lucky!" unless math.random! > 0.1 +print "Você tem sorte!" unless math.random! > 0.1 ``` ```yue -print "You're lucky!" unless math.random! > 0.1 +print "Você tem sorte!" unless math.random! > 0.1 ``` -## In Expression +## Em expressão -You can write range checking code with an `in-expression`. +Você pode escrever código de verificação de intervalo com uma `in-expression`. ```yuescript a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "verificando igualdade com valores discretos" if a in list - print "checking if `a` is in a list" + print "verificando se `a` está na lista" ``` @@ -129,21 +129,10 @@ if a in list a = 5 if a in [1, 3, 5, 7] - print "checking equality with discrete values" + print "verificando igualdade com valores discretos" if a in list - print "checking if `a` is in a list" -``` - - - -```yuescript -print "You're lucky!" unless math.random! > 0.1 -``` - - -```yue -print "You're lucky!" unless math.random! > 0.1 + print "verificando se `a` está na lista" ``` diff --git a/doc/docs/pt-br/doc/control-flow/continue.md b/doc/docs/pt-br/doc/control-flow/continue.md index b000765..8a3cdff 100644 --- a/doc/docs/pt-br/doc/control-flow/continue.md +++ b/doc/docs/pt-br/doc/control-flow/continue.md @@ -1,6 +1,6 @@ # Continue -A continue statement can be used to skip the current iteration in a loop. +Uma instrução continue pode ser usada para pular a iteração atual em um loop. ```yuescript i = 0 @@ -21,7 +21,7 @@ while i < 10 -continue can also be used with loop expressions to prevent that iteration from accumulating into the result. This examples filters the array table into just even numbers: +continue também pode ser usado com expressões de loop para impedir que essa iteração seja acumulada no resultado. Este exemplo filtra a tabela array para apenas números pares: ```yuescript my_numbers = [1, 2, 3, 4, 5, 6] diff --git a/doc/docs/pt-br/doc/control-flow/for-loop.md b/doc/docs/pt-br/doc/control-flow/for-loop.md index cabcde5..dfd8285 100644 --- a/doc/docs/pt-br/doc/control-flow/for-loop.md +++ b/doc/docs/pt-br/doc/control-flow/for-loop.md @@ -1,12 +1,12 @@ -# For Loop +# Loop For -There are two for loop forms, just like in Lua. A numeric one and a generic one: +Existem duas formas de loop for, assim como no Lua. Uma numérica e uma genérica: ```yuescript for i = 10, 20 print i -for k = 1, 15, 2 -- an optional step provided +for k = 1, 15, 2 -- um passo opcional fornecido print k for key, value in pairs object @@ -18,7 +18,7 @@ for key, value in pairs object for i = 10, 20 print i -for k = 1, 15, 2 -- an optional step provided +for k = 1, 15, 2 -- um passo opcional fornecido print k for key, value in pairs object @@ -27,7 +27,7 @@ for key, value in pairs object -The slicing and **\*** operators can be used, just like with comprehensions: +Os operadores de slicing e **\*** podem ser usados, assim como com compreensões: ```yuescript for item in *items[2, 4] @@ -42,7 +42,7 @@ for item in *items[2, 4] -A shorter syntax is also available for all variations when the body is only a single line: +Uma sintaxe mais curta também está disponível para todas as variações quando o corpo é apenas uma linha: ```yuescript for item in *items do print item @@ -59,9 +59,9 @@ for j = 1, 10, 3 do print j -A for loop can also be used as an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating array table. +Um loop for também pode ser usado como expressão. A última instrução no corpo do loop for é convertida em expressão e anexada a uma tabela array acumuladora. -Doubling every even number: +Dobrando cada número par: ```yuescript doubled_evens = for i = 1, 20 @@ -82,9 +82,9 @@ doubled_evens = for i = 1, 20 -In addition, for loops support break with a return value, allowing the loop itself to be used as an expression that exits early with a meaningful result. +Além disso, os loops for suportam break com valor de retorno, permitindo que o próprio loop seja usado como expressão que sai antecipadamente com um resultado significativo. -For example, to find the first number greater than 10: +Por exemplo, para encontrar o primeiro número maior que 10: ```yuescript first_large = for n in *numbers @@ -99,18 +99,18 @@ first_large = for n in *numbers -This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. +Esta sintaxe de break-com-valor permite padrões concisos e expressivos de busca ou saída antecipada diretamente em expressões de loop. -You can also filter values by combining the for loop expression with the continue statement. +Você também pode filtrar valores combinando a expressão do loop for com a instrução continue. -For loops at the end of a function body are not accumulated into a table for a return value (Instead the function will return nil). Either an explicit return statement can be used, or the loop can be converted into a list comprehension. +Loops for no final do corpo de uma função não são acumulados em uma tabela para valor de retorno (em vez disso, a função retornará nil). Uma instrução return explícita pode ser usada, ou o loop pode ser convertido em compreensão de lista. ```yuescript func_a = -> for i = 1, 10 do print i func_b = -> return for i = 1, 10 do i -print func_a! -- prints nil -print func_b! -- prints table object +print func_a! -- imprime nil +print func_b! -- imprime objeto table ``` @@ -118,10 +118,10 @@ print func_b! -- prints table object func_a = -> for i = 1, 10 do print i func_b = -> return for i = 1, 10 do i -print func_a! -- prints nil -print func_b! -- prints table object +print func_a! -- imprime nil +print func_b! -- imprime objeto table ``` -This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. +Isso é feito para evitar a criação desnecessária de tabelas para funções que não precisam retornar os resultados do loop. diff --git a/doc/docs/pt-br/doc/control-flow/switch.md b/doc/docs/pt-br/doc/control-flow/switch.md index f503a80..5c87327 100644 --- a/doc/docs/pt-br/doc/control-flow/switch.md +++ b/doc/docs/pt-br/doc/control-flow/switch.md @@ -1,33 +1,33 @@ # Switch -The switch statement is shorthand for writing a series of if statements that check against the same value. Note that the value is only evaluated once. Like if statements, switches can have an else block to handle no matches. Comparison is done with the == operator. In switch statement, you can also use assignment expression to store temporary variable value. +A instrução switch é uma forma abreviada de escrever uma série de instruções if que verificam o mesmo valor. Observe que o valor é avaliado apenas uma vez. Como as instruções if, os switches podem ter um bloco else para tratar ausência de correspondências. A comparação é feita com o operador ==. Na instrução switch, você também pode usar expressão de atribuição para armazenar valor de variável temporária. ```yuescript switch name := "Dan" when "Robert" - print "You are Robert" + print "Você é Robert" when "Dan", "Daniel" - print "Your name, it's Dan" + print "Seu nome é Dan" else - print "I don't know about you with name #{name}" + print "Não sei quem você é com o nome #{name}" ``` ```yue switch name := "Dan" when "Robert" - print "You are Robert" + print "Você é Robert" when "Dan", "Daniel" - print "Your name, it's Dan" + print "Seu nome é Dan" else - print "I don't know about you with name #{name}" + print "Não sei quem você é com o nome #{name}" ``` -A switch when clause can match against multiple values by listing them out comma separated. +Uma cláusula when de um switch pode corresponder a múltiplos valores listando-os separados por vírgula. -Switches can be used as expressions as well, here we can assign the result of the switch to a variable: +Os switches também podem ser usados como expressões; aqui podemos atribuir o resultado do switch a uma variável: ```yuescript b = 1 @@ -37,7 +37,7 @@ next_number = switch b when 2 3 else - error "can't count that high!" + error "não consigo contar tão alto!" ``` @@ -49,66 +49,66 @@ next_number = switch b when 2 3 else - error "can't count that high!" + error "não consigo contar tão alto!" ``` -We can use the then keyword to write a switch's when block on a single line. No extra keyword is needed to write the else block on a single line. +Podemos usar a palavra-chave then para escrever o bloco when de um switch em uma única linha. Nenhuma palavra-chave extra é necessária para escrever o bloco else em uma única linha. ```yuescript msg = switch math.random(1, 5) - when 1 then "you are lucky" - when 2 then "you are almost lucky" - else "not so lucky" + when 1 then "você tem sorte" + when 2 then "você quase tem sorte" + else "não tão sortudo" ``` ```yue msg = switch math.random(1, 5) - when 1 then "you are lucky" - when 2 then "you are almost lucky" - else "not so lucky" + when 1 then "você tem sorte" + when 2 then "você quase tem sorte" + else "não tão sortudo" ``` -If you want to write code with one less indent when writing a switch statement, you can put the first when clause on the statement start line, and then all other clauses can be written with one less indent. +Se você quiser escrever código com uma indentação a menos ao escrever uma instrução switch, pode colocar a primeira cláusula when na linha de início da instrução, e então todas as outras cláusulas podem ser escritas com uma indentação a menos. ```yuescript switch math.random(1, 5) when 1 - print "you are lucky" -- two indents + print "você tem sorte" -- duas indentações else - print "not so lucky" + print "não tão sortudo" switch math.random(1, 5) when 1 - print "you are lucky" -- one indent + print "você tem sorte" -- uma indentação else - print "not so lucky" + print "não tão sortudo" ``` ```yue switch math.random(1, 5) when 1 - print "you are lucky" -- two indents + print "você tem sorte" -- duas indentações else - print "not so lucky" + print "não tão sortudo" switch math.random(1, 5) when 1 - print "you are lucky" -- one indent + print "você tem sorte" -- uma indentação else - print "not so lucky" + print "não tão sortudo" ``` -It is worth noting the order of the case comparison expression. The case's expression is on the left hand side. This can be useful if the case's expression wants to overwrite how the comparison is done by defining an eq metamethod. +Vale notar a ordem da expressão de comparação do case. A expressão do case está no lado esquerdo. Isso pode ser útil se a expressão do case quiser sobrescrever como a comparação é feita definindo um metamétodo eq. -## Table Matching +## Correspondência de tabela -You can do table matching in a switch when clause, if the table can be destructured by a specific structure and get non-nil values. +Você pode fazer correspondência de tabela em uma cláusula when de switch, se a tabela puder ser desestruturada por uma estrutura específica e obter valores não-nil. ```yuescript items = @@ -122,7 +122,7 @@ for item in *items when :x, :y print "Vec2 #{x}, #{y}" when :width, :height - print "size #{width}, #{height}" + print "tamanho #{width}, #{height}" ``` @@ -138,39 +138,39 @@ for item in *items when :x, :y print "Vec2 #{x}, #{y}" when :width, :height - print "size #{width}, #{height}" + print "tamanho #{width}, #{height}" ``` -You can use default values to optionally destructure the table for some fields. +Você pode usar valores padrão para opcionalmente desestruturar a tabela para alguns campos. ```yuescript item = {} -{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') +{pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos') switch item when {pos: {:x = 50, :y = 200}} - print "Vec2 #{x}, #{y}" -- table destructuring will still pass + print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará ``` ```yue item = {} -{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos') +{pos: {:x = 50, :y = 200}} = item -- obtém erro: attempt to index a nil value (field 'pos') switch item when {pos: {:x = 50, :y = 200}} - print "Vec2 #{x}, #{y}" -- table destructuring will still pass + print "Vec2 #{x}, #{y}" -- a desestruturação de tabela ainda passará ``` -You can also match against array elements, table fields, and even nested structures with array or table literals. +Você também pode corresponder contra elementos de array, campos de tabela, e até estruturas aninhadas com literais de array ou tabela. -Match against array elements. +Corresponder contra elementos de array. ```yuescript switch tb @@ -178,7 +178,7 @@ switch tb print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" - when [1, 2, b = 3] -- b has a default value + when [1, 2, b = 3] -- b tem valor padrão print "1, 2, #{b}" ``` @@ -189,63 +189,63 @@ switch tb print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" - when [1, 2, b = 3] -- b has a default value + when [1, 2, b = 3] -- b tem valor padrão print "1, 2, #{b}" ``` -Match against table fields with destructuring. +Corresponder contra campos de tabela com desestruturação. ```yuescript switch tb when success: true, :result - print "success", result + print "sucesso", result when success: false - print "failed", result + print "falhou", result else - print "invalid" + print "inválido" ``` ```yue switch tb when success: true, :result - print "success", result + print "sucesso", result when success: false - print "failed", result + print "falhou", result else - print "invalid" + print "inválido" ``` -Match against nested table structures. +Corresponder contra estruturas de tabela aninhadas. ```yuescript switch tb when data: {type: "success", :content} - print "success", content + print "sucesso", content when data: {type: "error", :content} - print "failed", content + print "erro", content else - print "invalid" + print "inválido" ``` ```yue switch tb when data: {type: "success", :content} - print "success", content + print "sucesso", content when data: {type: "error", :content} - print "failed", content + print "erro", content else - print "invalid" + print "inválido" ``` -Match against array of tables. +Corresponder contra array de tabelas. ```yuescript switch tb @@ -255,7 +255,7 @@ switch tb {a: 5, b: 6} fourth ] - print "matched", fourth + print "correspondido", fourth ``` @@ -267,20 +267,20 @@ switch tb {a: 5, b: 6} fourth ] - print "matched", fourth + print "correspondido", fourth ``` -Match against a list and capture a range of elements. +Corresponder contra uma lista e capturar um intervalo de elementos. ```yuescript segments = ["admin", "users", "logs", "view"] switch segments when [...groups, resource, action] - print "Group:", groups -- prints: {"admin", "users"} - print "Resource:", resource -- prints: "logs" - print "Action:", action -- prints: "view" + print "Grupo:", groups -- imprime: {"admin", "users"} + print "Recurso:", resource -- imprime: "logs" + print "Ação:", action -- imprime: "view" ``` @@ -288,9 +288,9 @@ switch segments segments = ["admin", "users", "logs", "view"] switch segments when [...groups, resource, action] - print "Group:", groups -- prints: {"admin", "users"} - print "Resource:", resource -- prints: "logs" - print "Action:", action -- prints: "view" + print "Grupo:", groups -- imprime: {"admin", "users"} + print "Recurso:", resource -- imprime: "logs" + print "Ação:", action -- imprime: "view" ``` diff --git a/doc/docs/pt-br/doc/control-flow/while-loop.md b/doc/docs/pt-br/doc/control-flow/while-loop.md index 502935e..f47f00c 100644 --- a/doc/docs/pt-br/doc/control-flow/while-loop.md +++ b/doc/docs/pt-br/doc/control-flow/while-loop.md @@ -1,6 +1,6 @@ -# While Loop +# Loop While -The while loop also comes in four variations: +O loop while também vem em quatro variações: ```yuescript i = 10 @@ -43,11 +43,11 @@ until running == false do my_function! -Like for loops, the while loop can also be used an expression. Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. +Como os loops for, o loop while também pode ser usado como expressão. Além disso, para uma função retornar o valor acumulado de um loop while, a instrução deve ser explicitamente retornada. -## Repeat Loop +## Loop Repeat -The repeat loop comes from Lua: +O loop repeat vem do Lua: ```yuescript i = 10 diff --git a/doc/docs/pt-br/doc/data-structures/comprehensions.md b/doc/docs/pt-br/doc/data-structures/comprehensions.md index 3a92167..1694813 100644 --- a/doc/docs/pt-br/doc/data-structures/comprehensions.md +++ b/doc/docs/pt-br/doc/data-structures/comprehensions.md @@ -1,10 +1,10 @@ -# Comprehensions +# Compreensões -Comprehensions provide a convenient syntax for constructing a new table by iterating over some existing object and applying an expression to its values. There are two kinds of comprehensions: list comprehensions and table comprehensions. They both produce Lua tables; list comprehensions accumulate values into an array-like table, and table comprehensions let you set both the key and the value on each iteration. +As compreensões fornecem uma sintaxe conveniente para construir uma nova tabela iterando sobre algum objeto existente e aplicando uma expressão a seus valores. Existem dois tipos de compreensões: compreensões de lista e compreensões de tabela. Ambas produzem tabelas Lua; as compreensões de lista acumulam valores em uma tabela semelhante a array, e as compreensões de tabela permitem definir tanto a chave quanto o valor em cada iteração. -## List Comprehensions +## Compreensões de lista -The following creates a copy of the items table but with all the values doubled. +O seguinte cria uma cópia da tabela items mas com todos os valores dobrados. ```yuescript items = [ 1, 2, 3, 4 ] @@ -19,7 +19,7 @@ doubled = [item * 2 for i, item in ipairs items] -The items included in the new table can be restricted with a when clause: +Os itens incluídos na nova tabela podem ser restringidos com uma cláusula when: ```yuescript slice = [item for i, item in ipairs items when i > 1 and i < 3] @@ -32,7 +32,7 @@ slice = [item for i, item in ipairs items when i > 1 and i < 3] -Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as: +Como é comum iterar sobre os valores de uma tabela indexada numericamente, um operador **\*** é introduzido. O exemplo doubled pode ser reescrito como: ```yuescript doubled = [item * 2 for item in *items] @@ -45,7 +45,7 @@ doubled = [item * 2 for item in *items] -In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: +Nas compreensões de lista, você também pode usar o operador spread `...` para achatar listas aninhadas, alcançando um efeito de flat map: ```yuescript data = @@ -53,7 +53,7 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat agora é [1, 2, 3, 4, 5, 6] ``` @@ -63,14 +63,14 @@ data = b: [4, 5, 6] flat = [...v for k,v in pairs data] --- flat is now [1, 2, 3, 4, 5, 6] +-- flat agora é [1, 2, 3, 4, 5, 6] ``` -The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause. +As cláusulas for e when podem ser encadeadas tanto quanto desejado. O único requisito é que uma compreensão tenha pelo menos uma cláusula for. -Using multiple for clauses is the same as using nested loops: +Usar múltiplas cláusulas for é o mesmo que usar loops aninhados: ```yuescript x_coords = [4, 5, 6, 7] @@ -91,7 +91,7 @@ for y in *y_coords] -Numeric for loops can also be used in comprehensions: +Loops for numéricos também podem ser usados em compreensões: ```yuescript evens = [i for i = 1, 100 when i % 2 == 0] @@ -104,11 +104,11 @@ evens = [i for i = 1, 100 when i % 2 == 0] -## Table Comprehensions +## Compreensões de tabela -The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. +A sintaxe para compreensões de tabela é muito semelhante, diferindo apenas por usar **{** e **}** e receber dois valores de cada iteração. -This example makes a copy of the tablething: +Este exemplo faz uma cópia da tabela thing: ```yuescript thing = { @@ -144,7 +144,7 @@ no_color = {k, v for k, v in pairs thing when k != "color"} -The **\*** operator is also supported. Here we create a square root look up table for a few numbers. +O operador **\*** também é suportado. Aqui criamos uma tabela de consulta de raiz quadrada para alguns números. ```yuescript numbers = [1, 2, 3, 4] @@ -159,9 +159,9 @@ sqrts = {i, math.sqrt i for i in *numbers} -The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value: +A tupla chave-valor em uma compreensão de tabela também pode vir de uma única expressão, caso em que a expressão deve retornar dois valores. O primeiro é usado como chave e o segundo é usado como valor: -In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value. +Neste exemplo convertemos um array de pares em uma tabela onde o primeiro item do par é a chave e o segundo é o valor. ```yuescript tuples = [ ["hello", "world"], ["foo", "bar"]] @@ -178,9 +178,9 @@ tbl = {unpack tuple for tuple in *tuples} ## Slicing -A special syntax is provided to restrict the items that are iterated over when using the **\*** operator. This is equivalent to setting the iteration bounds and a step size in a for loop. +Uma sintaxe especial é fornecida para restringir os itens sobre os quais se itera ao usar o operador **\***. Isso é equivalente a definir os limites de iteração e um tamanho de passo em um loop for. -Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive: +Aqui podemos definir os limites mínimo e máximo, pegando todos os itens com índices entre 1 e 5 inclusive: ```yuescript slice = [item for item in *items[1, 5]] @@ -193,7 +193,7 @@ slice = [item for item in *items[1, 5]] -Any of the slice arguments can be left off to use a sensible default. In this example, if the max index is left off it defaults to the length of the table. This will take everything but the first element: +Qualquer um dos argumentos do slice pode ser omitido para usar um padrão sensato. Neste exemplo, se o índice máximo for omitido, ele usa como padrão o comprimento da tabela. Isso pegará tudo exceto o primeiro elemento: ```yuescript slice = [item for item in *items[2,]] @@ -206,7 +206,7 @@ slice = [item for item in *items[2,]] -If the minimum bound is left out, it defaults to 1. Here we only provide a step size and leave the other bounds blank. This takes all odd indexed items: (1, 3, 5, …) +Se o limite mínimo for omitido, ele usa como padrão 1. Aqui fornecemos apenas um tamanho de passo e deixamos os outros limites em branco. Isso pega todos os itens com índice ímpar: (1, 3, 5, …) ```yuescript slice = [item for item in *items[,,2]] @@ -219,22 +219,22 @@ slice = [item for item in *items[,,2]] -Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. +Tanto o limite mínimo quanto o máximo podem ser negativos, o que significa que os limites são contados a partir do fim da tabela. ```yuescript --- take the last 4 items +-- pegar os últimos 4 itens slice = [item for item in *items[-4,-1]] ``` ```yue --- take the last 4 items +-- pegar os últimos 4 itens slice = [item for item in *items[-4,-1]] ``` -The step size can also be negative, which means that the items are taken in reverse order. +O tamanho do passo também pode ser negativo, o que significa que os itens são tomados em ordem reversa. ```yuescript reverse_slice = [item for item in *items[-1,1,-1]] @@ -247,24 +247,24 @@ reverse_slice = [item for item in *items[-1,1,-1]] -### Slicing Expression +### Expressão de slicing -Slicing can also be used as an expression. This is useful for getting a sub-list of a table. +O slicing também pode ser usado como expressão. Isso é útil para obter uma sublista de uma tabela. ```yuescript --- take the 2nd and 4th items as a new list +-- pegar o 2º e 4º itens como nova lista sub_list = items[2, 4] --- take the last 4 items +-- pegar os últimos 4 itens last_four_items = items[-4, -1] ``` ```yue --- take the 2nd and 4th items as a new list +-- pegar o 2º e 4º itens como nova lista sub_list = items[2, 4] --- take the last 4 items +-- pegar os últimos 4 itens last_four_items = items[-4, -1] ``` diff --git a/doc/docs/pt-br/doc/data-structures/table-literals.md b/doc/docs/pt-br/doc/data-structures/table-literals.md index c1adcab..f0fbdc5 100644 --- a/doc/docs/pt-br/doc/data-structures/table-literals.md +++ b/doc/docs/pt-br/doc/data-structures/table-literals.md @@ -1,6 +1,6 @@ -# Table Literals +# Literais de tabela -Like in Lua, tables are delimited in curly braces. +Como no Lua, as tabelas são delimitadas por chaves. ```yuescript some_values = [1, 2, 3, 4] @@ -13,7 +13,7 @@ some_values = [1, 2, 3, 4] -Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). +Diferente do Lua, atribuir um valor a uma chave em uma tabela é feito com **:** (em vez de **=**). ```yuescript some_values = { @@ -34,7 +34,7 @@ some_values = { -The curly braces can be left off if a single table of key value pairs is being assigned. +As chaves podem ser omitidas se uma única tabela de pares chave-valor está sendo atribuída. ```yuescript profile = @@ -53,7 +53,7 @@ profile = -Newlines can be used to delimit values instead of a comma (or both): +Quebras de linha podem ser usadas para delimitar valores em vez de vírgula (ou ambos): ```yuescript values = { @@ -76,7 +76,7 @@ values = { -When creating a single line table literal, the curly braces can also be left off: +Ao criar um literal de tabela em uma única linha, as chaves também podem ser omitidas: ```yuescript my_function dance: "Tango", partner: "none" @@ -93,7 +93,7 @@ y = type: "dog", legs: 4, tails: 1 -The keys of a table literal can be language keywords without being escaped: +As chaves de um literal de tabela podem ser palavras-chave da linguagem sem precisar escapar: ```yuescript tbl = { @@ -112,7 +112,7 @@ tbl = { -If you are constructing a table out of variables and wish the keys to be the same as the variable names, then the **:** prefix operator can be used: +Se você está construindo uma tabela a partir de variáveis e deseja que as chaves sejam iguais aos nomes das variáveis, então o operador de prefixo **:** pode ser usado: ```yuescript hair = "golden" @@ -133,7 +133,7 @@ print_table :hair, :height -If you want the key of a field in the table to to be result of an expression, then you can wrap it in **[ ]**, just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters. +Se você quiser que a chave de um campo na tabela seja o resultado de uma expressão, então pode envolvê-la em **[ ]**, assim como no Lua. Você também pode usar um literal de string diretamente como chave, omitindo os colchetes. Isso é útil se sua chave tiver caracteres especiais. ```yuescript t = { @@ -152,7 +152,7 @@ t = { -Lua tables have both an array part and a hash part, but sometimes you want to make a semantic distinction between array and hash usage when writing Lua tables. Then you can write Lua table with **[ ]** instead of **{ }** to represent an array table and writing any key value pair in a list table won't be allowed. +As tabelas Lua têm tanto uma parte array quanto uma parte hash, mas às vezes você quer fazer uma distinção semântica entre uso de array e hash ao escrever tabelas Lua. Então você pode escrever tabela Lua com **[ ]** em vez de **{ }** para representar uma tabela array, e escrever qualquer par chave-valor em uma tabela lista não será permitido. ```yuescript some_values = [1, 2, 3, 4] diff --git a/doc/docs/pt-br/doc/functions/backcalls.md b/doc/docs/pt-br/doc/functions/backcalls.md index e34331e..924c10a 100644 --- a/doc/docs/pt-br/doc/functions/backcalls.md +++ b/doc/docs/pt-br/doc/functions/backcalls.md @@ -1,6 +1,6 @@ # Backcalls -Backcalls are used for unnesting callbacks. They are defined using arrows pointed to the left as the last parameter by default filling in a function call. All the syntax is mostly the same as regular arrow functions except that it is just pointing the other way and the function body does not require indent. +Backcalls são usados para desaninhar callbacks. Eles são definidos usando setas apontando para a esquerda como o último parâmetro, preenchendo por padrão uma chamada de função. Toda a sintaxe é basicamente a mesma das funções seta regulares, exceto que apenas aponta para o outro lado e o corpo da função não requer indentação. ```yuescript x <- f @@ -15,7 +15,7 @@ print "hello" .. x -Fat arrow functions are also available. +Funções seta "fat" também estão disponíveis. ```yuescript <= f @@ -30,7 +30,7 @@ print @value -You can specify a placeholder for where you want the backcall function to go as a parameter. +Você pode especificar um placeholder para onde deseja que a função backcall vá como parâmetro. ```yuescript (x) <- map _, [1, 2, 3] @@ -45,7 +45,7 @@ x * 2 -If you wish to have further code after your backcalls, you can set them aside with a do statement. And the parentheses can be omitted with non-fat arrow functions. +Se você desejar ter mais código após seus backcalls, pode colocá-los em uma instrução do. E os parênteses podem ser omitidos com funções seta não-fat. ```yuescript result, msg = do diff --git a/doc/docs/pt-br/doc/functions/function-literals.md b/doc/docs/pt-br/doc/functions/function-literals.md index 316e07c..e63888f 100644 --- a/doc/docs/pt-br/doc/functions/function-literals.md +++ b/doc/docs/pt-br/doc/functions/function-literals.md @@ -1,21 +1,21 @@ -# Function Literals +# Literais de função -All functions are created using a function expression. A simple function is denoted using the arrow: **->**. +Todas as funções são criadas usando uma expressão de função. Uma função simples é denotada usando a seta: **->**. ```yuescript my_function = -> -my_function() -- call the empty function +my_function() -- chama a função vazia ``` ```yue my_function = -> -my_function() -- call the empty function +my_function() -- chama a função vazia ``` -The body of the function can either be one statement placed directly after the arrow, or it can be a series of statements indented on the following lines: +O corpo da função pode ser uma instrução colocada diretamente após a seta, ou pode ser uma série de instruções indentadas nas linhas seguintes: ```yuescript func_a = -> print "hello world" @@ -36,7 +36,7 @@ func_b = -> -If a function has no arguments, it can be called using the ! operator, instead of empty parentheses. The ! invocation is the preferred way to call functions with no arguments. +Se uma função não tem argumentos, ela pode ser chamada usando o operador !, em vez de parênteses vazios. A invocação ! é a forma preferida de chamar funções sem argumentos. ```yuescript func_a! @@ -51,7 +51,7 @@ func_b() -Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: +Funções com argumentos podem ser criadas precedendo a seta com uma lista de nomes de argumentos entre parênteses: ```yuescript sum = (x, y) -> print "sum", x + y @@ -64,7 +64,7 @@ sum = (x, y) -> print "sum", x + y -Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left. +Funções podem ser chamadas listando os argumentos após o nome de uma expressão que avalia para uma função. Ao encadear chamadas de função, os argumentos são aplicados à função mais próxima à esquerda. ```yuescript sum 10, 20 @@ -83,7 +83,7 @@ a b c "a", "b", "c" -In order to avoid ambiguity in when calling functions, parentheses can also be used to surround the arguments. This is required here in order to make sure the right arguments get sent to the right functions. +Para evitar ambiguidade ao chamar funções, parênteses também podem ser usados para envolver os argumentos. Isso é necessário aqui para garantir que os argumentos certos sejam enviados às funções certas. ```yuescript print "x:", sum(10, 20), "y:", sum(30, 40) @@ -96,9 +96,9 @@ print "x:", sum(10, 20), "y:", sum(30, 40) -There must not be any space between the opening parenthesis and the function. +Não deve haver espaço entre o parêntese de abertura e a função. -Functions will coerce the last statement in their body into a return statement, this is called implicit return: +As funções convertem a última instrução em seu corpo em uma instrução de retorno, isso é chamado de retorno implícito: ```yuescript sum = (x, y) -> x + y @@ -113,7 +113,7 @@ print "The sum is ", sum 10, 20 -And if you need to explicitly return, you can use the return keyword: +E se você precisar retornar explicitamente, pode usar a palavra-chave return: ```yuescript sum = (x, y) -> return x + y @@ -126,7 +126,7 @@ sum = (x, y) -> return x + y -Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: +Assim como no Lua, as funções podem retornar múltiplos valores. A última instrução deve ser uma lista de valores separados por vírgulas: ```yuescript mystery = (x, y) -> x + y, x - y @@ -141,9 +141,9 @@ a, b = mystery 10, 20 -## Fat Arrows +## Setas fat -Because it is an idiom in Lua to send an object as the first argument when calling a method, a special syntax is provided for creating functions which automatically includes a self argument. +Como é um idioma em Lua enviar um objeto como primeiro argumento ao chamar um método, uma sintaxe especial é fornecida para criar funções que incluem automaticamente um argumento self. ```yuescript func = (num) => @value + num @@ -156,9 +156,9 @@ func = (num) => @value + num -## Argument Defaults +## Valores padrão de argumentos -It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run. +É possível fornecer valores padrão para os argumentos de uma função. Um argumento é determinado como vazio se seu valor for nil. Qualquer argumento nil que tenha valor padrão será substituído antes da execução do corpo da função. ```yuescript my_function = (name = "something", height = 100) -> @@ -175,7 +175,7 @@ my_function = (name = "something", height = 100) -> -An argument default value expression is evaluated in the body of the function in the order of the argument declarations. For this reason default values have access to previously declared arguments. +Uma expressão de valor padrão de argumento é avaliada no corpo da função na ordem das declarações de argumentos. Por esse motivo, os valores padrão têm acesso aos argumentos declarados anteriormente. ```yuescript some_args = (x = 100, y = x + 1000) -> @@ -190,11 +190,11 @@ some_args = (x = 100, y = x + 1000) -> -## Considerations +## Considerações -Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. +Devido à forma expressiva de chamar funções sem parênteses, algumas restrições devem ser colocadas para evitar ambiguidade de análise envolvendo espaço em branco. -The minus sign plays two roles, a unary negation operator and a binary subtraction operator. Consider how the following examples compile: +O sinal de menos desempenha dois papéis: um operador de negação unário e um operador de subtração binário. Considere como os seguintes exemplos compilam: ```yuescript a = x - 10 @@ -213,11 +213,11 @@ d = x- z -The precedence of the first argument of a function call can be controlled using whitespace if the argument is a literal string. In Lua, it is common to leave off parentheses when calling a function with a single string or table literal. +A precedência do primeiro argumento de uma chamada de função pode ser controlada usando espaço em branco se o argumento for um literal de string. Em Lua, é comum omitir parênteses ao chamar uma função com uma única string ou literal de tabela. -When there is no space between a variable and a string literal, the function call takes precedence over any following expressions. No other arguments can be passed to the function when it is called this way. +Quando não há espaço entre uma variável e um literal de string, a chamada de função tem precedência sobre quaisquer expressões seguintes. Nenhum outro argumento pode ser passado para a função quando ela é chamada dessa forma. -Where there is a space following a variable and a string literal, the function call acts as show above. The string literal belongs to any following expressions (if they exist), which serves as the argument list. +Quando há um espaço após uma variável e um literal de string, a chamada de função age como mostrado acima. O literal de string pertence a quaisquer expressões seguintes (se existirem), que servem como lista de argumentos. ```yuescript x = func"hello" + 100 @@ -232,11 +232,11 @@ y = func "hello" + 100 -## Multi-line arguments +## Argumentos multilinha -When calling functions that take a large number of arguments, it is convenient to split the argument list over multiple lines. Because of the white-space sensitive nature of the language, care must be taken when splitting up the argument list. +Ao chamar funções que recebem um grande número de argumentos, é conveniente dividir a lista de argumentos em várias linhas. Devido à natureza sensível a espaço em branco da linguagem, deve-se ter cuidado ao dividir a lista de argumentos. -If an argument list is to be continued onto the next line, the current line must end in a comma. And the following line must be indented more than the current indentation. Once indented, all other argument lines must be at the same level of indentation to be part of the argument list +Se uma lista de argumentos for continuada na próxima linha, a linha atual deve terminar em vírgula. E a linha seguinte deve estar mais indentada que a indentação atual. Uma vez indentada, todas as outras linhas de argumentos devem estar no mesmo nível de indentação para fazer parte da lista de argumentos. ```yuescript my_func 5, 4, 3, @@ -261,7 +261,7 @@ cool_func 1, 2, -This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. +Este tipo de invocação pode ser aninhado. O nível de indentação é usado para determinar a qual função os argumentos pertencem. ```yuescript my_func 5, 6, 7, @@ -280,7 +280,7 @@ my_func 5, 6, 7, -Because tables also use the comma as a delimiter, this indentation syntax is helpful for letting values be part of the argument list instead of being part of the table. +Como as tabelas também usam vírgula como delimitador, esta sintaxe de indentação ajuda a deixar os valores fazerem parte da lista de argumentos em vez de fazerem parte da tabela. ```yuescript x = [ @@ -301,7 +301,7 @@ x = [ -Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on. +Embora incomum, observe como podemos dar uma indentação mais profunda para argumentos de função se soubermos que usaremos uma indentação menor mais adiante. ```yuescript y = [ my_func 1, 2, 3, @@ -320,7 +320,7 @@ y = [ my_func 1, 2, 3, -The same thing can be done with other block level statements like conditionals. We can use indentation level to determine what statement a value belongs to: +A mesma coisa pode ser feita com outras instruções em nível de bloco como condicionais. Podemos usar o nível de indentação para determinar a qual instrução um valor pertence: ```yuescript if func 1, 2, 3, @@ -353,13 +353,13 @@ if func 1, 2, 3, -## Parameter Destructuring +## Desestruturação de parâmetros -YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: +YueScript agora suporta desestruturação de parâmetros de função quando o argumento é um objeto. Duas formas de literais de tabela de desestruturação estão disponíveis: -* **Curly-brace wrapped literals/object parameters**, allowing optional default values when fields are missing (e.g., `{:a, :b}`, `{a: a1 = 123}`). +* **Literais/parâmetros de objeto envolvidos em chaves**, permitindo valores padrão opcionais quando os campos estão ausentes (ex.: `{:a, :b}`, `{a: a1 = 123}`). -* **Unwrapped simple table syntax**, starting with a sequence of key-value or shorthand bindings and continuing until another expression terminates it (e.g., `:a, b: b1, :c`). This form extracts multiple fields from the same object. +* **Sintaxe de tabela simples não envolvida**, começando com uma sequência de ligações chave-valor ou abreviadas e continuando até outra expressão terminá-la (ex.: `:a, b: b1, :c`). Esta forma extrai múltiplos campos do mesmo objeto. ```yuescript f1 = (:a, :b, :c) -> @@ -390,9 +390,9 @@ f2 arg1, arg2 -## Prefixed Return Expression +## Expressão de retorno prefixada -When working with deeply nested function bodies, it can be tedious to maintain readability and consistency of the return value. To address this, YueScript introduces the **Prefixed Return Expression** syntax. Its form is as follows: +Ao trabalhar com corpos de função profundamente aninhados, pode ser tedioso manter a legibilidade e consistência do valor de retorno. Para resolver isso, YueScript introduz a sintaxe **Expressão de Retorno Prefixada**. Sua forma é a seguinte: ```yuescript findFirstEven = (list): nil -> @@ -415,7 +415,7 @@ findFirstEven = (list): nil -> -This is equivalent to: +Isso é equivalente a: ```yuescript findFirstEven = (list) -> @@ -440,16 +440,16 @@ findFirstEven = (list) -> -The only difference is that you can move the final return expression before the `->` or `=>` token to indicate the function’s implicit return value as the last statement. This way, even in functions with multiple nested loops or conditional branches, you no longer need to write a trailing return expression at the end of the function body, making the logic structure more straightforward and easier to follow. +A única diferença é que você pode mover a expressão de retorno final antes do token `->` ou `=>` para indicar o valor de retorno implícito da função como última instrução. Dessa forma, mesmo em funções com múltiplos loops aninhados ou ramificações condicionais, você não precisa mais escrever uma expressão de retorno no final do corpo da função, tornando a estrutura lógica mais direta e fácil de seguir. -## Named Varargs +## Varargs nomeados -You can use the `(...t) ->` syntax to automatically store varargs into a named table. This table will contain all passed arguments (including `nil` values), and the `n` field of the table will store the actual number of arguments passed (including `nil` values). +Você pode usar a sintaxe `(...t) ->` para armazenar automaticamente varargs em uma tabela nomeada. Esta tabela conterá todos os argumentos passados (incluindo valores `nil`), e o campo `n` da tabela armazenará o número real de argumentos passados (incluindo valores `nil`). ```yuescript f = (...t) -> - print "argument count:", t.n - print "table length:", #t + print "contagem de argumentos:", t.n + print "comprimento da tabela:", #t for i = 1, t.n print t[i] @@ -457,7 +457,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Tratando casos com valores nil process = (...args) -> sum = 0 for i = 1, args.n @@ -471,8 +471,8 @@ process 1, nil, 3, nil, 5 ```yue f = (...t) -> - print "argument count:", t.n - print "table length:", #t + print "contagem de argumentos:", t.n + print "comprimento da tabela:", #t for i = 1, t.n print t[i] @@ -480,7 +480,7 @@ f 1, 2, 3 f "a", "b", "c", "d" f! --- Handling cases with nil values +-- Tratando casos com valores nil process = (...args) -> sum = 0 for i = 1, args.n diff --git a/doc/docs/pt-br/doc/functions/function-stubs.md b/doc/docs/pt-br/doc/functions/function-stubs.md index 57a8b0c..d13f8ed 100644 --- a/doc/docs/pt-br/doc/functions/function-stubs.md +++ b/doc/docs/pt-br/doc/functions/function-stubs.md @@ -1,10 +1,10 @@ -# Function Stubs +# Stubs de função -It is common to pass a function from an object around as a value, for example, passing an instance method into a function as a callback. If the function expects the object it is operating on as the first argument then you must somehow bundle that object with the function so it can be called properly. +É comum passar uma função de um objeto como valor, por exemplo, passando um método de instância para uma função como callback. Se a função espera o objeto em que está operando como primeiro argumento, então você deve de alguma forma empacotar esse objeto com a função para que ela possa ser chamada corretamente. -The function stub syntax is a shorthand for creating a new closure function that bundles both the object and function. This new function calls the wrapped function in the correct context of the object. +A sintaxe de function stub é uma forma abreviada de criar uma nova função closure que empacota tanto o objeto quanto a função. Esta nova função chama a função empacotada no contexto correto do objeto. -Its syntax is the same as calling an instance method with the \ operator but with no argument list provided. +Sua sintaxe é a mesma que chamar um método de instância com o operador \, mas sem lista de argumentos fornecida. ```yuescript my_object = { @@ -16,12 +16,12 @@ run_callback = (func) -> print "running callback..." func! --- this will not work: --- the function has to no reference to my_object +-- isso não funcionará: +-- a função não tem referência a my_object run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- sintaxe de function stub +-- nos permite empacotar o objeto em uma nova função run_callback my_object\write ``` @@ -36,12 +36,12 @@ run_callback = (func) -> print "running callback..." func! --- this will not work: --- the function has to no reference to my_object +-- isso não funcionará: +-- a função não tem referência a my_object run_callback my_object.write --- function stub syntax --- lets us bundle the object into a new function +-- sintaxe de function stub +-- nos permite empacotar o objeto em uma nova função run_callback my_object\write ``` diff --git a/doc/docs/pt-br/doc/getting-started/installation.md b/doc/docs/pt-br/doc/getting-started/installation.md index a93ddfd..c5ee875 100644 --- a/doc/docs/pt-br/doc/getting-started/installation.md +++ b/doc/docs/pt-br/doc/getting-started/installation.md @@ -1,43 +1,43 @@ -# Installation +# Instalação -## Lua Module +## Módulo Lua -Install [luarocks](https://luarocks.org), a package manager for Lua modules. Then install it as a Lua module and executable with: +Instale o [luarocks](https://luarocks.org), um gerenciador de pacotes para módulos Lua. Em seguida, instale-o como módulo Lua e executável com: ```shell luarocks install yuescript ``` -Or you can build `yue.so` file with: +Ou você pode compilar o arquivo `yue.so` com: ```shell make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua ``` -Then get the binary file from path **bin/shared/yue.so**. +Depois, obtenha o arquivo binário no caminho **bin/shared/yue.so**. -## Build Binary Tool +## Compilar ferramenta binária -Clone this repo, then build and install executable with: +Clone este repositório e compile e instale o executável com: ```shell make install ``` -Build YueScript tool without macro feature: +Compilar a ferramenta YueScript sem o recurso de macro: ```shell make install NO_MACRO=true ``` -Build YueScript tool without built-in Lua binary: +Compilar a ferramenta YueScript sem o binário Lua embutido: ```shell make install NO_LUA=true ``` -## Download Precompiled Binary +## Baixar binário pré-compilado -You can download precompiled binary files, including binary executable files compatible with different Lua versions and library files. +Você pode baixar arquivos binários pré-compilados, incluindo executáveis compatíveis com diferentes versões do Lua e arquivos de biblioteca. -Download precompiled binary files from [here](https://github.com/IppClub/YueScript/releases). +Baixe os arquivos binários pré-compilados [aqui](https://github.com/IppClub/YueScript/releases). diff --git a/doc/docs/pt-br/doc/getting-started/introduction.md b/doc/docs/pt-br/doc/getting-started/introduction.md index a9a9389..8c3f30a 100644 --- a/doc/docs/pt-br/doc/getting-started/introduction.md +++ b/doc/docs/pt-br/doc/getting-started/introduction.md @@ -1,16 +1,16 @@ -# Introduction +# Introdução -YueScript is a dynamic language that compiles to Lua. And it's a [MoonScript](https://github.com/leafo/moonscript) dialect. The codes written in YueScript are expressive and extremely concise. And it is suitable for writing some changing application logic with more maintainable codes and runs in a Lua embeded environment such as games or website servers. +YueScript é uma linguagem dinâmica que compila para Lua. É um dialeto do [MoonScript](https://github.com/leafo/moonscript). O código escrito em YueScript é expressivo e extremamente conciso. É adequado para escrever lógica de aplicação variável com código mais manutenível e roda em ambientes Lua embutidos, como jogos ou servidores web. -Yue (月) is the name of moon in Chinese and it's pronounced as [jyɛ]. +Yue (月) é o nome da lua em chinês e é pronunciado como [jyɛ]. -## An Overview of YueScript +## Uma visão geral do YueScript ```yuescript --- import syntax +-- sintaxe de importação import p, to_lua from "yue" --- object literals +-- literais de objeto inventory = equipment: - "sword" @@ -21,7 +21,7 @@ inventory = - name: "bread" count: 3 --- list comprehension +-- compreensão de lista map = (arr, action) -> [action item for item in *arr] @@ -31,14 +31,14 @@ filter = (arr, cond) -> reduce = (arr, init, action): init -> init = action init, item for item in *arr --- pipe operator +-- operador pipe [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print --- metatable manipulation +-- manipulação de metatable apple = size: 15 : @@ -47,17 +47,17 @@ apple = with apple p .size, .color, . if .<>? --- js-like export syntax -export 🌛 = "月之脚本" +-- sintaxe de exportação estilo js +export 🌛 = "Script da Lua" ``` ```yue --- import syntax +-- sintaxe de importação import p, to_lua from "yue" --- object literals +-- literais de objeto inventory = equipment: - "sword" @@ -68,7 +68,7 @@ inventory = - name: "bread" count: 3 --- list comprehension +-- compreensão de lista map = (arr, action) -> [action item for item in *arr] @@ -78,14 +78,14 @@ filter = (arr, cond) -> reduce = (arr, init, action): init -> init = action init, item for item in *arr --- pipe operator +-- operador pipe [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print --- metatable manipulation +-- manipulação de metatable apple = size: 15 : @@ -94,12 +94,12 @@ apple = with apple p .size, .color, . if .<>? --- js-like export syntax -export 🌛 = "月之脚本" +-- sintaxe de exportação estilo js +export 🌛 = "Script da Lua" ``` -## About Dora SSR +## Sobre o Dora SSR -YueScript is being developed and maintained alongside the open-source game engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). It has been used to create engine tools, game demos and prototypes, validating its capabilities in real-world scenarios while enhancing the Dora SSR development experience. \ No newline at end of file +O YueScript está sendo desenvolvido e mantido em conjunto com o motor de jogo open-source [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). Tem sido usado para criar ferramentas do motor, demonstrações de jogos e protótipos, validando suas capacidades em cenários do mundo real e aprimorando a experiência de desenvolvimento do Dora SSR. diff --git a/doc/docs/pt-br/doc/getting-started/usage.md b/doc/docs/pt-br/doc/getting-started/usage.md index 45161c6..7653838 100644 --- a/doc/docs/pt-br/doc/getting-started/usage.md +++ b/doc/docs/pt-br/doc/getting-started/usage.md @@ -1,20 +1,20 @@ -# Usage +# Uso -## Lua Module +## Módulo Lua -Use YueScript module in Lua: +Use o módulo YueScript em Lua: -* **Case 1** +* **Caso 1** - Require "your_yuescript_entry.yue" in Lua. + Use require em "your_yuescript_entry.yue" no Lua. ```Lua require("yue")("your_yuescript_entry") ``` - And this code still works when you compile "your_yuescript_entry.yue" to "your_yuescript_entry.lua" in the same path. In the rest YueScript files just use the normal **require** or **import**. The code line numbers in error messages will also be handled correctly. + E esse código continua funcionando quando você compila "your_yuescript_entry.yue" para "your_yuescript_entry.lua" no mesmo caminho. Nos demais arquivos YueScript, use normalmente o **require** ou **import**. Os números de linha nas mensagens de erro também serão tratados corretamente. -* **Case 2** +* **Caso 2** - Require YueScript module and rewite message by hand. + Requerer o módulo YueScript e reescrever a mensagem manualmente. ```lua local yue = require("yue") @@ -26,9 +26,9 @@ Use YueScript module in Lua: end) ``` -* **Case 3** +* **Caso 3** - Use the YueScript compiler function in Lua. + Usar a função compiladora do YueScript em Lua. ```lua local yue = require("yue") @@ -48,9 +48,9 @@ Use YueScript module in Lua: }) ``` -## YueScript Tool +## Ferramenta YueScript -Use YueScript tool with: +Use a ferramenta YueScript com: ```shell > yue -h @@ -60,52 +60,53 @@ Usage: yue yue -w [] [options] yue - -Notes: - - '-' / '--' must be the first and only argument. - - '-o/--output' can not be used with multiple input files. - - '-w/--watch' can not be used with file input (directory only). - - with '-e/--execute', remaining tokens are treated as script args. - -Options: - -h, --help Show this help message and exit. - -e , --execute Execute a file or raw codes - -m, --minify Generate minified codes - -r, --rewrite Rewrite output to match original line numbers +Notas: + - '-' / '--' deve ser o primeiro e único argumento. + - '-o/--output' não pode ser usado com múltiplos arquivos de entrada. + - '-w/--watch' não pode ser usado com entrada de arquivo (apenas diretório). + - com '-e/--execute', os tokens restantes são tratados como argumentos do script. + +Opções: + -h, --help Mostrar esta mensagem de ajuda e sair. + -e , --execute Executar um arquivo ou código bruto + -m, --minify Gerar código minificado + -r, --rewrite Reescrever saída para corresponder aos números de linha originais -t , --output-to - Specify where to place compiled files - -o , --output Write output to file - -p, --print Write output to standard out - -b, --benchmark Dump compile time (doesn't write output) - -g, --globals Dump global variables used in NAME LINE COLUMN - -s, --spaces Use spaces in generated codes instead of tabs - -l, --line-numbers Write line numbers from source codes - -j, --no-implicit-return Disable implicit return at end of file - -c, --reserve-comments Reserve comments before statement from source codes + Especificar onde colocar os arquivos compilados + -o , --output Escrever saída em arquivo + -p, --print Escrever saída na saída padrão + -b, --benchmark Mostrar tempo de compilação (não grava saída) + -g, --globals Listar variáveis globais usadas em NOME LINHA COLUNA + -s, --spaces Usar espaços no código gerado em vez de tabulações + -l, --line-numbers Escrever números de linha do código fonte + -j, --no-implicit-return Desabilitar retorno implícito no final do arquivo + -c, --reserve-comments Preservar comentários antes de instruções do código fonte -w [], --watch [] - Watch changes and compile every file under directory - -v, --version Print version - - Read from standard in, print to standard out - (Must be first and only argument) - -- Same as '-' (kept for backward compatibility) - - --target Specify the Lua version that codes will be generated to - (version can only be 5.1 to 5.5) - --path Append an extra Lua search path string to package.path - --= Pass compiler option in key=value form (existing behavior) - - Execute without options to enter REPL, type symbol '$' - in a single line to start/stop multi-line mode + Observar alterações e compilar cada arquivo no diretório + -v, --version Imprimir versão + - Ler da entrada padrão, imprimir na saída padrão + (Deve ser o primeiro e único argumento) + -- Igual a '-' (mantido para compatibilidade retroativa) + + --target Especificar a versão do Lua para a qual o código será gerado + (a versão pode ser apenas 5.1 a 5.5) + --path Adicionar um caminho de busca Lua extra ao package.path + --= Passar opção do compilador no formato key=value (comportamento existente) + + Execute sem opções para entrar no REPL, digite o símbolo '$' + em uma única linha para iniciar/parar o modo multilinha ``` -Use cases: -Recursively compile every YueScript file with extension **.yue** under current path: **yue .** +Casos de uso: -Compile and save results to a target path: **yue -t /target/path/ .** +Compilar recursivamente todos os arquivos YueScript com extensão **.yue** no caminho atual: **yue .** -Compile and reserve debug info: **yue -l .** +Compilar e salvar resultados em um caminho de destino: **yue -t /target/path/ .** -Compile and generate minified codes: **yue -m .** +Compilar e preservar informações de debug: **yue -l .** -Execute raw codes: **yue -e 'print 123'** +Compilar e gerar código minificado: **yue -m .** -Execute a YueScript file: **yue -e main.yue** +Executar código bruto: **yue -e 'print 123'** + +Executar um arquivo YueScript: **yue -e main.yue** diff --git a/doc/docs/pt-br/doc/language-basics/attributes.md b/doc/docs/pt-br/doc/language-basics/attributes.md index e6fd5a7..8e27f21 100644 --- a/doc/docs/pt-br/doc/language-basics/attributes.md +++ b/doc/docs/pt-br/doc/language-basics/attributes.md @@ -1,21 +1,21 @@ -# Attributes +# Atributos -Syntax support for Lua 5.4 attributes. And you can still use both the `const` and `close` declaration and get constant check and scoped callback working when targeting Lua versions below 5.4. +Suporte de sintaxe para atributos do Lua 5.4. E você ainda pode usar tanto a declaração `const` quanto `close` e obter verificação de constante e callback com escopo funcionando ao direcionar para versões do Lua abaixo da 5.4. ```yuescript const a = 123 -close _ = : -> print "Out of scope." +close _ = : -> print "Fora do escopo." ``` ```yue const a = 123 -close _ = : -> print "Out of scope." +close _ = : -> print "Fora do escopo." ``` -You can do desctructuring with variables attributed as constant. +Você pode fazer desestruturação com variáveis atribuídas como constante. ```yuescript const {:a, :b, c, d} = tb @@ -30,7 +30,7 @@ const {:a, :b, c, d} = tb -You can also declare a global variable to be `const`. +Você também pode declarar uma variável global como `const`. ```yuescript global const Constant = 123 diff --git a/doc/docs/pt-br/doc/language-basics/comment.md b/doc/docs/pt-br/doc/language-basics/comment.md index b67c97d..ed3102d 100644 --- a/doc/docs/pt-br/doc/language-basics/comment.md +++ b/doc/docs/pt-br/doc/language-basics/comment.md @@ -1,13 +1,13 @@ -# Comment +# Comentário ```yuescript --- I am a comment +-- Eu sou um comentário str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Este é um comentário multilinha. +Está OK. +]] strA \ -- comentário 1 + .. strB \ -- comentário 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" @@ -15,13 +15,13 @@ func --[[port]] 3000, --[[ip]] "192.168.1.1" ```yue --- I am a comment +-- Eu sou um comentário str = --[[ -This is a multi-line comment. -It's OK. -]] strA \ -- comment 1 - .. strB \ -- comment 2 +Este é um comentário multilinha. +Está OK. +]] strA \ -- comentário 1 + .. strB \ -- comentário 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" diff --git a/doc/docs/pt-br/doc/language-basics/literals.md b/doc/docs/pt-br/doc/language-basics/literals.md index e097c62..b32b73a 100644 --- a/doc/docs/pt-br/doc/language-basics/literals.md +++ b/doc/docs/pt-br/doc/language-basics/literals.md @@ -1,33 +1,33 @@ -# Literals +# Literais -All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. +Todos os literais primitivos do Lua podem ser usados. Isso se aplica a números, strings, booleanos e **nil**. -Unlike Lua, Line breaks are allowed inside of single and double quote strings without an escape sequence: +Diferente do Lua, quebras de linha são permitidas dentro de strings com aspas simples e duplas sem sequência de escape: ```yuescript -some_string = "Here is a string - that has a line break in it." +some_string = "Aqui está uma string + que tem uma quebra de linha." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. -print "I am #{math.random! * 100}% sure." +-- Você pode misturar expressões em literais de string usando a sintaxe #{}. +-- Interpolação de string está disponível apenas em strings com aspas duplas. +print "Tenho #{math.random! * 100}% de certeza." ``` ```yue -some_string = "Here is a string - that has a line break in it." +some_string = "Aqui está uma string + que tem uma quebra de linha." --- You can mix expressions into string literals using #{} syntax. --- String interpolation is only available in double quoted strings. -print "I am #{math.random! * 100}% sure." +-- Você pode misturar expressões em literais de string usando a sintaxe #{}. +-- Interpolação de string está disponível apenas em strings com aspas duplas. +print "Tenho #{math.random! * 100}% de certeza." ``` -## Number Literals +## Literais numéricos -You can use underscores in a number literal to increase readability. +Você pode usar underscores em um literal numérico para aumentar a legibilidade. ```yuescript integer = 1_000_000 @@ -44,9 +44,9 @@ binary = 0B10011 -## YAML Multiline String +## String multilinha estilo YAML -The `|` prefix introduces a YAML-style multiline string literal: +O prefixo `|` introduz um literal de string multilinha no estilo YAML: ```yuescript str = | @@ -67,9 +67,9 @@ str = | -This allows writing structured multiline text conveniently. All line breaks and indentation are preserved relative to the first non-empty line, and expressions inside `#{...}` are interpolated automatically as `tostring(expr)`. +Isso permite escrever texto estruturado multilinha convenientemente. Todas as quebras de linha e indentação são preservadas em relação à primeira linha não vazia, e expressões dentro de `#{...}` são interpoladas automaticamente como `tostring(expr)`. -YAML Multiline String automatically detects the common leading whitespace prefix (minimum indentation across all non-empty lines) and removes it from all lines. This makes it easy to indent your code visually without affecting the resulting string content. +A string multilinha YAML detecta automaticamente o prefixo comum de espaço em branco à esquerda (indentação mínima em todas as linhas não vazias) e remove-o de todas as linhas. Isso facilita a indentação visual do seu código sem afetar o conteúdo da string resultante. ```yuescript fn = -> @@ -90,21 +90,21 @@ fn = -> -Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. +A indentação interna é preservada em relação ao prefixo comum removido, permitindo estruturas aninhadas limpas. -All special characters like quotes (`"`) and backslashes (`\`) in the YAMLMultiline block are automatically escaped so that the generated Lua string is syntactically valid and behaves as expected. +Todos os caracteres especiais como aspas (`"`) e barras invertidas (`\`) no bloco YAML Multiline são escapados automaticamente para que a string Lua gerada seja sintaticamente válida e se comporte como esperado. ```yuescript str = | path: "C:\Program Files\App" - note: 'He said: "#{Hello}!"' + note: 'Ele disse: "#{Hello}!"' ``` ```yue str = | path: "C:\Program Files\App" - note: 'He said: "#{Hello}!"' + note: 'Ele disse: "#{Hello}!"' ``` diff --git a/doc/docs/pt-br/doc/language-basics/operator.md b/doc/docs/pt-br/doc/language-basics/operator.md index 9a2e89b..aba9c50 100644 --- a/doc/docs/pt-br/doc/language-basics/operator.md +++ b/doc/docs/pt-br/doc/language-basics/operator.md @@ -1,6 +1,6 @@ -# Operator +# Operador -All of Lua's binary and unary operators are available. Additionally **!=** is as an alias for **~=**, and either **\\** or **::** can be used to write a chaining function call like `tb\func!` or `tb::func!`. And Yuescipt offers some other special operators to write more expressive codes. +Todos os operadores binários e unários do Lua estão disponíveis. Além disso, **!=** é um alias para **~=**, e **\\** ou **::** podem ser usados para escrever uma chamada de função encadeada como `tb\func!` ou `tb::func!`. E o YueScript oferece alguns outros operadores especiais para escrever códigos mais expressivos. ```yuescript tb\func! if tb ~= nil @@ -15,32 +15,32 @@ tb::func! if tb != nil -## Chaining Comparisons +## Comparações encadeadas -Comparisons can be arbitrarily chained: +Comparações podem ser encadeadas arbitrariamente: ```yuescript print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 --- output: true +-- saída: true a = 5 print 1 <= a <= 10 --- output: true +-- saída: true ``` ```yue print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 --- output: true +-- saída: true a = 5 print 1 <= a <= 10 --- output: true +-- saída: true ``` -Note the evaluation behavior of chained comparisons: +Observe o comportamento de avaliação das comparações encadeadas: ```yuescript v = (x) -> @@ -49,7 +49,7 @@ v = (x) -> print v(1) < v(2) <= v(3) --[[ - output: + saída: 2 1 3 @@ -58,7 +58,7 @@ print v(1) < v(2) <= v(3) print v(1) > v(2) <= v(3) --[[ - output: + saída: 2 1 false @@ -73,7 +73,7 @@ v = (x) -> print v(1) < v(2) <= v(3) --[[ - output: + saída: 2 1 3 @@ -82,7 +82,7 @@ print v(1) < v(2) <= v(3) print v(1) > v(2) <= v(3) --[[ - output: + saída: 2 1 false @@ -91,11 +91,11 @@ print v(1) > v(2) <= v(3) -The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) and v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `and` operator should be used explicitly. +A expressão do meio é avaliada apenas uma vez, em vez de duas vezes como seria se a expressão fosse escrita como `v(1) < v(2) and v(2) <= v(3)`. No entanto, a ordem das avaliações em uma comparação encadeada é indefinida. É fortemente recomendado não usar expressões com efeitos colaterais (como impressão) em comparações encadeadas. Se efeitos colaterais forem necessários, o operador de curto-circuito `and` deve ser usado explicitamente. -## Table Appending +## Anexar à tabela -The **[] =** operator is used to append values to tables. +O operador **[] =** é usado para anexar valores a tabelas. ```yuescript tab = [] @@ -110,13 +110,13 @@ tab[] = "Value" -You can also use the spread operator `...` to append all elements from one list to another: +Você também pode usar o operador spread `...` para anexar todos os elementos de uma lista a outra: ```yuescript tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA agora é [1, 2, 3, 4, 5, 6] ``` @@ -124,14 +124,14 @@ tbA[] = ...tbB tbA = [1, 2, 3] tbB = [4, 5, 6] tbA[] = ...tbB --- tbA is now [1, 2, 3, 4, 5, 6] +-- tbA agora é [1, 2, 3, 4, 5, 6] ``` -## Table Spreading +## Spread de tabela -You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. +Você pode concatenar tabelas de array ou tabelas hash usando o operador spread `...` antes de expressões em literais de tabela. ```yuescript parts = @@ -170,9 +170,9 @@ merge = {...a, ...b} -## Table Reversed Indexing +## Indexação reversa de tabela -You can use the **#** operator to get the last elements of a table. +Você pode usar o operador **#** para obter os últimos elementos de uma tabela. ```yuescript last = data.items[#] @@ -191,11 +191,11 @@ data.items[#] = 1 ## Metatable -The **<>** operator can be used as a shortcut for metatable manipulation. +O operador **<>** pode ser usado como atalho para manipulação de metatable. -### Metatable Creation +### Criação de metatable -Create normal table with empty bracekets **<>** or metamethod key which is surrounded by **<>**. +Crie tabela normal com chaves vazias **<>** ou chave de metamétodo cercada por **<>**. ```yuescript mt = {} @@ -203,14 +203,14 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- definir campo com variável de mesmo nome b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value -close _ = : -> print "out of scope" +close _ = : -> print "fora do escopo" ``` @@ -220,24 +220,24 @@ add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 - -- set field with variable of the same name + -- definir campo com variável de mesmo nome b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value -close _ = : -> print "out of scope" +close _ = : -> print "fora do escopo" ``` -### Metatable Accessing +### Acesso à metatable -Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. +Acesse a metatable com **<>** ou nome do metamétodo cercado por **<>** ou escrevendo alguma expressão em **<>**. ```yuescript --- create with metatable containing field "value" +-- criar com metatable contendo campo "value" tb = <"value">: 123 tb. = tb.<> print tb.value @@ -248,7 +248,7 @@ print tb.item ```yue --- create with metatable containing field "value" +-- criar com metatable contendo campo "value" tb = <"value">: 123 tb. = tb.<> print tb.value @@ -258,9 +258,9 @@ print tb.item -### Metatable Destructure +### Desestruturação de metatable -Destruct metatable with metamethod key surrounded by **<>**. +Desestruture a metatable com chave de metamétodo cercada por **<>**. ```yuescript {item, :new, :, : getter} = tb @@ -275,9 +275,9 @@ print item, new, close, getter -## Existence +## Existência -The **?** operator can be used in a variety of contexts to check for existence. +O operador **?** pode ser usado em diversos contextos para verificar existência. ```yuescript func?! @@ -312,16 +312,16 @@ with? io.open "test.txt", "w" -## Piping +## Pipe -Instead of a series of nested function calls, you can pipe values with operator **|>**. +Em vez de uma série de chamadas de função aninhadas, você pode encaminhar valores com o operador **|>**. ```yuescript "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder +1 |> print 2 -- insere o item do pipe como primeiro argumento +2 |> print 1, _, 3 -- pipe com um placeholder --- pipe expression in multiline +-- expressão pipe em multilinha readFile "example.txt" |> extract language, {} |> parse language @@ -333,9 +333,9 @@ readFile "example.txt" ```yue "hello" |> print -1 |> print 2 -- insert pipe item as the first argument -2 |> print 1, _, 3 -- pipe with a placeholder --- pipe expression in multiline +1 |> print 2 -- insere o item do pipe como primeiro argumento +2 |> print 1, _, 3 -- pipe com um placeholder +-- expressão pipe em multilinha readFile "example.txt" |> extract language, {} |> parse language @@ -346,9 +346,9 @@ readFile "example.txt" -## Nil Coalescing +## Coalescência de nil -The nil-coalescing operator **??** returns the value of its left-hand operand if it isn't **nil**; otherwise, it evaluates the right-hand operand and returns its result. The **??** operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-nil. +O operador de coalescência de nil **??** retorna o valor do operando esquerdo se não for **nil**; caso contrário, avalia o operando direito e retorna seu resultado. O operador **??** não avalia seu operando direito se o operando esquerdo avaliar para não-nil. ```yuescript local a, b, c, d a = b ?? c ?? d @@ -367,31 +367,31 @@ a ??= false -## Implicit Object +## Objeto implícito -You can write a list of implicit structures that starts with the symbol **\*** or **-** inside a table block. If you are creating implicit object, the fields of the object must be with the same indent. +Você pode escrever uma lista de estruturas implícitas que começa com o símbolo **\*** ou **-** dentro de um bloco de tabela. Se você está criando objeto implícito, os campos do objeto devem estar com a mesma indentação. ```yuescript --- assignment with implicit object +-- atribuição com objeto implícito list = * 1 * 2 * 3 --- function call with implicit object +-- chamada de função com objeto implícito func * 1 * 2 * 3 --- return with implicit object +-- retorno com objeto implícito f = -> return * 1 * 2 * 3 --- table with implicit object +-- tabela com objeto implícito tb = name: "abc" @@ -416,26 +416,26 @@ tb = ```yue --- assignment with implicit object +-- atribuição com objeto implícito list = * 1 * 2 * 3 --- function call with implicit object +-- chamada de função com objeto implícito func * 1 * 2 * 3 --- return with implicit object +-- retorno com objeto implícito f = -> return * 1 * 2 * 3 --- table with implicit object +-- tabela com objeto implícito tb = name: "abc" diff --git a/doc/docs/pt-br/doc/language-basics/whitespace.md b/doc/docs/pt-br/doc/language-basics/whitespace.md index d742a2b..df844f9 100644 --- a/doc/docs/pt-br/doc/language-basics/whitespace.md +++ b/doc/docs/pt-br/doc/language-basics/whitespace.md @@ -1,10 +1,10 @@ -# Whitespace +# Espaço em branco -YueScript is a whitespace significant language. You have to write some code block in the same indent with space **' '** or tab **'\t'** like function body, value list and some control blocks. And expressions containing different whitespaces might mean different things. Tab is treated like 4 space, but it's better not mix the use of spaces and tabs. +YueScript é uma linguagem sensível a espaço em branco. Você precisa escrever blocos de código na mesma indentação com espaço **' '** ou tabulação **'\t'**, como corpo de função, lista de valores e alguns blocos de controle. E expressões contendo diferentes espaços em branco podem significar coisas diferentes. Tabulação é tratada como 4 espaços, mas é melhor não misturar o uso de espaços e tabulações. -## Statement Separator +## Separador de instrução -A statement normally ends at a line break. You can also use a semicolon `;` to explicitly terminate a statement, which allows writing multiple statements on the same line: +Uma instrução normalmente termina em uma quebra de linha. Você também pode usar ponto e vírgula `;` para terminar explicitamente uma instrução, o que permite escrever múltiplas instruções na mesma linha: ```yuescript a = 1; b = 2; print a + b @@ -17,9 +17,9 @@ a = 1; b = 2; print a + b -## Multiline Chaining +## Encadeamento multilinha -You can write multi-line chaining function calls with a same indent. +Você pode escrever chamadas de função encadeadas em múltiplas linhas com a mesma indentação. ```yuescript Rx.Observable diff --git a/doc/docs/pt-br/doc/objects/object-oriented-programming.md b/doc/docs/pt-br/doc/objects/object-oriented-programming.md index 6a8559e..3d5f061 100644 --- a/doc/docs/pt-br/doc/objects/object-oriented-programming.md +++ b/doc/docs/pt-br/doc/objects/object-oriented-programming.md @@ -1,8 +1,8 @@ -# Object Oriented Programming +# Programação orientada a objetos -In these examples, the generated Lua code may appear overwhelming. It is best to focus on the meaning of the YueScript code at first, then look into the Lua code if you wish to know the implementation details. +Nestes exemplos, o código Lua gerado pode parecer avassalador. É melhor focar primeiro no significado do código YueScript e depois olhar o código Lua se desejar conhecer os detalhes da implementação. -A simple class: +Uma classe simples: ```yuescript class Inventory @@ -31,15 +31,15 @@ class Inventory -A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. +Uma classe é declarada com uma instrução class seguida de uma declaração semelhante a tabela onde todos os métodos e propriedades são listados. -The new property is special in that it will become the constructor. +A propriedade new é especial pois se tornará o construtor. -Notice how all the methods in the class use the fat arrow function syntax. When calling methods on a instance, the instance itself is sent in as the first argument. The fat arrow handles the creation of a self argument. +Observe como todos os métodos da classe usam a sintaxe de função seta fat. Ao chamar métodos em uma instância, a própria instância é enviada como primeiro argumento. A seta fat cuida da criação do argumento self. -The @ prefix on a variable name is shorthand for self.. @items becomes self.items. +O prefixo @ em um nome de variável é abreviação para self.. @items torna-se self.items. -Creating an instance of the class is done by calling the name of the class as a function. +Criar uma instância da classe é feito chamando o nome da classe como uma função. ```yuescript inv = Inventory! @@ -56,11 +56,11 @@ inv\add_item "pants" -Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. +Como a instância da classe precisa ser enviada aos métodos quando são chamados, o operador \ é usado. -All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur. +Todas as propriedades de uma classe são compartilhadas entre as instâncias. Isso é bom para funções, mas para outros tipos de objetos, resultados indesejados podem ocorrer. -Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another: +Considere o exemplo abaixo, a propriedade clothes é compartilhada entre todas as instâncias, então modificações nela em uma instância aparecerão em outra: ```yuescript class Person @@ -74,7 +74,7 @@ b = Person! a\give_item "pants" b\give_item "shirt" --- will print both pants and shirt +-- vai imprimir tanto pants quanto shirt print item for item in *a.clothes ``` @@ -91,13 +91,13 @@ b = Person! a\give_item "pants" b\give_item "shirt" --- will print both pants and shirt +-- vai imprimir tanto pants quanto shirt print item for item in *a.clothes ``` -The proper way to avoid this problem is to create the mutable state of the object in the constructor: +A forma correta de evitar esse problema é criar o estado mutável do objeto no construtor: ```yuescript class Person @@ -114,9 +114,9 @@ class Person -## Inheritance +## Herança -The extends keyword can be used in a class declaration to inherit the properties and methods from another class. +A palavra-chave extends pode ser usada em uma declaração de classe para herdar as propriedades e métodos de outra classe. ```yuescript class BackPack extends Inventory @@ -137,18 +137,18 @@ class BackPack extends Inventory -Here we extend our Inventory class, and limit the amount of items it can carry. +Aqui estendemos nossa classe Inventory e limitamos a quantidade de itens que ela pode carregar. -In this example, we don't define a constructor on the subclass, so the parent class' constructor is called when we make a new instance. If we did define a constructor then we can use the super method to call the parent constructor. +Neste exemplo, não definimos um construtor na subclasse, então o construtor da classe pai é chamado quando criamos uma nova instância. Se definirmos um construtor, podemos usar o método super para chamar o construtor pai. -Whenever a class inherits from another, it sends a message to the parent class by calling the method __inherited on the parent class if it exists. The function receives two arguments, the class that is being inherited and the child class. +Sempre que uma classe herda de outra, ela envia uma mensagem à classe pai chamando o método __inherited na classe pai se ele existir. A função recebe dois argumentos: a classe que está sendo herdada e a classe filha. ```yuescript class Shelf @__inherited: (child) => print @__name, "was inherited by", child.__name --- will print: Shelf was inherited by Cupboard +-- vai imprimir: Shelf was inherited by Cupboard class Cupboard extends Shelf ``` @@ -158,7 +158,7 @@ class Shelf @__inherited: (child) => print @__name, "was inherited by", child.__name --- will print: Shelf was inherited by Cupboard +-- vai imprimir: Shelf was inherited by Cupboard class Cupboard extends Shelf ``` @@ -166,27 +166,27 @@ class Cupboard extends Shelf ## Super -**super** is a special keyword that can be used in two different ways: It can be treated as an object, or it can be called like a function. It only has special functionality when inside a class. +**super** é uma palavra-chave especial que pode ser usada de duas formas diferentes: pode ser tratado como um objeto, ou pode ser chamado como uma função. Só tem funcionalidade especial quando está dentro de uma classe. -When called as a function, it will call the function of the same name in the parent class. The current self will automatically be passed as the first argument. (As seen in the inheritance example above) +Quando chamado como função, chamará a função de mesmo nome na classe pai. O self atual será automaticamente passado como primeiro argumento. (Como visto no exemplo de herança acima) -When super is used as a normal value, it is a reference to the parent class object. +Quando super é usado como valor normal, é uma referência ao objeto da classe pai. -It can be accessed like any of object in order to retrieve values in the parent class that might have been shadowed by the child class. +Pode ser acessado como qualquer objeto para recuperar valores na classe pai que possam ter sido sombreados pela classe filha. -When the \ calling operator is used with super, self is inserted as the first argument instead of the value of super itself. When using . to retrieve a function, the raw function is returned. +Quando o operador de chamada \ é usado com super, self é inserido como primeiro argumento em vez do valor do próprio super. Ao usar . para recuperar uma função, a função bruta é retornada. -A few examples of using super in different ways: +Alguns exemplos de uso de super de diferentes formas: ```yuescript class MyClass extends ParentClass a_method: => - -- the following have the same effect: + -- os seguintes têm o mesmo efeito: super "hello", "world" super\a_method "hello", "world" super.a_method self, "hello", "world" - -- super as a value is equal to the parent class: + -- super como valor é igual à classe pai: assert super == ParentClass ``` @@ -194,28 +194,28 @@ class MyClass extends ParentClass ```yue class MyClass extends ParentClass a_method: => - -- the following have the same effect: + -- os seguintes têm o mesmo efeito: super "hello", "world" super\a_method "hello", "world" super.a_method self, "hello", "world" - -- super as a value is equal to the parent class: + -- super como valor é igual à classe pai: assert super == ParentClass ``` -**super** can also be used on left side of a Function Stub. The only major difference is that instead of the resulting function being bound to the value of super, it is bound to self. +**super** também pode ser usado no lado esquerdo de um Function Stub. A única diferença principal é que, em vez da função resultante estar vinculada ao valor de super, ela está vinculada a self. -## Types +## Tipos -Every instance of a class carries its type with it. This is stored in the special __class property. This property holds the class object. The class object is what we call to build a new instance. We can also index the class object to retrieve class methods and properties. +Cada instância de uma classe carrega seu tipo consigo. Isso é armazenado na propriedade especial __class. Esta propriedade contém o objeto da classe. O objeto da classe é o que chamamos para construir uma nova instância. Também podemos indexar o objeto da classe para recuperar métodos e propriedades da classe. ```yuescript b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- imprime 10 ``` @@ -223,45 +223,45 @@ print BackPack.size -- prints 10 b = BackPack! assert b.__class == BackPack -print BackPack.size -- prints 10 +print BackPack.size -- imprime 10 ``` -## Class Objects +## Objetos de classe -The class object is what we create when we use a class statement. The class object is stored in a variable of the same name of the class. +O objeto da classe é o que criamos quando usamos uma instrução class. O objeto da classe é armazenado em uma variável com o mesmo nome da classe. -The class object can be called like a function in order to create new instances. That's how we created instances of classes in the examples above. +O objeto da classe pode ser chamado como uma função para criar novas instâncias. É assim que criamos instâncias de classes nos exemplos acima. -A class is made up of two tables. The class table itself, and the base table. The base is used as the metatable for all the instances. All properties listed in the class declaration are placed in the base. +Uma classe é composta por duas tabelas. A própria tabela da classe e a tabela base. A base é usada como metatable para todas as instâncias. Todas as propriedades listadas na declaração da classe são colocadas na base. -The class object's metatable reads properties from the base if they don't exist in the class object. This means we can access functions and properties directly from the class. +A metatable do objeto da classe lê propriedades da base se não existirem no objeto da classe. Isso significa que podemos acessar funções e propriedades diretamente da classe. -It is important to note that assigning to the class object does not assign into the base, so it's not a valid way to add new methods to instances. Instead the base must explicitly be changed. See the __base field below. +É importante notar que atribuir ao objeto da classe não atribui à base, então não é uma forma válida de adicionar novos métodos às instâncias. Em vez disso, a base deve ser alterada explicitamente. Veja o campo __base abaixo. -The class object has a couple special properties: +O objeto da classe tem algumas propriedades especiais: -The name of the class as when it was declared is stored as a string in the __name field of the class object. +O nome da classe quando foi declarada é armazenado como string no campo __name do objeto da classe. ```yuescript -print BackPack.__name -- prints Backpack +print BackPack.__name -- imprime Backpack ``` ```yue -print BackPack.__name -- prints Backpack +print BackPack.__name -- imprime Backpack ``` -The base object is stored in __base. We can modify this table to add functionality to instances that have already been created and ones that are yet to be created. +O objeto base é armazenado em __base. Podemos modificar esta tabela para adicionar funcionalidade a instâncias que já foram criadas e às que ainda serão criadas. -If the class extends from anything, the parent class object is stored in __parent. +Se a classe estende de algo, o objeto da classe pai é armazenado em __parent. -## Class Variables +## Variáveis de classe -We can create variables directly in the class object instead of in the base by using @ in the front of the property name in a class declaration. +Podemos criar variáveis diretamente no objeto da classe em vez da base usando @ na frente do nome da propriedade em uma declaração de classe. ```yuescript class Things @@ -269,7 +269,7 @@ class Things Things\some_func! --- class variables not visible in instances +-- variáveis de classe não visíveis em instâncias assert Things().some_func == nil ``` @@ -280,13 +280,13 @@ class Things Things\some_func! --- class variables not visible in instances +-- variáveis de classe não visíveis em instâncias assert Things().some_func == nil ``` -In expressions, we can use @@ to access a value that is stored in the __class of self. Thus, @@hello is shorthand for self.__class.hello. +Em expressões, podemos usar @@ para acessar um valor armazenado no __class de self. Assim, @@hello é abreviação para self.__class.hello. ```yuescript class Counter @@ -298,7 +298,7 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- imprime 2 ``` @@ -312,12 +312,12 @@ class Counter Counter! Counter! -print Counter.count -- prints 2 +print Counter.count -- imprime 2 ``` -The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. +A semântica de chamada de @@ é semelhante a @. Chamar um nome @@ passará a classe como primeiro argumento usando a sintaxe de dois pontos do Lua. ```yuescript @@hello 1,2,3,4 @@ -330,11 +330,11 @@ The calling semantics of @@ are similar to @. Calling a @@ name will pass the cl -## Class Declaration Statements +## Instruções de declaração de classe -In the body of a class declaration, we can have normal expressions in addition to key/value pairs. In this context, self is equal to the class object. +No corpo de uma declaração de classe, podemos ter expressões normais além de pares chave/valor. Neste contexto, self é igual ao objeto da classe. -Here is an alternative way to create a class variable compared to what's described above: +Aqui está uma forma alternativa de criar variável de classe comparada ao descrito acima: ```yuescript class Things @@ -349,9 +349,9 @@ class Things -These expressions are executed after all the properties have been added to the base. +Estas expressões são executadas após todas as propriedades terem sido adicionadas à base. -All variables declared in the body of the class are local to the classes properties. This is convenient for placing private values or helper functions that only the class methods can access: +Todas as variáveis declaradas no corpo da classe são locais às propriedades da classe. Isso é conveniente para colocar valores privados ou funções auxiliares que apenas os métodos da classe podem acessar: ```yuescript class MoreThings @@ -374,11 +374,11 @@ class MoreThings -## @ and @@ Values +## Valores @ e @@ -When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.__class. +Quando @ e @@ são prefixados na frente de um nome, eles representam, respectivamente, esse nome acessado em self e self.__class. -If they are used all by themselves, they are aliases for self and self.__class. +Se forem usados sozinhos, são aliases para self e self.__class. ```yuescript assert @ == self @@ -393,7 +393,7 @@ assert @@ == self.__class -For example, a quick way to create a new instance of the same class from an instance method using @@: +Por exemplo, uma forma rápida de criar uma nova instância da mesma classe a partir de um método de instância usando @@: ```yuescript some_instance_method = (...) => @@ ... @@ -406,15 +406,15 @@ some_instance_method = (...) => @@ ... -## Constructor Property Promotion +## Promoção de propriedade no construtor -To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: +Para reduzir o código repetitivo na definição de objetos de valor simples. Você pode escrever uma classe simples como: ```yuescript class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- O que é abreviação para class Something new: (foo, bar, biz, baz) => @@ -429,7 +429,7 @@ class Something class Something new: (@foo, @bar, @@biz, @@baz) => --- Which is short for +-- O que é abreviação para class Something new: (foo, bar, biz, baz) => @@ -441,7 +441,7 @@ class Something -You can also use this syntax for a common function to initialize a object's fields. +Você também pode usar esta sintaxe para uma função comum para inicializar os campos de um objeto. ```yuescript new = (@fieldA, @fieldB) => @ @@ -458,9 +458,9 @@ print obj -## Class Expressions +## Expressões de classe -The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. +A sintaxe de classe também pode ser usada como expressão que pode ser atribuída a uma variável ou retornada explicitamente. ```yuescript x = class Bucket @@ -477,9 +477,9 @@ x = class Bucket -## Anonymous classes +## Classes anônimas -The name can be left out when declaring a class. The __name attribute will be nil, unless the class expression is in an assignment. The name on the left hand side of the assignment is used instead of nil. +O nome pode ser omitido ao declarar uma classe. O atributo __name será nil, a menos que a expressão da classe esteja em uma atribuição. O nome no lado esquerdo da atribuição é usado em vez de nil. ```yuescript BigBucket = class extends Bucket @@ -498,7 +498,7 @@ assert Bucket.__name == "BigBucket" -You can even leave off the body, meaning you can write a blank anonymous class like this: +Você pode até omitir o corpo, significando que pode escrever uma classe anônima em branco assim: ```yuescript x = class @@ -511,9 +511,9 @@ x = class -## Class Mixing +## Mistura de classes -You can do mixing with keyword `using` to copy functions from either a plain table or a predefined class object into your new class. When doing mixing with a plain table, you can override the class indexing function (metamethod `__index`) to your customized implementation. When doing mixing with an existing class object, the class object's metamethods won't be copied. +Você pode fazer mistura com a palavra-chave `using` para copiar funções de uma tabela simples ou de um objeto de classe predefinido para sua nova classe. Ao fazer mistura com uma tabela simples, você pode sobrescrever a função de indexação da classe (metamétodo `__index`) para sua implementação personalizada. Ao fazer mistura com um objeto de classe existente, os metamétodos do objeto da classe não serão copiados. ```yuescript MyIndex = __index: var: 1 @@ -530,7 +530,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X não é pai de Y ``` @@ -549,7 +549,7 @@ class Y using X y = Y! y\func! -assert y.__class.__parent ~= X -- X is not parent of Y +assert y.__class.__parent ~= X -- X não é pai de Y ``` diff --git a/doc/docs/pt-br/doc/objects/with-statement.md b/doc/docs/pt-br/doc/objects/with-statement.md index 7786803..6495d09 100644 --- a/doc/docs/pt-br/doc/objects/with-statement.md +++ b/doc/docs/pt-br/doc/objects/with-statement.md @@ -1,13 +1,12 @@ -# With Statement +# Instrução With +Um padrão comum envolvendo a criação de um objeto é chamar uma série de funções e definir uma série de propriedades imediatamente após criá-lo. -A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it. +Isso resulta em repetir o nome do objeto várias vezes no código, adicionando ruído desnecessário. Uma solução comum para isso é passar uma tabela como argumento que contém uma coleção de chaves e valores para sobrescrever. O inconveniente é que o construtor desse objeto deve suportar essa forma. -This results in repeating the name of the object multiple times in code, adding unnecessary noise. A common solution to this is to pass a table in as an argument which contains a collection of keys and values to overwrite. The downside to this is that the constructor of this object must support this form. +O bloco with ajuda a aliviar isso. Dentro de um bloco with podemos usar instruções especiais que começam com . ou \ que representam essas operações aplicadas ao objeto com o qual estamos usando with. -The with block helps to alleviate this. Within a with block we can use a special statements that begin with either . or \ which represent those operations applied to the object we are using with on. - -For example, we work with a newly created object: +Por exemplo, trabalhamos com um objeto recém-criado: ```yuescript with Person! @@ -28,7 +27,7 @@ with Person! -The with statement can also be used as an expression which returns the value it has been giving access to. +A instrução with também pode ser usada como expressão que retorna o valor ao qual foi dado acesso. ```yuescript file = with File "favorite_foods.txt" @@ -43,7 +42,7 @@ file = with File "favorite_foods.txt" -Or… +Ou… ```yuescript create_person = (name, relatives) -> @@ -66,9 +65,9 @@ me = create_person "Leaf", [dad, mother, sister] -In this usage, with can be seen as a special form of the K combinator. +Neste uso, with pode ser visto como uma forma especial do combinador K. -The expression in the with statement can also be an assignment, if you want to give a name to the expression. +A expressão na instrução with também pode ser uma atribuição, se você quiser dar um nome à expressão. ```yuescript with str := "Hello" @@ -85,7 +84,7 @@ with str := "Hello" -You can access special keys with `[]` in a `with` statement. +Você pode acessar chaves especiais com `[]` em uma instrução `with`. ```yuescript with tb @@ -94,7 +93,7 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- anexando a "tb" ``` @@ -105,12 +104,12 @@ with tb with [abc] [3] = [2]\func! ["key-name"] = value - [] = "abc" -- appending to "tb" + [] = "abc" -- anexando a "tb" ``` -`with?` is an enhanced version of `with` syntax, which introduces an existential check to safely access objects that may be nil without explicit null checks. +`with?` é uma versão aprimorada da sintaxe `with`, que introduz uma verificação existencial para acessar com segurança objetos que podem ser nil sem verificações explícitas de null. ```yuescript with? obj diff --git a/doc/docs/pt-br/doc/reference/license-mit.md b/doc/docs/pt-br/doc/reference/license-mit.md index f1d5d60..0e00e90 100644 --- a/doc/docs/pt-br/doc/reference/license-mit.md +++ b/doc/docs/pt-br/doc/reference/license-mit.md @@ -1,23 +1,21 @@ -# License: MIT +# Licença: MIT Copyright (c) 2017-2026 Li Jin \ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +A permissão é concedida, gratuitamente, a qualquer pessoa que obtenha uma cópia +deste software e dos arquivos de documentação associados (o "Software"), para negociar +o Software sem restrições, incluindo, sem limitação, os direitos de usar, copiar, +modificar, mesclar, publicar, distribuir, sublicenciar e/ou vender +cópias do Software, e permitir que pessoas a quem o Software seja fornecido o façam, +sujeito às seguintes condições: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +O aviso de direitos autorais acima e este aviso de permissão devem ser incluídos em todas as +cópias ou partes substanciais do Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - +O SOFTWARE É FORNECIDO "NO ESTADO EM QUE SE ENCONTRA", SEM GARANTIA DE QUALQUER TIPO, +EXPRESSA OU IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO, +ADEQUAÇÃO A UM DETERMINADO FIM E NÃO VIOLAÇÃO. EM NENHUMA HIPÓTESE OS AUTORES OU +DETENTORES DOS DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUAISQUER REIVINDICAÇÕES, +DANOS OU OUTRAS RESPONSABILIDADES, SEJA EM UMA AÇÃO DE CONTRATO, ATO ILÍCITO OU OUTRA, +DECORRENTES DE, FORA DE OU RELACIONADAS COM O SOFTWARE OU O USO OU OUTRAS NEGOCIAÇÕES +NO SOFTWARE. diff --git a/doc/docs/pt-br/doc/reference/the-yuescript-library.md b/doc/docs/pt-br/doc/reference/the-yuescript-library.md index 3761755..2a65ffb 100644 --- a/doc/docs/pt-br/doc/reference/the-yuescript-library.md +++ b/doc/docs/pt-br/doc/reference/the-yuescript-library.md @@ -1,61 +1,61 @@ -# The YueScript Library +# A biblioteca YueScript -Access it by `local yue = require("yue")` in Lua. +Acesse com `local yue = require("yue")` no Lua. ## yue -**Description:** +**Descrição:** -The YueScript language library. +A biblioteca da linguagem YueScript. ### version -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The YueScript version. +A versão do YueScript. -**Signature:** +**Assinatura:** ```lua version: string ``` ### dirsep -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The file separator for the current platform. +O separador de arquivos da plataforma atual. -**Signature:** +**Assinatura:** ```lua dirsep: string ``` ### yue_compiled -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The compiled module code cache. +O cache de código de módulo compilado. -**Signature:** +**Assinatura:** ```lua yue_compiled: {string: string} ``` ### to_lua -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The YueScript compiling function. It compiles the YueScript code to Lua code. +A função de compilação do YueScript. Compila o código YueScript para código Lua. -**Signature:** +**Assinatura:** ```lua to_lua: function(code: string, config?: Config): --[[codes]] string | nil, @@ -63,682 +63,682 @@ to_lua: function(code: string, config?: Config): --[[globals]] {{string, integer, integer}} | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| code | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| code | string | O código YueScript. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string \| nil | The compiled Lua code, or nil if the compilation failed. | -| string \| nil | The error message, or nil if the compilation succeeded. | -| {{string, integer, integer}} \| nil | The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. | +| string \| nil | O código Lua compilado, ou nil se a compilação falhou. | +| string \| nil | A mensagem de erro, ou nil se a compilação foi bem-sucedida. | +| {{string, integer, integer}} \| nil | As variáveis globais que aparecem no código (com nome, linha e coluna), ou nil se a opção do compilador `lint_global` for false. | ### file_exist -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The source file existence checking function. Can be overridden to customize the behavior. +Função de verificação de existência do arquivo fonte. Pode ser sobrescrita para personalizar o comportamento. -**Signature:** +**Assinatura:** ```lua file_exist: function(filename: string): boolean ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | O nome do arquivo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the file exists. | +| boolean | Se o arquivo existe. | ### read_file -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The source file reading function. Can be overridden to customize the behavior. +Função de leitura do arquivo fonte. Pode ser sobrescrita para personalizar o comportamento. -**Signature:** +**Assinatura:** ```lua read_file: function(filename: string): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | +| filename | string | O nome do arquivo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The file content. | +| string | O conteúdo do arquivo. | ### insert_loader -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Insert the YueScript loader to the package loaders (searchers). +Insere o carregador YueScript nos carregadores de pacote (searchers). -**Signature:** +**Assinatura:** ```lua insert_loader: function(pos?: integer): boolean ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| pos | integer | [Optional] The position to insert the loader. Default is 3. | +| pos | integer | [Opcional] A posição para inserir o carregador. Padrão é 3. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the loader is inserted successfully. It will fail if the loader is already inserted. | +| boolean | Se o carregador foi inserido com sucesso. Falhará se o carregador já estiver inserido. | ### remove_loader -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Remove the YueScript loader from the package loaders (searchers). +Remove o carregador YueScript dos carregadores de pacote (searchers). -**Signature:** +**Assinatura:** ```lua remove_loader: function(): boolean ``` -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the loader is removed successfully. It will fail if the loader is not inserted. | +| boolean | Se o carregador foi removido com sucesso. Falhará se o carregador não estiver inserido. | ### loadstring -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a string into a function. +Carrega código YueScript de uma string em uma função. -**Signature:** +**Assinatura:** ```lua loadstring: function(input: string, chunkname: string, env: table, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| input | string | O código YueScript. | +| chunkname | string | O nome do chunk de código. | +| env | table | A tabela de ambiente. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadstring -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a string into a function. +Carrega código YueScript de uma string em uma função. -**Signature:** +**Assinatura:** ```lua loadstring: function(input: string, chunkname: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| input | string | The YueScript code. | -| chunkname | string | The name of the code chunk. | -| config | Config | [Optional] The compiler options. | +| input | string | O código YueScript. | +| chunkname | string | O nome do chunk de código. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadstring -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a string into a function. +Carrega código YueScript de uma string em uma função. -**Signature:** +**Assinatura:** ```lua loadstring: function(input: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| input | string | The YueScript code. | -| config | Config | [Optional] The compiler options. | +| input | string | O código YueScript. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadfile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function. +Carrega código YueScript de um arquivo em uma função. -**Signature:** +**Assinatura:** ```lua loadfile: function(filename: string, env: table, config?: Config): nil | function(...: any): (any...), string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| env | table | A tabela de ambiente. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### loadfile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function. +Carrega código YueScript de um arquivo em uma função. -**Signature:** +**Assinatura:** ```lua loadfile: function(filename: string, config?: Config): nil | function(...: any): (any...), string | nil ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| function \| nil | The loaded function, or nil if the loading failed. | -| string \| nil | The error message, or nil if the loading succeeded. | +| function \| nil | A função carregada, ou nil se o carregamento falhou. | +| string \| nil | A mensagem de erro, ou nil se o carregamento foi bem-sucedido. | ### dofile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function and executes it. +Carrega código YueScript de um arquivo em uma função e o executa. -**Signature:** +**Assinatura:** ```lua dofile: function(filename: string, env: table, config?: Config): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| env | table | The environment table. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| env | table | A tabela de ambiente. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Os valores de retorno da função carregada. | ### dofile -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads YueScript code from a file into a function and executes it. +Carrega código YueScript de um arquivo em uma função e o executa. -**Signature:** +**Assinatura:** ```lua dofile: function(filename: string, config?: Config): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| filename | string | The file name. | -| config | Config | [Optional] The compiler options. | +| filename | string | O nome do arquivo. | +| config | Config | [Opcional] As opções do compilador. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any... | The return values of the loaded function. | +| any... | Os valores de retorno da função carregada. | ### find_modulepath -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Resolves the YueScript module name to the file path. +Resolve o nome do módulo YueScript para o caminho do arquivo. -**Signature:** +**Assinatura:** ```lua find_modulepath: function(name: string): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| name | string | The module name. | +| name | string | O nome do módulo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The file path. | +| string | O caminho do arquivo. | ### pcall -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Calls a function in protected mode. -Catches any errors and returns a status code and results or error object. -Rewrites the error line number to the original line number in the YueScript code when errors occur. +Chama uma função em modo protegido. +Captura quaisquer erros e retorna um código de status e resultados ou objeto de erro. +Reescreve o número da linha do erro para o número da linha original no código YueScript quando ocorrem erros. -**Signature:** +**Assinatura:** ```lua pcall: function(f: function, ...: any): boolean, any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| f | function | The function to call. | -| ... | any | Arguments to pass to the function. | +| f | function | A função a chamar. | +| ... | any | Argumentos a passar para a função. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean, ... | Status code and function results or error object. | +| boolean, ... | Código de status e resultados da função ou objeto de erro. | ### require -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Loads a given module. Can be either a Lua module or a YueScript module. -Rewrites the error line number to the original line number in the YueScript code if the module is a YueScript module and loading fails. +Carrega um módulo dado. Pode ser um módulo Lua ou um módulo YueScript. +Reescreve o número da linha do erro para o número da linha original no código YueScript se o módulo for um módulo YueScript e o carregamento falhar. -**Signature:** +**Assinatura:** ```lua require: function(name: string): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| modname | string | The name of the module to load. | +| modname | string | O nome do módulo a carregar. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any | The value stored at package.loaded[modname] if the module is already loaded.Otherwise, tries to find a loader and returns the final value of package.loaded[modname] and a loader data as a second result. | +| any | O valor armazenado em package.loaded[modname] se o módulo já estiver carregado. Caso contrário, tenta encontrar um carregador e retorna o valor final de package.loaded[modname] e os dados do carregador como segundo resultado. | ### p -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Inspects the structures of the passed values and prints string representations. +Inspeciona as estruturas dos valores passados e imprime representações em string. -**Signature:** +**Assinatura:** ```lua p: function(...: any) ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| ... | any | The values to inspect. | +| ... | any | Os valores a inspecionar. | ### options -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The current compiler options. +As opções atuais do compilador. -**Signature:** +**Assinatura:** ```lua options: Config.Options ``` ### traceback -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -The traceback function that rewrites the stack trace line numbers to the original line numbers in the YueScript code. +A função traceback que reescreve os números das linhas do stack trace para os números das linhas originais no código YueScript. -**Signature:** +**Assinatura:** ```lua traceback: function(message: string): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| message | string | The traceback message. | +| message | string | A mensagem de traceback. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The rewritten traceback message. | +| string | A mensagem de traceback reescrita. | ### is_ast -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Checks whether the code matches the specified AST. +Verifica se o código corresponde ao AST especificado. -**Signature:** +**Assinatura:** ```lua is_ast: function(astName: string, code: string): boolean ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| astName | string | The AST name. | -| code | string | The code. | +| astName | string | O nome do AST. | +| code | string | O código. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| boolean | Whether the code matches the AST. | +| boolean | Se o código corresponde ao AST. | ### AST -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The AST type definition with name, row, column and sub nodes. +A definição do tipo AST com nome, linha, coluna e subnós. -**Signature:** +**Assinatura:** ```lua type AST = {string, integer, integer, any} ``` ### to_ast -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Converts the code to the AST. +Converte o código para o AST. -**Signature:** +**Assinatura:** ```lua to_ast: function(code: string, flattenLevel?: number, astName?: string, reserveComment?: boolean): --[[AST]] AST | nil, --[[error]] nil | string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| code | string | The code. | -| flattenLevel | integer | [Optional] The flatten level. Higher level means more flattening. Default is 0. Maximum is 2. | -| astName | string | [Optional] The AST name. Default is "File". | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is false. | +| code | string | O código. | +| flattenLevel | integer | [Opcional] O nível de achatamento. Nível mais alto significa mais achatamento. Padrão é 0. Máximo é 2. | +| astName | string | [Opcional] O nome do AST. Padrão é "File". | +| reserveComment | boolean | [Opcional] Se deve preservar os comentários originais. Padrão é false. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| AST \| nil | The AST, or nil if the conversion failed. | -| string \| nil | The error message, or nil if the conversion succeeded. | +| AST \| nil | O AST, ou nil se a conversão falhou. | +| string \| nil | A mensagem de erro, ou nil se a conversão foi bem-sucedida. | ### format -**Type:** Function. +**Tipo:** Função. -**Description:** +**Descrição:** -Formats the YueScript code. +Formata o código YueScript. -**Signature:** +**Assinatura:** ```lua format: function(code: string, tabSize?: number, reserveComment?: boolean): string ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| code | string | The code. | -| tabSize | integer | [Optional] The tab size. Default is 4. | -| reserveComment | boolean | [Optional] Whether to reserve the original comments. Default is true. | +| code | string | O código. | +| tabSize | integer | [Opcional] O tamanho da tabulação. Padrão é 4. | +| reserveComment | boolean | [Opcional] Se deve preservar os comentários originais. Padrão é true. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| string | The formatted code. | +| string | O código formatado. | ### __call -**Type:** Metamethod. +**Tipo:** Metamétodo. -**Description:** +**Descrição:** -Requires the YueScript module. -Rewrites the error line number to the original line number in the YueScript code when loading fails. +Requer o módulo YueScript. +Reescreve o número da linha do erro para o número da linha original no código YueScript quando o carregamento falha. -**Signature:** +**Assinatura:** ```lua metamethod __call: function(self: yue, module: string): any... ``` -**Parameters:** +**Parâmetros:** -| Parameter | Type | Description | +| Parâmetro | Tipo | Descrição | | --- | --- | --- | -| module | string | The module name. | +| module | string | O nome do módulo. | -**Returns:** +**Retorna:** -| Return Type | Description | +| Tipo de Retorno | Descrição | | --- | --- | -| any | The module value. | +| any | O valor do módulo. | ## Config -**Description:** +**Descrição:** -The compiler compile options. +As opções de compilação do compilador. ### lint_global -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should collect the global variables appearing in the code. +Se o compilador deve coletar as variáveis globais que aparecem no código. -**Signature:** +**Assinatura:** ```lua lint_global: boolean ``` ### implicit_return_root -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should do an implicit return for the root code block. +Se o compilador deve fazer retorno implícito para o bloco de código raiz. -**Signature:** +**Assinatura:** ```lua implicit_return_root: boolean ``` ### reserve_line_number -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should reserve the original line number in the compiled code. +Se o compilador deve preservar o número da linha original no código compilado. -**Signature:** +**Assinatura:** ```lua reserve_line_number: boolean ``` ### reserve_comment -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should reserve the original comments in the compiled code. +Se o compilador deve preservar os comentários originais no código compilado. -**Signature:** +**Assinatura:** ```lua reserve_comment: boolean ``` ### space_over_tab -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should use the space character instead of the tab character in the compiled code. +Se o compilador deve usar o caractere de espaço em vez do caractere de tabulação no código compilado. -**Signature:** +**Assinatura:** ```lua space_over_tab: boolean ``` ### same_module -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler should treat the code to be compiled as the same currently being compiled module. For internal use only. +Se o compilador deve tratar o código a ser compilado como o mesmo módulo que está sendo compilado atualmente. Apenas para uso interno. -**Signature:** +**Assinatura:** ```lua same_module: boolean ``` ### line_offset -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether the compiler error message should include the line number offset. For internal use only. +Se a mensagem de erro do compilador deve incluir o deslocamento do número da linha. Apenas para uso interno. -**Signature:** +**Assinatura:** ```lua line_offset: integer ``` ### yue.Config.LuaTarget -**Type:** Enumeration. +**Tipo:** Enumeração. -**Description:** +**Descrição:** -The target Lua version enumeration. +A enumeração da versão alvo do Lua. -**Signature:** +**Assinatura:** ```lua enum LuaTarget "5.1" @@ -751,71 +751,71 @@ end ### options -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The extra options to be passed to the compilation function. +As opções extras a serem passadas para a função de compilação. -**Signature:** +**Assinatura:** ```lua options: Options ``` ## Options -**Description:** +**Descrição:** -The extra compiler options definition. +A definição das opções extras do compilador. ### target -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The target Lua version for the compilation. +A versão alvo do Lua para a compilação. -**Signature:** +**Assinatura:** ```lua target: LuaTarget ``` ### path -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -The extra module search path. +O caminho de busca de módulo extra. -**Signature:** +**Assinatura:** ```lua path: string ``` ### dump_locals -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether to dump the local variables in the traceback error message. Default is false. +Se deve incluir as variáveis locais na mensagem de erro do traceback. Padrão é false. -**Signature:** +**Assinatura:** ```lua dump_locals: boolean ``` ### simplified -**Type:** Field. +**Tipo:** Campo. -**Description:** +**Descrição:** -Whether to simplify the error message. Default is true. +Se deve simplificar a mensagem de erro. Padrão é true. -**Signature:** +**Assinatura:** ```lua simplified: boolean ``` -- cgit v1.2.3-55-g6feb