Recap - Read-Only Table
Part of the Logic & Flow section of Coddy's Lua journey — lesson 23 of 54.
Challenge
EasyWrite a function makeReadOnly that takes original and returns a read-only version of the table.
Create a proxy table with a metatable that allows reading from the original table but prevents any modifications.
Logic:
- Create an empty proxy table
- Create a metatable with
__indexset to the original table (to allow reading) - Add
__newindexto the metatable that does nothing (to block modifications) - Attach the metatable to the proxy using
setmetatable() - Return the proxy table
Parameters:
original(table): The table to protect from modifications
Returns: A proxy table that provides read-only access to the original table (table)
Try it yourself
function makeReadOnly(original)
-- Write code here
end
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet4Introduction to Metatables
What is a Metatable?setmetatable & getmetatableThe __index MetamethodThe __newindex MetamethodThe __tostring MetamethodArithmetic Metamethods Part 1Arithmetic Metamethods Part 2Recap - Read-Only Table2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board