Menu
Coddy logo textTech

Fonksiyon: Öğe Detaylarını Al

Coddy'nin Lua Journey'sinin Luau'ya Giriş bölümünün bir parçası — ders 67 / 73.

challenge icon

Görev

Orta

Projeyi tamamlayın! Önceki dersteki her şeyi koruyun: Item<T>, addItem, findItem, Weapon/Potion takma adları ve her iki envanter (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • Weapon: [name] (damage [damage]) döndüren describeWeapon(item: Weapon): string işlevini yazın.
  • Potion: [name] (heals [heal]) döndüren describePotion(item: Potion): string işlevini yazın.
  • Sorgu sayısını tonumber(io.read()) ile okuyun.
  • Her sorgu için bir category satırı (weapon veya potion) ve bir id satırı (tonumber ile dönüştürün) okuyun. Eşleşen envanteri findItem ile arayın: öğe varsa açıklamayı, aksi takdirde Item not found yazdırın.

Örneğin, 2, weapon, 2, potion, 1 girdisi (her satırda bir değer) şunu yazdırır:

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

Kendin dene

-- Önceki derslerdeki envanter sistemi
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})

-- Kodu buraya yazın
-- 1) describeWeapon(item: Weapon): string ve describePotion(item: Potion): string
-- 2) sorgu sayısını oku, ardından her sorgu için: kategori satırı + id satırı
-- 3) findItem in the right inventory; print the description or "Item not found"

Luau'ya Giriş bölümündeki tüm dersler