Operators are symbols that instruct the CPU to perform some operation or process between one or more pieces of data. This is what is called an ‘expression.’
Depending on the data type, different sets of operators are available or for similar operators, data is processed in a different manner.
The operators you are likely most familiar with are mathematical operators.
In your script, delete the string between the parenthesis along with the quotes, and replace it with a mathematical expression.
print(1 + 2) --Output: 3
Lua’s arithmetic operators are:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Modulo (%)
- Exponent (^)
- Negation (-)
The ‘%’ is called the modulo operator which “returns” the remainder of a division.
print(5 / 2) --Output: 2.5
print(5 % 2) --Output: 1
Operations are not limited to just two numbers. This chains several operators together.
print(5 + 4 - 3 * 2)
Just like you learned in math class, the order of operations (“PEMDAS”) apply to scripting.
Anything within parentheses are calculated first, followed by Exponents then Multiplication/Division and finally Addition/Subtraction.
It is good practice to avoid such ambiguity by using parenthesis to separate parts of an expression.
Naturally, we would expect arithmetic operators to work with numbers. But what would happen if we attempt to use them with a string? What happens if we try to add a string to a number?
print("Hello" + 2) --Output: error
We get something along the lines of ‘attempt to perform arithmetic (add) on string and number.’
This is expected. It would not make sense how a number could be added to a letter.
So if a number is enclosed in quotes, that number would be the string data type like we saw earlier.
print("3.14") --Output: 3.14 (string)
print(3.14) --Output: 3.14 (number)
Which would also mean we cannot perform arithmetic on them, right?
print("3.14" * 2) --Output: 6.28
???
But this output gives us 6.28. Which clearly violates the previous rule. So what gives?
Even though “3.14” is a string, Lua recognizes that the string represents a number and saw that you were attempting to perform a mathematical operation. So it automatically converts it to a number.
This is known as ‘automatic type conversion‘ in computer science. Or ‘type coercion’ as Lua calls it.
And as long as there is not a non-number character aside from the decimal point, stringed numbers are automatically converted.
print("3.14" + "15") --Output: 18.14
print("3.14" - "15") --Output: -11.86
print("3.14" * "15") --Output: 47.1
print("3.14" / "15") --Output: 0.20933333333333334
print("3.14" % "15") --Output: 3.14
print("18.14" + "11.86" - "47.1" * "0.20933333333333334" / "3.14") --Output: 26.86
Okay, that’s cool and all but what if we really did want to add two strings together? So as to attach one string to another. Is there a way to do that?
I’m glad you asked…