Menu
CoddyTech

L'elenco delle armi

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

challenge icon

Sfida

Facile

Riempi un inventario di armi tipizzato con addItem.

  1. Elimina le righe sotto -- Try it.
  2. Sopra, crea local weapons: {Item<{damage: number}>} = {}.
  3. Usa addItem per aggiungere "Iron Sword" con {damage = 25}, poi "Fire Axe" con {damage = 40}.
  4. Sotto -- Try it, stampa #weapons e weapons[2].name.

Premi Esegui codice: l'output mostra 2 e Fire Axe.

Provalo tu

-- La struttura degli oggetti condivisa da 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
-- Provalo
print(addItem({}, "Old Map", "torn").id)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online