Lua中模拟class并支持setter与getter的实现

2018-03-25 12:12

这里编写class的方式参考了quick cocos的class实现。但在此之上添加setter与getter的实现,实现逻辑在了解lua元表概念的人眼中应该比较容易理解,所以就不做详细的解释了。


下面是class的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
local function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end

local function class(super)
local cls

if (super) then
cls = clone(super)
else
cls = {
ctor = function()
end
}
end

function cls.new(...)
local sets, gets = {}, {}
local instance = setmetatable({ },
{
__index = function(t, k)
if gets[k] then
return gets[k]()
end
return cls[k]
end,
__newindex = function(t, k, v)
if sets[k] then
return sets[k](v)
end
rawset(t, k, v)
end,
})
if instance.setter or instance.getter then
error("error : Prohibition of override 'setter' and 'getter' Function;");
end
instance.setter = function(_, name, func)
instance[name] = nil
sets[name] = func
return instance
end
instance.getter = function(_, name, func)
gets[name] = func
return instance
end

instance.class = cls
instance:ctor(...)
return instance
end

return cls
end

这个给出一个使用的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
local a = class()
function a:ctor()
print("a")
end
function a:funcA()
print("funcA")
end
------------------
local b = class(a)
function b:ctor()
a.ctor(self)
print("b")
end
function b:funcB()
print("funcB")
end
------------------
local c = class(b)
function c:ctor()
b.ctor(self)
print("c")
self._x = nil;
self:setter("x",function (v)
self._x = v;
print("setter x:" .. v)
end)
self:getter("x",function()
print("getter x:" .. self._x)
return self._x;
end)
end
function c:funcC()
print("funcC")
return self
end
------------------
local d = class(c)
function d:ctor()
c.ctor(self)
print("d")
end

local t = d.new()
t:funcA()
t.x = "hello";
print(t.x);
t:funcC():funcB()

这里建议的是如果你有setter与getter的需求,最好是在ctor方法中实现。需要注意的是setter与getter已经被class使用了,所以方法名使用setter或者getter将会造成错误。

它输出的结果如下:

1
2
3
4
5
6
7
8
9
10
> a
> b
> c
> d
> funcA
> setter x:hello
> getter x:hello
> hello
> funcC
> funcB

标签: lua,

Creative Commons ©fox 2017 - 2018 | Theme based on fzheng.me &