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

How to sort a table of bool values, with true bool values being the first priority?

Asked by 4 years ago

I have tried using table.sort to sort my table of mixed bool values in order to have the true values first in line, and then the false values last in line in the table. As so:

a = true
b = false
c = true
vals = {a, b, c}

local sorted_vals = table.sort(vals, function(a, b) if a == true then return a elseif b == true then return b end end)

print(unpack)

--[[
the new order of the table should be:
a, c, b
--]]
0
The problem I have is that this isimply does not work, and I cannot find any workaround. I have scarce knowledge of any sorting algorithms as well . laughablehaha 494 — 4y

1 answer

Log in to vote
1
Answered by
gskw 1046 Moderation Voter
4 years ago

When you give a sorting callback to table.sort, it shouldn't return the value that goes in the table. Instead, it should return a boolean value indicating whether a should be placed before b. If a and b have equal precedence, the function should return false. Also note that table.sort doesn't return a table; it sorts the table in place. Using this logic, we can fix the sorting code:

table.sort(vals, function(a, b)
    return a and not b
end)

print(unpack(vals))

I get some xy-problem vibes here, though. You might want to consider counting the true and false values in your table instead of sorting the table, if that's useful for your game.

Ad

Answer this question