Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 32 ยท Metatables and OOP

Objects and Classes

Build classes in Lua with tables and metatables: the colon call syntax and self, class tables with __index, constructors, and private state with closures.

Lua has no class keyword, yet Lua programs are full of objects. An object is a table that holds some data, and a class is another table that holds the functions those objects share. A metatable connects the two. Once you see how self, the colon syntax and __index fit together, the pattern is only a few lines long.

This lesson relies on Metatables and Metamethods (especially __index) and on how tables hold functions as values (see Functions). The Lua code is read-only; the live editors are JavaScript stand-ins that mirror the same structure with prototypes.

The recipe for a class

Class table Holds the shared methods.
__index Points the class at itself.
new Creates a table, sets its metatable.
self The object a method works on.

Method lookup falls through from the object to its class.

1 / 2

Methods and the colon syntax

A method is a function stored in a table field that takes the object as its first parameter, conventionally called self. Lua gives you sugar for both halves:

LUA
local account = {balance = 100}

function account.deposit(self, amount)
  self.balance = self.balance + amount
end

account.deposit(account, 50)    -- explicit self
account:deposit(25)             -- the colon passes `account` as self
print(account.balance)          --> 175

Two rules cover it:

  • obj:method(args) is exactly obj.method(obj, args), with obj evaluated only once.
  • function t:name(args) ... end is exactly function t.name(self, args) ... end.

The most common beginner bug is using a dot where the colon was meant. account.deposit(25) passes 25 as self and leaves amount as nil, which fails with an error such as attempt to index a number value (local 'self'). If a method complains about self, check the call site first.

JS Stand-in: what the colon really does

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

No output.

A class with __index

Putting the shared methods in every object would waste memory. Instead, put them once in a class table and make objects fall back to it through __index. Setting Class.__index = Class lets the class serve as its own metatable:

LUA
local Account = {}
Account.__index = Account

function Account.new(owner, balance)
  local self = setmetatable({}, Account)
  self.owner = owner
  self.balance = balance or 0
  return self
end

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

function Account:describe()
  return self.owner .. " has " .. self.balance
end

local a = Account.new("Ada", 100)
a:deposit(50)
print(a:describe())             --> Ada has 150

When you call a:deposit(50), Lua reads a.deposit. The object has no such field, so __index sends the lookup to Account, which has it. Each object stores only its own data (owner, balance); the functions live in one place.

Name the constructor new and use capitalized class names. It is not a language rule, but nearly every Lua codebase follows it, so your code will look familiar to other readers.

JS Stand-in: a class whose methods are shared

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

No output.

Giving objects a nicer face

Combine classes with the metamethods you already know. Adding __tostring to the class makes print(a) readable; __eq, __lt and __add work the same way. Because Account is the metatable of its objects, you define them directly on it:

LUA
function Account:__tostring()
  return "Account(" .. self.owner .. ", " .. self.balance .. ")"
end
print(a)                        --> Account(Ada, 150)

Note that metamethods are looked up in the metatable without going through __index, so they must be defined on the class itself (they are not found by walking up the chain from the object).

Encapsulation with closures

Fields in a table are public: any code can read or change a.balance. Lua has no private keyword. When you need real privacy, store the state in local variables captured by closures (see Varargs and Closures) and expose only functions:

LUA
local function newCounter()
  local count = 0               -- invisible from outside
  return {
    increment = function() count = count + 1 end,
    value = function() return count end,
  }
end

local c = newCounter()
c.increment()
c.increment()
print(c.value())                --> 2
print(c.count)                  --> nil

This costs more memory, because each object carries its own closures instead of sharing class methods, so reserve it for cases where hiding data truly matters. A cheaper convention is to prefix internal fields with an underscore (self._cache) and agree not to touch them.

JS Stand-in: private state in a closure

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is obj:method(1) equivalent to?

    The colon passes the object itself as the first argument, named self inside the method.
  2. 2. Why does Account.__index = Account appear in most class definitions?

    Objects use the class as their metatable, and __index tells Lua to search the class when a key is missing from the object.
  3. 3. A method fails with 'attempt to index a number value (local self)' right after you call acct.deposit(25). What is the likely cause?

    With the dot, no self is passed. The 25 lands in self and amount stays nil.
  4. 4. How do you make a field truly private in Lua?

    Lua has no private keyword. An underscore is only a convention, while a captured local variable cannot be reached from outside.

Summary

  • A method is a function in a table that takes self first; obj:m(x) means obj.m(obj, x) and function T:m() adds self for you.
  • A class is a table with Class.__index = Class; new creates a table and calls setmetatable(obj, Class).
  • Objects hold their own data; shared functions live once in the class.
  • Metamethods such as __tostring are defined on the class itself.
  • Use closures for real privacy, an underscore prefix for a convention.

Next, extend classes with Inheritance and Mixins.