Menu
Coddy logo textTech

פונקציה: הוספת פריטים

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

challenge icon

אתגר

קל

הרחב את הפרויקט שלך מהשיעור הקודם (השאר את הטיפוס Item<T>).

  • כתוב פונקציה גנרית addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T> שיוצרת פריט עם id = #inventory + 1, מוסיפה אותו אל inventory באמצעות table.insert ומחזירה אותו.
  • צור מערך מטיפוס מוגדר מראש וריק בשם weapons מהטיפוס {Item<{damage: number}>}.
  • השתמש ב-addItem כדי להוסיף את "Iron Sword" עם {damage = 25}, ושמור את התוצאה ב-sword.
  • השתמש ב-addItem כדי להוסיף את "Fire Axe" עם {damage = 40}, ושמור את התוצאה ב-axe.

לאחר מכן הדפס, כל אחד בשורה נפרדת:

  1. #weapons
  2. sword.id
  3. sword.name
  4. axe.id
  5. weapons[2].data.damage

נסו בעצמכם

-- The generic item shape every inventory will share
type Item<T> = {
    id: number,
    name: string,
    data: T,
}

-- A weapon item: T is filled in with {damage: number}
local sword: Item<{damage: number}> = {
    id = 1,
    name = "Iron Sword",
    data = {damage = 25},
}

-- A potion item: same shape, different data type
local potion: Item<{heal: number}> = {
    id = 2,
    name = "Health Potion",
    data = {heal = 40},
}

print(sword.id)
print(sword.name)
print(sword.data.damage)
print(potion.id)
print(potion.name)
print(potion.data.heal)

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

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