Created
June 28, 2013 17:11
-
-
Save handsomematt/5886329 to your computer and use it in GitHub Desktop.
Classes in 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
-- class.lua | |
-- Compatible with Lua 5.1 (not 5.0). | |
function Class(base, _ctor) | |
local c = {} -- a new class instance | |
if not _ctor and type(base) == 'function' then | |
_ctor = base | |
base = nil | |
elseif type(base) == 'table' then | |
-- our new class is a shallow copy of the base class! | |
for i,v in pairs(base) do | |
c[i] = v | |
end | |
c._base = base | |
end | |
-- the class will be the metatable for all its objects, | |
-- and they will look up their methods in it. | |
c.__index = c | |
-- expose a constructor which can be called by <classname>(<args>) | |
local mt = {} | |
mt.__call = function(class_tbl, ...) | |
local obj = {} | |
setmetatable(obj,c) | |
if _ctor then | |
_ctor(obj,...) | |
end | |
return obj | |
end | |
c._ctor = _ctor | |
c.is_a = function(self, klass) | |
local m = getmetatable(self) | |
while m do | |
if m == klass then return true end | |
m = m._base | |
end | |
return false | |
end | |
setmetatable(c, mt) | |
return c | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment