G’day, I am trying to make a script where players’ score is ordered in a table, the problem is I keep getting this error: “invalid order function for sorting” This is a little strange to me, because it is inconsistent. Sometimes it errors and sometimes it doesn’t, why is this?
local score = (player.RaceInfo.TotalCheckpoints.Value + sectionPercentage) * player.Laps.Value
local newTable = {}
table.insert(newTable, score)
table.insert(newTable, player.Name)
table.insert(RaceTable, newTable)
table.sort(RaceTable, function(a, b)
return a[1] >= b[1]
end)
I looked around because this question interested me. This behaviour is happening because if comp(element1, element2) is false, not comp(element2, element1) should also be false. These are two elements we must consider:
First off,
local function sortFuncInvalid(one,two)
return one[1] >= two[1] -- if this is true, then one[1] > two[1] also has to be true– but if we pass equal values, it won't be true.
-- by putting this, you're saying 1 > 1 which as stated above, one cannot be greater than one, therefore this function should return false but it doesn't.
-- 1 is not greater than 1. by doing this, you're saying that one is equal to or greater than two, which is true, but by that same logic, you're saying two is smaller one 1 which is not true
end
Second,
local function sortFuncValid(one,two)
return one[1] < two[1] -- now, by using this, we are checking that one is smaller than two, which is false because 1 is not smaller than 1, so this would return true.
-- by the same logic used above, by checking that one < two, we are also checking that two >= one, which is true because 1 is equal or greater than 1
-- now, if we called the same function with the order swapped, then we use the `not` operator on it, we are checking if one >= two, which once again, is true. 1 is equal to or greater than 1
end
Consensus: 1 is never greater than 1, but 1 is always smaller than or equal to 1.
Yeah, exactly. I honestly had a hard time understanding it and it really is a difficult concept to understand but table.sort’s source code uses loops (while something do), so checking if the function is valid is essential in preventing a stack overflow.