[英]Lua script throws error “attempt to call a nil value (field 'deposit')”
I have this Lua script, which is supposed to create a new class, create an instance and call functions, but there's an error in which I actually call the methods. 我有这个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)
It keeps throwing this error: 它不断抛出这个错误:
attempt to call a nil value (field 'deposit')
It seems to work like this: 它看起来像这样:
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())
I don't seem to get what's wrong. 我似乎没有弄错。 Maybe it's the ':' operator that only works? 也许它只是':'运算符才有效?
Yes, you need to use :
to call methods: 是的,你需要使用:
来调用方法:
new_account = Account:new()
print(new_account.balance)
new_account:deposit(23)
new_account:deposit(1)
print(new_account.balance)
Account:new()
is sugar for Account.new(Account)
, etc. Account:new()
是Account.new(Account)
等的糖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.