Lua中的类编程代码实例
Lua的类有点像javascript,但是更简明灵活,table即对象,对象就是类。Metatables比起ruby里的MetaClass更加好用,缺点是实例化和继承的代码有点多,
不像ruby里的“<”和“<<”,继承链就是查找方法时的方法链。
Account={
test1=function(a)print("Accounttest1")end
}
Account.test2=function(a)print("Accounttest2")end
functionAccount.test3(a)print("Accounttest3")end
functionAccount:new(o)--类的实例化
o=oor{}
setmetatable(o,self)
self.__index=self
returno
end
functionAccount.print0(o,a)
print(a)
end
functionAccount:print1(a)
print(a)
end
--方法定义测试
Account.test1()
Account.test2()
Account.test3()
--类测试
acc=Account:new()
acc.test1()
acc.print0(acc,"dotprint0")
acc:print0("notdotprint0")
acc.print1(acc,"dotprint1")
acc:print1("notdotprint1")
acc.specialMethod=function(specialMethodTest)
print(specialMethodTest)
end
acc.specialMethod("smttest")
--继承测试
SpecialAccount=Account:new()
s=SpecialAccount:new{limit=1000.00}
--多重继承测试
Named={}
functionNamed:getname()
returnself.name
end
functionNamed:setname(n)
self.name=n
end
localfunctionsearch(k,plist)
fori=1,table.getn(plist)do
localv=plist[i][k]
ifvthenreturnvend
end
end
functioncreateClass(...)
localc={}--newclass
setmetatable(c,{__index=function(t,k)
returnsearch(k,arg)
end})
c.__index=c
functionc:new(o)
o=oor{}
setmetatable(o,c)
returno
end
returnc
end
NamedAccount=createClass(Account,Named)
account=NamedAccount:new{name="Paul"}
print(account:getname())