Object-oriented programming in Lua
Lua does not have built-in support for object-oriented programming, but it does have powerful features for creating custom data types and implementing object-oriented programming patterns using tables and metatables.
In Lua, you can define a class as a table with methods that operate on the data contained in the table. You can create objects of the class by copying the table and adding data specific to each object. You can use metatables to implement inheritance, operator overloading, and other advanced features.
Here's an example of how to define a simple class Person:
-- define the class
local Person = {
name = "",
age = 0,
}
-- define a method of the class
function Person:greet()
print("Hello, my name is " .. self.name .. ". Nice to meet you!")
end
-- create an object of the class
local person1 = {
name = "Alice",
age = 30,
}
setmetatable(person1, {__index = Person})
-- call a method of the object
person1:greet()
In this case, the variable Person is a table that defines the class with two properties name and age, and a method greet that prints a message using the name property. The greet method uses the self keyword to refer to the object that the method is called on.
To create an object of the Person class, we create a new table person1 with the properties name and age, and then set the metatable of the table to the Person table. This allows us to call the greet method on the person1 object using the : syntax.
Here's an example of how to implement inheritance in Lua using metatables:
-- define the base class
local Shape = {
x = 0,
y = 0,
}
function Shape:new(x, y)
local obj = {
x = x,
y = y,
}
setmetatable(obj, {__index = self})
return obj
end
function Shape:move(dx, dy)
self.x = self.x + dx
self.y = self.y + dy
end
-- define the subclass
local Circle = Shape:new()
function Circle:new(x, y, r)
local obj = Shape.new(self, x, y)
obj.r = r
return obj
end
function Circle:area()
return math.pi * self.r^2
end
-- create an object of the subclass
local circle1 = Circle:new(0, 0, 5)
-- call a method of the subclass
circle1:move(1, 1)
print(circle1.x, circle1.y) -- prints 1 1
print(circle1:area()) -- prints 78.539816339745
In this case, we define a base class Shape that has properties x and y and a method move that changes the position of the shape. We define a subclass Circle that extends the Shape class with a new property r and a method area that computes the area of the circle. We use the Shape:new method to create the Circle object and set its metatable to the Shape table. This allows the Circle object to inherit the move method from the Shape class. We can then call the move and area methods on the circle1 object.
In conclusion, Lua provides a flexible and powerful way to implement object-oriented programming using tables and metatables.
Leave a Comment