Originally Posted by Mayron
Thank you very much for your work! That works perfectly Really appreciate your help!
|
Actually that code has errors in it. Other than the obvious, it assumes that the array you are passing in is sorted which was never a stated condition. This will fix the errors as well as that assumption:
Code:
local math_abs = math.abs
local resArray = { 7, 11, 12, 13, 15, 16 }
local resIndex = GetCurrentResolution()
local function GetClosestNumber(num, array)
local id = 1
local closest = math_abs(array[id] - num)
for index = 2, #array do
local delta = math_abs(array[index] - num)
if delta < closest or (closest == delta and array[index] > array[id]) then
closest, id = delta, index
end
end
return array[id]
end
print(GetClosestNumber(resIndex, resArray))
If the array will always be pre-sorted then this is what you want:
Code:
local function GetClosestMatch(num, array)
local id = 1
local closest = math_abs(array[id] - num)
for index = 2, #array do
local delta = math_abs(array[index] - num)
if delta < closest then
closest, id = delta, index
elseif delta == 0 or closest == delta then
id = index
break
else
break
end
end
return array[id]
end