試試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()