如果 Luau 尝试在操作中使用值或 变量 (例如 算术 、 连接 或 分配 ),但值不是操作所期望的类型,那么 Luau 将( 强制 )将值转换为更改其数据输入。强制发生在运行时对该操作,并不会改变变量的值。
算法
Luau强制字符串转换为数字在 算术操作 。该行为已集成到 Luau 中。如果类型不兼容于算术,Luau 将抛出错误,并不运行剩余的脚本。例如,如果字符串不代表数字,你不能将字符串添加到数字上。
print(100 + "7") -- 107print(100 - "7") -- 93print("1000" + 234) -- 1234print("1000" - 234) -- 766print("hello" + 234) -- error: attempt to perform arithmetic (add) string and number
连接方式
在 concatenation 中,Luau 强制数字转换为字符串。要无需使用强制转换将数字转换为字符串,请使用 string.format() 函数。
print("Pi is " .. math.pi) --> Pi 是 3.1415926535898print("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 = 816part1.Parent = Workspaceprint(part1.Material) -- Enum.Material.Concretelocal part2 = Instance.new("Part")part2.Material = "Concrete"part2.Parent = Workspaceprint(part2.Material) -- Enum.Material.Concrete-- 这是最佳实践,因为它是最明确的local part3 = Instance.new("Part")part3.Material = Enum.Material.Concretepart3.Parent = Workspaceprint(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:00Lighting.TimeOfDay = 5print(Lighting.TimeOfDay) -- 05:00:00