Menu
CoddyTech

Function: Describe Items

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

challenge icon

Challenge

Medium

Add a description function for each kind of item.

  1. Delete the lines under -- Try it.
  2. Write local function describeWeapon(item: Weapon): string returning `Weapon: {item.name} (damage {item.data.damage})`.
  3. Write describePotion(item: Potion): string returning `Potion: {item.name} (heals {item.data.heal})`.
  4. Under -- Try it, print describeWeapon(weapons[2]) and describePotion(potions[1]).

Press Run Code: the output shows Weapon: Fire Axe (damage 40) and Potion: Health Potion (heals 40).

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
type Weapon = Item<{damage: number}>
type Potion = Item<{heal: number}>
local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- The item with this id, or nil
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
local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
-- Try it
print(potions[1].data.heal)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler