If Luau tries to use a value or variable in an operation, such as arithmetic, concatenation, or assignment, but the value isn't the type that the operation expects, then Luau converts (coerces) the value to change its data type. Coercion happens at run time for that operation and doesn't change the value of a variable.
Luau coerces strings to numbers in arithmetic operations. This behavior is built into Luau. If the types are incompatible for arithmetic, Luau throws an error and doesn't run the rest of the script. For example, you can't add a string to a number if the string does not represent a number.
1print(100 + "7") -- 1072print(100 - "7") -- 933print("1000" + 234) -- 12344print("1000" - 234) -- 7665print("hello" + 234) -- error: attempt to perform arithmetic (add) string and number6
In concatenation, Luau coerces numbers to strings. To convert a number to a string without using coercion, use the string.format() function.
1print("Pi is " .. math.pi) -- 3.14159265358982print("Pi is " .. 3.1415927) -- 3.141592734-- Rounds to three decimal places5print("Pi is " .. string.format("%.3f", 3.1415927)) -- Pi is 3.1426
Some properties expect certain data types, such as an Enum or string, but you can assign a value of a different type to it and Luau converts the value to the type the property expects.
Luau coerces numbers and strings of enum values into the full enum name. For example, you can name the value of the Part.Material property using a number, string, or full enum name, and the print() function always prints the full enum name. It's best practice to be explicit and use the full enum name. For more information on Enums, see Enums.
1local part1 = Instance.new("Part")2part1.Parent = workspace3part1.Material = 8164print(part1.Material) -- Enum.Material.Concrete56local part2 = Instance.new("Part")7part2.Parent = workspace8part2.Material = "Concrete"9print(part2.Material) -- Enum.Material.Concrete1011-- This is best practice because it's the most explicit12local part3 = Instance.new("Part")13part3.Parent = workspace14part3.Material = Enum.Material.Concrete15print(part3.Material) -- Enum.Material.Concrete16
The Lighting.TimeOfDay property, which defines whether it is night, day, or any other time, is a string representation of the DateTime data type. If you assign a number to Lighting.TimeOfDay, Luau converts it to the string representation of DateTime.
1game.Lighting.TimeOfDay = "05:00:00"2print(game.Lighting.TimeOfDay) -- 05:00:0034game.Lighting.TimeOfDay = 55print(game.Lighting.TimeOfDay) -- 05:00:006