Menu
CoddyTech

Value Equality Metamethods

Lesson 41 of 48 in Coddy's Luau for Dart Developers course.

Dart custom value equality requires a compatible hashCode when used in hashed collections. Luau shared __eq behavior must be installed deliberately, and table-valued keys still use raw identity. Structural annotations do not synthesize equality, hashing or immutability.

Dart comparison

class Point {final int x,y; Point(this.x,this.y);
@override bool operator ==(Object other)=>other is Point && x==other.x && y==other.y;
@override int get hashCode=>Object.hash(x,y);}
void main() {
final a=Point(1,2), b=Point(1,2); print(a==b);
}

Luau behavior

Value equality requires a deliberate runtime design. These tasks use a shared equality metamethod and compare the relevant fields. A structural type alone does not supply equality, hashing, or immutability. Freeze and clone are separate choices with shallow behavior.

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

Expected Luau output:

true
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.luau, model.luau. The visible locked main.luau 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 Luau for Dart Developers

Practice on your own: Online Luau compiler