jille_Jr

CC: motley - Class

Mar 30th, 2015
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.22 KB | None | 0 0
  1. -- class.lua
  2. -- Compatible with Lua 5.1 (not 5.0).
  3. local function class(base, init)
  4.    local c = {}    -- a new class instance
  5.    if not init and type(base) == 'function' then
  6.       init = base
  7.       base = nil
  8.    elseif type(base) == 'table' then
  9.     -- our new class is a shallow copy of the base class!
  10.       for i,v in pairs(base) do
  11.          c[i] = v
  12.       end
  13.       c._base = base
  14.    end
  15.    -- the class will be the metatable for all its objects,
  16.    -- and they will look up their methods in it.
  17.    c.__index = c
  18.  
  19.    -- expose a constructor which can be called by <classname>(<args>)
  20.    local mt = {}
  21.    mt.__call = function(class_tbl, ...)
  22.    local obj = {}
  23.    setmetatable(obj,c)
  24.    if init then
  25.       init(obj,...)
  26.    else
  27.       -- make sure that any stuff from the base class is initialized!
  28.       if base and base.init then
  29.       base.init(obj, ...)
  30.       end
  31.    end
  32.    return obj
  33.    end
  34.    c.init = init
  35.    c.is_a = function(self, klass)
  36.       local m = getmetatable(self)
  37.       while m do
  38.          if m == klass then return true end
  39.          m = m._base
  40.       end
  41.       return false
  42.    end
  43.    setmetatable(c, mt)
  44.    return c
  45. end
  46.  
  47. -- when loaded as an API
  48. -- class.new(base, init)
  49. new = class
Advertisement
Add Comment
Please, Sign In to add comment