I am new to Lua, so while creating and accessing a class in a lua code. I am getting the following error
attempt to index global 'BankAccount' (a function value)
The code block is below for reference.
-- classes in lua
-- bank account is a table
BankAccount = {
account_number = 0,
holder_name = "",
balance = 0.0
}
function BankAccount:deposit(amount)
self.balance = self.balance + amount
end
function BankAccount(amount)
self.balance = self.balance - amount
end
function BankAccount:new(t)
t = t or {}
setmetatable(t,self)
self.__index= self
return t
end
-- instantiate an object of the class BankAccount
johns_account = BankAccount:new({
account_number = 12345678,
holder_name = "John",
balance = 0.0
})
print(johns_account.account_number)
Could anyone explain what error am I making or something else I am missing?
BankAccountrefers to a function value. search for the word BankAccount. Your first hit will be:BankAccount = {}so it refers to a table, a bit later you'll findfunction BankAccount(amount) endwhich is equvalent toBankAccount = function(amount) endso whoops nowBankAccountrefers to a function value! something is wrong here, you didn't mean to do this. so what is missing? when presented with errors, always check if the variables related to that error have the value they#re supposed to have and find out why not - Piglet