lua中的元方法__index __newIndex
2017-09-21 23:58
288 查看
__index用于lua中table的查询;
__newindex用于lua中table的更新。当一个table中不存在的索引赋值时,解析器就会查找__newindex元方法。如果有这个元方法,解析器就会调用它,而不是进行赋值。如果这个元方法是一个table,解析器就在此table中执行赋值,而不是对原来的table赋值。
有元方法__newindex
无元方法__newindex
local t1 = {}
local mt = {
__index = smartMan,
-- __newindex = function(table, key, value)
-- print(key .. " not exist "..value);
-- end
}
setmetatable(t1, mt)
t1.sayHello = "sfsdsfsf"
print("6666666=====",t1.sayHello)
__newindex用于lua中table的更新。当一个table中不存在的索引赋值时,解析器就会查找__newindex元方法。如果有这个元方法,解析器就会调用它,而不是进行赋值。如果这个元方法是一个table,解析器就在此table中执行赋值,而不是对原来的table赋值。
有元方法__newindex
local t1 = {} local mt = { __index = smartMan, __newindex = function(table, key, value) print(key .. " not exist "..value); end } setmetatable(t1, mt) t1.sayHello = "sfsdsfsf" print("6666666=====",t1.sayHello)
无元方法__newindex
local t1 = {}
local mt = {
__index = smartMan,
-- __newindex = function(table, key, value)
-- print(key .. " not exist "..value);
-- end
}
setmetatable(t1, mt)
t1.sayHello = "sfsdsfsf"
print("6666666=====",t1.sayHello)
相关文章推荐
- 了解Lua语言中的_index,newindex,rawget和rawset
- Lua查找表元素过程(元表、__index方法是如何工作的)
- Lua语言中的__index,__newindex,rawget和rawset
- Lua中的元方法__newindex详解
- Lua查找表元素过程(元表、__index方法是如何工作的)
- Lua查找表元素过程(元表、__index方法是如何工作的)
- Lua中__index和__newindex之间的沉默与合作
- 了解Lua语言中的_index,newindex,rawget和rawset
- Lua查找表元素过程(元表、__index方法是如何工作的)
- Lua查找表元素过程(元表、__index方法是如何工作的)
- 理解Lua语言中的__index,__newindex,rawget和rawset 标签: luametatable__index__newindexrawget 2013-09-27 20:02
- lua中查找表的过程已经(以及对元表和__index方法的理解)
- Lua查找表元素过程(元表、__index方法是如何工作的)
- lua setmetatable __index __newindex
- Lua查找表元素过程(元表、__index方法是如何工作的 , 后续需整理一下实现多重继承的思路)
- Lua查找表元素过程(元表、__index方法是如何工作的)
- Lua查找表元素过程(元表、__index方法是如何工作的)
- 了解Lua语言中的_index,newindex,rawget和rawset
- 了解Lua语言中的_index,newindex,rawget和rawset
- Lua查找表元素过程(元表、__index方法是如何工作的)