関数:項目詳細の取得
CoddyのLuaジャーニー「Luau入門」セクションの一部 — レッスン 67/73。
チャレンジ
中級プロジェクトを完成させましょう!前のレッスンで作った Item<T>、addItem、findItem、Weapon/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入門のすべてのレッスン
7プロジェクト:Typed Task Manager
プロジェクト:タスクの型定義タスクを追加する関数