运算符

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

An operator is a symbol for performing an operation or conditional evaluation.

逻辑

逻辑运算符根据给定参数的布尔值返回值。如果参数不是 falsenil,则运算符将其评估为 true。与许多其他语言不同,Luau 将零和空字符串视为 true。以下表格总结了逻辑运算符在 条件语句 中的行为。

运算符描述
and仅在两个条件都为真时评估为 true
or如果任一条件为真,则评估为 true
not评估为条件的相反值

and

二元运算符 and 返回两个参数中的一个。如果第一个参数评估为 true,则返回第二个参数。否则,它返回第一个参数。


print(4 and 5) -- 5
print(nil and 12) -- nil
print(false and 12) -- false
print(false and true) -- false
print(false and false) -- false
print(true and false) -- false
print(true and true) -- true

您可以使用 and控制结构 中测试多个条件,例如 if 语句while 循环。例如,以下 ifthen 语句测试两个条件是否都为真:


local pasta = true
local tomatoSauce = true
if pasta == true and tomatoSauce == true then
print("我们有意大利面晚餐")
else
print("缺少一些东西...")
end
-- 输出: 我们有意大利面晚餐

or

二元运算符 or 返回两个参数中的一个。如果第一个参数评估为 true,则返回第一个参数。否则,它返回第二个参数。


local y = x or 1
print(y) -- 1,因为 x 不存在,所以是 nil
local d = false
local e = d or 1
print(e) -- 1,因为 d 为 false
print(4 or 5) -- 4
print(nil or 12) -- 12
print(false or 12) -- 12
print(false or true) -- true
print(false or false) -- false
print(true or false) -- true
print(true or true) -- true

您可以使用 or控制结构 中执行复杂的逻辑测试。例如,以下 ifthen 语句测试两个条件是否为真 第三个条件是否为真:


local pasta = false
local tomatoSauce = true
local garlicBread = true
if (pasta == true and tomatoSauce == true) or garlicBread == true then
print("我们有意大利面晚餐或大蒜面包")
else
print("缺少一些东西...")
end
-- 输出: 我们有意大利面晚餐或大蒜面包

not

一元运算符 not 返回参数的相反布尔值。如果参数为 falsenil,则返回 true。否则,返回 false


print(not true) -- false
print(not false) -- true
print(not nil) -- true
print(not "text") -- false
print(not 0) -- false

您可以使用 not 运算符在变量为 falsenil 时触发条件或循环。


local nilVariable -- 变量被声明但没有值,因此是 nil
local falseVariable = false -- 变量被声明为 false 的值
if not nilVariable then
print(nilVariable) -- 输出 "nil" 因为 nil 不是 true
end
if not falseVariable then
print(falseVariable) -- 输出 "false" 因为 false 不是 true
end

您还可以使用 not 运算符测试整个多条件语句的相反。在以下代码示例中,ifthen 条件测试三大于四和五大于四均不为真。


local three = 3
local four = 4
local five = 5
if not (three > four or five < four) then
print("三小于4,且五大于4。")
end
-- 输出: 三小于4,且五大于4。

关系运算符

关系运算符比较两个参数并返回一个 booleantruefalse

运算符描述示例相关元方法
==等于3 == 5false__eq
~=不等于3 ~= 5true
>大于3 > 5false
<小于3 < 5true__lt
>=大于或等于3 >= 5false
<=小于或等于3 <= 5true__le

算术

Luau 支持通常的二元运算符,以及指数运算、取模和一元取反。

运算符描述示例相关元方法
+加法1 + 1 = 2__add
-减法1 - 1 = 0__sub
*乘法5 * 5 = 25__mul
/除法10 / 5 = 2__div
//向下取整除法

10 // 4 = 2
-10 // 4 = -3

__idiv
^乘方运算2 ^ 4 = 16__pow
%取模13 % 7 = 6__mod
-一元取反-2 = 0 - 2__unm

复合赋值

您可以使用复合赋值运算符将变量设置为操作结果,操作的第一个参数是变量的当前值。

复合赋值中的操作发生一次。例如,如果一个表达式在一个表中生成一个随机索引,Luau 将在操作和赋值中使用相同的索引。

在以下示例中,假设 local x = 3

运算符操作示例新值的 x
+=加法x += 25
-=减法x -= 21
*=乘法x *= 26
/=除法x /= 21.5
//=向下取整除法x //= 21
%=取模x %= 21
^=乘方运算x ^= 29
..=字符串连接x ..= " World!" "3 World!"

其他

其他运算符包括 字符串连接长度

运算符描述示例相关元方法
..连接两个字符串print("你好 " .. "世界!")__concat
#表的长度如果 tableVar = {1, 2, 3},则 #tableVar == 3__len
©2026 Roblox Corporation、Roblox、Roblox 标志及 Powering Imagination 是我们在美国及其他国家或地区的注册与未注册商标。