Menu
Coddy logo textTech

Funzione: Trovare un elemento per ID

Fa parte della sezione Introduzione a Luau del percorso Lua di Coddy. Lezione 65 di 73.

challenge icon

Sfida

Facile

Estendi il tuo progetto della lezione precedente (mantieni Item<T>, addItem e l’inventario weapons con i suoi due oggetti).

  • Scrivi una funzione generica findItem<T>(inventory: {Item<T>}, id: number): Item<T>? che scorra l’inventario e restituisca l’oggetto il cui id corrisponde, oppure nil se non ne trova nessuno.
  • Chiama findItem(weapons, 2). Se restituisce un oggetto, stampa il suo name e poi il suo data.damage (due righe); altrimenti stampa Item not found.
  • Chiama findItem(weapons, 99). Se restituisce un oggetto, stampa il suo name; altrimenti stampa Item not found.

Provalo tu

-- From the previous lesson
type Item<T> = {
    id: number,
    name: string,
    data: T,
}

-- NEW: create an item, store it, return it
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

-- Build the weapons inventory with the new function
local weapons: {Item<{damage: number}>} = {}
local sword = addItem(weapons, "Iron Sword", {damage = 25})
local axe = addItem(weapons, "Fire Axe", {damage = 40})

print(#weapons)
print(sword.id)
print(sword.name)
print(axe.id)
print(weapons[2].data.damage)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online