Function: Add Items
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 64 of 73.
Challenge
EasyExtend your project from the previous lesson (keep the Item<T> type).
- Write a generic function
addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T>that creates an item withid = #inventory + 1, inserts it intoinventorywithtable.insert, and returns it. - Create an empty typed array
weaponsof type{Item<{damage: number}>}. - Use
addItemto add"Iron Sword"with{damage = 25}, storing the result insword. - Use
addItemto add"Fire Axe"with{damage = 40}, storing the result inaxe.
Then print, each on its own line:
#weaponssword.idsword.nameaxe.idweapons[2].data.damage
Try it yourself
-- The generic item shape every inventory will share
type Item<T> = {
id: number,
name: string,
data: T,
}
-- A weapon item: T is filled in with {damage: number}
local sword: Item<{damage: number}> = {
id = 1,
name = "Iron Sword",
data = {damage = 25},
}
-- A potion item: same shape, different data type
local potion: Item<{heal: number}> = {
id = 2,
name = "Health Potion",
data = {heal = 40},
}
print(sword.id)
print(sword.name)
print(sword.data.damage)
print(potion.id)
print(potion.name)
print(potion.data.heal)
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions7Project: Typed Task Manager
Project: The Task ShapeFunction to Add a Task10Project: Generic Inventory
Project: Inventory ItemFunction: Add Items2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps