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)。

  • describeWeapon(item: Weapon): stringを記述し、Weapon: [name] (damage [damage])を返します。
  • describePotion(item: Potion): stringを記述し、Potion: [name] (heals [heal])を返します。
  • tonumber(io.read())を使ってクエリの数を読み取ります。
  • 各クエリについて、category行(weaponまたはpotion)とid行(tonumberで変換)を読み取ります。findItemで該当するインベントリを検索し、itemが存在する場合は説明を出力し、存在しない場合は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入門のすべてのレッスン

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