Rounding values to the nearest one in a table

local function RoundToNearestTableValue(Table, Number)
	table.sort(Table)
	local ClosestValue, ClosestDifference = nil, math.huge
	for Index, Value in ipairs(Table) do
		local Difference = math.abs(Number - Value)
		if Difference > ClosestDifference then continue end
		ClosestDifference = Difference
		ClosestValue = Value
	end
	return ClosestValue
end

local Result = RoundToNearestTableValue({1, 5, 9}, 6)
print(Result) --5

This can be cut down even further.

local function RoundToNearestTableValue(Table, Number)
	table.sort(Table, function(Left, Right) return math.abs(Number - Left) < math.abs(Number - Right) end)
	return Table[1]
end

local Result = RoundToNearestTableValue({1, 5, 9}, math.pi)
print(Result) --5
3 Likes