Selling a Potion
Part of the Fundamentals section of Coddy's Lua journey — lesson 82 of 90.
Challenge
EasyComplete your potion shop project by implementing a sales transaction system. Building on your search functionality, create a system that processes a potion sale by reducing the stock quantity and providing transaction confirmation.
The following input will be provided:
- A string containing the name of the potion to sell
Use a numeric for loop to iterate through your inventory table to find the specified potion. When you locate the matching potion using the equality operator ==, decrease its stock value by 1 to simulate the sale.
After updating the stock, print a confirmation message showing the potion name and its new stock level in the format:
Sold 1 [potion name]
Remaining stock: [new stock count]Use string concatenation to combine the descriptive text with the potion's name and updated stock quantity. After processing the sale, use the break statement to exit the loop.
Try it yourself
-- Inventory table with potion data
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}
}
-- Read the potion name to search for
search_name = io.read()
-- Use a numeric for loop to search through the inventory
for i = 1, #inventory do
if inventory[i].name == search_name then
print("Found: " .. inventory[i].name)
print("Price: " .. inventory[i].price .. " gold")
print("Stock: " .. inventory[i].stock .. " units")
break
end
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