Menu
Coddy logo textTech

Recap - Wallet Math

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

challenge icon

Challenge

Easy

Let's build a Wallet class that brings together the operator overloading skills you've learned in this chapter. Your wallet will store an amount of money and support two key operations: combining wallets with + and comparing wallets with <code>< and .

You'll organize your code across two files:

  • Wallet.lua: Define your Wallet class with an amount field representing how much money it holds. Include a :new(amount) constructor and implement two metamethods:
    • __add: Adding two wallets creates a new wallet containing the combined total
    • __lt: Comparing wallets determines which holds less money
  • main.lua: Require your Wallet module, create wallet instances, and demonstrate both operations working together.

You will receive three inputs:

  1. Amount in the first wallet
  2. Amount in the second wallet
  3. Amount in the third wallet

In your main file, create three wallets with the given amounts. Then:

  1. Add the first and second wallets together to create a combined wallet
  2. Print the combined wallet's amount
  3. Compare the combined wallet with the third wallet using <code>< and print the result (true or false)
  4. Compare the combined wallet with the third wallet using and print the result (true or false)

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

80
true
false

The first wallet (50) plus the second wallet (30) creates a combined wallet with 80. Since 80 is less than 100, the first comparison is true. Since 80 is not greater than 100, the second comparison is false.

Try it yourself

local Wallet = require('Wallet')

-- Read input
local amount1 = tonumber(io.read())
local amount2 = tonumber(io.read())
local amount3 = tonumber(io.read())

-- TODO: Create three wallets with the given amounts

-- TODO: Add the first and second wallets together to create a combined wallet

-- TODO: Print the combined wallet's amount

-- TODO: Compare the combined wallet with the third wallet using < and print the result

-- TODO: Compare the combined wallet with the third wallet using > and print the result

All lessons in Object Oriented Programming