Lesson 9 of 10

Operators on your objects

Goal

Define addition, equality, comparison and string conversion

01

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.

02

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
  1. The + operator adds the coordinates
  2. The + operator doesn't change the original vector
  3. The sum is a vector, just like its operands
  4. The == operator compares the coordinates
  5. The < operator makes the shorter vector the smaller one
  6. tostring shows (x, y)
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.