Created
February 2, 2012 06:08
-
-
Save Deco/1721823 to your computer and use it in GitHub Desktop.
Object Orientation model for Lua
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
local setmetatable = setmetatable | |
local table, debug = table, debug | |
do --_G.class | |
local function class_new(self, ...) | |
return setmetatable({}, self) | |
end | |
_G.class = function(...) | |
local supers = {...} | |
local class = table.remove(supers, #supers) | |
class.__index = ( | |
class.__index ~= nil and class.__index | |
or class.__index_def and class.__index_def(class) | |
or class | |
) | |
class[class] = true | |
class.__init = class.__init or class_new | |
local supers_len = #supers -- hopefully this will help LuaJIT unroll the loop statically | |
return setmetatable( | |
class, | |
{ | |
__supers = supers, | |
__class = class, | |
__call = function(self, ...) return self.__init(self, ...) end, | |
__index = ( | |
supers_len == 0 and nil | |
or supers_len == 1 and supers[1] | |
or function(self, key) | |
for super_i = 1, supers_len do | |
local value = supers[super_i][key] | |
if value then return value end | |
end | |
end | |
), | |
} | |
) | |
end | |
end | |
do _G.classof | |
= debug.getmetatable -- hopefully this aliasing doesn't mess up the fast function optimisation | |
end | |
do _G.instanceof | |
= function(instance, class) | |
local mt = debug.getmetatable(instance) | |
return mt and mt[class] | |
end | |
end | |
do _G.supersof | |
= function(class) | |
return debug.getmetatable(class).__supers | |
end | |
end | |
do _G.supersofinstance -- == supersof(classof(instance)) | |
= function(instance) | |
return debug.getmetatable(debug.getmetatable(instance)).__supers | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment