Menu
CoddyTech

מענה לשאילתות על פריטים

חלק מהיחידה מבוא ל-Luau במסלול ה-Lua של Coddy. שיעור 73 מתוך 80.

challenge icon

אתגר

בינוני

ענה לשחקן ששואל על פריט אחד.

  1. מחק את השורות שמתחת ל־-- Try it.
  2. מתחתיהן, קרא את local category = io.read() ואת local id: number = tonumber(io.read()) or 0.
  3. עבור "weapon", הדפס את describeWeapon(item) עבור findItem(weapons, id); אחרת, השתמש ב־potions וב־describePotion.
  4. הדפס את Item not found כאשר findItem מחזירה nil.

לחץ על הרצת קוד: עם הקלט weapon ו־2, תראה את Weapon: Fire Axe (damage 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})
-- תיאור אחד לכל סוג פריט
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
-- נסה זאת
print(describeWeapon(weapons[2]))
print(describePotion(potions[1]))

כל השיעורים ביחידה מבוא ל-Luau

תרגלו בעצמכם: קומפיילר Luau אונליין