Unsupported Sensors? Try Arduino + Lua!

In a separate/private conversation, I was asked whether Lua provides a built-in map() function like the one provided by the Arduino libraries. I thought the answer might be of use to some of you:

To my knowledge, there is no map() function provided natively in Lua.

Here is the Arduino map() function from WMath.cpp:

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

In Lua, it looks like this:

local function map(x, in_min, in_max, out_min, out_max)
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
end

But the Arduino function does integer math, so if you want (nearly) identical output:

local function map(x, in_min, in_max, out_min, out_max)
    return math.floor((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
end
2 Likes