I was looking for a 'map' function as per Arduino 'map() for lua / AM and could find nothing obvious so put this together.
Based on -
https://www.arduino.cc/reference/en/lan ... /math/map/
This is adapted from the Arduino map() and works fine and accurately as it is not restricted to integer as per arduino. It might be worth adding this or similar as a 'helper' ?
Handles negative values just fine.
edit - I have added an optional 'constrain' parameter which effectively does a var_cap on the input value if required.
Syntax
map(value, fromLow, fromHigh, toLow, toHigh, constrain)
Parameters
value: the number to map.
fromLow: the lower bound of the value’s current range.
fromHigh: the upper bound of the value’s current range.
toLow: the lower bound of the value’s target range.
toHigh: the upper bound of the value’s target range.
constrain (optional) if true then value is constrained within fromLow to fromHigh
Returns
The mapped value.
Code: Select all
-- Lua map function similar to Arduino 'map' function but fully 'float'
-- OPTIONAL 'constrain' parameter
-- JPH - Joe Hanley 2022
-- see https://www.arduino.cc/reference/en/language/functions/math/map/ for some notes
-- afaik lua will use floats as needed so the notes above regarding accuracy are moot. Joe
-- added optional parameter 'constrain' which will limit the value of the input to the uper and lower limits with var_cap
function map ( x, in_min, in_max, out_min, out_max, constrain )
if constrain then x = var_cap(x,in_min,in_max) end
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
end
-- examples
--value = map(0,-1000,1000,0,2000) -- another negative value example
-- value = map(0.5,0,1,-0.5,1) -- example using negative values - as in convert 0 - 1 to a value from -0.5 to 1
--value = map(4,0,51,51,0) -- example to reverse a number order
-- value = map(0.5,0.162,0.748,-0.5,1)
value = map(0.7,0.178,0.743,-0.5,1,true) -- optional constrain value performs var_cap on x
print (value)
edit - add the optional 'constrain' for value to in_min in_max