-
Notifications
You must be signed in to change notification settings - Fork 19
/
OOP.bit
117 lines (89 loc) · 1.76 KB
/
OOP.bit
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
package:application/vnd.bitty-archive;
data:text/json;count=139;path=info.json;
{
"id": 0,
"title": "Basics/06. OOP",
"description": "",
"author": "Tony",
"version": "1.0",
"genre": "TUTORIAL",
"url": ""
}
data:text/lua;count=747;path=class.lua;
--[[
Example for the Bitty Engine
Copyright (C) 2020 - 2024 Tony Wang, all rights reserved
Homepage: https://paladin-t.github.io/bitty/
]]
-- Declares a class.
function class(kls, base)
if not base then
base = { }
end
kls.new = function (...)
local obj = { }
setmetatable(obj, kls)
if obj.ctor then -- `ctor` is short for "constructor", where you can initialize your instance.
obj:ctor(...)
end
return obj
end
kls.__index = kls
setmetatable(kls, base)
return kls
end
-- Determines whether an object is instance of a specific class.
function is(obj, kls)
if kls == nil then
error('Invalid class.')
end
repeat
if obj == kls then
return true
end
obj = getmetatable(obj)
until not obj
return false
end
data:text/lua;count=758;path=main.lua;
--[[
Example for the Bitty Engine
Copyright (C) 2020 - 2024 Tony Wang, all rights reserved
Homepage: https://paladin-t.github.io/bitty/
]]
require 'class'
A = class({
ctor = function (self, n)
print('A:ctor')
self.n = n
end,
fun = function (self)
print('A:fun')
return self.n
end
})
B = class({
ctor = function (self, n)
A.ctor(self, n)
print('B:ctor')
end
}, A)
C = class({
ctor = function (self, n)
print('C:ctor')
self.n = n
end,
fun = function (self)
print('C:fun')
return self.n
end
})
local a = A.new(1)
local b = B.new(2)
local c = C.new(3)
print(a:fun())
print(b:fun())
print(c:fun())
print('a is A: ' .. tostring(is(a, A)))
print('b is A: ' .. tostring(is(b, A)))
print('c is A: ' .. tostring(is(c, A)))