Menu
Coddy logo textTech

Funkcja: pobieranie szczegółów elementu

Część sekcji Wprowadzenie do Luau ścieżki Lua w Coddy. Lekcja 67 z 73.

challenge icon

Wyzwanie

Średni

Dokończ projekt! Zachowaj wszystko z poprzedniej lekcji: Item<T>, addItem, findItem, aliasy Weapon/Potion oraz oba ekwipunki (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • Napisz describeWeapon(item: Weapon): string, które zwraca Weapon: [name] (damage [damage]).
  • Napisz describePotion(item: Potion): string, które zwraca Potion: [name] (heals [heal]).
  • Odczytaj liczbę zapytań za pomocą tonumber(io.read()).
  • Dla każdego zapytania odczytaj wiersz z kategorią (weapon lub potion) oraz wiersz z identyfikatorem (przekonwertuj go za pomocą tonumber). Wyszukaj element w odpowiednim ekwipunku za pomocą findItem: wypisz opis, jeśli element istnieje, lub Item not found w przeciwnym razie.

Na przykład wejście 2, weapon, 2, potion, 1 (jedna wartość w każdym wierszu) wypisuje:

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

Spróbuj swoich sił

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

Wszystkie lekcje w sekcji Wprowadzenie do Luau

Poćwicz samodzielnie: Kompilator Luau online