Recap - Vector Math
Part of the Logic & Flow section of Coddy's Lua journey — lesson 54 of 54.
Challenge
EasyWrite 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
__addthat adds corresponding x and y components - Define
__tostringto return the formatVector(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 vectorsy(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
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board3Advanced Function Concepts
Returning Multiple ValuesVariadic Functions (...)Functions First-Class ValuesAnonymous FunctionsWhat is a Closure?Recap - Simple Event Handler9Coroutines for Beginners
What is a Coroutine?coroutine create & resumePausing with coroutine.yield()resume & yieldChecking Coroutine StatusRecap - Number GeneratorRecap - Vector Math