Is there any way I can sort a table using table.sort based on true/false values?

I am trying to sort a table where true values come first and false values go last. However, it is more complicated than I thought. Here is one method that I used.

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

	table.sort(vals, function(a, b) 
		if a ~= nil and a == true then
			return a, b
		elseif a ~= nil and a == false then
			return b, a
		end
		return a, b
	end)

--[[
the new order of the table should be:
a, c, b
--]]

the problem I have here is that it says that the table is an invalid table sort function, although by my observations this would perfectly sort the table. Also some of the values became nil which completely broke the table sort function. I have nil checks for the if statements which I omitted in this question to focus on the point of my problem.

I found my own solution haha.

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

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

This works 100%. The tables unpack in this order. a => c => b

2 Likes