类型转换

*此内容使用人工智能(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) -- 错误:尝试对字符串和数字进行算术(加法)操作

连接

在连接操作中,Luau会将数字强制转换为字符串。要在不使用强制转换的情况下将数字转换为字符串,可以使用string.format()函数。


print("圆周率是 " .. math.pi) --> 圆周率是 3.1415926535898
print("圆周率是 " .. 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 = 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

一天中的时间

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
©2026 Roblox Corporation、Roblox、Roblox 标志及 Powering Imagination 是我们在美国及其他国家或地区的注册与未注册商标。