类型强制

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

如果 Luau 尝试在操作中使用值或 变量 (例如 算术连接分配 ),但值不是操作所期望的类型,那么 Luau 将( 强制 )将值转换为更改其数据输入。强制发生在运行时对该操作,并不会改变变量的值。

算法

Luau强制字符串转换为数字在 算术操作 。该行为已集成到 Luau 中。如果类型不兼容于算术,Luau 将抛出错误,并不运行剩余的脚本。例如,如果字符串不代表数字,你不能将字符串添加到数字上。


print(100 + "7") -- 107
print(100 - "7") -- 93
print("1000" + 234) -- 1234
print("1000" - 234) -- 766
print("hello" + 234) -- error: attempt to perform arithmetic (add) string and number

连接方式

在 concatenation 中,Luau 强制数字转换为字符串。要无需使用强制转换将数字转换为字符串,请使用 string.format() 函数。


print("Pi is " .. math.pi) --> Pi 是 3.1415926535898
print("Pi is " .. 3.1415927) --> Pi 是 3.1415927
-- 回合到三位数字位置
print("Pi is " .. string.format("%.3f", 3.1415927)) -- Pi is 3.142

分配

有些属性期望特定数据类型,例如 Enum 或字符串,但您可以将不同类型的值分配给它,Luau将值转换为属性所期望的类型。

枚数

Luau强制枚举值的数字和字符串转换为完整的枚举名称。例如,你可以使用数字、字符串或完整枚举名称命名 Part.Material 属性的值,而 print() 函数始终打印完整枚举名称。最好采用明确的方式并使用完整的枚举名称。了解更多关于枚数的信息,请参阅枚数


local Workspace = game:GetService("Workspace")
local part1 = Instance.new("Part")
part1.Material = 816
part1.Parent = Workspace
print(part1.Material) -- Enum.Material.Concrete
local part2 = Instance.new("Part")
part2.Material = "Concrete"
part2.Parent = Workspace
print(part2.Material) -- Enum.Material.Concrete
-- 这是最佳实践,因为它是最明确的
local part3 = Instance.new("Part")
part3.Material = Enum.Material.Concrete
part3.Parent = Workspace
print(part3.Material) -- Enum.Material.Concrete

时间 of 一天

决定是否为夜间、白天或其他时间的 Lighting.TimeOfDay 属性,是 DateTime 数据类输入的字符串表示。如果您将数字分配给 Lighting.TimeOfDay,Luau将其转换为 DateTime 的字符串表示。


local Lighting = game:GetService("Lighting")
Lighting.TimeOfDay = "05:00:00"
print(Lighting.TimeOfDay) -- 05:00:00
Lighting.TimeOfDay = 5
print(Lighting.TimeOfDay) -- 05:00:00