Lua 脚本出错,打印 "attempt to call a nil value (field 'deposit')"

我有这份 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())

我不明白错在哪里。也许是 “:” 运算符只能按照特定的方式使用?

点赞
用户107090
用户107090

是的,你需要使用 : 来调用方法:

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) 的简写,等等。

2016-04-19 00:03:24