Last active
February 15, 2017 10:23
-
-
Save revolucas/ebae2ae22f382684ca981991cfb0aad9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
author: Alundaio (aka Revolucas) | |
A function that creates a new class-like table suitable for combining table properties. | |
It is very simple, only 20 lines and it is very aesthetically pleasing to define new 'classes' | |
ex 1. Class "new_class" | |
ex 2. Class "new_class" (inherit) | |
ex 3. Class "new_class" (inherit1,inherit2,...) | |
The only requirement is that you need to give _G a metatable where 'this' returns the table | |
being indexed, which in my opinion is useful on it's own as it will return the current table | |
environment. | |
example usage: | |
Class "human" | |
function human:__init(name) | |
self.name = name | |
end | |
function human:printf() | |
print(self.name) | |
end | |
Class "girl" (human) | |
function girl:__init(name) | |
self.inherited[1].__init(self,name) | |
end | |
Class "boy" (human) | |
Class "transgender" (boy,girl) | |
local instance = transgender("bob") | |
instance:printf() -- prints 'bob' | |
--]] | |
-- Set _G metatable where 'this' returns self of __index. | |
setmetatable(_G, {__index=function(t,k) | |
if (k == "this") then | |
return t | |
end | |
return rawget(_G,k) | |
end | |
}) | |
function Class(name) | |
this[name] = setmetatable({},{ | |
__index = getmetatable(_G).__index, | |
__call = function(t,...) | |
local o = setmetatable({},{__index=t}) | |
o:__init(...) | |
return o | |
end | |
}) | |
return function(...) | |
local p = {...} | |
this[name].inherited = p | |
getmetatable(this[name]).__index=function(t,k) | |
for i,v in ipairs(p) do | |
local ret = rawget(v,k) | |
if (ret ~= nil) then | |
return ret | |
end | |
end | |
return getmetatable(_G).__index(_G,k) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment