Arithmetic and comparison operators
Lua has the usual maths operators, plus floor division and a power operator.
In this page:
Arithmetic and comparison operators
Lua provides +, -, *, /, %, ^ for power and // for floor division. The / and ^ operators always give floats, while // and % give integers when both operands are integers. Comparisons use ==, ~=, <, <=, > and >=, and note that not-equal is written ~=.
Note:
Modulo in Lua takes the sign of the divisor, so -7 % 3 is 2.
Example: Arithmetic and comparison operators
print(7 / 2, 7 // 2, 7 % 3)
print(-7 // 2, -7 % 3)
print(2 ^ 10, 6 / 3)
print(7.5 // 2)
print(1 ~= 2, 1 == 1.0)
-- Output:
-- 3.5 3 1
-- -4 2
-- 1024.0 2.0
-- 3.0
-- true true
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing != for not equal
- Expecting 7 / 2 to be 3
- Expecting a negative modulo result to be negative
Chapter Summary
- / always gives a float
- // is floor division
- ^ raises to a power
- Not equal is ~=
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: