Part 6 mini-project: Inventory System
This project uses chapters 26 and 27: methods, colon syntax, the
.new constructor pattern, one metatable per class.
Item and Inventory manage a bag of loot.
What to build
Two classes in the same module file:
Item — one collectable thing.
Item.new(name, weight, value)— constructor.- Fields:
name(string),weight(number),value(number). Item:describe()— one-line summary, e.g."sword (3.5kg, 50g)".
Inventory — a container of items.
Inventory.new()— constructor; starts with an empty list.- Field:
items(a list ofIteminstances). Inventory:add(item)— append an item.Inventory:remove(name)— remove the first item with that name; returns it, ornilif none matches.Inventory:list()— print each item's:describe()on its own line, then a totals footer.Inventory:totalWeight()— sum of weights.Inventory:totalValue()— sum of values.
main.lua:
- Creates a few items.
- Creates an inventory and adds them.
- Lists the inventory.
- Removes one item by name.
- Lists again.
- Prints total weight and value as a summary.
A sample run:
Inventory (3 items):
- sword (3.5kg, 50g)
- shield (5.0kg, 30g)
- potion (0.2kg, 5g)
Totals: 8.70kg, 85g
(removed sword)
Inventory (2 items):
- shield (5.0kg, 30g)
- potion (0.2kg, 5g)
Totals: 5.20kg, 35g
File layout
Two files. As in Part 5, cd into the project folder
first:
cd projects/05-inventory/starter
lua main.lua
Files (in both starter/ and finished/):
inventory.lua— definesItemandInventory, returns a table with both:local M = {} M.Item = Item M.Inventory = Inventory return Mmain.lua—requires the module, pulls out both classes, runs the scenario.
Hints
- Both classes use the chapter 27
__indexpattern: two class tables, two metatables, two constructors. Inventory:remove(name)walksself.itemswithipairsfor a matchingname, thentable.remove(self.items, i)drops it.- Use
string.formatfor the totals line inInventory:list:"Totals: %.2fkg, %dg".
What is fair game
Anything from Parts 2-6: variables, control flow, functions, modules, tables, methods, metatables.
Done?
When the scenario runs cleanly from main.lua, you're
done. Next: Chapter 31 — From Lua to
Luau, the bridge to Roblox Studio.