Skip to content

Instantly share code, notes, and snippets.

@Jaezmien
Last active January 22, 2021 14:22
Show Gist options
  • Save Jaezmien/57ad4ae3b26299f1adc8e705cd7a8079 to your computer and use it in GitHub Desktop.
Save Jaezmien/57ad4ae3b26299f1adc8e705cd7a8079 to your computer and use it in GitHub Desktop.
Class handler for Lua >= 5.0
-- class.lua
-- By: Jaezmien Naejara
local clone
do
clone = function (orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[ clone(orig_key) ] = clone(orig_value)
end
setmetatable(copy, clone(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
end
local function create_child_class(orig, args)
local child = clone( orig )
if args then
for key, value in pairs( args ) do
child[ key ] = value
end
end
return child
end
local classes = {}
class = setmetatable(
{
New = function(self, id, t, constructor)
if not id or not t then
print('[Class] Missing arguments')
return
end
if type(id) ~= 'string' or type(t) ~= 'table' then
print('[Class] Invalid argument type')
return
end
local c
if t.__classID then
c = t
else
c = clone( t )
c.__classID = id
end
constructor = constructor or (function() return {} end)
local v = setmetatable(
{
__parentID = id,
Create = function(self,...)
local args = {}
if type(arg) == 'table' and table.getn(arg) ~= 1 then
constructor( args, unpack(arg) )
elseif type(arg[1]) == 'table' then
args = arg[1]
else args = nil end
return create_child_class( c, args )
end,
Inherit = function(_,new_id, new_args, constructor)
if not new_id then
print('[Class Inherit] Missing arguments')
return
end
if type(new_id) ~= 'string' or type(new_args) ~= 'table' then
print('[Class Inherit] Invalid argument type')
return
end
local i = clone( c )
for key, value in pairs( new_args ) do i[key] = value end
i.__classID = new_id
return self:New( new_id, i, constructor )
end,
},
{
__call = function(self,...) self:Create( unpack(arg) ) end,
__newindex = function(_,k,v) c[k] = v end,
}
)
classes[ id ] = v
return v
end,
Get = function(self, id) return classes[id] end,
},
{
__newindex = function() end,
__index = function(s,k) return classes[k] end,
__call = function(self,...) self:New( unpack(arg) ) end,
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment