lua如何构造类

复制代码
 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
复制代码

 

posted @   云轩奕鹤  阅读(561)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示