Menu
Coddy logo textTech

Recap - Secure Vault

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

challenge icon

Challenge

Easy

Let's build a Vault class that uses closure-based privacy to create a truly secure storage system! The vault will hold secret contents that can only be accessed by providing the correct password.

You'll organize your code across two files:

  • Vault.lua: Create a class where both the contents and password are stored in local variables inside the constructor—completely hidden from outside access. The constructor :new(contents, password) should store these values in local variables, then define a method directly on the object instance:
    • :open(attemptedPassword) — checks if the attempted password matches the stored password. If correct, returns the secret contents. If incorrect, returns "Access Denied".
  • main.lua: Require your Vault module and read three inputs: the secret contents to store, the password to set, and a password attempt. Create a vault with the contents and password, then try to open it with the attempted password and print the result. Also demonstrate that the contents are truly private by attempting to access vault.contents directly and printing what you get.

You will receive three inputs:

  1. The secret contents to store in the vault
  2. The password to protect the vault
  3. A password attempt to try opening the vault

Your output should be two lines:

Result: {resultFromOpen}
Direct access: {whatYouGetFromVaultContents}

For example, if the inputs are Gold Coins, secret123, and secret123, the output should be:

Result: Gold Coins
Direct access: nil

If the inputs are Diamond, mypass, and wrongpass, the output should be:

Result: Access Denied
Direct access: nil

The key insight here is that both contents and password exist only as local variables inside the constructor. The :open() method can access them through closure, but nothing else can—not even vault.contents, vault._contents, or vault.password. This is true encapsulation!

Try it yourself

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

-- Read inputs
local contents = io.read()
local password = io.read()
local attemptedPassword = io.read()

-- TODO: Create a vault with the contents and password

-- TODO: Try to open the vault with the attempted password

-- TODO: Print the result in the format: "Result: {resultFromOpen}"

-- TODO: Try to access vault.contents directly and print what you get
-- Print in the format: "Direct access: {whatYouGetFromVaultContents}"

All lessons in Object Oriented Programming