Lua Intermediate: OOP, Closures & Patterns

Lesson 5 of 5

Final Project: Build a Contact Book with Validated Errors

Combine closures, OOP, patterns, and error handling into one small but real program: a contact book.

Requirements

  1. Model a ContactBook "class" (metatable + __index, like the Object-Oriented lesson) with methods to add, remove, and list contacts.
  2. Each contact needs a name and an email; validate the email with a string pattern (at minimum, requires an @ and at least one . after it) and error()/assert() if it's invalid.
  3. Wrap every call that adds a contact in pcall, so a bad email prints a friendly error message instead of crashing the whole program.
  4. Add a search(term) method that uses string.find or gmatch to return every contact whose name contains term (case-insensitive).
  5. Use a closure to track how many contacts have ever been added in total (including ones later removed), exposed through a ContactBook:totalEverAdded() method, without storing it as a plain field on the instance.

Stretch goals

  • Support multiple emails per contact (a table of emails instead of one string).
  • Add an export() method that returns a single formatted string listing every contact, built with table.concat.
  • Persist contacts to a file with Lua's io library and reload them on startup (only relevant if you're running outside this course's browser sandbox).

Submit a link to your finished script (a repo or gist) below, an instructor will review it before you can mark this lesson complete.

This lesson ends in a project. Build it on your own machine, there's nowhere to submit it here, but the brief above is everything you need.