Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Going about Best way to sort a table by number with keys?[READ DESC]

**So the background view is that ** I am trying to make an UI appear when a player gets close enough to an object, something like press E to Interact with an object something like Adopt Me.

The Script I have right now


local Folder = workspace.Folder

while wait(.25) do
	local Table = {}

	for i,v in pairs(Folder:GetChildren()) do
		if LocalPlayer:DistanceFromCharacter(v.Position) <= 25 then

		end
	end
		

The problem

Its easy getting the closest part but Im trying to get the closest part to show something different so the closest part will be different and anything else will have the same UI's so I need to distinguish the closest part from all the parts that were found in that 25 stud radius.

To visualize it think of

{

ClosestPart = "Special GUI",

AnyPartInThe25StudRadius = {
--same UI

}



}

I will make a Special GUI popup for the closest part

the rest will have the same GUI popup

Right now all I can think of is using table.sort to do this

answer me if you have any better solutions

1 comment

0

Try proximity prompts. They're a new thing introduced by roblox, you can either use the default UI or a custom made one. I recommend looking at Proximity Prompt Service and more into proximity prompts. https://developer.roblox.com/en-us/articles/proximity-prompts

1 answer

Using table.sort should allow you to use a custom callback to sort by keys instead of values, however, you don't need the second closest or third closest part, so that would be a bit excessive to use. Instead, I'd recommend that you store the closest part and the distance to that part, and if any part is closer, make that the closest part, and set the closest distance to that part's distance. Then, once you've gone through all items, go through all items in Table, and if it is the closest part, apply the special GUI, otherwise apply the normal GUI.

local Folder = workspace.Folder

while wait(.25) do
    local Table = {}

    local ClosestPart, ClosestDistance = nil, 25
    for i,v in pairs(Folder:GetChildren()) do
		local PartDis = LocalPlayer:DistanceFromCharacter(v.Position)
		
		if PartDis <= 25 then
			table.insert(Table, v)
		end
		if PartDis <= ClosestDistance then
			ClosestDistance = PartDis
			ClosestPart = v
		end
	end

	for i, v in pairs(Table) do
		if v == ClosestPart then
			-- Special GUI
		else
			-- Normal GUI
		end
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.