lua-users home
lua-l archive

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


In my opinion, this is not lua's flaw. balance is a class variable like in c++. Instances of Account don't have a field named balance.Then when you write a.balance=xxx, it will set the value to the metatable of a, which is Account.
So the correct way is to set property to instance not to metatable when you create the instance.Like following:
Account={
    new = function(self, balance)
        o={}
        o.balance=balance
        setmetatable(o,self)
        self.__index=self
        return o
    end
}

 
在06-4-13,许斌 <xbcqu0708@163.com> 写道:
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



--
Best Regards.

Chen guo
Tongji University, China