Lua编程示例(二):面向对象、metatable对表进行扩展
counter={ count=0 } functioncounter.get(self) returnself.count end functioncounter:inc() self.count=self.count+1 end print(counter.get(counter)) counter.inc(counter) print(counter.get(counter)) counter2={ count=4, get=counter.get, inc=counter.inc, } print(counter2:get()) counter.inc(counter2) print(counter2.get(counter2)) print() tb1={"alpha","beta","gamma"} mt={} setmetatable(tb1,mt) print(getmetatable(tb1)==mt) print() functionmt.__add(a,b) localresult=setmetatable({},mt) fori=1,#ado table.insert(result,a[i]) end fori=1,#bdo table.insert(result,b[i]) end returnresult end tb2={"aaa","bbb","ccc"} res=tb1+tb2 fori,vinipairs(res)do print(v) end print() functionmt.__unm(a) localresult=setmetatable({},mt) fori=#a,1,-1do table.insert(result,a[i]) end returnresult end res=-tb1+tb2 fori,vinipairs(res)do print(v) end print() functionmt.__tostring(a) localresult="{" fori,vinipairs(a)do result=result..""..v end result=result.."}" returnresult end print(tb1) functionmt.__index(tb1,key) print("thereisno"..key.."inthetable") returnnil end print(tb1["fsy"]) functionmt.__newindex(a,key,v) if(key=="haha")then error("Stoplaugh!",2) else rawset(a,key,v) end end tb1.haha="heihei"
运行结果:
0 1 4 5 true alpha beta gamma aaa bbb ccc gamma beta alpha aaa bbb ccc {alphabetagamma} thereisnofsyinthetable nil lua:my_test.lua:166:Stoplaugh! stacktraceback: [C]:infunction'error' my_test.lua:160:infunction<my_test.lua:158> my_test.lua:166:inmainchunk [C]:?