Menu
Coddy logo textTech

関数:項目詳細の取得

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

challenge icon

チャレンジ

中級

プロジェクトを完成させましょう!前のレッスンで作った Item<T>addItemfindItemWeapon/Potion のエイリアス、および両方のインベントリ(weapons: Iron Sword 25 / Fire Axe 40、potions: Health Potion 40 / Mega Potion 90)をすべて維持してください。

  • Weapon: [name] (damage [damage]) を返す describeWeapon(item: Weapon): string を記述します。
  • Potion: [name] (heals [heal]) を返す describePotion(item: Potion): string を記述します。
  • tonumber(io.read()) でクエリの数を読み込みます。
  • 各クエリについて、category 行(weapon または potion)と id 行(tonumber で変換)を読み込みます。findItem を使用して対応するインベントリを検索し、item が存在する場合は説明を print し、存在しない場合は Item not found を出力します。

たとえば、入力 2, weapon, 2, potion, 1(1行に1つの値)の場合、次のように出力されます:

Weapon: Fire Axe (damage 40)
Potion: Health Potion (heals 40)

自分で試してみよう

-- 前のレッスンのインベントリシステム
type Item<T> = {
    id: number,
    name: string,
    data: T,
}

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

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

type WeaponData = {damage: number}
type PotionData = {heal: number}

type Weapon = Item<WeaponData>
type Potion = Item<PotionData>

local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})

local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
addItem(potions, "Mega Potion", {heal = 90})

-- ここにコードを書いてください
-- 1) describeWeapon(item: Weapon): string と describePotion(item: Potion): string
-- 2) クエリ数を読み取り、各クエリごとに: カテゴリ行 + id 行
-- 3) findItem in the right inventory; print the description or "Item not found"

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