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:

local travel_destinations = {
    France = {capital = "Paris", visited = false},
    Italy = {capital = "Rome", visited = true},
    Spain = {capital = "Madrid", visited = false},
}

local destination = "France"

if travel_destinations[destination] and travel_destinations[destination].visited then
    print("You have already visited " .. destination .. "!")
elseif travel_destinations[destination] then
    print("It seems you haven't visited " .. destination .. " yet. Get ready for an exciting adventure in " .. travel_destinations[destination].capital .. "!")
else
    print("Destination not found in your travel list.")
end

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:

It seems you haven't visited France yet. Get ready for an exciting adventure in Paris!

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 if block is skipped.
  • The elseif condition checks if travel_destinations["France"] exists, which it does, so this block runs.
  • The message printed uses the capital from the table (Paris) and tells the user they haven't visited France yet.
  • The else block is not executed because the destination exists in the table.
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