向表插入对象将覆盖表的其他成员

时间:2019-06-07 09:10:19

标签: lua lua-5.1

我需要在Lua中创建对象表。 但是,当我将对象插入表中时,之前插入的所有成员都会更改值。所有这些对象的哈希码都不同

Rectangle = {area = 0, length = 0, breadth = 0}
function Rectangle:new (o,length,breadth)
   o = o or {}
   setmetatable(o, self)
   self.__index = self
   self.length = length or 0
   self.breadth = breadth or 0
   self.area = length*breadth;
   return o
end

foo = {}
r1 = Rectangle:new(nil, 10, 10);
table.insert(foo,r1)

r2 = Rectangle:new(nil, 20, 20);
table.insert(foo, r2)

r3 = Rectangle:new(nil, 50, 50);
table.insert(foo, r3)

print(r1.length) -- 50, should be 10
print(r2.length) -- 50, should be 20
print(r3.length) -- 50 is 50

如何在不影响其他成员的情况下插入对象? 我在网上搜索过,我认为这在5.2中已修复。但是我需要使用5.1。

有人可以帮忙吗,谢谢

已解决

Rectangle = {area = 0, length = 0, breadth = 0}
function Rectangle:new (o,length,breadth)
   o = o or {}
   o.length = length or 0
   o.breadth = breadth or 0
   o.area = length*breadth
   setmetatable(o, self)
   self.__index = self
   return o
end

1 个答案:

答案 0 :(得分:1)

Rectangle:new中,做

   o.length = length or 0
   o.breadth = breadth or 0
   o.area = length*breadth
呼叫self

Rectangle将包含Rectangle:new()