Skip to content

Instantly share code, notes, and snippets.

@pablophg
Created December 22, 2014 08:41
Show Gist options
  • Save pablophg/49dc667562b42b5d74c4 to your computer and use it in GitHub Desktop.
Save pablophg/49dc667562b42b5d74c4 to your computer and use it in GitHub Desktop.
SimpleLuaClasses
-- check "http://lua-users.org/wiki/SimpleLuaClasses" for this file
-- class.lua
-- Compatible with Lua 5.1 (not 5.0).
function class(base, init)
local c = {} -- a new class instance
if not init and type(base) == 'function' then
init = 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)
-- below 2 lines are updated based on the Comments from 'http://lua-users.org/wiki/SimpleLuaClasses'
-- if init then
-- init(obj,...)
if class_tbl.init then
class_tbl.init(obj,...)
else
-- make sure that any stuff from the base class is initialized!
if base and base.init then
base.init(obj, ...)
end
end
return obj
end
c.init = init
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