mirror of
https://github.com/SquidDev-CC/CC-Tweaked
synced 2025-04-21 02:03:13 +00:00
Add cc.expect.range (#790)
This commit is contained in:
parent
953b94fd08
commit
28165bfcd6
src
main/resources/data/computercraft/lua/rom/modules/main/cc
test/resources/test-rom/spec/modules/cc
@ -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,
|
||||
}
|
||||
|
@ -50,4 +50,25 @@ describe("cc.expect", function()
|
||||
:eq("bad field 'l' (expected string, table or number, got boolean)")
|
||||
end)
|
||||
end)
|
||||
|
||||
describe("range", function()
|
||||
it("works fith full args", function()
|
||||
expect(e.range(1, 1, 1)):eq(1)
|
||||
expect(e.range(2, 1, 3)):eq(2)
|
||||
|
||||
expect.error(e.range, 2, 0, 1):eq("number outside of range (expected 2 to be within 0 and 1)")
|
||||
expect.error(e.range, 0, 1, 2):eq("number outside of range (expected 0 to be within 1 and 2)")
|
||||
local NaN = 0 / 0
|
||||
expect.error(e.range, NaN, 1, 2):eq(("number outside of range (expected %s to be within 1 and 2)"):format(tostring(NaN)))
|
||||
end)
|
||||
|
||||
it("fills in min and max if they are nil", function()
|
||||
expect(e.range(1, 1)):eq(1)
|
||||
expect(e.range(2, nil, 3)):eq(2)
|
||||
expect(e.range(2)):eq(2)
|
||||
|
||||
expect.error(e.range, 2, nil, 1):eq("number outside of range (expected 2 to be within -inf and 1)")
|
||||
expect.error(e.range, 0, 1):eq("number outside of range (expected 0 to be within 1 and inf)")
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
|
Loading…
x
Reference in New Issue
Block a user