Menu
Coddy logo textTech

Function: Find Item By ID

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 65 of 73.

challenge icon

Challenge

Easy

Extend your project from the previous lesson (keep Item<T>, addItem, and the weapons inventory with its two items).

  • Write a generic function findItem<T>(inventory: {Item<T>}, id: number): Item<T>? that loops over the inventory and returns the item whose id matches, or nil if none does.
  • Call findItem(weapons, 2). If it returns an item, print the item's name and then its data.damage (two lines); otherwise print Item not found.
  • Call findItem(weapons, 99). If it returns an item, print the item's name; otherwise print Item not found.

Try it yourself

-- From the previous lesson
type Item<T> = {
    id: number,
    name: string,
    data: T,
}

-- NEW: create an item, store it, return it
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

-- Build the weapons inventory with the new function
local weapons: {Item<{damage: number}>} = {}
local sword = addItem(weapons, "Iron Sword", {damage = 25})
local axe = addItem(weapons, "Fire Axe", {damage = 40})

print(#weapons)
print(sword.id)
print(sword.name)
print(axe.id)
print(weapons[2].data.damage)

All lessons in Introduction To Luau

Practice on your own: Online Lua compiler