Lua的類有點(diǎn)像javascript,但是更簡明靈活,table即對象,對象就是類。Metatables比起ruby里的MetaClass更加好用,缺點(diǎn)是實(shí)例化和繼承的代碼有點(diǎn)多,
不像ruby里的“”和“”,繼承鏈就是查找方法時(shí)的方法鏈。
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) --類的實(shí)例化 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())
標(biāo)簽:天門 德宏 天門 濰坊 宣城 臺灣 金昌 儋州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Lua中的類編程代碼實(shí)例》,本文關(guān)鍵詞 Lua,中的,類,編程,代碼,實(shí)例,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。