🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Classes with Tables

A Lua class is a table that holds shared methods for objects of one kind.

A class table shares methods through __index

Dog.new builds an object with a name. The object has no speak field of its own, so the lookup falls back to Dog.

local Dog = {}
Dog.__index = Dog
function Dog.new(name)
  local self = setmetatable({}, Dog)
  self.name = name
  return self
end
function Dog.speak(self)
  return "Woof from " .. self.name
end
local a = Dog.new("Rex")
print(a.name)
print(a.speak(a))

A colon call passes the object as self

A colon method is written with a colon after the class name. A colon call passes the object in front of the colon as the first value.

local Dog = {}
Dog.__index = Dog
function Dog.new(name)
  local self = setmetatable({}, Dog)
  self.name = name
  return self
end
function Dog:greet()
  return "Hello, I am " .. self.name
end
local a = Dog.new("Rex")
print(a:greet())

Each object keeps its own fields

Two objects come from the same class. Changing the name on one object leaves the name on the other object unchanged.

local Dog = {}
Dog.__index = Dog
function Dog.new(name)
  local self = setmetatable({}, Dog)
  self.name = name
  return self
end
local a = Dog.new("Rex")
local b = Dog.new("Bella")
a.name = "Max"
print(a.name)
print(b.name)

Example

local Player = {}
Player.__index = Player
function Player.new(name)
  local self = setmetatable({}, Player)
  self.name = name
  self.score = 0
  return self
end
function Player:add(points)
  self.score = self.score + points
end
function Player:report()
  return self.name .. " has " .. self.score .. " points"
end
local a = Player.new("Ana")
local b = Player.new("Ben")
a:add(10)
a:add(5)
b:add(7)
print(a:report())
print(b:report())

Key points

  • Class table: A class table stores the methods that all its objects share.
  • Constructor: A constructor builds a fresh object table and links it to the class.
  • Index fallback: Setting __index to the class lets a missing key on an object fall back to the class table.
  • Colon method: A colon method receives the calling object as its first value, named self.
  • Instance state: Each object keeps its own fields, so changing one object does not change another object.

In this example, Player is a class table with __index set to itself. Player.new builds an object with a name and a score of zero. The add method adds points to the calling object, and report builds a sentence from its name and score. Two players are made. Ana gains ten points and then five points, while Ben gains seven points, so the two reports show fifteen points and seven points.

Note

Lua has no built-in class keyword, so a class is a way to build shared methods from tables and metatables.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the call a:greet() pass to the greet method?