Arithmetic on Boolean values

Hi there.

In another programming language, I always liked using Boolean values in calculations to avoid if-statements. An example:

a = 2
b = 5 + (a==2)*5

Instead of

a = 2
if a==2 then
    b = 10
else
    b = 5
end

Unfortunately, arithmetic on Boolean values is not possible in Codea. I think I can solve this using a meta table, changing the _lt and _le (less than and less or equal then, respectively) functions. But I was wondering if any of you might know an easier way, making true equal 1 and false equal 0?

PS: Thank you @Ignatz, since your ebook taught me about meta tables.

There’s a simple way to get around this - fake them

True, False=1,0
a=True
print(5*a)

@Kjel, you can always create a small function around this, like

function setup()
    a = 2
    b = 5 + BoolToNumber(a==2)*5
    print(b)
end

function BoolToNumber(bool)
    if bool then
        return 1
    end
    return 0
end

@Ignatz How does that method work exactly? It doesn’t change the outcome (error) of (a==2)*4, since the == operator wouldn’t return my fake True.

@stevon8ter That sounds like an easy solution, odd I didn’t come up with that myself, doh! And choosing a short name for such a function, makes that it doesn’t get in the way too much.

Thank you both for your quick replies!

@Kjell yeah a shorter name would work best, I just chose this name to make it clear :wink:

My method wouldn’t do your example, you would need a function instead

There is a much easier way!

a = 2
b = 5 + (a == 2 and 1 or 0) * 5

@Jordan, very neat