Menu
CoddyTech

Fungsi: Dapatkan Detail Barang

Termasuk bagian Pengantar Luau dalam perjalanan Lua di Coddy. Pelajaran 67 dari 73.

challenge icon

Tantangan

Sedang

Selesaikan proyeknya! Pertahankan semua yang dibuat pada pelajaran sebelumnya: Item<T>, addItem, findItem, alias Weapon/Potion, dan kedua inventory (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • Tulis describeWeapon(item: Weapon): string yang mengembalikan Weapon: [name] (damage [damage]).
  • Tulis describePotion(item: Potion): string yang mengembalikan Potion: [name] (heals [heal]).
  • Baca jumlah query dengan tonumber(io.read()).
  • Untuk setiap query, baca baris kategori (weapon atau potion) dan baris id (konversikan dengan tonumber). Cari di inventory yang sesuai dengan findItem: cetak deskripsi jika item ditemukan, atau Item not found jika tidak.

Misalnya, input 2, weapon, 2, potion, 1 (satu nilai per baris) mencetak:

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

Coba sendiri

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

Semua pelajaran di Pengantar Luau

Latihan sendiri: Compiler Luau online