From 18d5d64a4d7242a4a532b276f26b773b8ca7d905 Mon Sep 17 00:00:00 2001
From: Inuyasha <MattWCSTRFAN@gmail.com>
Date: Mon, 18 Apr 2016 14:50:15 -0700
Subject: [PATCH] error conditions for Lua fixed point math

---
 src/lua_mathlib.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/lua_mathlib.c b/src/lua_mathlib.c
index fd00180d5..00379b888 100644
--- a/src/lua_mathlib.c
+++ b/src/lua_mathlib.c
@@ -100,7 +100,11 @@ static int lib_fixedint(lua_State *L)
 
 static int lib_fixeddiv(lua_State *L)
 {
-	lua_pushfixed(L, FixedDiv(luaL_checkfixed(L, 1), luaL_checkfixed(L, 2)));
+	fixed_t i = luaL_checkfixed(L, 1);
+	fixed_t j = luaL_checkfixed(L, 2);
+	if (j == 0)
+		return luaL_error(L, "divide by zero");
+	lua_pushfixed(L, FixedDiv(i, j));
 	return 1;
 }
 
@@ -112,7 +116,10 @@ static int lib_fixedrem(lua_State *L)
 
 static int lib_fixedsqrt(lua_State *L)
 {
-	lua_pushfixed(L, FixedSqrt(luaL_checkfixed(L, 1)));
+	fixed_t i = luaL_checkfixed(L, 1);
+	if (i < 0)
+		return luaL_error(L, "can't take the square root of a negative number");
+	lua_pushfixed(L, FixedSqrt(i));
 	return 1;
 }