Lua中rawset和rawget的作用浅析
rawget是为了绕过__index而出现的,直接点,就是让__index方法的重写无效。(我这里用到"重写"二字,可能不太对,希望能得到纠正)
Window={}
Window.prototype={x=0,y=0,width=100,height=100,}
Window.mt={}
functionWindow.new(o)
setmetatable(o,Window.mt)
returno
end
Window.mt.__index=function(t,key)
return1000
end
Window.mt.__newindex=function(table,key,value)
ifkey=="wangbin"then
rawset(table,"wangbin","yes,iam")
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={}
functionWindow.new(o)
setmetatable(o,Window.mt)
returno
end
Window.mt.__index=function(t,key)
return1000
end
Window.mt.__newindex=function(table,key,value)
table.key="yes,iam"
end
w=Window.new{x=10,y=20}
w.wangbin="55"
然后我们的程序就stackoverflow了。可见,程序陷入了死循环。因为w.wangbin这个元素本来就不存在表中,然后这里不断执行进入__newindex,陷入了死循环。
热门推荐
10 喜得孙子祝福语简短唯美
11 婚礼祝福语简短朴实大众
12 员工周年祝福语大全简短
13 家长回复节日祝福语简短
14 简短生日祝福语老同学
15 夜雨祝福语简短10字
16 蛋糕祝福语简短闺蜜
17 部门过年祝福语简短独特
18 简短精炼的结婚祝福语