Lua 类与继承
试试lua中的对象与继承,多说句,多继承我写c++也没用过,直接上组合就ok,因此lua的多继承如果非必须也同样可用用其他方法来实现
--lua 类与继承的实验
local Str={str="",num=0}
function Str:new(s)
s = s or {}
--为对象绑定metatable为Str
setmetatable(s,{__index=self})
return s
end
function Str:count(line)
self.str=line
for w in string.gmatch(line,"%w+")
do
self.num = self.num + 1
end
end
--这就相当于是继承下来,之后调用Driver的函数时,self都是Driver
Driver = Str:new()
function Driver:count(line)
self.str=line
self.num=string.len(line)
end
function Driver:print()
io.write(string.format("Driver print,member str '%s' meber num '%d'\n",self.str,self.num))
end
obj1=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()