Classes with Metatables

In the last exercise you built one bank account with a deposit method. But a bank has many accounts. You could copy the table and its methods for each one, but then every account carries its own copy of every method.

A better plan: keep the methods in one table, and give each account only its own data. In Lua, a metatable connects the two.

local Account = {}
Account.__index = Account

function Account.new(balance)
    local acc = {balance = balance}
    return setmetatable(acc, Account)
end

function Account:deposit(n)
    self.balance = self.balance + n
end

local a = Account.new(100)
local b = Account.new(20)
a:deposit(50)
print("a: " .. a.balance)
print("b: " .. b.balance)

Output:

a: 150
b: 20

a and b are two separate tables, so each has its own balance. The deposit changed only a. But neither table has a deposit field. So how does a:deposit(50) work?

setmetatable and __index

setmetatable(acc, Account) makes Account the metatable of acc. A metatable is a normal table that tells Lua how another table should behave. setmetatable returns acc, so Account.new can return it directly.

The line Account.__index = Account gives the rule. When you read a key that a table does not have, Lua checks its metatable for a field named __index (two underscores). If that field holds a table, Lua looks for the key there. So a:deposit(50) works like this:

  1. Lua looks for deposit in a. It is not there.
  2. a has the metatable Account, and Account.__index is Account.
  3. Lua finds deposit in Account and calls it, with self set to a.

A table like Account, which makes objects that share its methods, is often called a class. Account.new uses a dot, not a colon, because it makes a new object and has no self to work with.

Forgetting __index

Without the __index line, Lua has nowhere else to look:

local Account = {}

function Account.new(balance)
    local acc = {balance = balance}
    return setmetatable(acc, Account)
end

function Account:deposit(n)
    self.balance = self.balance + n
end

local a = Account.new(100)
a:deposit(50)

Output:

/usr/bin/lua5.4: main.lua:13: attempt to call a nil value (method 'deposit')

If you see this error on a method call, check the __index line first.

In the exercise, complete the Account class so that two accounts keep separate balances.