I saw a help post for OOP recently, and honestly I couldn’t find it but I decided to provide a java-like solution for OOP, in case anyone decides they like this option more than other solutions.
It does not use metatables (because Java does not have implicit encapsulation), but it works just fine regardless.
First I’ll provide the facilitating function:
local class = function(t)
local template = {};
local static = {};
if t.extends~=nil then
for i,v in pairs(t.extends.raw)do
if i~='init' and i~='extends' and i~= 'static'then
t[i] = v;
elseif i=='static' then
static = v;
end;
end;
end;
t.super = t.extends;
t.extends = nil;
t.class = template;
template.raw = t;
local s2 = t.static;
if s2~=nil then
for i,v in pairs(s2)do
static[i]=v;
end;
end;
for i,v in pairs(static)do
template[i] = v;
end;
function template.new(...)
local instance = {};
for i,v in pairs(t)do
instance[i]=v;
end;
if instance.init~=nil then
instance:init(...);
end;
return instance;
end;
return template;
end;
Some example code:
local LivingThing = class{
static = {
Species = "Human";
printSpecies = function(self) print(self.Species) end;
}
}
local Person = class{
extends = LivingThing; --inherit both static and instance-fields/methods.
static = {
Species = "Human";
}
Name = "Freddy"; --set a property for any class instance to contain
init = function(self,name)
self.Name = name;
print(self.super) --super class, aka LivingThing
self.class:printSpecies(); --access the static method printSpecies
end;
}
local phil = Person.new("phil");
phil.Name = "Not phil"
Basically its a bunch of table play, but its useful if you have a large amount of code you want to manage through OOP, instead of typical ROBLOX workflow.