[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Inserting objects into tables
- From: "Kristofer Karlsson" <kristofer.karlsson@...>
- Date: Thu, 12 Jun 2008 14:11:49 +0200
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()
****************