Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 8 years ago

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

Log in to vote
1
Answered by 8 years ago
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
Ad

Answer this question