我想创建一个非常简单的面向对象程序。如何列出对象字段(例如,所有客户名称)?以下代码有什么问题? for k, v in ipairs()
无效。
do
local Account = {}
function Account:Current()
return self.B
end
function Account:Deposit(D)
self.B = self.B + D
end
function Account:Withdraw(W)
self.B = self.B - W
end
function BankAccount(Id, Name, N)
return {B=N,Current=Account.Current,Deposit=Account.Deposit,Withdraw=Account.Withdraw,AccountName=Name,AccountId=Id}
end
end
local Id = 1
local CustomerDatabase = {}
while true do
print("Select an option or press q to quit")
print("1. Create new customer entry")
print("5. List current customer database")
local Option = io.read("*line")
if Option == "q" then break
elseif Option == "1" then
print("Enter the name")
local Name = io.read("*line")
print("Enter initial amount")
local InitialAmount = io.read("*line")
BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, BankAccount)
Id = Id + 1
elseif Option == "5" then
for k, v in ipairs(CustomerDatabase) do
print(k .. v.AccountName)
end
end
end
答案 0 :(得分:2)
BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, BankAccount)
这里,BankAccount
是一个函数,您正在向表中插入一个函数。这就是v.AccountName
无效的原因,无法对函数编制索引。
您应该做的是添加帐户对象:
local account = BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, account)