设置元表:setmetatable(表,元表)

原表内置特殊属性:

属性 作用
__index 索引,在表内找不到时到__index设置的表找,或执行__index的函数
__newindex 增加新键时,执行设置的函数或者添加到newindex设置的表
__call(…) 当表被当作函数调用时执行call设置的函数,可以传参
__tostring 当表被当作字符串运算或输出时,执行tostring设置的函数
__add(self,other) 对应的运算符 +
__sub(self,other) 对应的运算符 -
__mul(self,other) 对应的运算符 *
__div(self,other) 对应的运算符 /
__mod(self,other) 对应的运算符 %
__unm(self) 对应的运算符 -(负号)
__concat(self,other) 对应的运算符 ..
__eq(self,other) 对应的运算符 ==
__lt(self,other) 对应的运算符 <
__le(self,other) 对应的运算符 <=
__len(self) 对应的运算符 #

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
mt = {name = 'bk',age = 18}

nt = {}

mt.__index = mt;

mt.__newindex = nt;

mt.__call = function(args)
print("hello !!!"..args.name)
end

mt.__add = function(selftb,othertb)
return #selftb + #othertb
end

mt.__tostring = function()
return "sssss"
end

mt.__len = function()
return 888
end

local b = setmetatable({},mt)

print(b.name) --输出bk
print(b.age) --输出18

print(#b) -- 输出 0

local tlen = b + {1,2,3}

print(tlen) --输出3

b() -- 输出hello !!!bk

b.sex = "男"

print(b.sex) --输出 nil

print(nt.sex) -- 输出男

print(#b) --输出888