Menu
CoddyTech

Funzione: Descrivere gli oggetti

Fa parte della sezione Introduzione a Luau del percorso Lua di Coddy. Lezione 72 di 80.

challenge icon

Sfida

Medio

Aggiungi una funzione di descrizione per ogni tipo di elemento.

  1. Elimina le righe sotto -- Try it.
  2. Scrivi local function describeWeapon(item: Weapon): string che restituisce `Weapon: {item.name} (damage {item.data.damage})`.
  3. Scrivi describePotion(item: Potion): string che restituisce `Potion: {item.name} (heals {item.data.heal})`.
  4. Sotto -- Try it, stampa describeWeapon(weapons[2]) e describePotion(potions[1]).

Premi Esegui codice: l'output mostra Weapon: Fire Axe (damage 40) e Potion: Health Potion (heals 40).

Provalo tu

-- La struttura degli elementi comune a tutti gli inventari
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}}
-- Crea un elemento con il prossimo id disponibile, memorizzalo e restituiscilo
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})
-- L'elemento con questo id, oppure 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})
-- Provalo
print(potions[1].data.heal)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online