Arithmetic Operators
Language: | [[::Arithmetic Operators|English]] |
---|
This short tutorial will cover the basic arithmetic operators used within Lua.
So in a nutshell, the math operators include:
- + Addition
- - Subtraction
- * Multiplication
- / Division
- ^ Power of / Exponentiation
We can see these in action:
print(2 + 3)
print(2 - 3)
print(2 * 3)
print(2 ^ 3)
print(2 - 3 + 4 * 5 ^ 6)
Precedence
With the last example we should also mention precedence. Precedence refers to the order in which operations are performed in. This is standardised for consistency:
- ^ (Exponentiation, right associative)
- * (Multiplication), / (division)
- + (Addition), - (Subtraction)
- * (Multiplication), / (division)
Everything except exponentiation is left associative, meaning that any operations with the same precendence are done from left to right, while exponentiation is done from right to left. Of course you can override precedence simply by placing anything you want done first within parentheses. Like this:
print(4 + 5 * 10)
print((4 + 5) * 10) --This will have a different result
In the last example I placed a comment by using two dashed lines (--). This signifies something you want the Lua interpreter to ignore, and is often used to mark code so yourself and others can understand it more easily. It is considered good programming etiquette to comment your code, and is invaluable when trying to learn.
Here are some more examples using variables from the first tutorial:
b = 5
a = b + 2*3
b = a / b
print(b, a)
Note that you cannot use arithmetic operators on anything other than the numbers datatype. However, if a string consists entirely of numbers, then Lua is smart enough to convert the datatype to avoid errors:
print("200" + 25)
a = "Even if it contained a non-number once"
a = 25
print("200" + a)
a = "25"
print(type(a))
a = a + a
print(a)
print(type(a))
You might have noticed that it was still considered a string before being used by the arithmetic operator. As a general rule, you should avoid storing numbers as strings.
Summary
- There are five arithmetic operators: Addition (+), Subtraction (-), Multiplication (*), Division (/), Exponentiation (^)
- These are performed in order of precedence
- Precedence can be overriden with parentheses
- Math operators can only be used on the number datatype, but Lua converts number only strings to the number datatype when used
- Comments can be placed in code using two dashes: --