Menu
CoddyTech

函数:描述物品

本课属于 Coddy Lua 学习旅程的“Luau 入门”单元。第 72 课,共 80 课。

challenge icon

挑战

中等

为每种物品添加一个描述函数。

  1. 删除 -- Try it 下方的代码行。
  2. 编写 local function describeWeapon(item: Weapon): string,返回 `Weapon: {item.name} (damage {item.data.damage})`。
  3. 编写 describePotion(item: Potion): string,返回 `Potion: {item.name} (heals {item.data.heal})`。
  4. 在 -- Try it 下方,打印 describeWeapon(weapons[2]) 和 describePotion(potions[1])。

点击运行代码:输出会显示 Weapon: Fire Axe (damage 40) 和 Potion: Health Potion (heals 40)。

亲手试试

-- 所有库存共用的物品结构
type Item<T> = {
    id: number,
    name: string,
    data: T,
}
local sword: Item<{damage: number}> = {id = 1, name = "Iron Sword", data = {damage = 25}}
local potion: Item<{heal: number}> = {id = 2, name = "Health Potion", data = {heal = 40}}
-- 用下一个可用的 id 创建物品,保存并返回它
local function addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T>
    local item: Item<T> = {id = #inventory + 1, name = name, data = data}
    table.insert(inventory, item)
    return item
end
type Weapon = Item<{damage: number}>
type Potion = Item<{heal: number}>
local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- 具有此 id 的物品,找不到则返回 nil
local function findItem<T>(inventory: {Item<T>}, id: number): Item<T>?
    for _, item in ipairs(inventory) do
        if item.id == id then
            return item
        end
    end
    return nil
end
local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
-- 试试看
print(potions[1].data.heal)

Luau 入门中的所有课

自己练习: Luau 在线编译器