lua-users home
lua-l archive

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


Remember that given:

a = {};

a is just a reference to the table constructed by {}.  This is evidenced
by the fact that you can alias the table:

b = a;
b.member = 1;
=a.member;

Since a and b reference the same table, changing one will change the
other.  I try to keep in mind this simple rule when dealing with Lua:
tables are only created when you see the table constructor {}.

So, your problem is analogous to a class in C++ which has pointer
members.  You must either manually initialize the pointers once you
instantiate a class, or else you can use a constructor.

In Lua the problem is not pointers but references to tables.  To fix the
problem you can either initialize the references manually or in your
constructor:

Example = {
    member1 = "hello world";
    member2 = {};
};

function Example:new (obj)
    obj = obj or {};
    obj.member2 = {};  --initialize member table references
...



On Thu, 2006-04-13 at 17:01 +0800, 许斌 wrote:
> Hi!
> 
>     I'm using Lua.5.1, I have been trying to emulate class in Lua. I have been reading the chapter 16 in the PIL.
> it does well, but it has a flaw:
>     Account = {balance = 0}
> 
>     function Account:deposit(v)
>         self.balance = self.balance + v
>     end
>     function Account:new(o)
>          o = o or {}
>          setmetatable(o, self)
>          self.__index = self
>          return o     
>     end
>     a = Account:new()
>     b = Account:new()
>     
>     a:deposit(2)
>     print("a=", a.balance)
>     print("b=", b.balance)
> output:
>     a=2
>     b=0
> 
> but there is a problem. if the balance is not a number, it's a table, as follows:
>       Account = {balance = {0}}
> 
>     function Account:deposit(v)
>         self.balance[1] = self.balance[1] + v
>     end
>     function Account:new(o)
>          o = o or {}
>          setmetatable(o, self)
>          self.__index = self
>          return o     
>     end
>     a = Account:new()
>     b = Account:new()
>     
>     a:deposit(2)
>     print("a=", a.balance)
>     print("b=", b.balance)
> 
> output:
>     a = {2}
>     b = {2}
> The instance a is changed and the instance b is changed too. This may be a flaw, how to improve it!
> 
> Thanks you!
> 
> ----
> bean