From 9e002beed785f274839085b4a2853b5a3b030d63 Mon Sep 17 00:00:00 2001 From: Lupus590 Date: Mon, 17 May 2021 17:49:48 +0100 Subject: [PATCH] Add cc.expect.range (#790) --- .../lua/rom/modules/main/cc/expect.lua | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/main/resources/data/computercraft/lua/rom/modules/main/cc/expect.lua b/src/main/resources/data/computercraft/lua/rom/modules/main/cc/expect.lua index 6be4e135d..930e72fc6 100644 --- a/src/main/resources/data/computercraft/lua/rom/modules/main/cc/expect.lua +++ b/src/main/resources/data/computercraft/lua/rom/modules/main/cc/expect.lua @@ -88,7 +88,34 @@ local function field(tbl, index, ...) end end +local function is_nan(num) + return num ~= num +end + +--- Expect a number to be within a specific range. +-- +-- @tparam number num, The value to check. +-- @tparam number min The minimum value, if nil then `-math.huge` is used. +-- @tparam number max The maximum value, if nil then `math.huge` is used. +-- @return The given `value`. +-- @throws If the value is outside of the allowed range. +local function range(num, min, max) + expect(1, num, "number") + min = expect(2, min, "number", "nil") or -math.huge + max = expect(3, max, "number", "nil") or math.huge + if min > max then + error("min must be less than or equal to max)", 2) + end + + if is_nan(num) or num < min or num > max then + error(("number outside of range (expected %s to be within %s and %s)"):format(num, min, max), 3) + end + + return num +end + return { expect = expect, field = field, + range = range, }