2.5 Relational Operators

The comparison of two values are often important in the decision making process.

But a computer cannot tell you how those two values compare. It can only evaluate if some relationship between two numbers is true or false.

To check that relationship, we use ‘relational operators‘:

  • Less than (<)
  • Less than or equal (<=)
  • Greater than (>)
  • Greater than or equal (=>)
  • Equal (==)
  • Not equal (~=)
Lua
print(1 < 2) --Output: true
print(1 <= 2) --Output: true
print(1 == 2) --Output: false
print(1 ~= 2) --Output: true

Relational operations are performed after arithmetic operations.

Lua
print(1 + 1 + 1 + 1 < 3) --Output: false

For two values of the same data type, the equality operators can be used to make a comparison.

Here, two strings are checked for similarity using the equality operators.

Lua
print("Hello world!" == "Hello world!") --Output: true
print("Hello!" == "world!") --Output: false
print("Hello!" ~= "world!") --Output: true

The less-than/greater-than operators can also compare two strings. In this mode, Lua will make an alphabetic order comparison based on position:

Lua
print("a" < "b") --Output: true
print("az" < "a") --Output: false
print("Hello!" >= "world!") --Output: false

Unlike with arithmetic operators, relational operators do not perform a type conversion.

So if you try to compare a string and a number representing the same quantity, it will evaluate false under the equality operator, true under the ‘not-equal’ operator, and throw an error for any other.

Lua
print("3.14" == 3.14) --Output: false
print("3.14" ~= 3.14) --Output: true
print("3.14" <= 3.14) --Output: error