Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

1 comment

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 .

1 answer

✓ Accepted answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.