Skip to content

Instantly share code, notes, and snippets.

@AlphaTechNinja
Last active March 18, 2024 17:58
Show Gist options
  • Select an option

  • Save AlphaTechNinja/f5a09c2c283b92dbc8f0f203a0036396 to your computer and use it in GitHub Desktop.

Select an option

Save AlphaTechNinja/f5a09c2c283b92dbc8f0f203a0036396 to your computer and use it in GitHub Desktop.
A simple class library for Lua
--classes in lua
local classes = {}
function classes.create(name, inherit)
local class = setmetatable({}, inherit or classes)
class.__name = name
class.__index = class
return class
end
--meta
setmetatable(
classes,
{
__call = function(self,name,inherit)
return classes.create(name,inherit)
end
}
)
classes.__index = classes
function classes:__call(...)
return self:new(...)
end
function classes:new(...)
return (self.constructor and self:constructor(...)) or setmetatable({}, self)
end
function classes:__add(name)
assert(type(name) == "string", ("Invalid use of (Class)+(%s) proper use (Class)+(string)"):format(type(other)))
return classes(name, self)
end
function classes:isOf(other)
assert(type(other) == "table","Invalid use of (class:isOf(other)) provided object is not a table")
if getmetatable(self) == other then
return true
elseif getmetatable(self) == classes then
return false
else
return getmetatable(self):isOf(other)
end
end
function classes:multiClass(name, ...)
--this is a special case
local group = {...}
local mt = {}
function mt:__index(key)
for i, v in ipairs(group) do
if v[key] then
return v[key]
end
end
end
--create class
local class = classes(name)
setmetatable(class, mt)
return class
end
--end
return classes
@AlphaTechNinja

Copy link
Copy Markdown
Author

Sorry for not telling you how to use it.
To create a class you can either do class.create(“name”,[inherited class]) or class(“name”,[inherited class]).
To use a class you first have to create a constructor like

local class = require(“class”)(“Test”)
function class:constructor(name,value)
return setmetatable({name=name,value=value},self)
end
--test object
local object = class(“some”,”value”)
print(object.name,object.value)
print(object:isOf(class))

This snippet should result in the lua console outputing some, value, and true
That’s all to using the basics of it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment