5 Boolean Operators
Logical Operations: And, Or
Hasan Malik and Rutwa Engineer
Learning Objectives
- Learn the and operator
- Learn the or operator
- Learn the precedence of boolean operators
Introduction
This module discusses Boolean and Logical Operators.
Just like the number
operators and string
operators we’ve discussed previously, Boolean Operators (also called Logical Operators) operate on the boolean data type.
We will discuss two boolean operators: and
and or
.
The result of a boolean operation is always either true of false.
This is a relatively short chapter—these operators are fairly straightforward. However, it is imperative for you to have a strong grip on how boolean operators function to understand our next chapter: conditional statements.
The and Operator
We will first understand how the and operator works by combining it with comparison operators that we learnt in the number section.
Recall
Remember that comparison operators return boolean results. For example 5<10 returns true, and 7 <= 4 returns false.
The and operator only returns true if both conditions are true. If even one condition is false, the whole expression is false.
Example
print(5<10 and 7>3)
Output: true
This is because the 5<10
condition is true, and the 7>3
condition is also true. Hence, the overall and operation evaluates to true.
print(5<10 and 7<3)
Output: false
This is because the 5<10
condition is true and the 7<3
condition is false. Hence, the and operation evaluates to false, because the conditions are not both true.
Evaluting and
The and operator returns true if and only if both conditions evaluate to true.
The or Operator
The or operator returns true if at least one of the conditions is true. It only returns false if both conditions are false.
Example
print(5<10 or 7<3)
Output: true
This is because the 5<10
condition is true, and the 7<3
condition is false. Hence, the overall or operation evaluates to true, because at least one of the conditions is true.
print(5>10 or 7<3)
Output: false
This is because the 5<10
condition is false and the 7<3
condition is false. Hence, the or operation evaluates to false, because the conditions are both false.
Combining Operators
You can even mix and and or in the same line, but you should use brackets to make sure Lua knows the order you want!
Example
print((5<10 and 7>3) or (2==3))
Output: true
Order of Precedence: and is evaluated first!
and
is more powerful than or
, meaning Lua will always check and
first if no brackets are used. This is a common source of mistakes, so be careful when combining these operators!
For example consider:
print(5<10 and 7<3 or 2==2)
This expression will be treated as this:
print((5<10 and 7<3) or 2==2)
Which evaluates to ((true and false) or true), which evaluates to (true or true), which evaluates to true.
Exercise
Congratulations—you now know the basics of boolean operations in Lua!