Lua中的类编程代码实例
程序员文章站
2022-04-09 22:56:28
lua的类有点像javascript,但是更简明灵活,table即对象,对象就是类。metatables比起ruby里的metaclass更加好用,缺点是实例化和继承的代码...
lua的类有点像javascript,但是更简明灵活,table即对象,对象就是类。metatables比起ruby里的metaclass更加好用,缺点是实例化和继承的代码有点多,
不像ruby里的“<”和“<<”,继承链就是查找方法时的方法链。
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())
上一篇: 理解Lua中的__index和__newindex
下一篇: ps怎么画围着拉风的围巾的小白兔?