In the last lesson, you learned how to use nested if statements in Lua to make decisions based on more than one condition. Now, let's take your skills a step further. In this lesson, you will discover how to use logical operators — and, or, and not — to combine and control multiple conditions in a single line. This will help you write cleaner, more flexible code and make your programs even smarter.
Logical operators allow you to check several requirements at once without needing to nest multiple if statements. Here’s a quick look at how each operator works:
and: Both conditions must be true.or: At least one condition must be true.not: Reverses the meaning of a condition.
Let’s look at a real example:
In the first part, the program checks if the traveler has both a passport and a visa. If either is missing, it prints a reminder. Next, it checks if the traveler has either a train or a plane ticket. Finally, it uses not to remind the traveler if they still need to get a visa.
Expected Output:
Why do we see this output?
- The first
ifstatement usesand. Sincehas_passportis but is , the combined condition is , so the branch runs and prints
When you combine multiple logical operators in a single condition, Lua follows a specific order called operator precedence: not is evaluated first, then and, and finally or. This can sometimes lead to surprising results if you’re not careful. For example:
In this example, b and c is evaluated first (which is true), then a or true is evaluated (which is also true). So the message prints. However, if you want to change the order, you should use parentheses:
Using parentheses makes your intentions clear and your code easier to read. As a best practice, always use parentheses when mixing and, or, and not to avoid confusion and bugs.
Logical operators are essential for writing clear and powerful code. They let you handle real-life situations where you need to check several things at once — like making sure someone has all the documents needed for a trip or checking if at least one ticket is available. By mastering these operators, you can make your programs more efficient and easier to read.
Ready to practice using logical operators and see how they can simplify your code? Let’s get started!
