最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Lua編程示例(二):面向對象、metatable對表進行擴展

 更新時間:2015年07月09日 10:33:30   投稿:junjie  
這篇文章主要介紹了Lua編程示例(二):面向對象、metatable對表進行擴展,本文直接給出實例代碼,需要的朋友可以參考下
counter = {
 count = 0
}
function counter.get(self)
 return self.count
end

function counter: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()

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 result
end

tb2={"aaa","bbb","ccc"}
res=tb1+tb2
for i,v in ipairs(res) do
 print(v)
end
print()
function mt.__unm(a)
 local result = setmetatable({},mt)
 for i=#a , 1 ,-1 do
 table.insert(result,a[i])
 end
 return result
end

res=-tb1+tb2
for i,v in ipairs(res) do
 print(v)
end

print()
function mt.__tostring(a)
 local result = "{"
 for i,v in ipairs(a) do
 result = result.." "..v
 end
 result = result.." } "
 return result
end

print(tb1)

function mt.__index(tb1,key)
 print("there is no "..key.." in the table")
 return nil
end

print(tb1["fsy"])

function mt.__newindex(a,key,v)
 if( key == "haha") then
 error(" Stop laugh!",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

{ alpha beta gamma } 
there is no fsy in the table
nil
lua: 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]: ?

 

相關文章

最新評論

青河县| 闻喜县| 安塞县| 富阳市| 海门市| 元氏县| 开远市| 巧家县| 屏山县| 福建省| 芒康县| 镇康县| 伊金霍洛旗| 潞城市| 绥阳县| 榆社县| 荆门市| 游戏| 江口县| 保德县| 淅川县| 永宁县| 克拉玛依市| 元阳县| 泰和县| 大姚县| 宣汉县| 城市| 抚州市| 瑞安市| 布尔津县| 合作市| 克东县| 布尔津县| 东乌珠穆沁旗| 施秉县| 台山市| 乌什县| 清远市| 渝中区| 腾冲县|