typecode
LuaMetatables/vector.lua
1local Vector = {}
2Vector.__index = Vector
3
4function Vector.new(x, y, z)
5 local self = setmetatable({}, Vector)
6 self.x = x or 0
7 self.y = y or 0
8 self.z = z or 0
9 return self
10end
11
12function Vector.__add(a, b)
13 return Vector.new(a.x + b.x, a.y + b.y, a.z + b.z)
14end
15
16function Vector.__sub(a, b)
17 return Vector.new(a.x - b.x, a.y - b.y, a.z - b.z)
18end
19
20function Vector.__mul(a, b)
21 if type(a) == "number" then
22 return Vector.new(a * b.x, a * b.y, a * b.z)
23 elseif type(b) == "number" then
24 return Vector.new(a.x * b, a.y * b, a.z * b)
25 end
26 return a.x * b.x + a.y * b.y + a.z * b.z
27end
28
29function Vector:magnitude()
30 return math.sqrt(self.x^2 + self.y^2 + self.z^2)
31end
32
33function Vector:normalized()
34 local mag = self:magnitude()
35 if mag == 0 then return Vector.new() end
36 return Vector.new(self.x / mag, self.y / mag, self.z / mag)
37end
38
39function Vector:cross(other)
40 return Vector.new(
41 self.y * other.z - self.z * other.y,
42 self.z * other.x - self.x * other.z,
43 self.x * other.y - self.y * other.x
44 )
45end
46
47function Vector.__tostring(v)
48 return string.format("(%g, %g, %g)", v.x, v.y, v.z)
49end
50
51function Vector.__eq(a, b)
52 return a.x == b.x and a.y == b.y and a.z == b.z
53end
54
55function Vector.lerp(a, b, t)
56 t = math.max(0, math.min(1, t))
57 return a + (b - a) * t
58end
59
60return Vector
0WPM
100%Accuracy
00:00Time
0%
Progress