Menu
Coddy logo textTech

Function: Add Items

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 64 of 73.

challenge icon

Challenge

Easy

Extend your project from the previous lesson (keep the Item<T> type).

  • Write a generic function addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T> that creates an item with id = #inventory + 1, inserts it into inventory with table.insert, and returns it.
  • Create an empty typed array weapons of type {Item<{damage: number}>}.
  • Use addItem to add "Iron Sword" with {damage = 25}, storing the result in sword.
  • Use addItem to add "Fire Axe" with {damage = 40}, storing the result in axe.

Then print, each on its own line:

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

Try it yourself

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

All lessons in Introduction To Luau