Lua编程示例(二):面向对象、metatable对表进行扩展

时间:2021-05-22

counter = { count = 0}function counter.get(self) return self.countendfunction counter:inc() self.count=self.count+1endprint(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()function mt.__add(a,b) local result = setmetatable({},mt) for i=1,#a do table.insert(result,a[i]) end for i=1,#b do table.insert(result,b[i]) end return resultendtb2={"aaa","bbb","ccc"}res=tb1+tb2for i,v in ipairs(res) do print(v)endprint()function mt.__unm(a) local result = setmetatable({},mt) for i=#a , 1 ,-1 do table.insert(result,a[i]) end return resultendres=-tb1+tb2for i,v in ipairs(res) do print(v)endprint()function mt.__tostring(a) local result = "{" for i,v in ipairs(a) do result = result.." "..v end result = result.." } " return resultendprint(tb1)function mt.__index(tb1,key) print("there is no "..key.." in the table") return nilendprint(tb1["fsy"])function mt.__newindex(a,key,v) if( key == "haha") then error(" Stop laugh!",2) else rawset(a,key,v) endendtb1.haha="heihei"


运行结果:

0145truealphabetagammaaaabbbcccgammabetaalphaaaabbbccc{ alpha beta gamma } there is no fsy in the tablenillua: my_test.lua:166: Stop laugh!stack traceback: [C]: in function 'error' my_test.lua:160: in function <my_test.lua:158> my_test.lua:166: in main chunk [C]: ?

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章