Menu
CoddyTech

Funzione: Trovare un oggetto per ID

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

challenge icon

Sfida

Facile

Aggiungi una funzione che cerca un oggetto tramite il suo id.

  1. Elimina le righe sotto -- Try it.
  2. Scrivi local function findItem<T>(inventory: {Item<T>}, id: number): Item<T>? che restituisca l'oggetto il cui id corrisponde, oppure nil.
  3. Sotto -- Try it, stampa findItem(weapons, 99), poi memorizza findItem(weapons, 2) in local found e stampa found.name all'interno di if found then.

Premi Run Code: l'output mostra nil e Fire Axe.

Provalo tu

-- La struttura degli oggetti 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 oggetto 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
local weapons: {Item<{damage: number}>} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- Provalo
print(#weapons)
print(weapons[2].name)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online