Lua的类有点像javascript,但是更简明灵活,table即对象,对象就是类。Metatables比起ruby里的MetaClass更加好用,缺点是实例化和继承的代码有点多,
不像ruby里的“<”和“<<”,继承链就是查找方法时的方法链。
Account={ test1=function(a) print("Account test1") end}Account.test2=function(a) print("Account test2") endfunction Account.test3(a) print("Account test3") endfunction Account:new (o) --类的实例化 o = o or {} setmetatable(o, self) self.__index = self return oendfunction Account.print0(o,a) print(a)endfunction 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)endacc.specialMethod("smt test")--继承测试SpecialAccount = Account:new()s = SpecialAccount:new{limit=1000.00}--多重继承测试Named = {}function Named:getname () return self.nameendfunction Named:setname (n) self.name = nendlocal function search (k, plist) for i=1, table.getn(plist) do local v = plist[i][k] if v then return v end endendfunction createClass (...) local c = {} -- new class setmetatable(c, {__index = function (t, k) return search(k, arg)end})c.__index = cfunction c:new (o) o = o or {} setmetatable(o, c) return oend return cendNamedAccount = createClass(Account, Named)account = NamedAccount:new{name = "Paul"}print(account:getname())
新闻热点
疑难解答