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 of Item instances).
  • Inventory:add(item) — append an item.
  • Inventory:remove(name) — remove the first item with that name; returns it, or nil if 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:

  1. Creates a few items.
  2. Creates an inventory and adds them.
  3. Lists the inventory.
  4. Removes one item by name.
  5. Lists again.
  6. 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 — defines Item and Inventory, returns a table with both:

    local M = {}
    M.Item = Item
    M.Inventory = Inventory
    return M
  • main.luarequires the module, pulls out both classes, runs the scenario.

Hints

  • Both classes use the chapter 27 __index pattern: two class tables, two metatables, two constructors.
  • Inventory:remove(name) walks self.items with ipairs for a matching name, then table.remove(self.items, i) drops it.
  • Use string.format for the totals line in Inventory: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.