Question

I want to create a very simple object oriented program. How can I list object fields (e.g., all customer names)? What is wrong with the following code? for k, v in ipairs() didn't work.

 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
Was it helpful?

Solution

BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, BankAccount)

Here, BankAccount is a function, you are inserting into the table a function. That's why v.AccountName is invalid, functions can't be indexed.

What you should do is to add the account object:

local account = BankAccount(Id, Name, InitialAmount)
table.insert(CustomerDatabase, account)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top