我有这个 Lua 脚本,它应该创建一个新类,创建一个实例并调用函数,但是在我实际调用方法时出现错误。
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())
我似乎不明白出了什么问题。也许是“:”运算符才有效?
最佳答案
是的,您需要使用 :
来调用方法:
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)
等的糖。关于oop - Lua 脚本抛出错误 "attempt to call a nil value (field ' deposit')",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36706176/