Menu
Coddy logo textTech

Get Balance

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

challenge icon

Challenge

Easy

Your Digital Bank is really taking shape! Accounts can receive deposits and handle withdrawals with proper fund checking. Now let's add a getter method to retrieve the balance, and then put everything together in a realistic banking scenario.

You'll continue building on your existing files:

  • Account.lua: Add a :getBalance() method that returns the current balance. This follows the getter pattern you learned earlier—providing controlled access to internal data rather than accessing the field directly. Keep all your existing functionality (constructor, deposit, and withdraw methods).
  • main.lua: Create an account and run through a sequence of banking operations to demonstrate how deposits, withdrawals, and balance checks work together in a real scenario.

You will receive five inputs:

  1. Initial deposit amount
  2. First withdrawal amount
  3. Second deposit amount
  4. Second withdrawal amount
  5. Third withdrawal amount

In your main file, create an account and perform these operations in order:

  1. Deposit the initial amount, then print the balance using :getBalance()
  2. Withdraw the first amount, then print the balance
  3. Deposit the second amount, then print the balance
  4. Withdraw the second amount, then print the balance
  5. Attempt the third withdrawal, then print the balance

Remember that failed withdrawals will print Insufficient funds before you print the balance.

For example, if the inputs are 200, 50, 100, 180, and 100, the output should be:

200
150
250
70
Insufficient funds
70

The account starts at 200, drops to 150 after the first withdrawal, rises to 250 after another deposit, falls to 70 after withdrawing 180, and stays at 70 when the final withdrawal of 100 fails due to insufficient funds.

Try it yourself

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

-- Read the five inputs
local initialDeposit = tonumber(io.read())
local withdrawal1 = tonumber(io.read())
local deposit2 = tonumber(io.read())
local withdrawal2 = tonumber(io.read())
local withdrawal3 = tonumber(io.read())

-- Create a single account
local account = Account:new()

-- Deposit the initial amount and print balance using :getBalance()
account:deposit(initialDeposit)
print(account:getBalance())

-- Attempt first withdrawal and print balance
account:withdraw(withdrawal1)
print(account:getBalance())

-- Deposit the second amount and print balance
account:deposit(deposit2)
print(account:getBalance())

-- Attempt second withdrawal and print balance
account:withdraw(withdrawal2)
print(account:getBalance())

-- Attempt third withdrawal and print balance
account:withdraw(withdrawal3)
print(account:getBalance())

All lessons in Object Oriented Programming