Lua中rawset和rawget的作用浅析
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,陷入了死循环。
相关推荐
峰哥 2020-09-23
陈云佳 2020-08-15
wqiaofujiang 2020-07-05
wordmhg 2020-06-26
wqiaofujiang 2020-06-16
zllbirdonland 2020-06-16
eroshn 2020-06-10
长安长夜Saint 2020-06-07
Dawnworld 2020-06-07
fansenjun 2020-03-01
CSDNMrWang 2020-05-11
Dawnworld 2020-05-05
陈云佳 2020-04-21
Neptune 2020-04-20
shunelly 2020-04-16
aolishuai 2020-04-15
YukiRain 2020-04-14
陈云佳 2020-03-07
陈云佳 2020-03-05