[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Inserting objects into tables
- From: Eike Decker <eike@...>
- Date: Thu, 12 Jun 2008 15:32:44 +0200
Hi
You are mixing up the class and the object tables
> function ClassA:new(name)
> object = {}
> setmetatable(object, self)
> self.__index = self
> self.name = name
> return object
> end
it should be
> ClassA.__index = ClassA
> function ClassA:new(name)
> local object = {} -- use the local keyword, it's important!
> setmetatable(object, self)
> object.name = name
> return object
> end
Similiar errors are in the rest of your code. Also, you should use the
keyword "local", declaring variables local if they don't need to be global.
Otherwise, you might run into errors that are rather difficult to debug.
Eike
> Hi,
> This is my first post to the lua mailing list.
> I have just started learning lua.
> Please just check the following code:
> ****************
> ClassA = {}
> function ClassA:new(name)
> object = {}
> setmetatable(object, self)
> self.__index = self
> self.name = name
> return object
> end
>
> ClassB = {}
> function ClassB:new()
> object = {}
> setmetatable(object, self)
> self.__index = self
> self.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()
> ****************
> Shouldn't the above code print:
> Earth
> Mars
> But it doesn't. It prints
> Mars
> Mars
>
> What mistake am I making?
> Thanks for your help.
>