rawget是為了繞過__index而出現的,直接點,就是讓__index方法的重寫無效。(我這里用到"重寫"二字,可能不太對,希望能得到糾正)
復制代碼 代碼如下:
Window = {}
Window.prototype = {x = 0 ,y = 0 ,width = 100 ,height = 100,}
Window.mt = {}
function Window.new(o)
setmetatable(o ,Window.mt)
return o
end
Window.mt.__index = function (t ,key)
return 1000
end
Window.mt.__newindex = function (table ,key ,value)
if key == "wangbin" then
rawset(table ,"wangbin" ,"yes,i am")
end
end
w = Window.new{x = 10 ,y = 20}
print(rawget(w ,w.wangbin))
打印結果是:nil。這里的元表中__index函數就不再起作用了。
但是rawset呢,起什么作用呢?我們再來運行一段代碼。
復制代碼 代碼如下:
Window = {}
Window.prototype = {x = 0 ,y = 0 ,width = 100 ,height = 100,}
Window.mt = {}
function Window.new(o)
setmetatable(o ,Window.mt)
return o
end
Window.mt.__index = function (t ,key)
return 1000
end
Window.mt.__newindex = function (table ,key ,value)
table.key = "yes,i am"
end
w = Window.new{x = 10 ,y = 20}
w.wangbin = "55"
然后我們的程序就stack overflow了??梢?,程序陷入了死循環。因為w.wangbin這個元素本來就不存在表中,然后這里不斷執行進入__newindex,陷入了死循環。