Lua Arithmetic
Arithmetic operators are the symbols Lua uses to do maths with numbers. Lua has special signs for whole-number division, remainders and powers.
Division always gives a float
The / sign keeps the decimal part of an answer. Even an exact division prints with .0 at the end.
print(7 / 2)
print(10 / 5)Floor division and modulo split a value
The // sign gives the whole part of a division. The % sign gives what is left over, and negative values follow the sign rule.
print(7 // 2)
print(7 % 3)
print(-7 // 2)
print(-7 % 3)Power gives a float
The ^ sign raises the first number to the power of the second. The result is a float, so it prints with .0 when it is whole.
print(2 ^ 10)
print(5 ^ 2)Example
local bill = 50
local people = 4
local share = bill / people
print(string.format("Each person pays $%.2f", share))
print("Whole dollars each: " .. (bill // people))
print("Left over: " .. (bill % people))Key points
- Division: the / sign always gives a float result, even when the answer is a whole number.
- Floor division: the // sign divides and then rounds the answer down to a whole number.
- Modulo: the % sign gives the remainder left over after division.
- Sign rule: a % result takes the sign of the second number, the divisor.
- Power: the ^ sign raises a number to a power and gives a float result.
- Negative values: floor division rounds down, so -7 // 2 gives -4 and not -3.
In this example, the bill of 50 is split between 4 people with / to get the exact share of 12.5. The string.format call prints that share as money with two decimal places. The // sign then shows 12 whole dollars each, and % shows the 2 dollars left over.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does print(9 // 2) print?