Understand OOP concepts and how to apply them in Lua.
Metatables allow you to change the behavior of tables.
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.
Use metatables to create class-like structures.
-- 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.
Create subclasses that inherit from parent classes.
-- 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.
Create a Player class with health and methods.
-- Create your Player class here
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)
Continue your learning journey