Finding a Specific Potion
Part of the Fundamentals section of Coddy's Lua journey — lesson 81 of 90.
Challenge
EasyBuilding on your inventory value calculation system, implement a search feature that allows you to find and display detailed information about a specific potion in your shop's inventory.
The following input will be provided:
- A string containing the name of the potion to search for
Use a numeric for loop to iterate through your inventory table. For each potion, check if the potion's name matches the search term using the equality operator ==.
When you find the matching potion, print all of its details in the following format:
Found: [name]
Price: [price] gold
Stock: [stock] unitsUse string concatenation to combine the descriptive text with each potion property. After finding and displaying the potion details, use the break statement to exit the loop since you've found what you were looking for.
Try it yourself
-- Inventory table with potion data
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}
}
-- Initialize total value variable
local totalValue = 0
-- Calculate total inventory value using numeric for loop
for i = 1, #inventory do
local itemValue = inventory[i].price * inventory[i].stock
totalValue = totalValue + itemValue
end
-- Print the total inventory value
print("Total inventory value: " .. totalValue .. " gold")All 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