繁体   English   中英

Lua脚本抛出错误“尝试调用零值(字段'存款')”

[英]Lua script throws error “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())

我似乎没有弄错。 也许它只是':'运算符才有效?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM