Menu
Coddy logo textTech

Function: Get Item Details

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

challenge icon

Challenge

Medium

Finish the project! Keep everything from the previous lesson: Item<T>, addItem, findItem, the Weapon/Potion aliases, and both inventories (weapons: Iron Sword 25 / Fire Axe 40, potions: Health Potion 40 / Mega Potion 90).

  • Write describeWeapon(item: Weapon): string returning Weapon: [name] (damage [damage]).
  • Write describePotion(item: Potion): string returning Potion: [name] (heals [heal]).
  • Read the number of queries with tonumber(io.read()).
  • For each query, read a category line (weapon or potion) and an id line (convert with tonumber). Search the matching inventory with findItem: print the description if the item exists, or Item not found otherwise.

For example, the input 2, weapon, 2, potion, 1 (one value per line) prints:

Weapon: Fire Axe (damage 40)
Potion: Health Potion (heals 40)

Try it yourself

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

All lessons in Introduction To Luau