Refined Classes - Simplifying OOP in Lua

What is Refined Classes?

It’s a module I created that hugely simplifies replicating OOP in Lua. I’ve recently been working on a 2D Game Engine and I have an insane amount of classes & subclasses that each take a lot of time to create and decided to make this module. It simplified a tremendous amount of work I was doing and I believe it has a wide variety of uses.

How do I use it?

Here’s a pretty simple example of creating a projectile class and then giving it some properties.

local RC = require(game:GetService("ReplicatedFirst").RefinedClasses);

-- Create a new Projectile class with default 'speed' and 'gravity' attributes
local Projectile = RC("Projectile", {
    speed = 10,
    gravity = 9.8
});

-- Create a constructor for this class
-- 'Initialize' is reserved specifically for constructors within classes
function Projectile:Initialize(newSpeed, newGravity)
    self.speed = newSpeed or self.speed;
    self.gravity = newGravity or self.gravity;
end

-- Create a projectile instance passing in arguments for its constructor
-- The first argument is a table for default metamethods which can be left as nil
local newProjectile = Projectile({
    __call = function(self)
        print(self.speed);
    end
}, 99, 0);

-- Treats the instance like a function using the __call metamethod set earlier
-- Prints '99' which is the speed passed to the constructor in the instance's creation
newProjectile(); 

This is a pretty bare bones example of the module but it showcases what it can do. The module also has support for subclasses that inherit properties and methods as well as mixins.

Full Documentation

You can find full documentation alongside examples over at the project’s GitHub wiki page here.

Download

You can download the module for ROBLOX use here.

3 Likes