Skip to content

Instantly share code, notes, and snippets.

@speedmax
Created August 18, 2008 06:23
Show Gist options
  • Save speedmax/5942 to your computer and use it in GitHub Desktop.
Save speedmax/5942 to your computer and use it in GitHub Desktop.
class = {}
class['@instance_protocol'] = {
-- Dispatch instance methods
__index= function(instance, member) end
}
class['@protocol'] = {
class = class,
-- Instantiation
__call = function(class_obj, ...) end,
-- Dispatch class methods
__index = class['@instance_protocol'].__index
}
function class.constructor(self, prototype)
end
class.prototype = {
is_domain_of = function(self, instance)
local metatable = getmetatable(instance)
if metatable then
return metatable.class == self
else
return false
end
end;
subclass = function(superclass, prototype)
-- Missing constructor
if not (prototype[1] and type(prototype[1]) == 'function') then
prototype[1] = superclass.constructor
end
local classobj = class(prototype)
-- set superclass on classobj metatable, what about instance metatable
local protocol = table.merge(
getmetatable(classobj), { superclass = superclass }
)
setmetatable(classobj, protocol)
classobj.prototype.super = superclass.constructor
return classobj
end;
}
setmetatable(class, class['@protocol'])
----- example
do -- test inhieritance
local mammal = class {
function(self, name)
self.name = name
self.body_features = {'hair', 'heart', 'teeth'}
end;
talk = function(self)
print 'i am a mammal'
end;
}
local pet = mammal.subclass {
function(self, ...)
self.name, self.owner = ...
self.super(self.name)
end;
eat = function(self)
print 'feeting the pet'
end;
}
local mydog = pet('bobo', 'taylor luk')
print(mydog.body_features)
mydog.eat()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment