advanced
45 min

Object-Oriented Programming

Understand OOP concepts and how to apply them in Lua.

MetatablesClassesInheritance__index

1
Introduction to Metatables

Metatables allow you to change the behavior of tables.

Basic Metatable

local myTable = {value = 10}
local metatable = {
  __add = function(a, b)
    return a.value + b.value
  end
}

setmetatable(myTable, metatable)

local table2 = {value = 5}
setmetatable(table2, metatable)

local result = myTable + table2  -- Uses __add metamethod
print(result)  -- 15

Metamethods like __add define custom behavior for operators.

2
Creating Classes

Use metatables to create class-like structures.

Simple Class

-- Class definition
local Car = {}
Car.__index = Car

function Car.new(brand, color)
  local self = setmetatable({}, Car)
  self.brand = brand
  self.color = color
  self.speed = 0
  return self
end

function Car:drive()
  self.speed = 60
  print(self.brand .. " is driving at " .. self.speed .. " mph")
end

function Car:stop()
  self.speed = 0
  print(self.brand .. " has stopped")
end

-- Usage
local myCar = Car.new("Toyota", "Red")
myCar:drive()
myCar:stop()

Classes group related data and functions together.

💡 Tips:

  • • Use : for methods that need self
  • • __index allows instances to access class methods
  • • new() is a convention for constructor functions

3
Inheritance

Create subclasses that inherit from parent classes.

Class Inheritance

-- Parent class
local Vehicle = {}
Vehicle.__index = Vehicle

function Vehicle.new(brand)
  local self = setmetatable({}, Vehicle)
  self.brand = brand
  return self
end

function Vehicle:start()
  print(self.brand .. " started")
end

-- Child class
local Car = setmetatable({}, {__index = Vehicle})
Car.__index = Car

function Car.new(brand, doors)
  local self = setmetatable(Vehicle.new(brand), Car)
  self.doors = doors
  return self
end

function Car:honk()
  print(self.brand .. " honks!")
end

-- Usage
local myCar = Car.new("Honda", 4)
myCar:start()  -- Inherited from Vehicle
myCar:honk()   -- Car's own method

Child classes inherit methods from parent classes.

Practice Exercises

Exercise 1: Player Class

Create a Player class with health and methods.

Starter Code:

-- Create your Player class here
Show Solution
local Player = {}
Player.__index = Player

function Player.new(name, health)
  local self = setmetatable({}, Player)
  self.name = name
  self.health = health
  return self
end

function Player:takeDamage(amount)
  self.health = self.health - amount
  print(self.name .. " took " .. amount .. " damage")
end

function Player:heal(amount)
  self.health = self.health + amount
  print(self.name .. " healed " .. amount .. " HP")
end

local player1 = Player.new("Hero", 100)
player1:takeDamage(25)
player1:heal(10)

Ready for more?

Continue your learning journey

Executors.Online - Your Roblox Developer Hub