How do I make a sorted list of Derma Elements from top to bottom?

The title does need a little explanation, so here it is:

(Referring to the picture below) I have a list of DButtons that are created via a for k,v in pairs() loop off of a table of (in this case,) names and xp needed, how would I make these elements sort themselves from top to bottom based on the xp needed to achieve them?

If you’re wondering by the way, this is how I’m currently setting the position of the buttons:

local margin = 0

--[[the variable `selected` is the name of the category, in the picture above's case it would be 'kills'
    and also, iExp['categories'][<string category>]['xp'] is the localplayer's current xp in that category, 
    and iExp['categories'][<string category>]['upgrades'][<string upgrade>]['xp'] is the xp needed to achieve that upgrade; just to clear any confusion --]]
--(also i know my tables are wack, you don't need to tell me XD)
for upgradeName, upgradeTbl in pairs(iExp['categories'][selected]['upgrades']) do
    --This button variable goes off of a library I chucked together to make using derma less of a pain, here's the meaning behind the values:
    --CreateButton(bool centered, string text, string font, int radius, bool units, int x, int y, int width, int height, Color color, Color textColor, panel parent)
    --Everything should be self explanatory, maybe except units but that doesn't really matter here because it's false anyways
	local button = CreateButton(true, upgradeName, "DermaDefault", 0, false, 0, margin, main:GetWide(), 150, Color(255,255,255,10), Color(255,255,255), main)

	margin = margin + (button:GetTall() + 2)

And yes, I know that what I have there isn’t going to achieve the effect I want, but is just how i have it set up to show my point.
Because of the way for loops work, I don’t know if they’ll work for what I want to do here; but I can’t think of any other ethical solutions, it’s really throwing a spanner in the works XD

Thanks for your time by the way, and it’s entirely possible that I’m just having a mega brainfart but I’ve been at this pretty much all day and could really use some fresh ideas, so yeah, thanks :smiley:

I am not very comfortable with data sorting, but it seems to me this function could satisfy you: table.sort - Garry's Mod Wiki. It allows you to order a table with a sorting function, for example start the table with the largest number, or the smallest, etc. Obviously, this should be put before the loop.

You can’t sort a non-sequential table. I recommend you to take a look at using the SortedPairs/SortedPairsByMemberValue iterator instead of using pairs.

Thanks for the help guys!
I got it to work with SortedPairsByMemberValue (thanks again, Lukas :slight_smile:)