Lua rawset和rawget的作用浅析 Lua中rawset和rawget的作用浅析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Lua rawset和rawget的作用浅析 Lua中rawset和rawget的作用浅析

  2021-03-21 我要评论
想了解Lua中rawset和rawget的作用浅析的相关内容吗,在本文为您仔细讲解Lua rawset和rawget的作用浅析的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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,陷入了死循环。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们