Skip to content

Instantly share code, notes, and snippets.

@Ethan-Pixelate
Created February 5, 2022 05:36
Show Gist options
  • Save Ethan-Pixelate/fca4e62798b2eb131cf9d4c5582e33de to your computer and use it in GitHub Desktop.
Save Ethan-Pixelate/fca4e62798b2eb131cf9d4c5582e33de to your computer and use it in GitHub Desktop.
OOP in lua, not perfect at all but good enough lol
local function LightCopy(x)
local NewT = {}
for k,v in pairs(x) do NewT[k]=v end
return NewT
end
function class(ClassName, Template,Extend,NotGlobal)
if DEBUG_CLASS then
print(
"Creating "..
(NotGlobal and"local "or"")..
"class \""..ClassName..
((Extend~=nil)and("\" extends \""..Extend:WhatIsThis().."\"")or"\"")
)
end
if not Template.__meta then Template.__meta = {} end
Template.__meta.__index = Template
Template.__meta.__call = function(...)
local Args = {...}
table.remove(Args,1)
Template.new(unpack(Args))
end
Template.new = function(...)
local Instance = {}
if Extend then Instance = Extend.new() end
setmetatable(Instance,Template.__meta)
if Template.__construct ~= nil then
Instance:__construct(...)
end
return Instance
end
Template.WhatIsThis = function(self) return self.__inheritance[1] end
Template.IsA = function(self,ClassName)
for k,v in pairs(self.__inheritance) do
if v==ClassName then
return true
end
end
return false
end
if Extend~=nil then
setmetatable(Template,{__index=Extend})
Template.__inheritance = LightCopy(Extend.__inheritance)
table.insert(Template.__inheritance,1,ClassName)
else
Template.__inheritance = {ClassName}
end
if not NotGlobal then
_G[ClassName] = Template
end
return Template
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment