Menu
Coddy logo textTech

Recap - Score Tracker

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

challenge icon

Challenge

Easy

Let's build a score tracking system for a gaming leaderboard! You'll create two classes that work together—one representing individual score entries, and another managing the leaderboard with sorting capabilities powered by operator overloading.

You'll organize your code across three files:

  • ScoreEntry.lua: Create a ScoreEntry class that represents a single player's score. Each entry has a playerName and a score. Include a :getInfo() method that returns a string in the format "{playerName}: {score} points". The key feature here is implementing the __lt metamethod—but remember, for descending order (highest scores first), your comparison should return true when the first entry's score is greater than the second's.
  • Leaderboard.lua: Build a Leaderboard class that manages a collection of score entries. Your leaderboard needs:
    • :addEntry(entry) — adds a ScoreEntry to the internal list
    • :sort() — sorts entries from highest to lowest score using table.sort
    • :display() — prints the info for each entry, one per line
  • main.lua: Bring everything together! Create a Leaderboard, add score entries based on the inputs you receive, sort the leaderboard, and display the results.

The elegant part of this design is that table.sort automatically uses your __lt metamethod to compare ScoreEntry objects. By defining how entries compare to each other, Lua's built-in sorting just works with your custom objects!

You will receive six inputs representing three players:

  1. First player's name
  2. First player's score (a number)
  3. Second player's name
  4. Second player's score (a number)
  5. Third player's name
  6. Third player's score (a number)

In your main file, create a leaderboard, add all three entries, call :sort(), then call :display() to show the sorted results.

For example, if the inputs are Alice, 1500, Bob, 2300, Charlie, and 1800, the output should be:

Bob: 2300 points
Charlie: 1800 points
Alice: 1500 points

If the inputs are Zara, 500, Max, 750, Luna, and 600, the output should be:

Max: 750 points
Luna: 600 points
Zara: 500 points

Try it yourself

-- Main file: Bring everything together
local ScoreEntry = require('ScoreEntry')
local Leaderboard = require('Leaderboard')

-- Read inputs for three players
local name1 = io.read()
local score1 = tonumber(io.read())
local name2 = io.read()
local score2 = tonumber(io.read())
local name3 = io.read()
local score3 = tonumber(io.read())

-- TODO: Create a new Leaderboard

-- TODO: Create ScoreEntry objects for each player

-- TODO: Add all three entries to the leaderboard

-- TODO: Sort the leaderboard

-- TODO: Display the sorted results

All lessons in Object Oriented Programming