Lesson 9 of 10
Operators on your objects
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Define addition, equality, comparison and string conversion
Explanation
The metatable isn't limited to __index. You can also use it to define what operators mean for your objects: __add for addition a + b, __eq for the comparison ==, __lt for < and with it >, since Lua reads a > b as b < a, and __tostring for what print and tostring show.
This lets you write pos + velocity just as you would in math, instead of adding up x and y yourself everywhere. If you don't define __eq, == asks "are these the same table?", so two vectors with the same coordinates aren't equal. If you don't define __tostring, print shows something like table: 0x10fb78. Note that .. doesn't use __tostring, so write "Position " .. tostring(pos).
The classic mistake in __add is changing a and then returning it. The addition looks right, but local nextPos = pos + velocity moves pos itself without you noticing. So always return a new vector with Vector2.new.
Your task
Add four functions to Vector2: __add, which returns a new vector, __eq, which compares x and y, __lt, which makes the shorter vector the smaller one, and __tostring, which returns a string like (3, -1).
Checks
6 checks- The + operator adds the coordinates
- The + operator doesn't change the original vector
- The sum is a vector, just like its operands
- The == operator compares the coordinates
- The < operator makes the shorter vector the smaller one
- tostring shows (x, y)