Menu
Coddy logo textTech

Funktion: Elementdetails abrufen

Teil des Abschnitts Einführung in Luau der Lua-Journey von Coddy — Lektion 67 von 73.

challenge icon

Aufgabe

Mittel

Schließe das Projekt ab! Behalte alles aus der vorherigen Lektion bei: Item<T>, addItem, findItem, die Weapon/Potion-Aliase und beide Inventare (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • Schreibe describeWeapon(item: Weapon): string, das Weapon: [name] (damage [damage]) zurückgibt.
  • Schreibe describePotion(item: Potion): string, das Potion: [name] (heals [heal]) zurückgibt.
  • Lies die Anzahl der Abfragen mit tonumber(io.read()) ein.
  • Lies für jede Abfrage eine category-Zeile (weapon oder potion) und eine ID-Zeile (mit tonumber umwandeln) ein. Durchsuche das passende inventory mit findItem: Gib die Beschreibung aus, wenn das item existiert, andernfalls Item not found.

Zum Beispiel gibt die Eingabe 2, weapon, 2, potion, 1 (ein Wert pro Zeile) Folgendes aus:

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

Probier es selbst

-- Das Inventarsystem aus den vorherigen Lektionen
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

type WeaponData = {damage: number}
type PotionData = {heal: number}

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

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

-- Schreibe hier den Code
-- 1) describeWeapon(item: Weapon): string und describePotion(item: Potion): string
-- 2) lies die Abfrageanzahl, dann pro Abfrage: Kategoriezeile + ID-Zeile
-- 3) findItem in the right inventory; print the description or "Item not found"

Alle Lektionen in Einführung in Luau