Classes and methods
A class is a table of shared methods, and the colon syntax passes the object as self.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Calling a method with a dot and forgetting self
- Defining a method with a colon and forgetting that self is implicit
- 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: