如果Luau尝试在某个操作中使用一个值或变量,例如算术、连接或赋值,但该值不是操作所期望的类型,那么Luau会转换(强制转换)该值以更改其数据类型。强制转换在运行时发生,并不会改变变量的值。
算术
在算术操作中,Luau会将字符串强制转换为数字。这种行为是Luau内置的。如果在算术操作中类型不兼容,Luau会抛出错误,并且不会运行脚本的其余部分。例如,如果字符串不代表数字,则无法将字符串与数字相加。
print(100 + "7") -- 107print(100 - "7") -- 93print("1000" + 234) -- 1234print("1000" - 234) -- 766print("hello" + 234) -- 错误:尝试对字符串和数字进行算术(加法)操作
连接
在连接操作中,Luau会将数字强制转换为字符串。要在不使用强制转换的情况下将数字转换为字符串,可以使用string.format()函数。
print("圆周率是 " .. math.pi) --> 圆周率是 3.1415926535898print("圆周率是 " .. 3.1415927) --> 圆周率是 3.1415927-- 四舍五入到小数点后三位print("圆周率是 " .. string.format("%.3f", 3.1415927)) -- 圆周率是 3.142
赋值
某些属性期望特定的数据类型,例如枚举或字符串,但可以将不同类型的值赋给它,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
一天中的时间
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