File: test-class.lua

package info (click to toggle)
lua-penlight 1.0.2%2Bhtmldoc-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,860 kB
  • sloc: makefile: 7
file content (109 lines) | stat: -rw-r--r-- 1,444 bytes parent folder | download
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
require 'pl'
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

asserteq(B(),{a=1,b=2})

-- can continue this chain

C = class(B)

function C:_init ()
    self:super()
    self.c = 3
end

--- 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))