Menu
CoddyTech

计算库存总价值

本课属于 Coddy Lua 学习旅程的“基础知识”单元。第 80 课,共 90 课。

challenge icon

挑战

简单

现在使用以下库存(你可以替换当前库存):

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}
}


你的目标是计算库存中所有药水的金币总价值。

请按以下步骤操作:

1. 创建一个名为 totalValue 的变量,并将它设为 0。遍历每种药水时,用它来记录总值。

2. 使用数值型 for 循环遍历 inventory 表中的每个物品。对于每种药水,将它的 price 乘以 stock,计算这瓶药水的价值。把这个数值加到 totalValue 上。

3. 循环结束后,按如下方式打印结果:

Total inventory value: 291 gold

使用字符串拼接(..)将文本与 totalValue 的值组合起来。

亲手试试

-- 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

基础知识中的所有课

自己练习: Lua 在线编译器