Menu
CoddyTech

显示库存

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

challenge icon

挑战

简单

在只有一种药水的库存基础上,创建一个展示系统,用来显示商店中所有可用的药水。首先,创建一个名为 manaPotion 的字典式表,为库存添加第二种药水,并设置以下属性:

  • name 的值为 "Mana Potion"
  • price 的值为 12
  • stock 的值为 5

使用 table.insert() 将这个 manaPotion 添加到 inventory 表中。

接下来,使用数值型 for 循环遍历 inventory 表,创建一个展示系统。对于库存中的每种药水,按照以下格式输出药水的名称和价格:"[name]: [price] gold"。使用字符串拼接,将药水的 name 和 price 与描述文本组合起来。

亲手试试

-- Create empty inventory table
local inventory = {}

-- Create health potion table
local healthPotion = {
    name = "Health Potion",
    price = 15,
    stock = 8
}

-- Add health potion to inventory
table.insert(inventory, healthPotion)

-- Print the length of inventory
print(#inventory)

基础知识中的所有课

自己练习: Lua 在线编译器