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

How would I make a script which checks if a number is close or further away from another number?

I have 15 values in an array and I want to be able to check them all and get the ones closest to the number 30 and have the top 5 in another table. How would I go about doing that?

1 answer

local Array = {
	5,
	20,
	56,
	-200,
	20 --etc.
}

local Nearest = nil
local NearestIndex = nil --Index in the table

for Index,Num in pairs(Array) do --Loops through array
	local Diff = math.abs(Num-30) --Gets the difference between the number, and 30
	if (not Nearest) then --If this is the first value, then set it anyway
		Nearest = Diff
		NearestIndex = Index
	elseif (Diff < Nearest) then --If the difference is smaller than the current smallest value
		Nearest = Diff
		NearestIndex = Index
	end
end

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