Menu
CoddyTech

Odpowiadanie na zapytania o przedmioty

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

challenge icon

Wyzwanie

Średni

Odpowiedz graczowi, który pyta o jeden przedmiot.

  1. Usuń wiersze pod -- Try it.
  2. Pod nim odczytaj local category = io.read() i local id: number = tonumber(io.read()) or 0.
  3. Dla "weapon" wypisz describeWeapon(item) dla findItem(weapons, id); w przeciwnym razie użyj potions i describePotion.
  4. Wypisz Item not found, gdy findItem zwróci nil.

Naciśnij Uruchom kod: po wpisaniu weapon i 2 zobaczysz Weapon: Fire Axe (damage 40).

Spróbuj swoich sił

-- Struktura elementu wspólna dla wszystkich ekwipunków
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}}
-- Utwórz element z kolejnym wolnym id, zapisz go i zwróć
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
type Weapon = Item<{damage: number}>
type Potion = Item<{heal: number}>
local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- Element o tym id lub nil
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
local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
-- Osobny opis dla każdego rodzaju elementu
local function describeWeapon(item: Weapon): string
    return `Weapon: {item.name} (damage {item.data.damage})`
end

local function describePotion(item: Potion): string
    return `Potion: {item.name} (heals {item.data.heal})`
end
-- Wypróbuj to
print(describeWeapon(weapons[2]))
print(describePotion(potions[1]))

Wszystkie lekcje w sekcji Wprowadzenie do Luau

Poćwicz samodzielnie: Kompilator Luau online