For loop randomly picking an index?

Hello!
I’m working on a rarity system and i need to be able to loop through a table from the lowest value to the highest, going incrementally from top to bottom.

But for some reason even when i use a sorted table it just randomly picks?

Currently i have this script:

local sStorage = game:GetService("ServerStorage")

local helpModule = {}

local baseRarities = {
	[sStorage.Part1] = 250,
	[sStorage.Part2] = 80,
	[sStorage.Part3] = 65,
	[sStorage.Part4] = 50,
	[sStorage.Part5] = 1,
}

helpModule.LoopThroughSorted = function() :SharedTable
	-- Sort the table directly
	table.sort(baseRarities, function(a, b)
		return a < b
	end)
	
	for i, v in baseRarities do
		print(i,v)
	end
end


return helpModule

Which produces this output:

  Part5 1  -  Server - Helper:16
  Part4 50 -  Server - Helper:16
  Part1 250  -  Server - Helper:16
  Part2 80  -  Server - Helper:16
  Part3 65  -  Server - Helper:16

as you can see, it still randomly picked one to print? :sad:
does anyone know why this happens? Any help is greatly appreciated!

You can’t sort dictionaries.

My guess is how you’re sorting the table itself since you’re using arbitrary keys. Take a look and attempt the following code where it sorts by value.

local sStorage = game:GetService("ServerStorage")

local helpModule = {}

local baseRarities = {
	[sStorage.Part1] = 250,
	[sStorage.Part2] = 80,
	[sStorage.Part3] = 65,
	[sStorage.Part4] = 50,
	[sStorage.Part5] = 1,
}

helpModule.LoopThroughSorted = function()
	local sortedRarities = {}
	for key, value in pairs(baseRarities) do
		table.insert(sortedRarities, {key = key, value = value})
	end
	
	table.sort(sortedRarities, function(a, b)
		return a.value < b.value
	end)
	
	for _, v in ipairs(sortedRarities) do
		print(v.key.Name, v.value)
	end
end

return helpModule

Wrote this on phone so apologies if anything’s missing!

This works! thank you so much!

1 Like

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