Menu
CoddyTech

دالة: وصف العناصر

جزء من قسم مقدمة إلى Luau في رحلة Lua على Coddy. الدرس 72 من 80.

challenge icon

التحدي

متوسط

أضف دالة وصف لكل نوع من العناصر.

  1. احذف الأسطر الموجودة تحت -- Try it.
  2. اكتب local function describeWeapon(item: Weapon): string بحيث تُرجع `Weapon: {item.name} (damage {item.data.damage})`.
  3. اكتب describePotion(item: Potion): string بحيث تُرجع `Potion: {item.name} (heals {item.data.heal})`.
  4. تحت -- Try it، اطبع describeWeapon(weapons[2]) وdescribePotion(potions[1]).

اضغط على Run Code: سيعرض الناتج Weapon: Fire Axe (damage 40) وPotion: Health Potion (heals 40).

جرّب بنفسك

-- بنية العنصر المشتركة بين جميع قوائم الجرد
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}}
-- أنشئ عنصرًا باستخدام أول id متاح، وخزّنه، ثم أعِده
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})
-- العنصر الذي يحمل هذا id، أو 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})
-- جرّبه
print(potions[1].data.heal)

جميع دروس مقدمة إلى Luau

تدرّب بنفسك: مترجم Luau عبر الإنترنت