Calculating Total Stock Value
Part of the Fundamentals section of Coddy's Lua journey — lesson 80 of 90.
Challenge
EasyNow 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 goldUse 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")
endAll lessons in Fundamentals
4Operators 2 Relational & Logic
Equality OperatorsRelational OperatorsThe 'and' OperatorThe 'or' OperatorThe 'not' OperatorShort-Circuit EvaluationTruthy and Falsy ValuesRecap - Simple Logic7Basic Conditional Logic
The if-then StatementThe if-then-else StatementThe elseif StatementRecap - Treasure Chest10Tables Part 1: List-Style
What is a Table?Creating a TableAccessing Elements by IndexModifying Elements by IndexThe Length Operator '#'table.insert()table.remove()Recap - Manage Party Members13Project: Simple Potion Shop
Project SetupAdding a Potion2Variables and Data Types
What is a Variable?NumbersStringsBooleansThe Value 'nil'The type() FunctionNaming ConventionsRecap - Character Profile5Basic Output
Printing LiteralsPrinting VariablesPrinting Multiple ValuesCombining Strings & VariablesThe tostring() FunctionInputCastRecap - Status ReportRecap - Till 1208String Manipulation Basics
string.len()string.upper & string.lowerstring.sub()string.rep()string.find()Recap - Format Username3Operators 1 Arithmetic & Conc
Arithmetic OperatorsModulo OperatorExponentiation OperatorString ConcatenationOperator PrecedenceRecap - Simple Calculations6Project: Character Stats Disp
Welcome MessageDeclare Character Stats9Functions Basics
Declaring a FunctionCalling a FunctionFunctions with ParametersFunctions with Multiple ParamsThe 'return' StatementRecap - Area Calculator