Created
July 6, 2012 12:58
-
-
Save blacktaxi/3060036 to your computer and use it in GitHub Desktop.
Another basic OOP in lua with inheritance and virtual methods.
This file contains hidden or 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
-- creates a class table which has a "new" method to create object instances. | |
class = function (parentclass, classdef) | |
local cls = { | |
__classdef__ = classdef or {}, | |
__parent__ = parentclass or {}, | |
-- instance constructor | |
new = function(cls, ...) | |
local instance = { | |
super = cls.__parent__.__classdef__, | |
__class__ = cls | |
} | |
-- if instance attr is not defined, the accessor will be referred to | |
-- class definition attribute | |
setmetatable(instance, {__index = cls.__classdef__}) | |
-- if class definition attribute is not defined, the accessor should | |
-- be referred to parent's class definition attribute (inheritance) | |
setmetatable( | |
cls.__classdef__, | |
{__index = cls.__parent__.__classdef__ } | |
) | |
-- call init method, if any | |
if instance.init then | |
instance:init(...) | |
end | |
return instance | |
end, | |
} | |
return cls | |
end | |
-- a short form of class() call | |
define = function(classdef) return class(nil, classdef) end | |
-- a "syntactic sugar" for defining class inheritance | |
extend = function(parent) | |
return function(classdef) return class(parent, classdef) end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment