Menu
CoddyTech

The Weapons List

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

challenge icon

Challenge

Easy

Fill a typed weapons inventory with addItem.

  1. Delete the lines under -- Try it.
  2. Above it, create local weapons: {Item<{damage: number}>} = {}.
  3. Use addItem to add "Iron Sword" with {damage = 25}, then "Fire Axe" with {damage = 40}.
  4. Under -- Try it, print #weapons and weapons[2].name.

Press Run Code: the output shows 2 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
-- Try it
print(addItem({}, "Old Map", "torn").id)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler