Introduction
A lightweight, flexible, and extensible object-oriented programming (OOP) system for Lua.
It provides class creation, inheritance, encapsulation, operator overloading, and utility helpers, all in a single file.
Designed for seamless integration into any Lua project, with support for private members and advanced debugging tools.
Installation
local Class = require("class")
init
Initialization function automatically called when creating an object via 'Class()'.
Defined inside the table passed to the constructor.
local A = Class{
init = function(self)
print("Object initialized!")
end,
}
local obj = A() -- Prints "Object initialized!"
include
Recursively merges two classes (or tables) by copying their members.
It respects metatables.
local Mixin = {
say = function() print("Hello") end
}
local A = Class{}
A = Class:include(A, Mixin)
A.say() -- Hello
clone
Creates a deep copy of a class or instance, preserving its metatable.
local A = Class{
foo = "bar"
}
local B = Class:clone(A)
print(B.foo) -- bar
DebugInfos
Prints the internal details of an instance: type, private members, methods.
local A = Class{
foo = function() end
}
local obj = A()
print(obj:DebugInfos())
accessor
Generates getter and setter functions for a private member.
local A = Class{
init = function(self)
Class:accessor(self, "sName", "Name", "John")
end
}
local a = A()
a:SetName("Doe")
print(a:GetName()) -- Doe
overloadOperators
Overloads the operator to merge two instances of the same type.
local A = Class{
init = function(self)
self.__private.value = 42
end
}
Class:overloadOperators(A)
local a1 = A()
local a2 = A()
local result = a1 + a2
new
Creates a new class, supports options like multiple inheritance via '__includes'.
local MyClass = Class:new{
init = function(self)
print("Hello world")
end
}
local obj = MyClass()
registerClass
Registers a class with a name, prototype, and optional parent class.
Useful for centralized registries.
local A = { foo = function() end }
local B = { bar = function() end }
local C = Class:registerClass("MyType", A, B)
print(C.__type) -- MyType
__includes
Inheritance helper that allows a class to include methods and properties from other classes or tables.
local A = Class{
foo = function() print('foo') end
}
-- single inheritance
B = Class{__includes = A}
instance = B()
instance:foo() -- prints 'foo'
instance:bar() -- error: function not defined
__type
Defines the internal type string of an object, useful for type checking and debugging.
local MyClass = {}
MyClass.__type = "MyClass"
local obj = setmetatable({}, { __index = MyClass })
print(obj.__type) -- Output: MyClass
__gc
Called by Lua garbage collector to perform cleanup when an object is destroyed.
local MyClass = {}
local mt = {
__gc = function(obj)
print("Object is being garbage collected")
end
}
local obj = setmetatable({}, mt)
obj = nil
collectgarbage() -- Triggers __gc and prints the message
License
This project is licensed under the MIT License.