lua 类与继承

来源:互联网 发布:适合程序员的电脑壁纸 编辑:程序博客网 时间:2024/05/06 13:54

试试lua中的对象与继承,多说句,多继承我写c++也没用过,直接上组合就ok,因此lua的多继承如果非必须也同样可用用其他方法来实现

--lua 类与继承的实验local Str={str="",num=0}function Str:new(s)s = s or {}--为对象绑定metatable为Strsetmetatable(s,{__index=self})return sendfunction Str:count(line)self.str=linefor w in string.gmatch(line,"%w+")doself.num = self.num + 1endend--这就相当于是继承下来,之后调用Driver的函数时,self都是DriverDriver = Str:new()function Driver:count(line)self.str=lineself.num=string.len(line)endfunction Driver:print()io.write(string.format("Driver print,member str '%s' meber num '%d'\n",self.str,self.num))endobj1=Str:new()teststr="a,b,c,213 helooa wod =af da"obj1:count(teststr)io.write(string.format("object one,member str '%s' meber num '%d'\n",obj1.str,obj1.num))--这3行输出表明了obj1的成员数据不会影响后续对象,也不会影响Str的数据变动obj2=Str:new()io.write(string.format("object two,member str '%s' meber num '%d'\n",obj2.str,obj2.num))io.write(string.format("object Str,member str '%s' meber num '%d'\n",Str.str,Str.num))--从Driver创建对象,相当于派生类obj3=Driver:new({name="object three base is driver"})obj3:count(teststr)obj3:print()