You have already learned how to use if, else, and elseif statements in Lua to handle multiple possibilities. Now, let's build on that foundation. In this lesson, you will discover how to use nested conditions — that is, placing one if statement inside another. This approach allows your programs to make more detailed and precise decisions, just as you might do in real life when you consider several factors before making a choice.
Nested conditions are useful when you need to check more than one factor before deciding what your program should do. For example, imagine you are helping someone choose a travel package. You want to check both their age and their budget before making a recommendation. Here’s how you might write this in Lua:
In this code, the program first checks if the person is older than 18. If they are, it then checks if their budget is high enough for international travel. If not, it suggests a local package. If the person is 18 or younger, it suggests the children’s package. This structure lets you handle more complex situations by breaking them down into smaller decisions.
Here’s how the checking works in the example, step by step:
-
The program first checks if
age > 18.- If this is true, it moves to the next check inside the first
ifblock. - If this is false, it skips the inner check and goes directly to the
elseblock at the end, printing:
"You are eligible for the children's travel package."
- If this is true, it moves to the next check inside the first
-
If
age > 18was , the program now checks if .
Many real-world problems require you to consider several things at once. For example, you might want to check both a user’s age and their membership status before giving them a discount, or you might need to look at both the weather and the time of day before suggesting an activity. Nested conditions give you the power to write programs that can handle these kinds of complex decisions smoothly and clearly.
Ready to see how nested conditions can make your code smarter? Let’s move on to the practice section and try it out for yourself!
