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)
return tonumber(string.sub(one.Name, 10)) < tonumber(string.sub(two.Name, 10))
end)

print(netWorths)

1 Like