lua-class
A tiny OOP helper for Lua that builds instances by copying tables instead of metatables. It started as a minimal replacement for middleclass.
Features
class.class(name, parent)— define a class and optionally inherit every field/method fromparent.class.new_instance(class, ...)— copy the class table into a fresh instance and callinitialize(...)if it exists.class.is_instance_of_by_name(instance, name)— simple ancestry check by class name.
Installation
Drop class.lua into your project and require it: local class = require "class". No dependencies.
Quick start
local class = require "class"
local Animal = class.class("Animal")
function Animal:initialize(name)
self.name = name or "Unknown"
end
function Animal:speak()
print(self.name .. " makes a sound")
end
local Dog = class.class("Dog", Animal)
function Dog:speak()
print(self.name .. " barks")
end
local cat = class.new_instance(Animal, "Milo")
local dog = class.new_instance(Dog, "Rex")
cat:speak() --> Milo makes a sound
dog:speak() --> Rex barks
Performance
By skipping __index and other metatable hooks, the library relies on raw table copies. Benchmarks show that deep inheritance trees favor this approach: copying can be up to 10× faster than walking multi-level metatables [lua-oo-speedcomp].
LuaJIT narrows the gap drastically: Mike Pall’s classic Object Benchmark Tests report that both “solid” classes and metatable-based classes take roughly 0.1 seconds to dispatch 1e8 calls on LuaJIT 2.0. So the copy-first strategy mainly helps on vanilla Lua 5.x or whenever you keep adding inheritance levels.
So in real apps use metatables or copy values don’t have any measurable impact on performance.