lua-users home
lua-l archive

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


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