Skip to content

Instantly share code, notes, and snippets.

@MatthewBlanchard
Created October 26, 2012 23:09
Show Gist options
  • Save MatthewBlanchard/3962094 to your computer and use it in GitHub Desktop.
Save MatthewBlanchard/3962094 to your computer and use it in GitHub Desktop.
Two small object systems.
Object={}Object.__index=Object
setmetatable(Object,Object)function Object:__call(...)return self:new(...)end
function Object:init()end
function Object:parent()return getmetatable(self)end
function Object:new(...)local e={}setmetatable(e,self)self.__index=self
e:init(...)return e
end
Object = {}
Object.__index = Object
setmetatable(Object, Object)
function Object:__call(...)
return self:new(...)
end
function Object:init()
end
function Object:parent()
return getmetatable(self)
end
function Object:new(...)
local o = {}
setmetatable(o, self)
self.__index = self
o:init(...)
return o
end
Object = {}
Object.__index = Object
setmetatable(Object, Object)
-- Variables
Object.__metamethods = {
"__add", "__sub", "__mul", "__div", "__mod", "__pow", "__unm",
"__len", "__lt", "__le", "__concat", "__tostring"
}
-- Metamethods
function Object:__call(...)
return self:new(...)
end
function Object:__newindex(k, v)
if k == "init" and not rawget(self, __init) then
rawset(self, "__init", v)
elseif getfenv(2)[k] == self and not rawget(self, __init) then
rawset(self, "__init", v)
end
rawset(self, k, v)
end
-- Constructor
function Object:__init()
end
-- Private/Static methods
function Object:__metamethod(event)
return function(...)
if self:parent() == self then
error "Unimplemented metamethod called on object."
end
func = rawget(self, event)
if func then
return func(...)
else
return self:parent()[event](...)
end
end
end
-- Methods
function Object:parent()
return getmetatable(self)
end
function Object:new(...)
local o = {}
setmetatable(o, self)
self.__index = self
self.__call = Object.__call
self.__newindex = Object.__newindex
for k,v in pairs(Object.__metamethods) do
o[v] = self:__metamethod(v)
end
o:__init(...)
return o
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment