lua如何构造类

简介: 1 function class(super, autoConstructSuper) 2 local classType = {}; 3 classType.autoConstructSuper = autoConstructSuper or (autoConstru...
 1 function class(super, autoConstructSuper)
 2     local classType = {};
 3     classType.autoConstructSuper = autoConstructSuper or (autoConstructSuper == nil);
 4     
 5     if super then
 6         classType.super = super;
 7         local mt = getmetatable(super);
 8         setmetatable(classType, { __index = super; __newindex = mt and mt.__newindex;});
 9     else
10         classType.setDelegate = function(self,delegate)
11             self.m_delegate = delegate;
12         end
13     end
14 
15     return classType;
16 end
17 
18 
19 function new(classType, ...)
20     local obj = {};
21     local mt = getmetatable(classType);
22     setmetatable(obj, { __index = classType; __newindex = mt and mt.__newindex;});
23     do
24         local create;
25         create =
26             function(c, ...)
27                 if c.super and c.autoConstructSuper then
28                     create(c.super, ...);
29                 end
30                 if rawget(c,"ctor") then
31                     obj.currentSuper = c.super;
32                     c.ctor(obj, ...);
33                 end
34             end
35 
36         create(classType, ...);
37     end
38     obj.currentSuper = nil;
39     return obj;
40 end
41 
42 
43 function delete(obj)
44     do
45         local destory =
46             function(c)
47                 while c do
48                     if rawget(c,"dtor") then
49                         c.dtor(obj);
50                     end
51               
52                     c = getmetatable(c);
53                     c = c and c.__index;                   
54                 end
55             end
56         destory(obj);
57     end
58 end

 

倾城之链 | NICE LINKS DJI Mavic Air
目录
相关文章
|
6天前
|
程序员
老程序员分享:lua类实现
老程序员分享:lua类实现
|
12天前
|
C++
2dx lua自定义类
2dx lua自定义类
Lua程序设计(三)面向对象实现一个简单的类
1.Lua面向对象实现步骤 ①创建一个全局表(称之为元表) ②设置这个元表的__index值(值通常为元表自己,这样就能通过__index查找到对应的属性和方法)__index 赋值其实是一个function的语法糖,Sharp.
1270 0
Lua程序设计(四)面向对象类继承
1.类继承  ①代码 Sharp = { _val = 1} --① 父类 function Sharp:new() local new_sharp = { } self.__index = self --②,self == Sharp setmetatable(n...
834 0