Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

دالة: الحصول على تفاصيل العنصر

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

challenge icon

التحدي

متوسط

أكمل المشروع! احتفظ بكل شيء من الدرس السابق: Item<T> وaddItem وfindItem والاسمين المستعارين Weapon/Potion وكلا المخزنين (weapons: Iron Sword 25 / Fire Axe 40، potions: Health Potion 40 / Mega Potion 90).

  • اكتب describeWeapon(item: Weapon): string بحيث تُرجع Weapon: [name] (damage [damage]).
  • اكتب describePotion(item: Potion): string بحيث تُرجع Potion: [name] (heals [heal]).
  • اقرأ عدد الاستعلامات باستخدام tonumber(io.read()).
  • لكل استعلام، اقرأ سطر الفئة (weapon أو potion) وسطر المعرّف (حوّله باستخدام tonumber). ابحث في المخزن المطابق باستخدام findItem: اطبع الوصف إذا كان العنصر موجودًا، أو Item not found خلاف ذلك.

على سبيل المثال، الإدخال 2, weapon, 2, potion, 1 (قيمة واحدة في كل سطر) يطبع:

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

جرّب بنفسك

-- نظام المخزون من الدروس السابقة
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

type WeaponData = {damage: number}
type PotionData = {heal: number}

type Weapon = Item<WeaponData>
type Potion = Item<PotionData>

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

-- اكتب الكود هنا
-- 1) describeWeapon(item: Weapon): string و describePotion(item: Potion): string
-- 2) اقرأ عدد الاستعلامات، ثم لكل استعلام: سطر الفئة + سطر المعرّف
-- 3) findItem in the right inventory; print the description or "Item not found"

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

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