Coercion: Difference between revisions
>Camoy formatted, categorized |
>Camoy formatted, categorized |
(No difference)
|
Revision as of 13:02, 1 November 2010
Coercion
What is Coercion?
Lua performs automatic conversion of numbers to strings and vice versa where it is appropriate. This is called coercion.
Lua will automatically convert string and number types to the correct format in order to perform calculations. For example, if you try to apply an arithmetic operation to a string, Lua will try to convert that string to a number first, otherwise the operation will not work. If the string cannot be converted to a number an error is raised.
print("This is Lua version " .. 5.1 .. " we are using.") Output: This is Lua version 5.1 we are using. print("Pi = " .. math.pi) Output: Pi = 3.1415926535898 print("Pi = " .. 3.1415927) Output: Pi = 3.1415927
As shown above, during coercion, we do not have full control over the formatting of the conversion. To format the number as a string as we would like we can use the string.format() function. e.g.:
print(string.format("%.3f", 5.1)) Output: 5.100 -- notice that there are three decimal places. print("Lua version " .. string.format("%.1f", 5.1)) Output: Lua version 5.1
This is explicit conversion using a function to convert the number, rather than coercion.
Using Coercion
print(100 + "7") Output: 107 print("1000" + 234) Output: 1234 print(234 + "1000") Output: 1234 print("hello" + 234) Output: Fri Oct 17 12:14:00 2008 - Workspace.Script:1: attempt to perform arithmetic on a string value
You can see where a string can be converted to number, the calculation succeeds. The string "hello" cannot be converted to a number and so an error occurs. In statically typed languages (e.g. C) this would cause an error as you cannot assign a value to a variable of an incompatible type. This works in Lua because it is dynamically typed.
A notable exception: comparison operators (== ~= < > <= >=) do not coerce their arguments. The (in)equality operators consider a number to be not equal to its string representation (or any non-number type in fact). Ordered comparison operators throw an error when you feed them different types:
print(100 == "100") Output: false print(100 ~= "hello") Output: true print(100 ~= {}) Output: true print(100 == tonumber("100")) Output: true print(100 <= "100") Output: Fri Oct 17 12:19:03 2008 - Workspace.Script:1: attempt to compare number with string Fri Oct 17 12:19:03 2008 - Workspace.Script, line 1 Fri Oct 17 12:19:03 2008 - stack end