Menu
CoddyTech

アイテムの問い合わせに答える

CoddyのLuaジャーニー「Luau入門」セクションの一部。レッスン 73/80。

challenge icon

チャレンジ

中級

1つのアイテムについて尋ねるプレイヤーに答えましょう。

  1. -- Try it の下にある行を削除します。
  2. その下に、local category = io.read() と local id: number = tonumber(io.read()) or 0 を読み取る処理を記述します。
  3. "weapon" の場合は、findItem(weapons, id) に対して describeWeapon(item) を出力します。それ以外の場合は、potions と describePotion を使います。
  4. findItem が nil を返したときは、Item not found を出力します。

Run Code を押します。入力に weapon と 2 を指定すると、Weapon: Fire Axe (damage 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})
-- アイテムの種類ごとに説明を1つ用意する
local function describeWeapon(item: Weapon): string
    return `Weapon: {item.name} (damage {item.data.damage})`
end

local function describePotion(item: Potion): string
    return `Potion: {item.name} (heals {item.data.heal})`
end
-- 試してみる
print(describeWeapon(weapons[2]))
print(describePotion(potions[1]))

Luau入門のすべてのレッスン

自分で練習してみよう: Luauオンラインコンパイラ