找到最近的值

Hul*_*tin 0 lua lua-table

我正在寻找一种方法来找出哪个值最接近表中的x并返回该值.

让我们假设,一秒钟,X是x = 15,我们有4个值{12,190,1,18}的表,我如何使它在这种情况下返回第一个键和值?

For*_*vin 5

x = 15
table = {190, 1, 12, 18}

function NearestValue(table, number)
    local smallestSoFar, smallestIndex
    for i, y in ipairs(table) do
        if not smallestSoFar or (math.abs(number-y) < smallestSoFar) then
            smallestSoFar = math.abs(number-y)
            smallestIndex = i
        end
    end
    return smallestIndex, table[smallestIndex]
end

index, value = NearestValue(table,x)

print(index)
print(value)
Run Code Online (Sandbox Code Playgroud)