2016-04-18 15 views
2

私はこのクラスの新しいクラスを作成し、インスタンスを作成して関数を呼び出すはずですが、実際にメソッドを呼び出します。Luaスクリプトでエラーが発生しました "nil値(フィールド 'deposit')を呼び出そうとしました"

Account = { 
    balance = 0, 
    new = function(self,o) 
     o = o or {} 
     setmetatable(o,self) 
     self.__index = self 
     return o 
    end, 
    deposit = function(self,money) 
     self.balance = self.balance + money 
    end, 
    withdraw = function(self,money) 
     self.balance = self.balance - money 
    end 

} 
new_account = Account.new() 
print(new_account.balance) 
new_account.deposit(23) 
new_account.deposit(1) 
print(new_account.balance) 

それはこのエラーを投げ続ける:

attempt to call a nil value (field 'deposit') 

このように動作しているようです:

Account = { 
    balance = 0, 
} 

function Account:new(o) 
    o = o or {} 
    setmetatable(o,self) 
    self.__index = self 
    return o 
end 

function Account:deposit(money) 
    self.balance = self.balance + money 
end 

function Account:withdraw(money) 
    self.balance = self.balance - money 
end 

function Account:get_balance() 
    return self.balance 
end 


acc = Account:new({}) 

print(acc.balance) 

acc:deposit(1920) 

print(acc:get_balance()) 

私が間違って何を取得していないようです。たぶん動作するのは ':'演算子でしょうか?

答えて

4

はい、あなたがメソッドを呼び出すために:を使用する必要があります。

new_account = Account:new() 
print(new_account.balance) 
new_account:deposit(23) 
new_account:deposit(1) 
print(new_account.balance) 

Account:new()

Account.new(Account)ための糖であります
関連する問題