lua class

 

 

 1 _class = {}
 2 
 3 function BaseClass(super)
 4     local class_type = {}
 5     local vtbl = {}
 6     _class[class_type] = vtbl
 7 
 8     setmetatable(class_type, {
 9         __newindex = function(t, k, v)
10             vtbl[k] = v
11         end,
12         __index = vtbl
13     })
14     if super then
15         setmetatable(vtbl, {
16             __index = _class[super]
17         })
18     end
19 
20 
21     class_type.__init = false
22     class_type.__delete = false
23     class_type.super = super
24     class_type.New = function(...)
25         local obj = {}
26         obj._class_type = class_type
27         setmetatable(obj, {__index = _class[class_type]})
28 
29         do
30             local create = function(c, ...)
31                 if c.super then
32                     create(c.super, ...)
33                 end
34                 if c.__init then
35                     c.__init(obj, ...)
36                 end
37             end
38 
39             create(class_type, ...)
40         end
41 
42         obj.DeleteMe = function(self)
43             local now_super = self._class_type
44             while now_super ~= nil  do
45                 if now_super.__delete then
46                     now_super.__delete(self)
47                 end
48                 now_super = now_super.super
49             end
50         end
51 
52         return obj
53     end
54 
55     return class_type
56 end

 

你可能感兴趣的:(lua class)