Using Logical Operators
Expanding Your Decision-Making Toolkit
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.
What You'll Learn
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_passportistruebuthas_visaisfalse, the combined condition isfalse, so theelsebranch runs and prints"Missing required documents." - The second
ifstatement usesor.has_train_ticketisfalse, buthas_plane_ticketistrue, so the combined condition istrue, and it prints"You have a ticket for your trip." - The third
ifstatement usesnot. Sincehas_visaisfalse,not has_visaistrue, so it prints"Reminder: You still need to apply for a visa."
Operator Precedence and Parentheses
