Lua Operator Precedence
Operator precedence is the fixed order Lua uses to work out the parts of an expression. An expression is a piece of code that works out to a single value.
Brackets change the answer
Both lines use the same three numbers and the same signs. Only the brackets differ, and the answers prove the order matters.
print(2 + 3 * 4)
print((2 + 3) * 4)Power is worked out before times and minus
In the first line, 3 ^ 2 is worked out before the multiplication. In the second line, 2 ^ 2 is worked out before the subtraction.
print(2 * 3 ^ 2)
print(10 - 2 ^ 2)And is worked out before or
In the first line, the and part is worked out before the or part. The second line shows or falling back to a word.
print(true or false and false)
print(false and true or "picked")Example
local price = 50
local saving = 10
local quantity = 3
print("Wrong total:", price - saving * quantity)
print("Right total:", (price - saving) * quantity)Key points
- Power first: ^ is worked out before the other arithmetic operators.
- Multiply group: *, /, // and % are worked out before + and -.
- Compare next: comparison operators are worked out after arithmetic.
- And before or: and is worked out before or.
- Brackets first: round brackets force the part inside them to be worked out before everything around it.
In this example, the first line works out saving * quantity first, so it takes three savings away from one single price and gets 20. The second line puts price - saving in brackets, so the discount is applied to one item first. Multiplying that by 3 then gives the right total of 120.
Note
when an expression gets long, clear brackets beat a memorised order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does print((4 + 2) * 3) print?