Adding Objects
Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 26 of 70.
You've already seen how metamethods like __tostring and __eq let you customize how objects behave. Now we'll extend this to arithmetic operations, starting with addition.
The __add metamethod defines what happens when you use the + operator between two objects. When Lua sees a + b, it looks for __add in the metatable of either operand.
local Vector = {}
Vector.__index = Vector
function Vector:new(x, y)
local obj = {x = x, y = y}
setmetatable(obj, Vector)
return obj
end
function Vector.__add(v1, v2)
return Vector:new(v1.x + v2.x, v1.y + v2.y)
endNotice that __add is defined with a dot, not a colon. It receives both operands as arguments and should return a new object rather than modifying either original. This keeps the operation predictable and safe.
local a = Vector:new(3, 4)
local b = Vector:new(1, 2)
local c = a + b
print(c.x, c.y) -- Output: 4 6The key insight is that __add must be in the metatable itself (here, Vector), not just in the object. Since we set Vector as the metatable for all instances, they all share this behavior automatically.
Challenge
EasyLet's build a Vector class that supports addition using the + operator. This is your first step into operator overloading—making your objects work naturally with Lua's built-in operators.
You'll organize your code across two files:
Vector.lua: Define your Vector class withxandycomponents. Include a:new(x, y)constructor and implement the__addmetamethod so that adding two vectors creates a new vector with the combined components. Remember that__adduses dot syntax (not colon) and receives both operands as arguments.main.lua: Require your Vector module, create vector instances, and demonstrate that adding them produces the correct result.
You will receive four inputs:
- First vector's x component
- First vector's y component
- Second vector's x component
- Second vector's y component
In your main file, create two vectors with the given components, add them together using the + operator, and print the resulting vector's x and y values on separate lines.
For example, if the inputs are 3, 4, 1, 2, the output should be:
4
6The first vector (3, 4) plus the second vector (1, 2) equals a new vector (4, 6).
Cheat sheet
The __add metamethod defines what happens when you use the + operator between two objects.
When Lua sees a + b, it looks for __add in the metatable of either operand.
local Vector = {}
Vector.__index = Vector
function Vector:new(x, y)
local obj = {x = x, y = y}
setmetatable(obj, Vector)
return obj
end
function Vector.__add(v1, v2)
return Vector:new(v1.x + v2.x, v1.y + v2.y)
end__add is defined with a dot, not a colon. It receives both operands as arguments and should return a new object rather than modifying either original.
local a = Vector:new(3, 4)
local b = Vector:new(1, 2)
local c = a + b
print(c.x, c.y) -- Output: 4 6__add must be in the metatable itself, not just in the object.
Try it yourself
-- Require the Vector module
local Vector = require('Vector')
-- Read input
local x1 = tonumber(io.read())
local y1 = tonumber(io.read())
local x2 = tonumber(io.read())
local y2 = tonumber(io.read())
-- TODO: Create two Vector instances using the input values
-- TODO: Add the two vectors using the + operator
-- TODO: Print the resulting vector's x and y values on separate lines
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