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

phriol picture phriol · Apr 19, 2016 · Viewed 22.2k times · Source

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.

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?

Answer

lhf picture lhf · Apr 19, 2016

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.