简体   繁体   中英

attempt to index global 'BankAccount' (a function value)

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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