Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

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

Asked by
Decemus 141
7 years ago

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?

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. TheeDeathCaster 2368 — 7y

1 answer

Log in to vote
0
Answered by
cabbler 1942 Moderation Voter
7 years ago
Edited 7 years ago

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!

Ad

Answer this question