add a barebones vector3 class

This commit is contained in:
Lera Elvoé 2025-02-02 03:28:32 +03:00
parent fe80231336
commit a84a9e98bb
Signed by: yagich
SSH Key Fingerprint: SHA256:6xjGb6uA7lAVcULa7byPEN//rQ0wPoG+UzYVMfZnbvc
2 changed files with 121 additions and 0 deletions

116
data/scripts/vector3.lua Normal file
View File

@ -0,0 +1,116 @@
local Vector3 = {
x = 0,
y = 0,
z = 0,
_CLASS_ = "Vector3"
}
setmetatable(Vector3, Vector3)
local function is_weak_vector3(t)
if type(t) ~= "table" then return false end
local haskeys = t.x ~= nil and t.y ~= nil and t.z ~= nil
if not haskeys then
return type(t[1]) == "number" and type(t[2]) == "number" and type(t[3]) == "number"
else
return type(t.x) == "number" and type(t.y) == "number" and type(t.z) == "number"
end
end
function Vector3:__mul(b)
if type(b) == "number" then
return Vector3{
x = self.x * b,
y = self.y * b,
z = self.z * b,
}
elseif type(b) == "table" and is_weak_vector3(b) then
local other = Vector3(b)
return Vector3{
self.x * other.x,
self.y * other.y,
self.z * other.z,
}
end
error("Vector3: other must be either a number or a Vector3-like table.")
return Vector3()
end
function Vector3:__div(b)
if type(b) == "number" then
return Vector3{
x = self.x / b,
y = self.y / b,
z = self.z / b,
}
elseif type(b) == "table" and is_weak_vector3(b) then
local other = Vector3(b)
return Vector3{
self.x / other.x,
self.y / other.y,
self.z / other.z,
}
end
error("Vector3: other must be either a number or a Vector3-like table.")
return Vector3()
end
function Vector3:__add(b)
if not is_weak_vector3(b) then
error("Vector3: other must be a Vector3-like table.")
return self
end
local other = Vector3(b)
return Vector3{
self.x + other.x,
self.y + other.y,
self.z + other.z,
}
end
function Vector3:__sub(b)
if not is_weak_vector3(b) then
error("Vector3: other must be a Vector3-like table.")
return self
end
local other = Vector3(b)
return Vector3{
self.x - other.x,
self.y - other.y,
self.z - other.z,
}
end
function Vector3:__unm()
return Vector3{
-self.x,
-self.y,
-self.z,
}
end
function Vector3:__call(...)
local args = ...
local nv = {x = 0, y = 0, z = 0}
setmetatable(nv, Vector3)
if type(args) == "number" then
nv.x, nv.y, nv.z = args, args, args
elseif type(args) == "table" then
if args.x ~= nil then
nv.x, nv.y, nv.z = args.x, args.y, args.z
else
nv.x, nv.y, nv.z = args[1], args[2], args[3]
end
end
return nv
end
function Vector3:__tostring()
return "Vector3(" .. tostring(self.x) .. ", " .. tostring(self.y) .. ", " .. tostring(self.z) .. ")"
end
return Vector3

View File

@ -0,0 +1,5 @@
local Vector3 = require "vector3"
local v1 = Vector3{x = 10, y = 20, z = 30}
local v2 = Vector3(5)
print(-v2)