summaryrefslogtreecommitdiffstats
path: root/acf/object.lua
blob: cbccf702ec03d5e710cd5db4c37ae96b4c02b9cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
--[[
Copyright (c) 2012 Kaarle Ritvanen
See LICENSE file for license details
--]]

module(..., package.seeall)

function class(base)
   local cls = {}

   local mt = {
      __call=function(self, ...)
		local obj = {}
		setmetatable(obj, {__index=cls, class=cls})
		obj:init(unpack(arg))
		return obj
	     end
   }

   if not base and Object then base = Object end
   if base then
      cls._base = base
      mt.__index = base
   end

   return setmetatable(cls, mt)
end


Object = class()

function Object:init(...) end


function super(obj, cls)
   assert(isinstance(obj, cls))

   local mt = {}

   function mt.__index(t, k)
      local v = cls._base[k]
      if type(v) ~= 'function' then return v end
      return function(...)
		arg[1] = obj
		return v(unpack(arg))
	     end
   end

   return setmetatable({}, mt)
end


function issubclass(cls1, cls2)
   if cls1 == cls2 then return true end
   if cls1._base then return issubclass(cls1._base, cls2) end
   return false
end

function isinstance(obj, cls)
   if not obj or type(obj) ~= 'table' then return false end
   local mt = getmetatable(obj)
   if not mt then return false end
   return type(obj) == 'table' and mt.class and issubclass(mt.class, cls)
end