Boolean truth in Spin
Erlend
Posts: 612
in Propeller 1
It took me a while before I hunted down this one:
Apparently
I am not sure why?
Erlend
Apparently
IF CupWas== FALSE AND CupIs== TRUEcompiles but does not work, whereas
IF NOT CupWas AND CupIsworks as intended.
I am not sure why?
Erlend
Comments
Erlend
It doesn't appear to be an operator precedence issue. Still, I am a big fan of parenthesis to make sure the compiler is evaluating things the way I want. I would code your first line like this Likewise, I would code the second variant like this: It's just a few extra keystrokes and removes any ambiguity. I think this is helpful because you're treating everything as a logical operator; this gives you a bit of flexibility with what is considered true (false is always 0).
It looks like you're doing a test of a transition from off to on. Here's a trick I use with a simple state variable. If you're using this to monitor an input pin you can modify the first line and get rid of the if() section. Again, using parenthesis makes the code absolutely clear -- to me, and to the compiler.
In Spin you also have the problem of non-Long variables. If you define A as a byte, and test (if A == TRUE) it will never be true because A is a byte and if it is "true" aka all-bits-on it will evaluate to 255, while TRUE is 32-bit -1. Spin provides the sign extension operators but these are very arcane and not found anywhere else, and it's safer just to understand that non-Long variables are never true unless evaluated via spelled logic operators.
All this can be very confusing if you're new to it and even more so if you're coming from a particular environment like BASIC where the spelled operators are bitwise, Javascript where all numeric data are the same, or Lua which actually has a boolean data type. Unfortunately the only sure cure for it is to understand that boolean data are numbers in Spin, and to know how and when they are zero and -1 and what pitfalls arise when other values are evaluated.
@Erland: If cupWas and cupIs are bytes, assigning either to true results in the value 255 (max value for 8 bits), which is not equal to the long value of true (-1) used by the language. In this case your code evaluates as: This illustrates how tricky using true and false with == can be. Since the value of false is always 0 and fits into any variable, you could do this: This will work, but seems inelegant. I think code should always be elegant.
It will translate exactly what you wrote into bytecode.
Such it is that is slower and bigger than which is in turn slower and bigger than
Thanks also for the state-monitoring code.
Erlend