Menu
CoddyTech

Fonksiyon: Öğeleri Açıklama

Coddy'nin Lua Journey'sinin Luau'ya Giriş bölümünün bir parçası. Ders 72 / 80.

challenge icon

Görev

Orta

Her öğe türü için bir açıklama işlevi ekle.

  1. -- Try it satırlarının altındaki satırları sil.
  2. local function describeWeapon(item: Weapon): string yaz ve `Weapon: {item.name} (damage {item.data.damage})` döndür.
  3. describePotion(item: Potion): string yaz ve `Potion: {item.name} (heals {item.data.heal})` döndür.
  4. -- Try it satırının altına describeWeapon(weapons[2]) ve describePotion(potions[1]) yazdır.

Kodu Çalıştır düğmesine bas: çıktı olarak Weapon: Fire Axe (damage 40) ve Potion: Health Potion (heals 40) görünür.

Kendin dene

-- Her envanterin paylaştığı öğe yapısı
type Item<T> = {
    id: number,
    name: string,
    data: T,
}
local sword: Item<{damage: number}> = {id = 1, name = "Iron Sword", data = {damage = 25}}
local potion: Item<{heal: number}> = {id = 2, name = "Health Potion", data = {heal = 40}}
-- Bir sonraki boş id ile bir öğe oluştur, sakla ve döndür
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
type Weapon = Item<{damage: number}>
type Potion = Item<{heal: number}>
local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- Bu id'ye sahip öğe veya nil
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
local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
-- Dene
print(potions[1].data.heal)

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

Kendi başına pratik yap: Online Luau derleyicisi