脚本专栏 
首页 > 脚本专栏 > 浏览文章

Lua中rawset和rawget的作用浅析

(编辑:jimmy 日期: 2025/5/15 浏览:3 次 )

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呢,起什么作用呢"codetitle">复制代码 代码如下:
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中操作json数据的方法
下一篇:lua中使用毫秒精度时间的方法
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。