proper vararg handling in vector3 constructor

This commit is contained in:
Lera Elvoé 2025-02-02 03:57:16 +03:00
parent 3bc5fe1d92
commit 53bfd04a04
Signed by: yagich
SSH Key Fingerprint: SHA256:6xjGb6uA7lAVcULa7byPEN//rQ0wPoG+UzYVMfZnbvc
2 changed files with 28 additions and 8 deletions

View File

@ -94,17 +94,21 @@ function Vector3:__unm()
end end
function Vector3:__call(...) function Vector3:__call(...)
local args = ... local args = {...}
local nv = {x = 0, y = 0, z = 0} local nv = {x = 0, y = 0, z = 0}
setmetatable(nv, Vector3) setmetatable(nv, Vector3)
if type(args) == "number" then if type(args[1]) == "number" then
nv.x, nv.y, nv.z = args, args, args if #args == 1 then
elseif type(args) == "table" then nv.x, nv.y, nv.z = args[1], args[1], args[1]
if args.x ~= nil then
nv.x, nv.y, nv.z = args.x, args.y, args.z
else else
nv.x, nv.y, nv.z = args[1], args[2], args[3] nv.x, nv.y, nv.z = args[1], args[2], args[3]
end end
elseif type(args[1]) == "table" then
if args[1].x ~= nil then
nv.x, nv.y, nv.z = args[1].x, args[1].y, args[1].z
else
nv.x, nv.y, nv.z = args[1][1], args[1][2], args[1][3]
end
end end
return nv return nv
end end
@ -115,4 +119,19 @@ end
Vector3.__index = Vector3 Vector3.__index = Vector3
--------API--------
function Vector3:length_squared()
local x2 = self.x * self.x
local y2 = self.y * self.y
local z2 = self.z * self.z
return x2 + y2 + z2
end
function Vector3:normalized()
local length = math.sqrt(self:length_squared())
return Vector3(self.x / length, self.y / length, self.z / length)
end
-------------------
return Vector3 return Vector3

View File

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