Menu
Coddy logo textTech

Funzione: Ottenere i dettagli dell'elemento

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

challenge icon

Sfida

Medio

Completa il progetto! Mantieni tutto dalla lezione precedente: Item<T>, addItem, findItem, gli alias Weapon/Potion ed entrambi gli inventari (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • Scrivi describeWeapon(item: Weapon): string che restituisca Weapon: [name] (damage [damage]).
  • Scrivi describePotion(item: Potion): string che restituisca Potion: [name] (heals [heal]).
  • Leggi il numero di query con tonumber(io.read()).
  • Per ogni query, leggi una riga con una categoria (weapon o potion) e una riga con un id (converti con tonumber). Cerca nell'inventario corrispondente con findItem: stampa la descrizione se l'elemento esiste, altrimenti Item not found.

Per esempio, l'input 2, weapon, 2, potion, 1 (un valore per riga) stampa:

Weapon: Fire Axe (damage 40)
Potion: Health Potion (heals 40)

Provalo tu

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

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 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

-- NEW: named data shapes and readable item aliases
type WeaponData = {damage: number}
type PotionData = {heal: number}

type Weapon = Item<WeaponData>
type Potion = Item<PotionData>

-- Two precisely-typed inventories, one set of tools
local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})

local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
addItem(potions, "Mega Potion", {heal = 90})

print(#weapons)
print(#potions)
print(weapons[1].name)
print(potions[2].data.heal)

local firstPotion = findItem(potions, 1)
if firstPotion then
    print(firstPotion.name)
else
    print("Item not found")
end

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online