How do I find the closest button?

So I am making a menu select system and I need to find the closest button to the currently selected button. However, the script finds the farthest button from it. I dont know how to fix this.

	local buttons = {}
	for index,button in pairs(focusedframe:GetChildren()) do
		if button:GetAttribute("Selected") == false then
			buttons[button.Name] = button.Position
		end
	end
	local p = 0
	for name,position in pairs(buttons) do
			p = p+1
		if position.Y.Scale > lastbutton.Position.Y.Scale then
		table.remove(buttons,p)
			
		end
	end
	p = 0
	
	local closest = 0
	local closestbutton 
	for NAME,POSITION in pairs(buttons) do
		if POSITION.Y.Scale - closest >0  then
			closest = POSITION.Y.Scale
			closestbutton = NAME
		end
	end
	
print(closestbutton)	
	
end

You’re not checking if the distance is less, only if its more than 0

It checks if the distance is more than 0. Then if it is, it sets “closest” to that position

You should check if the distance is less than the previous closest button

An example of getting the closest of something

local Closest = nil
local ClosestDistance = 100 --Button has to be closer than this

for Button, Distance in pairs(Buttons) do
    if Distance < ClosestDistance then
        Closest = Button
        ClosestDistance = Distance
    end
end
return Closest