Is there a way to get 1 with true and 0 with false in Lua?
There is the tobool
which gives true or false with 1 or 0, but tonumber
gives a nil value with true or false.
When dealing with lua it is important to differentiate between the boolean values true and false and values that evaluate to true or false. There are only two values in lua that evaluate to false: nil and false, while everything else, including the numerical 0 evaluate to true.
Is there a way to get 1 with true and 0 with false in Lua? There is the tobool which gives true or false with 1 or 0, but tonumber gives a nil value with true or false. Show activity on this post.
Lua tonumber | How tonumber function works in Lua? The Lua tonumber is one of the basic function for the lua script and it is mainly used for to convert the arguments to the number format. The argument will be already either string or number format by using the tonumber method.
You can multiply the return Boolean values (TRUE or FALSE) by 1, and then the TRUE will change to 1, and FALSE to 0. Assuming the original formula is =B2>C2, you can change it to =(B2>C2)*1.
You can combine and
and or
clauses like ternary operators.
function bool_to_number(value)
return value and 1 or 0
end
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With