Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 32 ยท Projects

Project: Inventory with Classes

Build an inventory in Lua with a class, a subclass, metamethods for printing and comparing, sorting and a formatted report, with a JavaScript stand-in you can run.

Lua has no class keyword, yet people write large object-oriented programs in it. The trick is that a class is just a table, an object is a table whose metatable points to that class, and inheritance is a chain of lookups. This project puts all of that to work on something practical: a shop inventory that stores items, merges duplicates, sorts by value and prints an aligned report.

You will use classes and self, a subclass with a super call, four metamethods (__tostring, __eq, __lt, __len), table.sort, and string.format for the columns. The Lua code is real and read-only; the runnable examples are JavaScript stand-ins that mirror it, using JavaScript methods where Lua uses metamethods. Review objects and classes, inheritance and metatables first if you need to.

A class is a table

Class table Holds methods and sets Class.__index = Class.
Object A table whose metatable is the class.
Lookup chain Missing keys are searched in the class, then its parent.

Method calls use a colon so self is passed in.

1 / 2

Step 1: the Item class

An item has a name, a unit price and a quantity. The class table holds the methods; Item.__index = Item tells Lua that when a key is missing from an object, it should look in Item.

LUA
local Item = {}
Item.__index = Item

function Item.new(name, price, qty)
  local self = setmetatable({}, Item)
  self.name = name
  self.price = price
  self.qty = qty or 1
  return self
end

function Item:total()
  return self.price * self.qty
end

function Item:describe()
  return string.format("%-10s %3d x %7.2f = %8.2f",
    self.name, self.qty, self.price, self:total())
end

function Item:total() is sugar for function Item.total(self), and item:total() is sugar for item.total(item). The dot version defines the constructor because it has no object yet.

Now the metamethods. They live in the class table, because that is the metatable of every item.

LUA
Item.__tostring = function(self)
  return self:describe()
end

-- Same name means "the same product".
Item.__eq = function(a, b)
  return a.name == b.name
end

-- Order by total value; break ties by name so the order is always the same.
Item.__lt = function(a, b)
  local ta, tb = a:total(), b:total()
  if ta ~= tb then
    return ta < tb
  end
  return a.name < b.name
end

The tie-break in __lt matters. table.sort is not stable, and its comparison must be a consistent strict ordering; ordering by name when the totals match makes the result predictable.

Step 2: a subclass with a super call

Perishable goods are items with a shelf life. They should print an extra exp column, and anything that expires within two days is sold at half price. A subclass sets its own __index and then makes the parent its fallback.

LUA
local Perishable = setmetatable({}, { __index = Item })
Perishable.__index = Perishable

function Perishable.new(name, price, qty, days)
  local self = Item.new(name, price, qty)   -- build the parent part
  setmetatable(self, Perishable)             -- then switch to the subclass
  self.days = days
  return self
end

function Perishable:total()
  local full = Item.total(self)              -- super call
  if self.days <= 2 then
    return full * 0.5
  end
  return full
end

function Perishable:describe()
  return Item.describe(self) .. string.format("  exp %dd", self.days)
end

-- Metamethods are NOT inherited through __index, so copy them.
Perishable.__tostring = Item.__tostring
Perishable.__eq = Item.__eq
Perishable.__lt = Item.__lt

Two details deserve attention. First, a "super call" is just calling the parent's function explicitly with self: Item.total(self). Second, Lua looks for metamethods with a raw lookup in the metatable, so __tostring defined on Item is not found through Perishable's __index chain. If you forget the three copy lines, print(milk) shows something like table: 0x... instead of your formatted line. This is the most common surprise in Lua inheritance.

The first runnable stand-in models Steps 1 and 2 with JavaScript classes. JavaScript inherits toString automatically, and we express __eq and __lt as ordinary methods because JavaScript cannot overload == or <.

JS Stand-in: Item and Perishable

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The milk line shows a total of 3.60: six litres at 1.20 is 7.20, halved because it expires in two days. That discount lives only in Perishable:total, yet describe (defined in Item) calls self:total() and picks up the right version. This is polymorphism: the method is chosen by the object, not by the code that calls it.

Step 3: the Inventory class

The inventory holds an array of items. Adding an item that is already present should add to the quantity rather than create a second entry, and the == operator, backed by __eq, tells us whether two items are the same product.

LUA
local Inventory = {}
Inventory.__index = Inventory

function Inventory.new()
  return setmetatable({ items = {} }, Inventory)
end

function Inventory:add(item)
  for _, existing in ipairs(self.items) do
    if existing == item then
      existing.qty = existing.qty + item.qty
      return existing
    end
  end
  self.items[#self.items + 1] = item
  return item
end

function Inventory:total()
  local sum = 0
  for _, item in ipairs(self.items) do
    sum = sum + item:total()
  end
  return sum
end

Inventory.__len = function(self)
  return #self.items
end

#inventory now returns the number of entries, because __len is called by the length operator. Be aware that __eq is only tried when both operands are tables and are not the very same table, so comparing an item with a number is simply false.

Step 4: sorting and the report

For sorting, copy the array first so the inventory keeps its insertion order, then sort the copy. With __lt defined, table.sort(copy) already works; for descending order we flip the arguments.

LUA
function Inventory:sorted(descending)
  local copy = table.move(self.items, 1, #self.items, 1, {})
  if descending then
    table.sort(copy, function(a, b) return b < a end)
  else
    table.sort(copy)
  end
  return copy
end

function Inventory:report()
  local lines = { string.rep("=", 44) }
  for _, item in ipairs(self:sorted(true)) do
    lines[#lines + 1] = tostring(item)
  end
  lines[#lines + 1] = string.rep("-", 44)
  lines[#lines + 1] = string.format("%d products, total value %.2f", #self, self:total())
  return table.concat(lines, "\n")
end

table.move(a, 1, #a, 1, {}) copies a range into a new table: a handy shallow copy. tostring(item) triggers __tostring. The comparator function(a, b) return b < a end uses __lt with the operands swapped, which is exactly what "descending" means.

The second stand-in assembles the whole inventory. JavaScript's sort is stable, but we still use the tie-breaking comparison to match the Lua behavior.

JS Stand-in: inventory, sorting and report

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The report shows Hammer first with a quantity of 5, proof that the second add merged instead of appending. Compare the sorted names with the original order printed last: sorting a copy leaves the inventory untouched.

Ideas to extend it

  • Add a remove(name, qty) method that lowers the quantity and deletes the entry at zero (use table.remove, and iterate backwards when removing while looping).
  • Add a Fragile subclass with an insurance fee, and check that it needs the three metamethod copy lines too.
  • Add __concat or __add so that inventoryA + inventoryB merges two stocks.
  • Add __index as a function on Inventory so that stock.Hammer looks an item up by name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Perishable need lines like Perishable.__tostring = Item.__tostring?

    Lua uses a raw lookup in the object's metatable for metamethods, so inheriting methods through __index does not inherit __tostring, __eq or __lt.
  2. 2. What is the difference between Item.new(...) and item:total() in terms of self?

    obj:method(args) is shorthand for obj.method(obj, args). The constructor is called with a dot because there is no object yet.
  3. 3. Why does __lt break ties using the item name?

    table.sort needs a consistent strict ordering and does not preserve the original order of equal elements, so a tie-break gives repeatable results.
  4. 4. How does Perishable:describe reuse the parent's formatting?

    Lua has no super keyword. A super call is an explicit call to the parent's function with self passed in.

Summary

  • A class is a table with Class.__index = Class; an object is a table whose metatable is that class.
  • Use : for methods so self is passed automatically, and . for constructors.
  • A subclass chains to its parent with setmetatable(Sub, { __index = Parent }) and calls parent methods with Parent.method(self, ...).
  • Metamethods such as __tostring, __eq, __lt and __len are not inherited through __index; copy them.
  • Sort a copy with table.move and a consistent comparator that breaks ties.
  • Build report text with string.format column widths and table.concat.

Next: Project: A Text Adventure State Machine