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 tamamla! Önceki dersteki her şeyi koru: Item<T>, addItem, findItem, Weapon/Potion takma adlarını ve her iki envanteri (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • describeWeapon(item: Weapon): string fonksiyonunu yaz; bu fonksiyon Weapon: [name] (damage [damage]) döndürmeli.
  • describePotion(item: Potion): string fonksiyonunu yaz; bu fonksiyon Potion: [name] (heals [heal]) döndürmeli.
  • Sorgu sayısını tonumber(io.read()) ile oku.
  • Her sorgu için bir kategori satırı (weapon veya potion) ve bir kimlik satırı oku (tonumber ile dönüştür). findItem ile eşleşen envanterde ara: öğe varsa açıklamasını yazdır, yoksa Item not found yazdır.

Örneğin, 2, weapon, 2, potion, 1 girdisi (her değer ayrı bir satırda) ş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

Kendi başına pratik yap: Online Lua derleyicisi