Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make a "map" function similar to JavaScript?

Hey there. I've been coding with JS recently, a little bit with the wonderful p5.js library. I'm wondering how I would go about converting the p5.js map function to Lua, specifically Roblox.

p5.js Description:

Re-maps a number from one range to another.

p5.js Parameters:

value: Number: the incoming value to be converted

start1: Number: lower bound of the value's current range

stop1: Number: upper bound of the value's current range

start2: Number: lower bound of the value's target range

stop2: Number: upper bound of the value's target range

withinBounds: Boolean: constrain the value to the newly mapped range

I'm just not exactly sure of the math or steps needed to get this to work in RbxLua. If someone could point me in the right direction that'd be fantastic!

PS: Here's a link to the reference page for it.

1 answer

✓ Accepted answer

I don't know how to explain the math, but here's the function:

function map(value, start1, stop1, start2, stop2, withinBounds)
	local range1 = stop1 - start1
	local range2 = stop2 - start2
	value = (value - start1) / range1 * range2 + start2
	return withinBounds and math.clamp(value, start2, stop2) or value
end

This discussion is preserved as it was. New answers, comments, and votes are closed.