Finding Closest Number In Table

I feel stupid for asking this but rn its like 3 in the morning and I just want to be over with this.
Basically im making something which checks a table to see which number in the table is the closest to the mouses z position. I have it working with negative values but positives are a no go and im not sure how to fix this.

Code:

local conenct4Plane = Instance.new("Part")
local mouseHoverTable = {}
for i,x in gridTable do
	local z = x.Position.Z
	table.insert(mouseHoverTable,z)
end

local closestZ = math.huge
for _,position in mouseHoverTable do
	if math.abs(mouse.Hit.Position.Z-2) < math.abs(closestZ) then
		closestZ = position
	end
end
mousePart.Position = Vector3.new(connect4Plane.Position.X-4,connect4Plane.Position.Y,closestZ)

if I missed anything sorry!

Set closetZ to 0, math.huge is infinite so nothing can be greater than it

They want to find the closest, not the highest. math.huge makes sense for them to use in this case.

1 Like

Woken up now and still cant figure it out.

Try

local connect4Plane = Instance.new("Part")
local mouseHoverTable = {}

for i, x in gridTable do
    local z = x.Position.Z
    table.insert(mouseHoverTable, z)
end

function findClosestNumber(number, table)
    local closestDifference = math.huge
    local closestNumber = nil

    for _, value in pairs(table) do
        local difference = math.abs(number - value)
        if difference <= closestDifference then
            closestDifference = difference
            closestNumber = value
        end
    end

    return closestNumber
end

local closestZ = findClosestNumber(mouse.Hit.Position.Z, mouseHoverTable)
mousePart.Position = Vector3.new(connect4Plane.Position.X - 4, connect4Plane.Position.Y, closestZ)

Loop comparison may be a bit off vs comparing the absolute differences between…

local connect4Plane=Instance.new("Part")
local mouseHoverTable={}

for i,x in gridTable do 
	local z=x.Position.Z
	table.insert(mouseHoverTable,z)
end

local closestZ=math.huge
for _,position in mouseHoverTable do
	if math.abs(mouse.Hit.Position.Z-position)<math.abs(mouse.Hit.Position.Z-closestZ)then
		closestZ=position
	end
end

mousePart.Position=Vector3.new(connect4Plane.Position.X-4,connect4Plane.Position.Y,closestZ)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.