在Lua中列出对象字段

在Lua中列出对象字段,lua,lua-table,Lua,Lua Table,我想创建一个非常简单的面向对象程序。如何列出对象字段(例如,所有客户名称)?以下代码有什么问题无效。 do local Account = {} function Account:Current() return self.B end function Account:Deposit(D) self.B = self.B + D end function Account:Withdraw(W)

我想创建一个非常简单的面向对象程序。如何列出对象字段(例如,所有客户名称)?以下代码有什么问题无效。

 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
这里,
BankAccount
是一个函数,您将在表中插入一个函数。这就是为什么
v.AccountName
无效,无法对函数进行索引

您应该做的是添加account对象:

local account = BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, account)
local account = BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, account)