Menu
Coddy logo textTech

Recap - Vector Math

Part of the Logic & Flow section of Coddy's Lua journey — lesson 54 of 54.

challenge icon

Challenge

Easy

Write a function createVector that takes x and y coordinates and returns a string demonstrating vector operations.

Create a vector constructor that builds a table with x and y fields, then attaches a metatable implementing __add for vector addition and __tostring for custom string representation. The function should create two vectors using the provided coordinates, add them together, and return the string representation of the result.

Logic:

  • Create a constructor function that builds a vector table with x and y fields
  • Define a metatable with __add that adds corresponding x and y components
  • Define __tostring to return the format Vector(x, y)
  • Attach the metatable to the vector using setmetatable()
  • Create the first vector with coordinates (x, y)
  • Create the second vector with coordinates (x, y)
  • Add the two vectors together using the + operator
  • Return the string representation of the resulting vector using tostring()

Parameters:

  • x (number): The x coordinate for both vectors
  • y (number): The y coordinate for both vectors

Returns: The string representation of the sum of two vectors (string). Format: Vector(6, 8) for input (3, 4)

Try it yourself

function createVector(x, y)
    -- Write code here
end

All lessons in Logic & Flow