lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


You're setting the name on the class instead of the object, so the
second call to add overwrites the name.

Also, you should use local variables when possible.

Here's some modified code
****************
ClassA = {}
ClassA.__index = ClassA

function ClassA:new(name)
       local object = {}
       setmetatable(object, self)
       object.name = name
       return object
end

ClassB = {}
ClassB.__index = ClassB
function ClassB:new()
       local object = {}
       setmetatable(object, self)
       object.tabs = {}
       return object
end

function ClassB:add(name)
       local ser = ClassA:new(name)
       table.insert(self.tabs,ser)
end

function ClassB:print()
       for i,obj in pairs(self.tabs) do
               print(obj.name)
       end
end

ob = ClassB:new()
ob:add('Earth')
ob:add('Mars')
ob:print()
****************