Bringing Conditionals and Data Structures Together

In the previous lessons, you learned how to use if, elseif, and logical operators to make decisions in your Lua programs. Now, let's take things further by combining these decision-making tools with data structures — specifically, tables. This is a key step in writing programs that can handle more complex, real-world information.

What You'll Learn

In this lesson, you will see how to use tables (Lua’s main data structure) together with conditional statements. This allows you to store and check information about many items at once and then make decisions based on that data.

For example, imagine you are keeping track of the countries you want to visit and whether you have already been there. You can store this information in a table and use an if statement to check if a destination is new or already visited:

In this code, we use a table to store information about each country. The if statement checks if the destination exists in the table and whether it has been visited, then prints a message based on the result.

Expected Output:

Explanation:

  • The variable destination is set to "France".
  • travel_destinations["France"] exists, so the first part of the if condition is true.
  • However, travel_destinations["France"].visited is false, so the first block is skipped.
Why This Matters

Combining conditionals with data structures is a powerful skill. It lets you write programs that can make smart decisions based on lots of information, just like real travel apps or booking systems do. By learning this, you will be able to build more useful and flexible Lua programs that can handle lists, records, and more.

Ready to see how this works in practice? Let’s move on and try it out together!

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