So sánh Luau và C#

*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.

Roblox sử dụng ngôn ngữ lập trình Luau. Các ví dụ mã và bảng sau đây cho thấy một số sự khác biệt giữa cú pháp cho C# và Luau.

Kết thúc dòng

Bạn không cần dấu phân cách trong Luau, nhưng chúng không vi phạm ngữ pháp.

Từ khóa được dự trữ

Bảng sau đây có các từ khóa được dự trữ của Luau được định vị tương đương với C#. Lưu ý rằng nó không hiển thị tất cả các từ khóa C#.

LuauC#
and
breakbreak
dodo
ifif
elseelse
elseifelse if
then
end
truetrue
falsefalse
forfor or foreach
function
inin
local
nilnull
not
or
repeat
returnreturn
until
whilewhile

Bình luận

Bình luận trong Luau

-- Bình bình luậndòng đơn
--[[ Kết quả ra:
Block comment
--]]
Comments in C#

// Single line comment
/*
Block comment
*/

Chuỗi

Chuỗi trong Luau

-- Chuỗi nhiều chuỗi
local multiLineString = [[This is a string that,
when printed, appears
on multiple lines]]
-- Sự kết hợp
local s1 = "This is a string "
local s2 = "made with two parts."
local endString = s1 .. s2
Strings in C#

// Multi-line string
string multiLineString1 = "This is a string that,\nwhen printed, appears\n on multiple lines.";
string multiLineString2 = @"This is a string that,
when printed, appears
on multiple lines";
// Concatenation
string s1 = "This is a string ";
string s2 = "made with two parts.";
string endString = s1 + s2;

Bảng

Để tìm hiểu thêm về các bảng trong Luau, xem Bảng.

Bảng từ điển

Bạn có thể sử dụng bảng trong Luau như là bách khoa toàn thư giống như trong C#.

Bảng từ điển trong Luau

local dictionary = {
val1 = "this",
val2 = "is"
}
print(dictionary.val1) -- Xuất 'this'
print(dictionary["val1"]) -- Xuất 'this'
dictionary.val1 = nil -- Loại bỏ 'val1' khỏi bảng
dictionary["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 dictionary
dictionary["val3"] = "a dictionary"; // Overwrites 'val3' or sets new key-value pair
dictionary.Add("val3", "a dictionary"); // Creates a new key-value pair

Bảng được đánh số theo thứ tự

Bạn có thể sử dụng các bảng trong Luau như mảng chỉ như trong C#. Chỉ mục bắt đầu tại 1 trong Luau và 0 trong C#.

Bảng được chỉ mục số trong Luau

local npcAttributes = {"strong", "intelligent"}
print(npcAttributes[1]) -- Xuất 'mạnh'
print(#npcAttributes) -- Xuất kích thước của danh sách
-- Thêm vào danh sách
table.insert(npcAttributes, "humble")
-- Cách khác...
npcAttributes[#npcAttributes+1] = "humble"
-- Chèn vào đầu danh sách
table.insert(npcAttributes, 1, "brave")
-- Loại bỏ mục tại một chỉ mục cụ thể
table.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 list
npcAttributes.Add("humble");
// Another way...
npcAttributes.Insert(npcAttributes.Count, "humble");
// Insert at the beginning of the list
npcAttributes.Insert(0, "brave");
// Remove item at a given index
npcAttributes.Remove(2);

Nhà điều hành

Các đối tượng điều kiện

Nhà điều hànhLuauC#
Bằng với====
Lớn hơn>>
Nhỏ hơn<<
Lớn hơn hoặc bằng>=>=
Nhỏ hơn hoặc bằng<=<=
Không bằng với~=!=
and&&
Oror||

Các phép toán học

LuauC#
Thêm++
Trừ bớt--
Nhân lên**
Sư đoàn//
Modulus Nhân%%
Nhân số lũy thừa^**

Biến

Trong Luau, biến không xác định loại của chúng khi bạn tuyên bố chúng.Biến Luau không có modifier truy cập, mặc dù bạn có thể đặt trước biến "riêng tư" với một dấu gạch ngang để dễ đọc.

Biến trong Luau

local stringVariable = "value"
-- Tuyên bố "Công cộng"
local variableName
-- Tuyên bố "Riêng tư" - được phân tích theo cùng một cách
local _variableName
Variables in C#

string stringVariable = "value";
// Public declaration
public string variableName
// Private declaration
string variableName;

Phạm vi

Trong Luau, bạn có thể viết các biến và logic trong phạm vi chặt chẽ hơn chức năng hoặc lớp của họ bằng cách lồng logic trong và từ khóa, tương tự như dấu ngoặc cong trong C#.Để biết thêm chi tiết, xem Phạm vi .

Phạm vi trong Luau

local outerVar = 'Outer scope text'
do
-- Sửa 'outerVar'
outerVar = 'Inner scope modified text'
-- Giới thiệu một biến địa phương
local innerVar = 'Inner scope text'
print('1: ' .. outerVar) -- in "1: Văn bản sửa đổi phạm vi bên trong"
print('2: ' .. innerVar) -- in "2: Văn bản phạm vi bên trong"
end
print('3: ' .. outerVar) -- in "3: "Văn bản sửa đổi phạm vi bên trong"
-- 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 variable
var 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

Tuyên bố điều kiện

Tuyên bố điều kiện trong Luau

-- Một điều kiện
if boolExpression then
doSomething()
end
-- Nhiều điều kiện
if not boolExpression then
doSomething()
elseif otherBoolExpression then
doSomething()
else
doSomething()
end
Conditional Statements in C#

// One condition
if (boolExpression) {
doSomething();
}
// Multiple conditions
if (!boolExpression) {
doSomething();
}
else if (otherBoolExpression) {
doSomething();
}
else {
doSomething();
}

Nhà điều kiện

Nhà vận hành điều kiện trong Luau

local max = if x > y then x else y
Conditional Operator in C#

int max = (x > y) ? x : y;

Vòng lặp

Để tìm hiểu thêm về vòng lặp trong Luau, xem Cấu trúc điều khiển .

Trong khi và lặp lại vòng lặp

Trong khi và lặp lại vòng trong Luau

while boolExpression do
doSomething()
end
repeat
doSomething()
until not boolExpression
While and Repeat Loops in C#

while (boolExpression) {
doSomething();
}
do {
doSomething();
} while (boolExpression)

Đối với vòng lặp

Thông thường cho vòng lặp trong Luau

-- Vòng lặp tiếp theo
for i = 1, 10 do
doSomething()
end
-- Vòng lặp ngược
for i = 10, 1, -1 do
doSomething()
end
Generic For Loops in C#

// Forward loop
for (int i = 1; i <= 10; i++) {
doSomething();
}
// Reverse loop
for (int i = 10; i >= 1; i--) {
doSomething();
}
Đối với vòng lặp trên các bảng trong Luau

local abcList = {"a", "b", "c"}
for i, v in ipairs(abcList) do
print(v)
end
local abcDictionary = { a=1, b=2, c=3 }
for k, v in pairs(abcDictionary) do
print(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 cũng hỗ trợ lặp lại chung, làm cho việc làm việc với bảng trở nên đơn giản hơn.

Chức năng

Để tìm hiểu thêm về chức năng trong Luau, xem Chức năng.

Chức năng chung

Chức năng chung trong Luau

-- Chức năng chung
local function increment(number)
return number + 1
end
Generic Functions in C#

// Generic function
int increment(int number) {
return number + 1;
}

Số tham số biến

Số tham số biến trong Luau

-- Số tham số biến
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);
}
}

Các tham số có tên

Luận định các tham số trong Luau

-- Các tham số có tên
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");

Cấu trúc thử bắt

Thử/Bắt cấu trúc trong Luau

local function fireWeapon()
if not weaponEquipped then
error("No weapon equipped!")
end
-- Tiếp tục...
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
}