Menu
CoddyTech

Displaying the Inventory

Part of the Fundamentals section of Coddy's Lua journey. Lesson 79 of 90.

challenge icon

Challenge

Easy

Building on your inventory with one potion, create a display system to show all available potions in your shop. First, add a second potion to your inventory by creating a dictionary-style table named manaPotion with the following properties:

  • name with the value "Mana Potion"
  • price with the value 12
  • stock with the value 5

Use table.insert() to add this manaPotion to your inventory table.

Next, create a display system using a numeric for loop to iterate through your inventory table. For each potion in the inventory, print the potion's name and price in the format: "[name]: [price] gold". Use string concatenation to combine the potion's name and price with the descriptive text.

To visit every entry of a list-style table, loop from 1 to its length (#) and read each entry's fields with a dot. For example, with a different table:

heroes = {
    {name = "Ana", level = 3},
    {name = "Ben", level = 7}
}

for i = 1, #heroes do
    print(heroes[i].name)
end

Remove the print(#inventory) line from the previous step, so only the potion list is printed.

Try it yourself

-- Create empty inventory table
local inventory = {}

-- Create health potion table
local healthPotion = {
    name = "Health Potion",
    price = 15,
    stock = 8
}

-- Add health potion to inventory
table.insert(inventory, healthPotion)

-- Print the length of inventory
print(#inventory)

All lessons in Fundamentals

Practice on your own: Online Lua compiler