Roblox usa el lenguaje de programación Luau. Los siguientes ejemplos de código y tablas indican algunas de las diferencias entre las sintaxis para C# y Luau.
Finales de línea
No necesitas comas en Luau, pero no rompen la sintaxis.
Palabras reservadas
La siguiente tabla tiene las palabras reservadas de Luau mapeadas a su equivalente de C#. Tenga en cuenta que no muestra todas las palabras reservadas de 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 |
Comentarios
Comentarios en Luau
-- hacer un comentariode una sola línea--[[ Resultado de Salida:Block comment--]]
Comments in C#
// Single line comment/*Block comment*/
Cuerdas
Cuerdas en Luau
-- Texto de múltiples cadenalocal multiLineString = [[This is a string that,when printed, appearson multiple lines]]-- Concatenaciónlocal 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;
Tablas
Para aprender más sobre tablas en Luau, vea Tablas.
Tablas de diccionario
Puedes usar tablas en Luau como diccionarios al igual que en C#.
Tablas de diccionario en Luau
local dictionary = {val1 = "this",val2 = "is"}print(dictionary.val1) -- Produce 'esto'print(dictionary["val1"]) -- Produce 'esto'dictionary.val1 = nil -- Elimina 'val1' de la tabladictionary["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
Tablas numéricamente indexadas
Puedes usar tablas en Luau como arrays al igual que en C#. Los índices comienzan en 1 en Luau y 0 en C#.
Tablas numéricamente indexadas en Luau
local npcAttributes = {"strong", "intelligent"}print(npcAttributes[1]) -- Produce 'fuerte'print(#npcAttributes) -- Muestra el tamaño de la lista-- Añadir a la listatable.insert(npcAttributes, "humble")-- Otra manera...npcAttributes[#npcAttributes+1] = "humble"-- Insertar al comienzo de la listatable.insert(npcAttributes, 1, "brave")-- Quitar ítem en un í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 condicionales
Operador | Luau | C# |
---|---|---|
Igual a | == | == |
Más grande que | > | > |
Menos de | < | < |
Mayor que o igual a | >= | >= |
Menos de o igual a | <= | <= |
No es igual a | ~= | != |
Y | and | && |
Or | or | || |
Operadores aritméticos
Luau | C# | |
---|---|---|
Adición | + | + |
Restitución | - | - |
Multiplicación | * | * |
División | / | / |
Módulo | % | % |
Exponenciación | ^ | ** |
Variables
En Luau, las variables no especifican su tipo cuando las declaras.Las variables Luau no tienen modificadores de acceso, aunque puedes preфиjar las variables "servidor privado" con una barra oblicua para la legibilidad.
Variables en Luau
local stringVariable = "value"-- Declaración "Pública"local variableName-- Declaración "Privada" - se analizó de la misma maneralocal _variableName
Variables in C#
string stringVariable = "value";// Public declarationpublic string variableName// Private declarationstring variableName;
Alcance
En Luau, puedes escribir variables y lógica en un alcance más estricto que su función o clase al anidar la lógica dentro de do y end palabras clave, similar a los corchetes curly {} en C#.Para más detalles, vea alcance.
Delimitación en Luau
local outerVar = 'Outer scope text'do-- Modificar 'outerVar'outerVar = 'Inner scope modified text'-- Introducir una variable locallocal innerVar = 'Inner scope text'print('1: ' .. outerVar) -- imprime "1: Texto modificado de alcance interno"print('2: ' .. innerVar) -- imprime "2: Texto del alcance interno"endprint('3: ' .. outerVar) -- imprime "3: "Texto modificado de alcance 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
Declaraciones condicionales
Declaraciones condicionales en Luau
-- Una condiciónif boolExpression thendoSomething()end-- Múltiples condicionesif 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 en Luau
local max = if x > y then x else y
Conditional Operator in C#
int max = (x > y) ? x : y;
Bucles
Para aprender más sobre bucles en Luau, vea Estructuras de control.
Mientras y repita bucles
Bucles mientras y repetición en Luau
while boolExpression dodoSomething()endrepeatdoSomething()until not boolExpression
While and Repeat Loops in C#
while (boolExpression) {doSomething();}do {doSomething();} while (boolExpression)
Para bucles
Genérico para bucles en Luau
-- Bucle hacia adelantefor i = 1, 10 dodoSomething()end-- Bucle inversofor 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 bucles sobre tablas en 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);}
Luau también soporta iteración generalizada , lo que simplifica aún más el trabajo con tablas.
Funciones
Para aprender más sobre funciones en Luau, vea Funciones.
Funciones genéricas
Funciones generales en Luau
-- Función 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 variable
Número de argumento variable en Luau
-- Número de argumento variable
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);
}
}
Argumentos nominales
Argumentos nominales en Luau
-- Argumentos nominales
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");
Estructuras de atrape-prueba
Probar/Capturar estructuras en Luau
local function fireWeapon()
if not weaponEquipped then
error("No weapon equipped!")
end
-- Proceder...
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
}