🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Comparison

Comparison operators compare two values and give true or false as the result. Lua uses them to check whether values are equal, different or in a certain order.

Number comparisons print true or false

Each line compares two numbers and prints the result directly. Read the four results from top to bottom.

print(5 > 3)
print(5 < 3)
print(4 <= 4)
print(9 >= 10)

Equal values can be written differently

The == sign checks sameness and ~= checks difference. The third line shows that 2 and 2.0 count as the same value.

print(7 == 7)
print(7 ~= 7)
print(2 == 2.0)
print("cat" == "dog")

Strings compare by alphabet order

A string that comes earlier in the alphabet counts as smaller. Equal strings give true for ==.

print("apple" < "banana")
print("banana" < "apple")
print("apple" == "apple")

Example

local mark = 72
local passMark = 50
print("Reached pass mark:", mark >= passMark)
print("Perfect score:", mark == 100)
print("Below pass mark:", mark < passMark)
print("Different from pass mark:", mark ~= passMark)

Key points

  • Equal: == checks whether two values are the same.
  • Not equal: ~= checks whether two values are different.
  • Order signs: <, >, <= and >= compare which of two values is bigger, and a sign with = in it also allows the values to be equal.
  • Result: every comparison gives a boolean value, either true or false.
  • Text order: strings compare by alphabet order, so "apple" comes before "banana".
  • Number values: an integer and a float compare by value, so 2 == 2.0 is true.

In this example, a mark of 72 is compared with a pass mark of 50 in four different ways. The mark reached the pass mark and is different from it, so those two lines print true. It is not a perfect score and it is not below the pass mark, so those two lines print false.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does print("apple" > "banana") print?