Function: Find Item By ID
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 65 of 73.
Challenge
EasyExtend your project from the previous lesson (keep Item<T>, addItem, and the weapons inventory with its two items).
- Write a generic function
findItem<T>(inventory: {Item<T>}, id: number): Item<T>?that loops over the inventory and returns the item whoseidmatches, ornilif none does. - Call
findItem(weapons, 2). If it returns an item, print the item'snameand then itsdata.damage(two lines); otherwise printItem not found. - Call
findItem(weapons, 99). If it returns an item, print the item'sname; otherwise printItem not found.
Try it yourself
-- From the previous lesson
type Item<T> = {
id: number,
name: string,
data: T,
}
-- NEW: create an item, 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
-- Build the weapons inventory with the new function
local weapons: {Item<{damage: number}>} = {}
local sword = addItem(weapons, "Iron Sword", {damage = 25})
local axe = addItem(weapons, "Fire Axe", {damage = 40})
print(#weapons)
print(sword.id)
print(sword.name)
print(axe.id)
print(weapons[2].data.damage)
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