Comparing Objects (<, >)
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 29 of 70.
Beyond arithmetic and concatenation, you can also define how objects compare to each other using comparison metamethods. The __lt metamethod handles the "less than" (<code><) operator.
When Lua evaluates a < b, it looks for __lt in the metatable. This metamethod should return true or false based on your comparison logic.
local Item = {}
Item.__index = Item
function Item:new(name, price)
local obj = {name = name, price = price}
setmetatable(obj, Item)
return obj
end
function Item.__lt(a, b)
return a.price < b.price
endWith __lt defined, you can now compare items directly:
local apple = Item:new("Apple", 2)
local laptop = Item:new("Laptop", 999)
print(apple < laptop) -- Output: true
print(laptop < apple) -- Output: falseHere's the clever part: Lua automatically derives the operator from __lt. When you write a > b, Lua simply evaluates b < a instead. So defining just __lt gives you both comparison directions for free.
Challenge
EasyLet's build a Product class that can be compared using the <code>< and operators based on price. This is perfect for scenarios like sorting items in a shopping cart or finding the cheapest option in a list.
You'll organize your code across two files:
Product.lua: Define your Product class withnameandpricefields. Include a:new(name, price)constructor and implement the__ltmetamethod to compare products by their price. Remember that defining__ltautomatically gives you theoperator as well—Lua handles that for you!main.lua: Require your Product module, create product instances from the inputs, and compare them to determine which costs more or less.
You will receive four inputs:
- First product's name
- First product's price
- Second product's name
- Second product's price
In your main file, create two products with the given names and prices. Then perform three comparisons and print the result of each on a separate line:
- Is the first product less than the second? (print
trueorfalse) - Is the first product greater than the second? (print
trueorfalse) - Print the name of the cheaper product
For example, if the inputs are Apple, 2, Laptop, and 999, the output should be:
true
false
AppleThe Apple (price 2) is less than the Laptop (price 999), so the first comparison is true. The Apple is not greater than the Laptop, so the second is false. And since Apple has the lower price, it's printed as the cheaper product.
Cheat sheet
The __lt metamethod handles the "less than" (<code><) operator for custom objects.
When Lua evaluates a < b, it looks for __lt in the metatable. This metamethod should return true or false based on your comparison logic.
local Item = {}
Item.__index = Item
function Item:new(name, price)
local obj = {name = name, price = price}
setmetatable(obj, Item)
return obj
end
function Item.__lt(a, b)
return a.price < b.price
endWith __lt defined, you can compare items directly:
local apple = Item:new("Apple", 2)
local laptop = Item:new("Laptop", 999)
print(apple < laptop) -- Output: true
print(laptop < apple) -- Output: falseLua automatically derives the operator from __lt. When you write a > b, Lua evaluates b < a instead. Defining just __lt gives you both comparison directions.
Try it yourself
-- Require the Product module
local Product = require('Product')
-- Read inputs
local name1 = io.read()
local price1 = tonumber(io.read())
local name2 = io.read()
local price2 = tonumber(io.read())
-- TODO: Create two Product instances using Product:new()
-- TODO: Compare products using < operator and print true/false
-- TODO: Compare products using > operator and print true/false
-- TODO: Print the name of the cheaper product
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1The 'Self' Concept
Tables with FunctionsExplicit 'self'The Colon SyntaxDot vs ColonRecap - Moving Point4Project: Digital Bank
Project SetupDeposit Method7Polymorphism & Overriding
Overriding MethodsCalling Parent MethodsDuck TypingCommon InterfaceChecking TypeRecap - Employee Roles10Project: Shape Manager
Project SetupRectangle Class2Class Prototype Pattern
The Prototype ConceptLinking with __indexThe :new() ConstructorInitializing AttributesIndependent InstancesRecap - Car Factory5Operator Overloading in OOP
Adding ObjectsSubtracting ObjectsConcatenating ObjectsComparing Objects (<, >)Recap - Wallet Math8Encapsulation
Naming ConventionsClosures for PrivacyAccess via ClosuresRead-Only TablesValidation LogicRecap - Secure Vault11Design Patterns (Lite)
Factory FunctionsSingleton TableIterator PatternObserver (Listener)Recap - Logger Factory3Object State and Behavior
Instance VariablesGetter MethodsSetter MethodsCalculated PropertiesFormatting StringsEquality ChecksRecap - Student Grade6Inheritance Basics
The Inheritance SetupInheriting MethodsExtending the ConstructorAdding Child MethodsShared vs UniqueRecap - Shape Hierarchy