Menu
CoddyTech

Function: Add Items

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

challenge icon

Challenge

Easy

Add a function that puts items into an inventory.

  1. Delete the lines under -- Try it.
  2. Above it, write local function addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T>: insert {id = #inventory + 1, name = name, data = data} into inventory and return it.
  3. Under -- Try it, print addItem({}, "Old Map", "torn").id.

Press Run Code: the output shows 1.

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}}
-- Try it
print(sword.name)
print(potion.data.heal)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler