出售药水
本课属于 Coddy Lua 学习旅程的“基础知识”单元。第 82 课,共 90 课。
挑战
简单通过实现销售交易系统,完成你的药水商店项目。在搜索功能的基础上,创建一个处理药水销售的系统,减少库存数量并提供交易确认。
将提供以下输入:
- 一个包含要出售药水名称的字符串
使用数值 for 循环遍历你的 inventory 表,查找指定的药水。使用相等运算符 == 找到匹配的药水后,将它的 stock 值减去 1,以模拟销售。
更新库存后,打印一条确认消息,显示药水名称和新的库存数量,格式如下:
Sold 1 [potion name]
Remaining stock: [new stock count]使用字符串拼接,将描述性文本与药水名称和更新后的库存数量组合起来。处理完销售后,使用 break 语句退出循环。
亲手试试
-- 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
end基础知识中的所有课
自己练习: Lua 在线编译器