Menu
Coddy logo textTech

Calculating Total Stock Value

Part of the Fundamentals section of Coddy's Lua journey — lesson 80 of 90.

challenge icon

Challenge

Easy

Now use the following inventory (you can override your current one):

local inventory = {
   {name = "Health Potion", price = 15, stock = 8},
   {name = "Mana Potion", price = 12, stock = 5},
   {name = "Strength Potion", price = 25, stock = 3},
   {name = "Speed Potion", price = 18, stock = 2}
}


Your goal is to find the total gold value of all potions in stock.

Here's what to do, step by step:

1. Create a variable called totalValue and set it to 0. This will keep track of the total as you go through each potion.

2. Use a numeric for loop to go through each item in the inventory table. For each potion, multiply its price by its stock to get how much that potion is worth. Add that number to totalValue.

3. After the loop, print the result like this:

Total inventory value: 291 gold

Use string concatenation (..) to combine the text with the value of totalValue.

Try it yourself

-- Create the initial inventory with health potion
inventory = {
    {name = "Health Potion", price = 15, stock = 8}
}

-- Create mana potion
manaPotion = {name = "Mana Potion", price = 12, stock = 5}

-- Add mana potion to inventory
table.insert(inventory, manaPotion)

-- Display all potions in inventory
for i = 1, #inventory do
    print(inventory[i].name .. ": " .. inventory[i].price .. " gold")
end

All lessons in Fundamentals