Skip to content

Instantly share code, notes, and snippets.

@blacktaxi
Created July 6, 2012 12:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacktaxi/3060036 to your computer and use it in GitHub Desktop.
Save blacktaxi/3060036 to your computer and use it in GitHub Desktop.
Another basic OOP in lua with inheritance and virtual methods.
-- 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