Advertisement
CloneTrooper1019

Vector3

Dec 23rd, 2014
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.33 KB | None | 0 0
  1. Vector3 = {}
  2.  
  3. function Vector3.IsVector(otherVec)
  4.     local is = pcall(function ()
  5.         -- If this is legitimate, it should concatenate without a problem.
  6.         return otherVec.X .. otherVec.Y .. otherVec.Z .. otherVec.magnitude .. otherVec.unit
  7.     end)
  8.     return is
  9. end
  10.  
  11. function Vector3.new(x,y,z)
  12.     local x,y,z = tonumber(x) or 0, tonumber(y) or 0, tonumber(z) or 0
  13.     local m = math.sqrt(x^2+y^2+z^2)
  14.     local meta = {}
  15.     local function insert(k,v)
  16.         meta["__"..k] = v
  17.     end
  18.     local vec = {}
  19.     vec.X = x;
  20.     vec.Y = y;
  21.     vec.Z = z;
  22.     vec.magnitude = m;
  23.     vec.unit = (vec.magnitude == 1 and vec or Vector3.new(x/m,y/m,z/m))
  24.     --
  25.     local vecStr = function ()
  26.         return vec.X .. ", " .. vec.Y .. ", " .. vec.Z
  27.     end
  28.     insert("newindex",error)
  29.     insert("tostring",vecStr)
  30.     local operators = {add = "+"; sub = "-"; mul = "*"; div = "/"};
  31.     for key,op in pairs(operators) do
  32.         insert(key,function (_,v)
  33.             local x,y,z do
  34.                 if type(v) == "number" then
  35.                     x,y,z = v,v,v
  36.                 else
  37.                     assert(Vector3.IsVector(v),"attempt to perform arithmetic on a Vector3 using a " .. type(v))
  38.                     x,y,z = v.X,v.Y,v.Z
  39.                 end
  40.             end
  41.             local xOp = vec.X .. op .. x
  42.             local yOp = vec.Y .. op .. y
  43.             local zOp = vec.Z .. op .. z
  44.             return loadstring("return Vector3.new(" .. xOp .. "," .. yOp .. "," .. zOp .. ")")()
  45.         end)
  46.     end
  47.     setmetatable(vec,meta)
  48.     return vec
  49. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement