# Lua Class OOP library

**URL:** <https://forum.defold.com/t/lua-class-oop-library/82113>\
**Category:** The Defoldmine\
**Created:** [December 17, 2025, 5:35am UTC](https://forum.defold.com/t/lua-class-oop-library/82113 "2025-12-17T05:35:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![d954mas](https://forum-defold.b-cdn.net/user_avatar/forum.defold.com/d954mas/32/5401_2.png) [@d954mas](https://forum.defold.com/u/d954mas)\
**Post date:** [December 17, 2025, 5:35am UTC](https://forum.defold.com/t/lua-class-oop-library/82113/1 "2025-12-17T05:35:39Z")

</div>

# lua-class

> **[GitHub - d954mas/lua-class](https://github.com/d954mas/lua-class)**
>
> Contribute to d954mas/lua-class development by creating an account on GitHub.

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 from `parent`.
- `class.new_instance(class, ...)` — copy the class table into a fresh instance and call `initialize(...)` 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

```lua
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](https://github.com/kengonakajima/lua-oo-speedcomp)].

LuaJIT narrows the gap drastically: Mike Pall’s classic [Object Benchmark Tests](https://lua-users.org/wiki/ObjectBenchmarkTests) 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.

[![](https://img.youtube.com/vi/DSJZ2OlB_dQ/maxresdefault.jpg "DAY 3. Advent Calendar 2025 by d954mas (lua-class)") ](https://www.youtube.com/watch?v=DSJZ2OlB_dQ)
