Lua中rawset和rawget的作用浅析

发布时间:2022-04-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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,陷入了死循环。

脚本宝典总结

以上是脚本宝典为你收集整理的Lua中rawset和rawget的作用浅析全部内容,希望文章能够帮你解决Lua中rawset和rawget的作用浅析所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Lua