gpt4 book ai didi

oop - Lua 脚本抛出错误 "attempt to call a nil value (field ' 存款')"

转载 作者:行者123 更新时间:2023-12-04 21:37:46 28 4
gpt4 key购买 nike

我有这个 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 ' 存款')",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706176/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com