Menu
Coddy logo textTech

פונקציה: קבלת פרטי פריט

חלק מהיחידה מבוא ל-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)

נסו בעצמכם

-- From the previous lessons
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

-- NEW: named data shapes and readable item aliases
type WeaponData = {damage: number}
type PotionData = {heal: number}

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

-- Two precisely-typed inventories, one set of tools
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})

print(#weapons)
print(#potions)
print(weapons[1].name)
print(potions[2].data.heal)

local firstPotion = findItem(potions, 1)
if firstPotion then
    print(firstPotion.name)
else
    print("Item not found")
end

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

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