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:

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:

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:

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.

Understanding Truthiness in Lua

In Lua, only false and nil are considered "falsy" values in conditions. This means that values like 0 (zero) and "" (an empty string) are actually treated as "truthy"—they count as true in an if statement. This is different from some other programming languages, where 0 or an empty string might be considered false. Keep this in mind when writing your conditions to avoid unexpected results.

Why This Is Important

Being able to make decisions in your code is essential. Almost every real-world program needs to react to different inputs or situations. For example, a travel booking system needs to check whether someone has the right documents before allowing them to book a trip. By mastering if statements, you will be able to write programs that are flexible and useful in many situations.

Ready to see how this works in practice? Let’s get started!

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