Boolean to number in Lua

You can also do this:

bool_to_number={ [true]=1, [false]=0 }

print(bool_to_number[value])

Or this:

debug.setmetatable(true, {__len = function (value) return value and 1 or 0 end})

print(#true)
print(#false)

You can combine and and or clauses like ternary operators.

function bool_to_number(value)
  return value and 1 or 0
end

The answer from hjpotter92 takes any value different to nil as a true value (returning 1). This instead takes the value true or false.

local value = true
print(value == true and 1 or value == false and 0)
-- we add the false check because it would drop 0 in case it was nil

If you want to use a function instead, this would be it

local value = true
local function bool_to_number(value)
 return value == true and 1 or value == false and 0
end

print(bool_to_number(value))

Tags:

Boolean

Lua