Value Equality Metamethods
Lesson 41 of 48 in Coddy's Lua for PHP Developers course.
PHP object equality with == compares the properties of objects of the same class, whereas === checks whether they are the same instance. Plain Lua tables compare identity. Install an __eq function to compare selected fields as a value object. In Lua 5.1 both operands must have the same equality metamethod function for that comparison to use it; sharing one metatable achieves this. Keep equality symmetric, include every field that defines the value, and avoid mutation during comparison.
PHP
<?php
class Point {
public int $x;
public int $y;
public function __construct(int $x, int $y) { $this->x = $x; $this->y = $y; }
}
$a = new Point(1, 2);
$b = new Point(1, 2);
echo ($a == $b ? "equal" : "different"), ":", ($a === $b ? "same" : "distinct"), "\n";Lua
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)Porting trap
An equality metamethod does not make equal tables interchangeable as map keys. Lua table-valued keys still use raw identity. PHP arrays cannot directly use arbitrary objects as keys either; choose a stable scalar key when value-based lookup is needed.
Challenge
EasyImplement 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for PHP Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
PHP Lists to Dense TablesAssociative Arrays and pairsSets and MembershipAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Readable ObjectsComposition and DelegationPrototype Lookup ChainsPolymorphism by ProtocolValue Equality MetamethodsRecap: Dispatch ReportsPractice on your own: Online Lua compiler