Menu
Coddy logo textTech

Funzione: Aggiungere elementi

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

challenge icon

Sfida

Facile

Estendi il tuo progetto della lezione precedente (mantieni il tipo Item<T>).

  • Scrivi una funzione generica addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T> che crea un elemento con id = #inventory + 1, lo inserisce in inventory con table.insert e lo restituisce.
  • Crea un array tipizzato vuoto weapons di tipo {Item<{damage: number}>}.
  • Usa addItem per aggiungere "Iron Sword" con {damage = 25}, memorizzando il risultato in sword.
  • Usa addItem per aggiungere "Fire Axe" con {damage = 40}, memorizzando il risultato in axe.

Quindi stampa, ciascuno su una riga:

  1. #weapons
  2. sword.id
  3. sword.name
  4. axe.id
  5. weapons[2].data.damage

Provalo tu

-- The generic item shape every inventory will share
type Item<T> = {
    id: number,
    name: string,
    data: T,
}

-- A weapon item: T is filled in with {damage: number}
local sword: Item<{damage: number}> = {
    id = 1,
    name = "Iron Sword",
    data = {damage = 25},
}

-- A potion item: same shape, different data type
local potion: Item<{heal: number}> = {
    id = 2,
    name = "Health Potion",
    data = {heal = 40},
}

print(sword.id)
print(sword.name)
print(sword.data.damage)
print(potion.id)
print(potion.name)
print(potion.data.heal)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online