1 指向table
t = {}
f = {key = "hjj"}
p = setmetatable(t, { __newindex = f })
p.key1 = 2
print(t.key1)
print(f.key1)
print(f.key)
-----输出----
nil
2
hjj
---等价代码
t = {}
f = {key = "hjj"}
p = setmetatable(t, { __newindex =
function(table, key, value)
f[key] = value
end})
p.key1 = 2
print(f.key1)
2 指向函数
t = {}
f = {key = "hjj"}
p = setmetatable(t, { __newindex =
function(table, key, value)
print("不存在数据")
print(key)
print(value)
print(table)
end})
p.key1 = 2
-----输出
不存在数据
key1
2
table: 0x56380445b290
3 构造继承(修改同一个基类数据和修改本类数据)
--注意输出数据
a = {["key"] = "hjj"}
function a:new(data, value)
o = {}
o = setmetatable(o, {__index = a})
self.key = value
o.data = data
return o
end
function a:printout()
print(self.data)
end
t1 = a:new(1, "zc")
t2 = a:new(2, "jc")
t1:printout() -- 1
t2:printout() --2
print(t1.key) --jc
print(t2.key) --jc
4 测试继承输出,同3,
a = {["key"] = "hjj"}
a.key2 = "lx"
function a:new(data, value)
o = {}
o = setmetatable(o, {__index = a})
self.key2 = data
o.key = value
return o
end
function a:printout()
print("key "..self.key)
print("key2 "..self.key2)
end
t1 = a:new(1, "zc")
t2 = a:new(2, "jc")
----输出-----
key zc
key2 2
key jc
key2 2