Reputation: 10236
How to compare / sort boolean values in Lua? Assume the "standard" ordering true
> false
.
local first = true
local second = false
first > second
stdin:1: attempt to compare two boolean values
stack traceback:
stdin:1: in main chunk
[C]: in ?
Upvotes: 1
Views: 1132
Reputation: 10236
Since both operands are booleans, you can use standard boolean techniques:
first or not second -- first >= second
first and not second -- first > second
Example:
my_table = {
{ name = "Max", strong = true },
{ name = "Ray", strong = false },
{ name = "Sam", strong = true }
}
table.sort(my_table, function(a, b)
return a.strong or not b.strong
end)
The version with >=
a or not b
is more performant for sorting because it would return true
for more boolean pairs, and would thus incur fewer "element swap" operations during sort.
Upvotes: 1
Reputation: 72312
Booleans cannot be compared for order.
But if you insist, try this:
debug.setmetatable(true,{
__lt = function (x,y) return (not x) and y end
})
print("false < false", false < false)
print("false < true", false < true)
print("true < false", true < false)
print("true < true", true < true)
Upvotes: 2