0Pricing
Lua Academy · Lesson

Classes via Metatables

Simulate classes using tables and __index for method lookup.

Class Table Pattern

In Lua, a "class" is just a table that stores methods. Instances are tables whose metatable's __index points to the class table. This makes all methods accessible on instances via the lookup chain.

local Animal = {}
Animal.__index = Animal

function Animal.new(name, sound)
  return setmetatable({name=name, sound=sound}, Animal)
end

function Animal:speak()
  print(self.name .. " says " .. self.sound)
end

local dog = Animal.new("Rex","Woof")
dog:speak()  -- Rex says Woof

__index Points to Class

Setting ClassName.__index = ClassName means "look up missing keys in the class table." When an instance method is called, Lua doesn't find it in the instance, checks the metatable (__index), finds the class, and looks up the method there.

local Point = {}
Point.__index = Point

Point.type = "2D Point"

function Point.new(x,y)
  return setmetatable({x=x,y=y}, Point)
end

function Point:magnitude()
  return math.sqrt(self.x^2 + self.y^2)
end

local p = Point.new(3,4)
print(p:magnitude())   -- 5.0
print(p.type)          -- 2D Point (from class)

All lessons in this course

  1. Classes via Metatables
  2. Constructors and new()
  3. Instance Methods and self
  4. Encapsulation with Closures
← Back to Lua Academy