日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

lua metatable 和 _index 实验

發布時間:2024/1/17 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 lua metatable 和 _index 实验 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

lua metatable 和 _index

中文博客解釋:

http://www.cnblogs.com/simonw/archive/2007/01/17/622032.html

?

metatable:http://www.lua.org/pil/13.html

??? 表的通用方法中,有些缺失的, 使用metatable可以定義表的這些默認方法:

add, sub, mul, div, mod, pow, unm, concat, len, eq, lt, le, tostring, gc, index, newindex, call...

?

__index: http://www.lua.org/pil/13.4.1.html

??? 當訪問表中無此元素, 則查詢metatable中是否有__index, 如果有則獲取_index調用結果, 如果沒有__index則返回nil

?

__newindex : http://www.lua.org/pil/13.4.2.html

  當設置表中不存在的key時候, 觸發調用metatable 的 __newindex, 如果沒有__newindex則設置到目標表的屬性上, 如果存在__newindex, 則執行它。

?

例子:

__index __newindex 對比:

local Bird = {CanFly = true}function Bird:New()local b = {}setmetatable(b, self)self.__index = self--self.__newindex = selfreturn b endlocal Ostrich = Bird:New() --Bird.CanFly is true, Ostrich.CanFly is true Ostrich.CanFly = false --Bird.CanFly is true, Ostrich.CanFly is falseprint("Ostrich.CanFly="..tostring(Ostrich.CanFly)) print("Bird.CanFly="..tostring(Bird.CanFly))

?

其他測試實驗:

--定義2個表 a = {5, 6} b = {7, 8} --用c來做Metatable c = {} --重定義加法操作 c.__add = function(op1, op2)for _, item in ipairs(op2) dotable.insert(op1, item)endreturn op1 end --自定義方法 c.print = function()print("c print!"); end --將a的Metatable設置為c, 報錯,print為nil NOK --[[ setmetatable(a, c) a.print() ]] --將a的Metatable設置為c, 調用c定義的內置函數 OK --d現在的樣子是{5,6,7,8} --[[ setmetatable(a, c) d = a + b for _, item in ipairs(d) doprint(item) end ]] --將a的__index設置為c, 可以調用c定義的print OK --[[ setmetatable(a, {__index = c}) a.print() ]] --將a的metatable設置為c, 可以調用c定義的print OK --[[ c.__index = c setmetatable(a, c) a.print() --]] --將a的__index不能直接復制為c, 報錯, NOK --[[ a.__index = c a.print() --]] --將a的__index設置為c, 報錯a不能執行算出運算, NOK --[[ setmetatable(a, {__index = c}) d = a + b for _, item in ipairs(d) doprint(item) end ]] --將a的__add設置為c的__add, OK --[[ setmetatable(a, {__add=c.__add}) d = a + b for _, item in ipairs(d) doprint(item) end --]] -- 可以調用自定義方法, 和 內置方法 OK --[[ setmetatable(a, {__index = c, __add=c.__add}) a.print() d = a + b for _, item in ipairs(d) doprint(item) end --]]

?

總結

以上是生活随笔為你收集整理的lua metatable 和 _index 实验的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。