Vector Math Library (`vector`)

PyLua includes native 2D and 3D vector types implemented in C (src/libraries/lveclib.c) designed for physics simulation, 2D graphics positioning, cameras, and raycasting.

1. Getting Started

Import the module at the beginning of your script:

import_vector.lua
import vector

v1 = vector.Vector2(3, 4)
v2 = vector.Vector3(1, 2, 3)

print("V1 Length: " .. v1:length())  -- Output: 5.0
print(v2)                            -- Output: Vector3(1.000000, 2.000000, 3.000000)

2. Type Constructors

Constructor Signature Description
vector.Vector2([x, y]) ([num, num]) → Vector2 Initializes a 2D vector. Defaults to x = 0, y = 0 if omitted.
vector.Vector3([x, y, z]) ([num, num, num]) → Vector3 Initializes a 3D vector. Defaults to x = 0, y = 0, z = 0 if omitted.

3. Operator Overloading

Vectors implement full C metamethods for seamless mathematical arithmetic:

vector_arithmetic.lua
a = vector.Vector2(10, 20)
b = vector.Vector2(5, 10)

-- Vector Addition and Subtraction:
sum = a + b    -- Vector2(15, 30)
diff = a - b   -- Vector2(5, 10)

-- Scalar Multiplication and Division:
scaled = a * 2.5  -- Vector2(25, 50)
half = a / 2      -- Vector2(5, 10)

-- Equality checking:
if (a == b) {
    print("Vectors are equal!")
}

4. Vector Methods

Method Applies To Signature Description
v:length() Vector2, Vector3 () → number Computes the Euclidean magnitude: \(\sqrt{x^2 + y^2}\) (or with \(z^2\)).
v:dot(other) Vector2, Vector3 (Vector) → number Calculates the dot product scalar \(a_x b_x + a_y b_y (+ a_z b_z)\).
v:cross(other) Vector3 (Vector3) → Vector3 Computes the 3D cross product vector orthogonal to both vectors.

Geometric Utility: Normalization & Distance

vector_utilities.lua
-- Normalize vector into a unit direction vector:
function normalize(v) {
    len = v:length()
    if (len == 0) { return vector.Vector2(0, 0) }
    return v / len
}

-- Calculate distance between two positions:
function distance(p1, p2) {
    delta = p2 - p1
    return delta:length()
}

playerPos = vector.Vector2(100, 150)
enemyPos = vector.Vector2(130, 190)

dist = distance(playerPos, enemyPos)
print("Distance to enemy: " .. dist .. " pixels")