Arithmetic and Relational Operators
Use +, -, *, /, //, %, ^ and comparison operators effectively.
Arithmetic Operators Overview
Lua provides a full set of arithmetic operators: + (add), - (subtract), * (multiply), / (float divide), // (floor divide), % (modulo), ^ (exponentiation), and unary - (negation). Understanding when each returns an integer vs float is crucial in Lua 5.3+.
print(10 + 3) -- 13
print(10 - 3) -- 7
print(10 * 3) -- 30
print(10 / 3) -- 3.3333... (always float)
print(10 // 3) -- 3 (floor division)
print(10 % 3) -- 1 (modulo)
print(2 ^ 10) -- 1024.0 (always float)
print(-5) -- -5Integer vs Float Division
The / operator always returns a float, even when dividing two integers that divide evenly. The // floor division operator returns an integer only when both operands are integers; if either is a float, the result is a float but still rounded down.
The ^ exponentiation operator always converts to float, so 2^3 gives 8.0, not 8. Use math.tointeger() to convert back if needed.
print(6 / 2) -- 3.0 (float!)
print(6 // 2) -- 3 (integer)
print(6.0 // 2) -- 3.0 (float floor)
print(7 // 2) -- 3 (floor toward -inf)
print(-7 // 2) -- -4 (floor, not truncate!)
print(2 ^ 3) -- 8.0 (always float)All lessons in this course
- Lua Data Types Overview
- Declaring Variables in Lua
- Arithmetic and Relational Operators
- Type Coercion and Conversion