Lua newindex元方法

Lua 中的 __newindex 元方法用来对表更新,__index 则用来对表访问。当你给表的一个缺少的索引赋值,解释器就会查找 __newindex 元方法,如果存在则调用这个函数而不进行赋值操作。

案例

Lua __newindex 元方法的使用

#!/usr/bin/lua print("haicoder(www.haicoder.net)\n") mymetatable = {} mytable = setmetatable({key1 = "value1"}, { __newindex = mymetatable }) print(string.format("mytable key1 = %s", mytable.key1)) mytable.newkey = "New Value2" print(string.format("mytable newkey = %s, mymetatable newkey = %s", mytable.newkey, mymetatable.newkey)) mytable.key1 = "New Value1" print(string.format("mytable = %s, mymetatable = %s", mytable.key1, mymetatable.key1))

程序运行后,控制台输出如下:

03_Lua newindex元方法.png

以上实例中表设置了元方法 __newindex,在对新索引键(newkey)赋值时(mytable.newkey = “New Value2”),会调用元方法,而不进行赋值。而如果对已存在的索引键(key1),则会进行赋值,而不调用元方法 __newindex

以下实例使用了 rawset 函数来更新表:

#!/usr/bin/lua print("haicoder(www.haicoder.net)\n") mytable = setmetatable({key1 = "value1"}, { __newindex = function(mytable, key, value) rawset(mytable, key, "\""..value.."\"") end }) mytable.key1 = "new value" mytable.key2 = 4 print(string.format("key1 = %s, key2 = %s", mytable.key1, mytable.key2))

程序运行后,控制台输出如下:

04_Lua newindex元方法.png

我们通过了 rawset 来更新了表。

Lua newindex元方法总结

Lua 中的 __newindex 元方法用来对表更新,__index 则用来对表访问。当你给表的一个缺少的索引赋值,解释器就会查找 __newindex 元方法,如果存在则调用这个函数而不进行赋值操作。