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 --]]
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.