lua __newindex元方法
__newindex 元方法用来对表更新,__index则用来对表访问 。
当你给表的一个缺少的索引赋值,解释器就会查找__newindex 元方法:如果存在则调用这个函数而不进行赋值操作。
而当你给表的一个已存在的索引键赋值,则会进行赋值。
> mymetatable = {} > mytable = setmetatable({key1 = "value1"}, {__newindex = mymetatable}) > print(mytable.key1)--输出表已存在索引键的值 value1 > mytable.newkey = "new value2"--给表一个缺少的索引键赋值 > print(mytable.newkey, mymetatable.newkey)--调用元方法 nil new value2 > mytable.key1 = "new value1"--给表一个已存在的索引键赋值 > print(mytable.key1, mymetatable.key1)--输出更新后的值 new value1 nil > mytable.newkey = "new value3"--给元表中一个已存在的索引键赋值 > print(mytable.newkey, mymetatable.newkey) nil new value3
__newindex 元方法用来对表更新:1.添加新的索引键到元表中;2.更新表和元表中的索引键的值
__index则用来对表访问:1.获取对应索引键的值
> mytable = setmetatable({key1 = "value1"}, {__newindex = function(mytable, key, value) rawset(mytable, key, "\"" ..value.. "\"") end })
> mytable.key1 = "new value"
> mytable.key2 = 4
> print(mytable.key1, mytable.key2)
new value "4"
上面代码,实现的功能:更新元表中的数据。使用了rawset函数。

浙公网安备 33010602011771号