Add sanity checks to vector functions

This commit is contained in:
ShadowNinja 2013-09-15 22:47:39 -04:00 committed by Perttu Ahola
parent 12504a18ec
commit e232f7311f

@ -2,25 +2,30 @@
vector = {} vector = {}
function vector.new(a, b, c) function vector.new(a, b, c)
assert(a)
if type(a) == "table" then if type(a) == "table" then
return {x=a.x, y=a.y, z=a.z} 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} return {x=a, y=b, z=c}
end end
return {x=0, y=0, z=0} return {x=0, y=0, z=0}
end end
function vector.equals(a, b) function vector.equals(a, b)
assert(a and b)
return a.x == b.x and return a.x == b.x and
a.y == b.y and a.y == b.y and
a.z == b.z a.z == b.z
end end
function vector.length(v) function vector.length(v)
assert(v)
return math.hypot(v.x, math.hypot(v.y, v.z)) return math.hypot(v.x, math.hypot(v.y, v.z))
end end
function vector.normalize(v) function vector.normalize(v)
assert(v)
local len = vector.length(v) local len = vector.length(v)
if len == 0 then if len == 0 then
return vector.new() return vector.new()
@ -30,6 +35,7 @@ function vector.normalize(v)
end end
function vector.round(v) function vector.round(v)
assert(v)
return { return {
x = math.floor(v.x + 0.5), x = math.floor(v.x + 0.5),
y = math.floor(v.y + 0.5), y = math.floor(v.y + 0.5),
@ -38,6 +44,7 @@ function vector.round(v)
end end
function vector.distance(a, b) function vector.distance(a, b)
assert(a and b)
local x = a.x - b.x local x = a.x - b.x
local y = a.y - b.y local y = a.y - b.y
local z = a.z - b.z local z = a.z - b.z
@ -45,6 +52,7 @@ function vector.distance(a, b)
end end
function vector.direction(pos1, pos2) function vector.direction(pos1, pos2)
assert(pos1 and pos2)
local x_raw = pos2.x - pos1.x local x_raw = pos2.x - pos1.x
local y_raw = pos2.y - pos1.y local y_raw = pos2.y - pos1.y
local z_raw = pos2.z - pos1.z local z_raw = pos2.z - pos1.z
@ -74,6 +82,7 @@ end
function vector.add(a, b) function vector.add(a, b)
assert(a and b)
if type(b) == "table" then if type(b) == "table" then
return {x = a.x + b.x, return {x = a.x + b.x,
y = a.y + b.y, y = a.y + b.y,
@ -86,6 +95,7 @@ function vector.add(a, b)
end end
function vector.subtract(a, b) function vector.subtract(a, b)
assert(a and b)
if type(b) == "table" then if type(b) == "table" then
return {x = a.x - b.x, return {x = a.x - b.x,
y = a.y - b.y, y = a.y - b.y,
@ -98,6 +108,7 @@ function vector.subtract(a, b)
end end
function vector.multiply(a, b) function vector.multiply(a, b)
assert(a and b)
if type(b) == "table" then if type(b) == "table" then
return {x = a.x * b.x, return {x = a.x * b.x,
y = a.y * b.y, y = a.y * b.y,
@ -110,6 +121,7 @@ function vector.multiply(a, b)
end end
function vector.divide(a, b) function vector.divide(a, b)
assert(a and b)
if type(b) == "table" then if type(b) == "table" then
return {x = a.x / b.x, return {x = a.x / b.x,
y = a.y / b.y, y = a.y / b.y,