core.moduleapi: Allow specifying an acceptable range for number options
authorKim Alvefur <zash@zash.se>
Tue, 05 Oct 2021 15:36:38 +0200
changeset 13207 aa6c2692a4be
parent 13206 173038306750
child 13208 c9ef35fab0b1
core.moduleapi: Allow specifying an acceptable range for number options
CHANGES
core/features.lua
core/moduleapi.lua
--- a/CHANGES	Sat Jan 16 21:04:58 2021 +0100
+++ b/CHANGES	Tue Oct 05 15:36:38 2021 +0200
@@ -41,6 +41,7 @@
 ### Module API
 
 - Config interface API can require that string values be picked from a provided set
+- Acceptable interval can be specified for number options
 
 ## Changes
 
--- a/core/features.lua	Sat Jan 16 21:04:58 2021 +0100
+++ b/core/features.lua	Tue Oct 05 15:36:38 2021 +0200
@@ -18,5 +18,6 @@
 
 		-- new moduleapi methods
 		"getopt-enum";
+		"getopt-interval";
 	};
 };
--- a/core/moduleapi.lua	Sat Jan 16 21:04:58 2021 +0100
+++ b/core/moduleapi.lua	Tue Oct 05 15:36:38 2021 +0200
@@ -232,12 +232,24 @@
 	return tostring(value);
 end
 
-function api:get_option_number(name, ...)
-	local value = self:get_option_scalar(name, ...);
+function api:get_option_number(name, default_value, min, max)
+	local value = self:get_option_scalar(name, default_value);
 	local ret = tonumber(value);
 	if value ~= nil and ret == nil then
 		self:log("error", "Config option '%s' not understood, expecting a number", name);
 	end
+	if ret == default_value then
+		-- skip interval checks for default or nil
+		return ret;
+	end
+	if min and ret < min then
+		self:log("warn", "Config option '%s' out of bounds %g < %g", name, ret, min);
+		return min;
+	end
+	if max and ret > max then
+		self:log("warn", "Config option '%s' out of bounds %g > %g", name, ret, max);
+		return max;
+	end
 	return ret;
 end