Lua 脚本抛出错误 "attempt to call a nil value (field 'deposit')"

Lua script throws error "attempt to call a nil value (field 'deposit')"

我有这个 Lua 脚本,它应该创建一个新的 class,创建一个实例并调用函数,但在我实际调用方法时出现错误。

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) 的糖,等等