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:

local has_passport = true
local has_visa = false

-- Using 'and' - both conditions must be true
if has_passport and has_visa then
    print("Ready for international travel!")
else
    print("Missing required documents.")
end

-- Using 'or' - at least one condition must be true
local has_train_ticket = false
local has_plane_ticket = true
if has_train_ticket or has_plane_ticket then
    print("You have a ticket for your trip.")
end

-- Using 'not' - inverts the boolean value
if not has_visa then
    print("Reminder: You still need to apply for a visa.")
end

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:

Missing required documents.
You have a ticket for your trip.
Reminder: You still need to apply for a visa.

Why do we see this output?

  • The first if statement uses and. Since has_passport is true but has_visa is false, the combined condition is false, so the else branch runs and prints "Missing required documents."
  • The second if statement uses or. has_train_ticket is false, but has_plane_ticket is true, so the combined condition is true, and it prints "You have a ticket for your trip."
  • The third if statement uses not. Since has_visa is false, not has_visa is true, so it prints "Reminder: You still need to apply for a visa."

Operator Precedence and Parentheses

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal