Menu
Coddy logo textTech

Account Info

Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 23 of 70.

challenge icon

Challenge

Easy

Your Digital Bank is becoming more professional! Now let's make your accounts display themselves nicely when printed. By adding a __tostring metamethod, you can control exactly how an account appears—showing both an account ID and the current balance in a clean, readable format.

You'll continue building on your existing files:

  • Account.lua: Extend your Account class with two new features:
    • Modify the :new() constructor to accept an id parameter that identifies each account
    • Add a __tostring metamethod that returns a formatted string showing the account's information
    Keep all your existing functionality (deposit, withdraw, and getBalance methods).
  • main.lua: Create accounts with IDs and demonstrate how they display themselves when printed.

The __tostring method should return a string in this exact format:

Account [ID]: Balance = BALANCE

Where ID is the account's ID and BALANCE is the current balance.

You will receive four inputs:

  1. First account's ID
  2. First account's deposit amount
  3. Second account's ID
  4. Second account's deposit amount

In your main file, create two accounts with the given IDs, deposit the respective amounts into each, then print each account directly using print(). The __tostring metamethod will automatically be called when you print the account object.

For example, if the inputs are 1001, 500, 1002, and 750, the output should be:

Account [1001]: Balance = 500
Account [1002]: Balance = 750

Each account now has a unique identity and can describe itself clearly—a much more professional banking experience!

Try it yourself

-- Require the Account module
local Account = require('Account')

-- Read the four inputs
local id1 = io.read()
local deposit1 = tonumber(io.read())
local id2 = io.read()
local deposit2 = tonumber(io.read())

-- Create two accounts with IDs
local account1 = Account:new(id1)
local account2 = Account:new(id2)

-- Deposit the respective amounts
account1:deposit(deposit1)
account2:deposit(deposit2)

-- Print each account (uses __tostring)
print(account1)
print(account2)

All lessons in Object Oriented Programming