Boolean (logical) operators

From Liberty BASIC Family
Jump to navigation Jump to search
Supported in Just BASIC Supported in Liberty BASIC Supported in Liberty BASIC 5 Not supported in Run BASIC

Description

Boolean (logical) expressions must produce a result that is either True (nonzero) or False (0). Logical refers to ways of combining two or more values to produce a True or False result.
The JB logical operators list:
AND, OR, XOR and the NOT() function.

Syntax

boolean_expression operator boolean_expression
Result is a boolean expression.

Hints

Usually logical operators are used to combine conditions in conditional statements or loops.
A boolean_expression is usually used by Relational operators. With that, you are safe, because they return strictly 0 or 1. But if you use numbers instead of boolean_expression, you may get unexpected results due to the fact that these operators actually are Boolean (bitwise) operators. For example, 2 is not 0 and 1 is not 0, both seem to be TRUE, but 1 AND 2 produces 0 (FALSE).
The function NOT returns TRUE as -1 for FALSE (0). If you use XOR, with one operand negated and second relational operator, then TRUE XOR TRUE will not return FALSE as it should (again, because of the Boolean (bitwise) operators)
It looks like operator precedence not implemented - use parentheses instead.
Here is how logical operators are defined ("truth tables"):
X NOT(X)
TRUE FALSE
FALSE TRUE
X Y X AND Y X OR Y X XOR Y
FALSE FALSE FALSE FALSE FALSE
FALSE TRUE FALSE TRUE TRUE
TRUE FALSE FALSE TRUE TRUE
TRUE TRUE TRUE TRUE FALSE

Example

Print the truth table

print "i", "NOT(i)"
for i = not(0) to 0
    print i, not(i)
next
print
print "i", "j", "i AND j", "i OR j", "i XOR j"
for i = not(1) to 1
    for j = not(1) to 1
        print i, j, i AND j, i OR j, i XOR j
    next
next
end

Using NOT:

'EOF means End Of File. So this piece reads file #1 , while end of file NOT reached.
while not(eof(#1))
    INPUT #1, txt$
    print "INPUT item is: ";txt$
wend

Using AND, OR, XOR:

'to check if both conditions hold, you use AND
if abs(x-x0)<10 and abs(y-y0)<10 then
    'if we got close enough to x0, y0 by x and y coordinates, count a hit
    goto [hit]
end if

'to check if at least one of conditions hold, you use OR
if x<0 or x>400 then
    'if we got out of game field, change the velocity sign to go back
    dx=-1*dx
end if

'to check if exactly ONE of two conditions hold, you use XOR
    'now if someone has an example with some meaning, please post

Useful Procedures

'usage sample:
'print x, "is between 2 and 8", between(x, 2, 8)
'between inclusive
function between(x, min, max)
    between = (x>=min) and (x<=max)
end function