Lua中的类编程代码实例

时间:2022-12-09 08:41:21

Lua的类有点像javascript,但是更简明灵活,table即对象,对象就是类。Metatables比起ruby里的MetaClass更加好用,缺点是实例化和继承的代码有点多,

不像ruby里的“<”和“<<”,继承链就是查找方法时的方法链。

?
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
Account={
  test1=function(a) print("Account test1") end
}
 
Account.test2=function(a) print("Account test2") end
 
function Account.test3(a) print("Account test3") end
 
 
function Account:new (o) --类的实例化
 
  o = o or {}
 
  setmetatable(o, self)
 
  self.__index = self
 
  return o
 
end
 
function Account.print0(o,a)
  print(a)
end
 
function Account:print1(a)
  print(a)
end
 
 
--方法定义测试
Account.test1()
Account.test2()
Account.test3()
 
--类测试
acc=Account:new()
acc.test1()
acc.print0(acc,"dot print0")
acc:print0("not dot print0")
acc.print1(acc,"dot print1")
acc:print1("not dot print1")
 
acc.specialMethod=function(specialMethodTest)
  print(specialMethodTest)
end
 
acc.specialMethod("smt test")
 
--继承测试
SpecialAccount = Account:new()
s = SpecialAccount:new{limit=1000.00}
 
--多重继承测试
Named = {}
 
function Named:getname ()
 
  return self.name
 
end
 
function Named:setname (n)
 
  self.name = n
 
end
 
local function search (k, plist)
 
  for i=1, table.getn(plist) do
 
    local v = plist[i][k]
 
    if v then return v end
 
  end
 
end
 
function createClass (...)
 
  local c = {}   -- new class
 
  setmetatable(c, {__index = function (t, k)
 
  return search(k, arg)
 
end})
 
c.__index = c
 
function c:new (o)
 
  o = o or {}
 
  setmetatable(o, c)
 
  return o
 
end
 
  return c
 
end
NamedAccount = createClass(Account, Named)
 
account = NamedAccount:new{name = "Paul"}
 
print(account:getname())