如果 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
連接字串
在連接中,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
時辰
定義是否為夜、白天或其他時間的 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