Menu
CoddyTech

Function: Find Item By ID

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 70 of 80.

challenge icon

Challenge

Easy

Add a function that looks an item up by its id.

  1. Delete the lines under -- Try it.
  2. Write local function findItem<T>(inventory: {Item<T>}, id: number): Item<T>? returning the item whose id matches, or nil.
  3. Under -- Try it, print findItem(weapons, 99), then store findItem(weapons, 2) in local found and print found.name inside if found then.

Press Run Code: the output shows nil and Fire Axe.

Try it yourself

-- The item shape every inventory shares
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}}
-- Make an item with the next free id, 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
local weapons: {Item<{damage: number}>} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- Try it
print(#weapons)
print(weapons[2].name)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler