How to sort a table by index?

How sort a table by its index?

My tables are being rearranged when I play the game, regardless of the order that I put it in.
Here’s my table:

local t = {
    [10] = { -- Look at the indexes
		Name = 'Common';
		Color = Color3.fromRGB(82, 81, 93);
		SoundID = 'rbxassetid://3450794184';
	};
	[100] = {
		Name = 'Uncommon';
		Color = Color3.fromRGB(50, 150, 20);
		SoundID = 'rbxassetid://9060788686';
	};
	[250] = {
		Name = 'Rare';
		Color =	Color3.fromRGB(15, 30, 200);
		SoundID = 'rbxassetid://6089762739';
	};
	[1000] = {
		Name = 'Legendary';
		Color = Color3.fromRGB(200, 200, 15);
		SoundID = 'rbxassetid://3997124966';
	};
	[100000] = {
		Name = 'Celestial';
		Color = Color3.fromRGB(200, 15, 200);
		SoundID = 'rbxassetid://3601621507';
	};
	[1000000] = {
		Name = 'Divine';
		Color = ColorSequence.new(
			Color3.fromRGB(150, 30, 50),
			Color3.fromRGB(200, 30, 50));
		SoundID = 'rbxassetid://5105488525';
	};
	[10000000] = {
		Name = 'Transcendent';
		Color = ColorSequence.new(
			Color3.fromRGB(170, 170, 170),
			Color3.fromRGB(255, 255, 255));
		SoundID = 'rbxassetid://';
	};
}

and here is what I get when using a for loop:

for i, v in pairs(t) do
	print(i)
end
-- [[
Prints this:
	250
	10000000
	1000000
	100
	100000
	1000
	10
Definitely not sorted or in the way that I put it
]]

Any way(s) that I can fix this issue? Thanks!

Change pairs to ipairs. Dictionaries (ipairs) do not have a key order, while list (ipairs) have an order of their keys.

2 Likes

That makes the loop not execute

Do you really need to index each of your values with numbers like 10,250,10000 ? That might be the problem here, so try to see if you can instead place the key (10,100,250, etc…) inside of the element (in the table, maybe like “key=10”?) and have your tables inserted in your table t like you would for a normal array (t = {1, 2, 3, ...}).

Btw, you can use for i, v in t do, roblox lua will automatically pick the pairs or ipairs depending on what type the table is.

1 Like

Or you can use this and keep your table just how it is

--convert the table t to a normal array with index as a property of its values
local newt = {}
for i, v in pairs(t) do
	v.Index = i
	table.insert(newt, v)
end

--sort the array in ascending order by said property
table.sort(newt, function(a, b)
	return a.Index < b.Index
end)

for _, v in pairs(newt) do
	print(v.Index) --indexes should be printed in ascending order
end
1 Like

here is a very simple fix

for i = 1, #t do
	local v = t[i]
	
	print(i, v)
end

just make a for loop, and start at 1 and continue till how many indexes are in the table. the for loop does in order no matter what, and you can get v by doing t[i]

1 Like

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