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

What does the second parameter in table.sort() mean?

I've read through the wiki, as it shows: table.sort (table [, comp]) It states, "If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead." I have no clue what this means. Could someone possibly give me an example? I'm using this for a table of arrays order in this sort of manner:

t = {
	["5"] = {"Name",1,},
	["2"] = {"Name",1,},
	["4"] = {"Name",1,},
	["1"] = {"Name",45827,},
	["3"] = {"Name",12,},
}

I had tried sorting them as so, but it did not order the keys from 1 to 5. Instead, it went off the values inside. Could using the second parameter fix this issue, and make it go off converting the key to a number and sorting it so? If so, what would the function be for that?

1 comment

0

Essentially what sort does is it sorts your table, #'s first (0-9), and letters last (A-Z); however, I'm not sure about special characters (*,&,^,#,$). To note, you don't require a second variable for the second table: all you need do is have your table set, then have sort go through & set everything into place.

1 answer

✓ Accepted answer

The second parameter is a function that takes the values a,b and compares them. For example the standard function is a<b. Doing table.sort(tab, function(a,b) return a>b end) sorts the table greatest to least rather than least to greatest. You can do anything to a,b but you must compare them.

The problem is you are trying to sort a dictionary, and dictionaries are not in any order by definition. So unless you convert it so that the keys are numbers, you can't use table.sort here. Sorry!

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