VasiliNovikov
VasiliNovikov

Reputation: 10236

How to sort / compare booleans in Lua

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

Answers (2)

VasiliNovikov
VasiliNovikov

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

lhf
lhf

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

Related Questions