Menu
Coddy logo textTech

함수: 항목 상세 정보 가져오기

Coddy Lua 여정의 Luau 소개 섹션에 포함된 레슨 — 73개 중 67번째.

challenge icon

챌린지

중급

프로젝트를 완성하세요! 이전 레슨의 모든 내용을 그대로 유지합니다: 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())를 사용하여 쿼리 수를 읽어옵니다.
  • 각 쿼리에 대해, 카테고리 줄(weapon 또는 potion)과 id 줄(tonumber로 변환)을 읽습니다. findItem을 사용하여 일치하는 인벤토리를 검색합니다: item이 존재하면 설명을 출력하고, 그렇지 않으면 Item not found를 출력합니다.

예를 들어, 입력 2, weapon, 2, potion, 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 소개의 모든 레슨