Menu
CoddyTech

Trả lời truy vấn vật phẩm

Thuộc phần Giới thiệu về Luau trong hành trình Lua của Coddy. Bài học 73 trên 80.

challenge icon

Thử thách

Trung bình

Trả lời người chơi khi họ hỏi về một vật phẩm.

  1. Xóa các dòng bên dưới -- Try it.
  2. Bên dưới đó, đọc local category = io.read() và local id: number = tonumber(io.read()) or 0.
  3. Với "weapon", in ra describeWeapon(item) cho findItem(weapons, id); nếu không thì dùng potions và describePotion.
  4. In ra Item not found khi findItem trả về nil.

Nhấn Run Code: với đầu vào là weapon và 2, bạn sẽ thấy Weapon: Fire Axe (damage 40).

Tự làm thử

-- Cấu trúc item chung cho mọi kho đồ
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}}
-- Tạo item với id chưa dùng tiếp theo, lưu rồi trả về item đó
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})
-- Item có id này, hoặc 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})
-- Mỗi loại item có một mô tả riêng
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
-- Chạy thử
print(describeWeapon(weapons[2]))
print(describePotion(potions[1]))

Tất cả bài học trong Giới thiệu về Luau

Tự luyện tập: Trình biên dịch Luau online