lualua-5.1

LUA: Insert object to a table overrides other members of table


I need to create a table of objects in Lua. But when I insert a object into a table all members inserted before will change values. Hash code of all off these objects is different

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

How do I insert a objects without affecting other members? I have searched online, and i think this is fixed in 5.2. But I need to use 5.1.

Can someone help, thanks

SOLVED

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

Solution

  • In Rectangle:new, do

       o.length = length or 0
       o.breadth = breadth or 0
       o.area = length*breadth
    

    self will contain Rectangle when you call Rectangle:new().