简体   繁体   English

尝试索引全局“BankAccount”(一个函数值)

[英]attempt to index global 'BankAccount' (a function value)

I am new to Lua, so while creating and accessing a class in a lua code.我是 Lua 的新手,所以在 lua 代码中创建和访问类时。 I am getting the following error我收到以下错误

attempt to index global 'BankAccount' (a function value)尝试索引全局“BankAccount”(一个函数值)

The code block is below for reference.代码块如下供参考。

-- classes in lua -- 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.function BankAccount(amount)BankAccount重新定义为一个函数。

The line should be function BankAccount:withdraw(amount) .该行应该是function BankAccount:withdraw(amount)

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

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