← Back to Lua Course | Chapter 6: OOP with Metatables | Lesson 3 of 7

Classes and methods

A class is a table of shared methods, and the colon syntax passes the object as self.

In this page:

  1. Classes and methods

Classes and methods

Lua has no built-in class keyword, so a class is a table that holds methods and serves as the metatable for its instances via __index. Defining function Class:method() is sugar for function Class.method(self), and calling obj:method() passes obj as self. Instances hold their own data and share the methods from the class.

Note: obj:method(x) is exactly obj.method(obj, x).

Example: Classes and methods

lua
local Dog = {}
Dog.__index = Dog

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

function Dog:speak()
  return self.name .. " says woof"
end

local d = Dog.new("Rex")
print(d:speak())
print(d.speak(d))
print(rawget(d, "speak"))

-- Output:
-- Rex says woof
-- Rex says woof
-- nil
Common Mistakes
  1. Calling a method with a dot and forgetting self
  2. Defining a method with a colon and forgetting that self is implicit
  3. Setting __index on the instance instead of the class
Chapter Summary
  • A class is a table of methods
  • Class.__index = Class
  • obj:method() passes self
  • Instances share methods
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.