SHOW:
|
|
- or go back to the newest paste.
1 | function class(constructor) | |
2 | namespace = {} | |
3 | namespace.__index = namespace | |
4 | namespace.new = function(...) | |
5 | local outerSelf = self | |
6 | -- aliases | |
7 | local this = {} | |
8 | self = this | |
9 | -- finish | |
10 | setmetatable(this,namespace) | |
11 | constructor(unpack(arg)) | |
12 | self = outerSelf -- used to allow constructors inside constructors | |
13 | return this | |
14 | end | |
15 | return namespace | |
16 | end | |
17 | ||
18 | -- I COULD MAKE class(namespace,extend,constructor) but new function name is clearer | |
19 | function classExtends(extend,constructor) | |
20 | namespace = {} | |
21 | namespace.__index = namespace | |
22 | namespace.new = function(...) | |
23 | local outerSelf = self | |
24 | -- aliases | |
25 | local this = extend.new() | |
26 | self = this | |
27 | -- finish | |
28 | setmetatable(this,namespace) | |
29 | constructor(unpack(arg)) | |
30 | self = outerSelf -- used to allow constructors inside constructors | |
31 | return this | |
32 | end | |
33 | return namespace | |
34 | end | |
35 | ||
36 | ---------- | |
37 | -- TEST -- | |
38 | ---------- | |
39 | Test = class(function() | |
40 | self.a = 1 | |
41 | self.b = 3 | |
42 | ||
43 | function self:set_a(new_a) | |
44 | self.a = new_a | |
45 | end | |
46 | end) | |
47 | ||
48 | App = classExtends(Test, function(c) | |
49 | print(self.a, self.b, c) | |
50 | end) | |
51 | ||
52 | local o = App.new(6) | |
53 | o:set_a(2) | |
54 | print(o.a) | |
55 | App.new(7) |