O Roblox usa o idioma de programação Luau. Os seguintes exemplos de código e tabelas indicam algumas das diferenças entre as sínteses para C# e Luau.
Finais de linha
Você não precisa de vírgulas em Luau, mas elas não quebram a sintaxe.
Palavras-chave reservadas
A tabela a seguir tem as palavras-chave reservadas do Luau mapeadas para o seu equivalente em C#. Observe que não mostra todas as palavras-chave em C#.
Luau | C# |
---|---|
and | |
break | break |
do | do |
if | if |
else | else |
elseif | else if |
then | |
end | |
true | true |
false | false |
for | for or foreach |
function | |
in | in |
local | |
nil | null |
not | |
or | |
repeat | |
return | return |
until | |
while | while |
Comentários
Comentários em Luau
-- Comentário de uma linha comentar--[[ saídaresultante:Block comment--]]
Comments in C#
// Single line comment/*Block comment*/
Cordas
Cordas em Luau
-- string / cadeia / textomultilinhalocal multiLineString = [[This is a string that,when printed, appearson multiple lines]]-- Concatenaçãolocal s1 = "This is a string "local s2 = "made with two parts."local endString = s1 .. s2
Strings in C#
// Multi-line stringstring multiLineString1 = "This is a string that,\nwhen printed, appears\n on multiple lines.";string multiLineString2 = @"This is a string that,when printed, appearson multiple lines";// Concatenationstring s1 = "This is a string ";string s2 = "made with two parts.";string endString = s1 + s2;
Tabelas
Para aprender mais sobre tabelas em Luau, veja Tabelas.
Tabelas de dicionário
Você pode usar tabelas em Luau como dicionários assim como em C#.
Tabelas de dicionário em Luau
local dictionary = {val1 = "this",val2 = "is"}print(dictionary.val1) -- Produz 'this'print(dictionary["val1"]) -- Produz 'this'dictionary.val1 = nil -- Remove 'val1' da tabeladictionary["val3"] = "a dictionary" -- Overwrites 'val3' or sets new key-value pair
Dictionary Tables in C#
Dictionary dictionary = new Dictionary(){{ "val1", "this" },{ "val2", "is" }};Console.WriteLine(dictionary["val1"]); // Outputs 'this'dictionary.Remove("val1"); // Removes 'val1' from dictionarydictionary["val3"] = "a dictionary"; // Overwrites 'val3' or sets new key-value pairdictionary.Add("val3", "a dictionary"); // Creates a new key-value pair
Tabelas numericamente indexadas
Você pode usar tabelas em Luau como arrays exatamente como no C#. Os índices começam em 1 em Luau e 0 em C#.
Tabelas Numericamente Indexadas em Luau
local npcAttributes = {"strong", "intelligent"}print(npcAttributes[1]) -- Produz 'forte'print(#npcAttributes) -- Exibe o tamanho da lista-- Apêndice à listatable.insert(npcAttributes, "humble")-- Outra maneira...npcAttributes[#npcAttributes+1] = "humble"-- Inserir no início da listatable.insert(npcAttributes, 1, "brave")-- Remover item em um índice dadotable.remove(npcAttributes, 3)
Numerically-Indexed Tables in C#
List npcAttributes = new List{"strong", "intelligent"};Console.WriteLine(npcAttributes[0]); // Outputs 'strong'Console.WriteLine(npcAttributes.Count); // Outputs the size of the list// Append to the listnpcAttributes.Add("humble");// Another way...npcAttributes.Insert(npcAttributes.Count, "humble");// Insert at the beginning of the listnpcAttributes.Insert(0, "brave");// Remove item at a given indexnpcAttributes.Remove(2);
Operadores
Operadores condicionais
Operador | Luau | C# |
---|---|---|
Equivalente a | == | == |
Maior que | > | > |
Menos que | < | < |
Maior que ou igual a | >= | >= |
Menos de ou igual a | <= | <= |
Não é igual a | ~= | != |
E | and | && |
Or | or | || |
Operadores aritméticos
Luau | C# | |
---|---|---|
Adição | + | + |
Subtração | - | - |
Multiplicação | * | * |
Divisão | / | / |
Módulo | % | % |
Exponenciação | ^ | ** |
Variáveis
Em Luau, variáveis não especificam seu tipo quando você as declara.As variáveis Luau não têm modificadores de acesso, embora você possa prefixar variáveis "privado" com um sublinhado para legibilidade.
Variáveis em Luau
local stringVariable = "value"-- Declaração "Pública"local variableName-- Declaração "Privada" - processada da mesma maneiralocal _variableName
Variables in C#
string stringVariable = "value";// Public declarationpublic string variableName// Private declarationstring variableName;
Escopo
Em Luau, você pode escrever variáveis e lógica em um escopo mais apertado do que sua função ou classe por meio de aninhamento de lógica dentro de do e end palavras-chave, semelhante a curly brackets {} em C#.Para mais detalhes, veja Escopo.
Delimitação em Luau
local outerVar = 'Outer scope text'do-- Modificar 'outerVar'outerVar = 'Inner scope modified text'-- Introduzir uma variável locallocal innerVar = 'Inner scope text'print('1: ' .. outerVar) -- imprime "1: Texto modificado de escopo interno"print('2: ' .. innerVar) -- imprime "2: Texto de escopo interno"endprint('3: ' .. outerVar) -- imprime "3: "Texto modificado de escopo interno"-- Attempting to print 'innerVar' here would fail
Scoping in C#
var outerVar = "Outer scope text";{// Modify 'outerVar'outerVar = "Inner scope modified text";// Introduce a local variablevar innerVar = "Inner scope text";Console.WriteLine("1: " + outerVar); // prints "1: Inner scope modified text"Console.WriteLine("2: " + innerVar); // prints "2: Inner scope text"}Console.WriteLine("3: " + outerVar); // prints "3: "Inner scope modified text"// Attempting to print 'innerVar' here would fail
Declarações condicionais
Declarações condicionais em Luau
-- Uma condiçãoif boolExpression thendoSomething()end-- Várias condiçõesif not boolExpression thendoSomething()elseif otherBoolExpression thendoSomething()elsedoSomething()end
Conditional Statements in C#
// One conditionif (boolExpression) {doSomething();}// Multiple conditionsif (!boolExpression) {doSomething();}else if (otherBoolExpression) {doSomething();}else {doSomething();}
Operador condicional
Operador condicional em Luau
local max = if x > y then x else y
Conditional Operator in C#
int max = (x > y) ? x : y;
Ciclos
Para aprender mais sobre loops em Luau, veja Estruturas de Controle.
Enquanto e repetir loops
Ciclos While e Repeat em Luau
while boolExpression dodoSomething()endrepeatdoSomething()until not boolExpression
While and Repeat Loops in C#
while (boolExpression) {doSomething();}do {doSomething();} while (boolExpression)
Para loops
Genérico para Laços em Luau
-- Ciclo em frentefor i = 1, 10 dodoSomething()end-- Ciclo reversofor i = 10, 1, -1 dodoSomething()end
Generic For Loops in C#
// Forward loopfor (int i = 1; i <= 10; i++) {doSomething();}// Reverse loopfor (int i = 10; i >= 1; i--) {doSomething();}
Para Laços Sobre Mesas em Luau
local abcList = {"a", "b", "c"}for i, v in ipairs(abcList) doprint(v)endlocal abcDictionary = { a=1, b=2, c=3 }for k, v in pairs(abcDictionary) doprint(k, v)end
For Loops Over Lists in C#
List<string> abcList = new List<string>{"a", "b", "c"};foreach (string v in abcList) {Console.WriteLine(v);}Dictionary<string, int> abcDictionary = new Dictionary<string, int>{ {"a", 1}, {"b", 2}, {"c", 3} };foreach (KeyValuePair<string, int> entry in abcDictionary) {Console.WriteLine(entry.Key + " " + entry.Value);}
O Luau também suporta iteração geralizada, o que simplifica ainda mais o trabalho com tabelas.
Funções
Para aprender mais sobre funções em Luau, veja Funções.
Funções genéricas
Funções genéricas em Luau
-- Função genérica
local function increment(number)
return number + 1
end
Generic Functions in C#
// Generic function
int increment(int number) {
return number + 1;
}
Número de argumento variável
Número de argumento variável em Luau
-- Número de argumento variável
local function variableArguments(...)
print(...)
end
Variable Argument Number in C#
// Variable argument number
void variableArguments(params string[] inventoryItems) {
for (item in inventoryItems) {
Console.WriteLine(item);
}
}
Argutos nomeados
Argumentos Nomeados em Luau
-- Argutos nomeados
local function namedArguments(args)
return args.name .. "'s birthday: " .. args.dob
end
namedArguments{name="Bob", dob="4/1/2000"}
Named Arguments in C#
// Named arguments
string namedArguments(string name, string dob) {
return name + "'s birthday: " + dob;
}
namedArguments(name: "Bob", dob: "4/1/2000");
Estruturas de captura de tentativa
Tentar/Capturar Estruturas em Luau
local function fireWeapon()
if not weaponEquipped then
error("No weapon equipped!")
end
-- Continuar...
end
local success, errorMessage = pcall(fireWeapon)
if not success then
print(errorMessage)
end
Try/Catch Structures in C#
void fireWeapon() {
if (!weaponEquipped) {
// Use a user-defined exception
throw new InvalidWeaponException("No weapon equipped!");
}
// Proceed...
}
try {
fireWeapon();
} catch (InvalidWeaponException ex) {
// An error was raised
}