Skip to content

Commit

Permalink
Add sanity checks to vector functions
Browse files Browse the repository at this point in the history
  • Loading branch information
ShadowNinja authored and celeron55 committed Oct 17, 2013
1 parent 12504a1 commit e232f73
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion builtin/vector.lua
Expand Up @@ -2,25 +2,30 @@
vector = {}

function vector.new(a, b, c)
assert(a)
if type(a) == "table" then
return {x=a.x, y=a.y, z=a.z}
elseif a and b and c then
else
assert(b and c)
return {x=a, y=b, z=c}
end
return {x=0, y=0, z=0}
end

function vector.equals(a, b)
assert(a and b)
return a.x == b.x and
a.y == b.y and
a.z == b.z
end

function vector.length(v)
assert(v)
return math.hypot(v.x, math.hypot(v.y, v.z))
end

function vector.normalize(v)
assert(v)
local len = vector.length(v)
if len == 0 then
return vector.new()
Expand All @@ -30,6 +35,7 @@ function vector.normalize(v)
end

function vector.round(v)
assert(v)
return {
x = math.floor(v.x + 0.5),
y = math.floor(v.y + 0.5),
Expand All @@ -38,13 +44,15 @@ function vector.round(v)
end

function vector.distance(a, b)
assert(a and b)
local x = a.x - b.x
local y = a.y - b.y
local z = a.z - b.z
return math.hypot(x, math.hypot(y, z))
end

function vector.direction(pos1, pos2)
assert(pos1 and pos2)
local x_raw = pos2.x - pos1.x
local y_raw = pos2.y - pos1.y
local z_raw = pos2.z - pos1.z
Expand Down Expand Up @@ -74,6 +82,7 @@ end


function vector.add(a, b)
assert(a and b)
if type(b) == "table" then
return {x = a.x + b.x,
y = a.y + b.y,
Expand All @@ -86,6 +95,7 @@ function vector.add(a, b)
end

function vector.subtract(a, b)
assert(a and b)
if type(b) == "table" then
return {x = a.x - b.x,
y = a.y - b.y,
Expand All @@ -98,6 +108,7 @@ function vector.subtract(a, b)
end

function vector.multiply(a, b)
assert(a and b)
if type(b) == "table" then
return {x = a.x * b.x,
y = a.y * b.y,
Expand All @@ -110,6 +121,7 @@ function vector.multiply(a, b)
end

function vector.divide(a, b)
assert(a and b)
if type(b) == "table" then
return {x = a.x / b.x,
y = a.y / b.y,
Expand Down

0 comments on commit e232f73

Please sign in to comment.