1
votes

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?

1
next time, open your script and ask yourself, why does Lua think BankAccount refers 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 find function BankAccount(amount) end which is equvalent to BankAccount = function(amount) end so whoops now BankAccount refers 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
@Piglet thanks for the comment. I understood the mistake. ☺ - Suel Ahmed

1 Answers

3
votes

The line function BankAccount(amount) redefines BankAccount to be a function.

The line should be function BankAccount:withdraw(amount).