1 @param string classname 类名
2 @param [mixed super] 父类或者创建对象实例的函数
3 @return table
4 function class(classname, super)
5
6 if _G[classname] then
7 error("this aleady define"..classname)
8 end
9
10 local superType = type(super)
11 local cls
12
13 if superType ~= "function" and superType ~= "table" then
14 superType = nil
15 super = nil
16 end
17
18 if superType == "function" or (super and super.__ctype == 1) then
19 -- inherited from native C++ Object
20 cls = {}
21
22 if superType == "table" then
23 -- copy fields from super
24 for k,v in pairs(super) do cls[k] = v end
25 cls.__create = super.__create
26 cls.super = super
27 else
28 cls.__create = super
29 cls.ctor = function() end
30 end
31
32 cls.__cname = classname
33 cls.__ctype = 1
34
35 function cls.new(...)
36 local instance = cls.__create(...)
37 -- copy fields from class to native object
38 for k,v in pairs(cls) do instance[k] = v end
39 instance.class = cls
40 instance:ctor(...)
41 return instance
42 end
43
44 else
45 -- inherited from Lua Object
46 if super then
47 cls = {}
48 setmetatable(cls, {__index = super})
49 cls.super = super
50 else
51 cls = {ctor = function() end}
52 end
53
54 cls.__cname = classname
55 cls.__ctype = 2 -- lua
56 cls.__index = cls
57
58 function cls.new(...)
59 local instance = setmetatable({}, cls)
60 instance.class = cls
61 instance:ctor(...)
62 return instance
63 end
64 end
65
66 _G[classname] = cls
67 return cls
68 end
69
70 function singleton_class(curClass)
71 if curClass.Instance == nil then
72 curClass.Instance = curClass.new()
73 end
74 return curClass.Instance
75 end
76
77 @param mixed obj 要检查的对象
78 @param string classname 类名
79 @return boolean
80 function iskindof(obj, classname)
81 local t = type(obj)
82 local mt
83 if t == "table" then
84 mt = getmetatable(obj)
85 elseif t == "userdata" then
86 mt = tolua.getpeer(obj)
87 end
88
89 while mt do
90 if mt.__cname == classname then
91 return true
92 end
93 mt = mt.super
94 end
95
96 return false
97 end
1 ---@class aa
2 ---@field public Instance aa
3 A= class("aa")
4 singleton_class(A)
5
6 function A:func1()
7 ...
8 end
9
10 function A.func2()
11 ...
12 end
13
14 require "aa"
15 ---直接生成全局变量A
16 A.instance:func1()
17 A.instance.func2()
1 ---@class bb:cc
2 bb= class("bb", cc)
3 function bb:ctor(...)
4 ...
5 end
6
7 function bb:func1()
8 ---:带隐藏参数self
9 ...
10 end
11
12 function bb.func2()
13 ...
14 end
15
16
17 require “bb”
18 B = bb:new(...)
19 B:func1()
20 b.func2()