/
class2.lua
78 lines (64 loc) · 1.78 KB
/
class2.lua
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
local class = {} -- Stores publics.
local _class = {} -- Stores privates.
setmetatable(class,{
__call = function(t,cls) -- t is class tab.
if class[cls] then
if type(class[cls]) ~= "function" then
print("Invalid class declaration: "..cls)
return
end
local self = {}
local private,public = class[cls]()
if not _class[cls] then
_class[cls] = {}
for a,b in pairs(private) do
_class[cls][a] = b
end
end
for a,b in pairs(public) do
self[a] = b
end
setmetatable(self,{
__index = function(t,k)
if _class[cls][k] then
if type(_class[cls][k]) == "function" then
print("Attempt to access private method: "..k)
else
print("Attempt to access private variable: "..k)
end
end
end
})
return self
else
print("Attempt to index non-existant class: "..cls)
end
end
})
-- Example Class Definition:
function class:Base()
local private = {}
local public = {}
private.x = 16
private.y = 16
private.w = 32
private.h = 32
function public:SetX(val)
private.x = val
end
function public:GetX()
return private.x
end
return private,public
end
local obj = class("Base")
local obj2 = class("Base")
obj:SetX(123)
print(obj:GetX())
print(obj2:GetX())
for a,b in pairs(obj) do print(a,b) end
-- Output:
-- 123
-- 16
-- GetX function: 0x00021bc0
-- SetX function: 0x00021b80