Advertisement
Guest User

class.lua

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