Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean to number in Lua

Tags:

boolean

lua

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.

like image 442
Hell Protection Avatar asked Jan 12 '18 16:01

Hell Protection


People also ask

How do I differentiate between Boolean values in Lua?

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.

How to get 1 with true and 0 with false in Lua?

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.

How tonumber function works in Lua?

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.

How to change the return value of a Boolean to 0?

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.


Video Answer


2 Answers

You can combine and and or clauses like ternary operators.

function bool_to_number(value)
  return value and 1 or 0
end
like image 143
hjpotter92 Avatar answered Oct 24 '22 01:10

hjpotter92


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)
like image 42
lhf Avatar answered Oct 24 '22 03:10

lhf