lua元方法__newindex
来源:互联网 发布:大数据人才的需求状况 编辑:程序博客网 时间:2024/06/03 23:49
-- __index和__newindex都是在访问table中不存在的项时会被调用的;
--当对一个table中不存在的索引赋值时,解释器就会查找__newindex元方法。如果有就调用它,而不是直接赋值。
--如果这个元方法指向一个table(此例是指向函数,但函数里面使用_t),Lua将对此table(_t)赋值,而不是对原有的table(agency_t)赋值
local _t = t --保持对原有table的私有访问。
local agency_t = {} --创建代理
--创建元表
local mt = {
__index = function(table,key)
print("access to element " .. tostring(key))
return _t[key] --通过访问原来的表返回字段值,如果注释此句话,agency_t[2]为nil(__index方法也没有对应的)
--如果把_t换成table,程序陷入了死循环
end,__newindex = function(table,key,value)
print("update of element " .. tostring(key) .. " to " .. tostring(value))
_t[key] = value
--更新原来的table,如果把_t换成table,程序陷入了死循环。
--因为agency_t[2]这个元素本来就不存在表中,然后这里不断执行进入__newindex,陷入了死循环
--rawset( table, key, value )来设置没有这个key的元素,
--lua table中__newindex的默认实现就是调用了rawset(绕过元方法)函数
end}
setmetatable(agency_t, mt)
agency_t[2] = "hello" --调用__newindex
print("+--------------------------------------+")
print(agency_t[2]) --有就调用它,而不是直接赋值
print("+--------------------------------------+")
print(rawget(agency_t,agency_t[2])) --rawget绕过元方法,直接访问
print("+--------------------------------------+")
print(t[2]) --没有使用元方法,所以没进入mt
结果:
>lua -e "io.stdout:setvbuf 'no'" "Lua.lua" update of element 2 to hello+--------------------------------------+access to element 2hello+--------------------------------------+access to element 2nil+--------------------------------------+hello>Exit code: 0
0 0
- lua元方法__newindex
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- lua中的元方法__index __newIndex
- Lua中__newindex元方法的使用
- lua 元方法__newindex,实现只读的table
- _index和__newindex元方法
- 【Lua】__newindex
- Lua __newindex
- lua 的__newindex
- lua setmetatable __index __newindex
- Lua __index和__newindex
- Lua 元表 元方法
- Android项目用到的一些开源项目
- Android2.1下调试3G模块(三)
- Mac下PHP连接MySQL报错"No such file or directory"的解决办法
- 在linux下安装并操作tomcat
- OC代码块block
- lua元方法__newindex
- POJ 3177 Redundant Paths(边双连通分量+缩点)
- 添加删除ASM磁盘
- Unity3D NGUI自适应屏幕分辨率(2014/4/17更新)
- Collections.sort()用法
- <实例>C++ 将一句话里的单词进行倒置,标点符号不倒换——使用string库实现
- Android之Adapter用法总结
- mysql帮助
- 新企代运营:如何去获取对手的关键词?