[Lua]元表

参考链接:

https://www.runoob.com/lua/lua-metatables.html

https://www.jianshu.com/p/cb945e7073a3

 

元表是一个table,可以让我们改变table的行为,每个行为有对应的元方法

例如,对table进行设置键值,查找键值,运算等,就会触发对应的元方法

 1 --__index:table被访问时,如果找不到这个键,就会触发元表的__index元方法;类似get
 2 function TestMetatableIndex()
 3     --__index的值为table,在table中找
 4     local a = {k1 = "hello"}
 5     setmetatable(a, {
 6         __index = {k1 = "hello2", k2 = "hi"}
 7     })
 8     print(a.k1, a.k2) --hello   hi
 9 
10     --__index的值为方法
11     local b = {}
12     setmetatable(b, {
13         __index = function (mytable, key)
14             return "qwe" .. key 
15         end
16     })
17     print(b[1]) --qwe1
18 end
19 
20 --__newindex:table被设置值时,如果找不到这个键,就会触发元表的__newindex元方法;类似set
21 function TestMetatableNewindex()
22     --__newindex的值为table,给该table设置值
23     local a = {}
24     local b = {}
25     setmetatable(a, {
26         __newindex = b
27     })
28     a.k1 = "asd"
29     print(a.k1, b.k1) --nil asd
30 
31     --__newindex的值为方法
32     local c = {}
33     setmetatable(c, {
34         __newindex = function (t, key, value)
35             print(key .. "_" .. value)
36         end
37     })
38     c[1] = "zxc" --1_zxc
39 end
40 
41 --__add:table被相加时,会触发该元方法
42 --两表相加,必须至少其中一个表设置了带__add键的元表
43 --如果两个表都设置了带__add键的元表,则程序会去执行"+"左侧的表中的元表的__add
44 function TestMetatableAdd()
45     local a = {1, 2, 3}
46     local b = {4, 5, 6}
47     setmetatable(b, {
48         __add = function (t1, t2)
49             local result = {}
50             for i=1,3 do
51                 result[i] = t1[i] + t2[i]
52             end
53             return result
54         end
55     })
56     local c = a + b
57     for k,v in pairs(c) do
58         print(k,v)
59     end
60     --打印:
61     --1 5
62     --2 7
63     --3 9
64 end
65 
66 --__call:table被调用时(像调用方法一样),会触发该元方法
67 function TestMetatableCall()
68     local a = setmetatable({10}, {
69         __call = function(t, b, c, d) --table会作为第一个参数,其他的为传入的参数
70             print(t[1], b, c, d) --10   2   5   nil
71             return 30, 40
72         end
73     })
74     print(a(2,5)) --30  40
75 end
76 
77 --__tostring:table被打印时,会触发该元方法
78 function TestMetatableTostring()
79     local a = setmetatable({10}, {
80         __tostring = function(t)
81             return "hello" .. t[1]
82         end
83     })
84     print(a) --hello10
85 end
86 
87 -- TestMetatableIndex()
88 -- TestMetatableNewindex()
89 -- TestMetatableAdd()
90 -- TestMetatableCall()
91 -- TestMetatableTostring()

其他运算符:

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...