Making Decisions with If Statements

Making Decisions with If Statements

Welcome to your first step into control structures in Lua! In this lesson, you will learn how to make your programs smarter by teaching them how to make decisions. This is a key skill for any programmer, and it will help you write code that can react to different situations.

What You'll Learn

In this lesson, you will discover how to use the if statement in Lua to check conditions and control what your program does next. You will see how to write simple decision-making code, like this example:

-- Checking if the Passport is true
local has_passport = true

if has_passport then
    print("You are eligible to travel.")
else
    print("You cannot travel without a passport.")
end

In the code above, we use an if statement to check whether the traveler has a passport. If has_passport is true, the program prints a message saying the person can travel. If not, it prints a different message. This is the foundation of making decisions in your code.

Understanding the == Operator

In Lua, the == operator is used to check if two values are equal. This is different from a single = sign, which is used to assign a value to a variable. When you use == inside an if statement, you are asking, "Are these two things the same?"

For example:

local country = "Brazil"

if country == "Brazil" then
    print("Welcome to Brazil!")
else
    print("You are not in Brazil.")
end

In this code, country == "Brazil" checks if the value stored in the variable country is exactly equal to the string "Brazil". If it is, the program prints a welcome message. If not, it prints a different message. Always use == when you want to compare values in a condition.

Checking for "Not Equal"

In addition to checking if two values are equal with ==, you can also check if they are not equal using the ~= operator in Lua. This is useful when you want your code to do something only if two values are different.

For example:

local country = "Argentina"

if country ~= "Brazil" then
    print("You are not in Brazil.")
else
    print("Welcome to Brazil!")
end

Here, country ~= "Brazil" checks if the value of country is not equal to "Brazil". If it isn't, the program prints a message saying you are not in Brazil. If it is, it prints a welcome message. Use ~= whenever you want to check for inequality in your conditions.

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