Menu
CoddyTech

Equality and Frozen Values

Lesson 22 of 29 in Coddy's Lua for Luau Developers course.

Luau table.freeze prevents mutation of the frozen table, but Lua 5.1 has no standard freeze function. Do not confuse immutability with value equality: separate records are still distinct unless a suitable equality metamethod is installed. In Lua 5.1, both operands must share the same equality metamethod for table equality to dispatch to it. Reuse one function or a common metatable and compare every coordinate. The task asks for coordinate equality, not a security boundary against mutation. If a real port needs enforced immutability, design that behavior separately; deleting a freeze call does not preserve it.

Luau

local mt = {__eq=function(a,b) return a.x==b.x and a.y==b.y end}
local a = table.freeze(setmetatable({x=1,y=2},mt))
local b = table.freeze(setmetatable({x=1,y=2},mt))
print(a==b)

Lua 5.1

local mt = {__eq=function(a,b) return a.x==b.x and a.y==b.y end}
local a = setmetatable({x=1,y=2},mt)
local b = setmetatable({x=1,y=2},mt)
print(a==b)

Porting trap

A type alias, a frozen table and a value equality rule solve different problems. State explicitly which one the target contract actually needs.

challenge icon

Challenge

Easy

Implement point objects with Model.new(x,y) and Model.__eq. Input has x1,y1,x2,y2 as four integer lines. The app uses a == b and returns equal or different.

Edit app.lua, model.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Public API checks: Point equality must be symmetric, compare both x and y, and distinguish a change in either coordinate. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local Model=require("model")
local a,b,c=Model.new(1,2),Model.new(1,2),Model.new(1,3)
assert(a==b and b==a and a~=c and c~=a,"point equality compares both coordinates symmetrically")
local d=Model.new(2,2)
assert(a~=d,"x also participates in equality")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Luau Developers

Practice on your own: Online Lua compiler