lua metatable 和 _index 实验
生活随笔
收集整理的這篇文章主要介紹了
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 实验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【MySql】在Linux下安装MySq
- 下一篇: redis 参考