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:
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.
