Expanding Your Decision-Making Skills

Now that you have learned how to use basic if statements in Lua to make simple decisions, it's time to take the next step. In this lesson, you will discover how to handle situations where there are more than just two possible outcomes. This is a natural progression from the previous lesson, where we focused on making a single yes-or-no choice. Here, you will learn how to use if-else and elseif to manage multiple possibilities in your programs.

What You'll Learn

You will see how to use if-else and elseif statements to check for several different conditions and respond to each one. This is especially useful when your program needs to choose among more than two options. For example, imagine you are building a travel booking system that offers different packages based on a traveler's age. Here’s how you might write that in Lua:

In this code, the program checks the traveler's age and prints a different message depending on which age group they belong to. The elseif keyword allows you to add as many extra checks as you need, making your code much more flexible.

Here’s how the logic in the example works:

The program checks the value of age step by step:

  1. First, it checks if age < 18.

    • If this is true, it prints the message for the children's travel package and skips the rest of the checks.
  2. If the first condition is false, it moves to the elseif age < 60 line.

    • If this is true, it prints the message for the adult's travel package.
  3. If neither of the above conditions is true (meaning age is 60 or more), it runs the code in the else block.

Understanding <= and >= in Conditions

You can use <= (less than or equal to) and >= (greater than or equal to) in your conditions to compare values.

Here are simple examples:

  • age >= 18 checks if age is 18 or more.
  • temperature <= 10 checks if temperature is 10 or less.
Why This Matters

Most real-world problems are not just black and white. You often need to handle many different cases, and being able to use if-else and elseif statements will help you write smarter, more adaptable programs. Whether you are sorting users into categories, checking for different error types, or offering personalized options, these tools are essential.

Let’s move on to the practice section and see how you can use these new skills to solve real problems!

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