Cant figure out how to get the lowest value from a table of instances

I have a tower defense game, and I cant figure out how to find the lowest value from a table that contains instances and how far along they are along the path:

{
[Instance(ID)] = distance to treasure
}

Ive tried multiple methods to find the lowest value and get the instance from it, but i couldnt get it working. Heres the script:

function PlayLandUnit(tower, map)
	local rangePart = tower.Range
	
	local foundMobs = {}

	local target		
	
	while task.wait() do
		task.spawn(function()
			
			local foundTouching = workspace:GetPartsInPart(rangePart, OverlapParams.new())
			
			for i, v in pairs(foundTouching) do
				if v:IsDescendantOf(map.mobs) then		
					foundMobs[v.Parent] = v.Parent.Distance.Value
				end
			end
			
			target = -- get the index with the lowest value from foundMobs somehow here
			
			if target then
				print(target)
			end
		end)
	end
end

If you have a numerical value for how far something is from the end, try iterating all those through a for loop. Something like this:

local lowestValue = math.huge()
local lowestInstance
for i,v in pairs(tableOfInstances) do
   if v.Distance < lowestValue then
      lowestInstance = v
   end
end

If you have an array of numbers, then you can just do this

local t -- array of numbers
local target = math.min(table.unpack(t))

I need to also get the instance associated with the number

I’m guessing this is the table with the values you need.

local t = {}
local target

for i, v in pairs(foundMobs) do
	table.insert(v)
end

local lovestVal = math.min(table.unpack(t))

for i, v in pairs(foundMobs) do
	if v == lowestVal then
		target= v
	end
end

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