# Table.Sort example

title says it all ( just ignore this)

2 Likes

table.sort sorts everything depending on its value.
for example it can sort

``````{23,45,64,11,2}
``````

as

``````{2,11,23,45,64}
``````

this would be done by doing table.sort on the table
or you can do a callback function
by default this function is (i think, im not 100% sure)

``````function(a,b)
return a < b
end
``````

the second paramater of table.sort is the callback function
example

``````table.sort({2,43,22,11},function(a,b)
return not a < b
end
``````

this would sort it in the opposite order. because if b greater than a it will put it in front. returning true makes it so b is put in front. returning false makes it stay the same. this is basically how it works. note that some things may be incorrect

2 Likes

`<` is the default sort operator. Meaning that the following code snippets are the same.

``````local t = {5, 4, 3, 2, 1}
table.sort(t)
print(table.concat(t, " ")) --1 2 3 4 5

local t2 = {5, 4, 3, 2, 1}
table.sort(t2, function(l, r)
return l < r
end)
print(table.concat(t2, " ")) --1 2 3 4 5
``````

Simply put, `table.sort()` returns the left item (callback functionâ€™s first parameter) if the conditional expression evaluates to true or the right item (callback functionâ€™s second parameter) if the conditional expression evaluates to false.

If one were to want to sort values in a descending order (largest to smallest) they would need to use the `>` operator instead.

1 Like

local netWorths = {
[0] = â€śBroke stragglerâ€ť,
[60] = â€śAbove average networthâ€ť,
[10] = â€śPoor networthâ€ť,
[20] = â€śDecent networthâ€ť,
[30] = â€śAverage networthâ€ť,
[120] = â€śGood networthâ€ť,
[500] = â€śGoated networthâ€ť,
[200] = â€śHigh networthâ€ť,
[1000] = â€ś??? networthâ€ť
}

table.sort(netWorths, function(one,two)