← Back to Lua Course | Chapter 2: Variables & Types | Lesson 5 of 7

Arithmetic and comparison operators

Lua has the usual maths operators, plus floor division and a power operator.

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

lua
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
Common Mistakes
  1. Writing != for not equal
  2. Expecting 7 / 2 to be 3
  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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.