From 53bfd04a04634da4d7efa64f3b60a6c4546ecde4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lera=20Elvo=C3=A9?= Date: Sun, 2 Feb 2025 03:57:16 +0300 Subject: [PATCH] proper vararg handling in vector3 constructor --- data/scripts/vector3.lua | 31 +++++++++++++++++++++++++------ data/scripts/vector3test.lua | 5 +++-- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/data/scripts/vector3.lua b/data/scripts/vector3.lua index b477492..0141e9c 100644 --- a/data/scripts/vector3.lua +++ b/data/scripts/vector3.lua @@ -94,17 +94,21 @@ function Vector3:__unm() end function Vector3:__call(...) - local args = ... + 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 + if type(args[1]) == "number" then + if #args == 1 then + nv.x, nv.y, nv.z = args[1], args[1], args[1] else nv.x, nv.y, nv.z = args[1], args[2], args[3] 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 return nv end @@ -115,4 +119,19 @@ end 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 \ No newline at end of file diff --git a/data/scripts/vector3test.lua b/data/scripts/vector3test.lua index 741b961..b115be4 100644 --- a/data/scripts/vector3test.lua +++ b/data/scripts/vector3test.lua @@ -1,5 +1,6 @@ local Vector3 = require "vector3" local v1 = Vector3{x = 10, y = 20, z = 30} -local v2 = Vector3(5) -print(-v2) +-- local v2 = Vector3(5) +-- print(v1:normalized()) +print(v1) \ No newline at end of file