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オンラインコンパイラ