Lua类的继承 参考实现

参考url: https://blog.codingnow.com/cloud/LuaOO

最近在思考lua类的继承实现 ,参考了云风的类实现,感觉他的更像是接口写法。于是尝试用自己的方式重写了类实例化部分,并注释了一些理解,代码如下

 1 --lua基础类
 2 --1.实现单向继承
 3 
 4 local _class={}
 5  
 6 function class(className, super)
 7     local class_type = {}
 8     class_type.super = super
 9     class_type.className = className
10     class_type.New = function(...)
11 
12 
13                         --创建实例2 
14                         --确定继承路径
15                         local instance = {}
16                         local inheritPath = {}
17                         table.insert(inheritPath, class_type)
18                         local classTemp = class_type
19                         while(classTemp.super)
20                         do
21                             table.insert(inheritPath, classTemp.super)
22                             classTemp = classTemp.super
23                         end
24                         --按继承路径实例化
25                         local obj = nil
26                         local superInstance = nil
27                         for i = #inheritPath, 1, -1  do
28                             if obj then
29                                 superInstance = obj
30                             end
31                             print("实例化 : ", inheritPath[i].className)
32                             obj = {}
33                             setmetatable(obj, { __index = _class[inheritPath[i]] })
34                             obj:Init(...)
35                             obj.base = superInstance
36                         end
37 
38                         instance = obj
39                         return instance
40                     end
41 
42     local vtbl={} --类属性表
43     _class[class_type] = vtbl
44  
45     setmetatable(class_type, {
46         __newindex = function(t,k,v) --更新vtbl表
47             vtbl[k] = v --将新建的属性保存到vtbl表
48         end,
49 
50         __index = vtbl --__newindex之后,vtbl表发生变化,所以需要重新更新class_type的__index元表
51     })
52 
53     if super then
54         --如果有父类,则设置子类属性表的__index键从父类查找子类未存在的属性,找到则将父类属性保存之子类属性表
55         setmetatable(vtbl, {__index=
56             function(t, k)
57                     local ret = _class[super][k]
58                     vtbl[k] = ret
59                     return ret
60             end
61         })
62     end
63  
64     return class_type
65 end

 

示例:

运行结果:

总结: 1.这是个人的继承实现方式

         2.子类实例化的时候,父类也会被实例化

    3.在子类可以使用self.base调用父类方法 

 

posted @ 2018-03-22 01:19  逆云之上  阅读(420)  评论(0编辑  收藏  举报