Repository navigation
Expand file tree
/
Copy pathtest-class.lua
More file actions
132 lines (91 loc) · 1.8 KB
/
Copy pathtest-class.lua
File metadata and controls
132 lines (91 loc) · 1.8 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
local class = require 'pl.class'
local test = require 'pl.test'
asserteq = test.asserteq
T = test.tuple
A = class()
function A:_init ()
self.a = 1
end
-- calling base class' ctor automatically
A1 = class(A)
asserteq(A1(),{a=1})
-- explicitly calling base ctor with super
B = class(A)
function B:_init ()
self:super()
self.b = 2
end
function B:foo ()
self.eee = 1
end
asserteq(B(),{a=1,b=2})
-- can continue this chain
C = class(B)
function C:_init ()
self:super()
self.c = 3
end
function C:foo ()
-- recommended way to call inherited version of method...
B.foo(self)
end
c = C()
c:foo()
asserteq(c,{a=1,b=2,c=3,eee=1})
--- class methods!
assert(c:is_a(C))
assert(c:is_a(B))
assert(c:is_a(A))
assert(c:is_a() == C)
assert(C:class_of(c))
assert(B:class_of(c))
assert(A:class_of(c))
--- metamethods!
function C:__tostring ()
return ("%d:%d:%d"):format(self.a,self.b,self.c)
end
function C.__eq (c1,c2)
return c1.a == c2.a and c1.b == c2.b and c1.c == c2.c
end
asserteq(C(),{a=1,b=2,c=3})
asserteq(tostring(C()),"1:2:3")
asserteq(C()==C(),true)
----- properties -----
local MyProps = class(class.properties)
local setted_a, got_b
function MyProps:_init ()
self._a = 1
self._b = 2
end
function MyProps:set_a (v)
setted_a = true
self._a = v
end
function MyProps:get_b ()
got_b = true
return self._b
end
function MyProps:set (a,b)
self._a = a
self._b = b
end
local mp = MyProps()
mp.a = 10
asserteq(mp.a,10)
asserteq(mp.b,2)
asserteq(setted_a and got_b, true)
class.MoreProps(MyProps)
local setted_c
function MoreProps:_init()
self:super()
self._c = 3
end
function MoreProps:set_c (c)
setted_c = true
self._c = c
end
mm = MoreProps()
mm:set(10,20)
mm.c = 30
asserteq(setted_c, true)
asserteq(T(mm.a, mm.b, mm.c),T(10,20,30))