Menu
CoddyTech

Hàm: mô tả 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 72 trên 80.

challenge icon

Thử thách

Trung bình

Thêm một hàm mô tả cho từng loại vật phẩm.

  1. Xóa các dòng bên dưới -- Try it.
  2. Viết local function describeWeapon(item: Weapon): string để trả về `Weapon: {item.name} (damage {item.data.damage})`.
  3. Viết describePotion(item: Potion): string để trả về `Potion: {item.name} (heals {item.data.heal})`.
  4. Bên dưới -- Try it, in ra describeWeapon(weapons[2]) và describePotion(potions[1]).

Nhấn Run Code: đầu ra hiển thị Weapon: Fire Axe (damage 40) và Potion: Health Potion (heals 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})
-- Thử nhé
print(potions[1].data.heal)

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