lua中类的属性是table时,多个类的实例使用了同一个table属性

来源:互联网 发布:网络成瘾的心理危害 编辑:程序博客网 时间:2024/06/14 15:59
定义类Array:
Array = {
     nextIdx = 1,
     content = {}
}
function Array:new(o)
     o = o or {}
     setmetatable(o, self)
     self.__index = self
     return o;
end

测试:
a = Array:new()
b = Array:new()
a. nextIdx = 10
print(a.nextIdx)
print(b.nextIdx)
print(a.content)
print(b.content)

输出为
10
1
table: 0021D528
table: 0021D528

发现a与b的nextIdx属性不同,但content值相同,为同一个表

但是在new时再为其幅值可避免这一问题,将其修改为
Array = {
     nextIdx = 1,
     content = nil
}

function Array:new(o)
     o = o or {}
     setmetatable(o, self)
     self.__index = self
     o.content = {}                   --此处再赋值创建空表
     return o;
end

调用同样测试函数结果为:
10
1
0023D668
0023D528
结果各不相同

0 0
原创粉丝点击