From 3c9f03477a1d8d6d7612d849e0c8dd4807beeef9 Mon Sep 17 00:00:00 2001 From: sorucoder <40341154+sorucoder@users.noreply.github.com> Date: Sun, 9 Dec 2018 00:37:23 -0500 Subject: [PATCH] Added util.signum, util.clamp, and fixed util.round Added commonly used math operations. Fixed bug where util.round(-0.5) returns 0. --- sys/apis/util.lua | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/sys/apis/util.lua b/sys/apis/util.lua index 40f3cb2..7d275a7 100644 --- a/sys/apis/util.lua +++ b/sys/apis/util.lua @@ -109,10 +109,30 @@ function Util.checkMinecraftVersion(minVersion) return convert(version) >= convert(tostring(minVersion)) end +function Util.signum(num) + if num > 0 then + return 1 + elseif num < 0 then + return -1 + else + return 0 + end +end + +function Util.clamp(lo, n, hi) + if num <= lo then + return lo + elseif num >= hi then + return hi + else + return n + end +end + -- http://lua-users.org/wiki/SimpleRound function Util.round(num, idp) local mult = 10^(idp or 0) - return math.floor(num * mult + 0.5) / mult + return util.signum(num) * math.floor(math.abs(num) * mult + 0.5) / mult end function Util.random(max, min)