HyperMath provides the logical keywords and, or and not. In HyperMath, both nil and the Boolean value false represent false in a logical expression. Anything that is not false (either nil or false) is true.
> print(false==nil) // although they represent the same thing they are not equivalent
false
> print(true==false, true~=false)
false true
> print(1==0)
false
The binary keyword and (or the equivalent && operator pair) does not necessarily return the Boolean values true or false to the logical expression x and y. In some languages, the and operator returns a Boolean dependent on the two inputs. In HyperMath, it returns the first argument if its value is false or nil, and the second argument if the first argument was not false. So, if both arguments are Boolean, it returns a Boolean value. This case is similar to other languages.
> print(false and true) // false is returned because it is the first argument
false
> print(1 && 1)
1
> print(nil and true)
nil
> print(nil and false)
nil
> print(nil and "hello", false and "hello")
nil false
The above expressions return the first argument. The following expressions returns the second argument, as the first is true.
> print(true and false)
false
> print(true && true)
true
> print(1 and "hello", "hello" and "there")
hello there
> print(true && nil)
nil
The logical expressions are still evaluated correctly, but there is some interesting behavior because of the values returned.
The or binary keyword (or the equivalent || operator pair) does not necessarily return a Boolean value. If the first argument is not false, it is returned; otherwise, the second argument is returned. A Boolean is returned if both arguments are Boolean.
> print(true or false)
true
> print(1 || 0)
1
> print(true or nil)
true
> print("hello" or "there", 1 or 0)
hello 1
All of the above expressions return the first argument. All of the following expressions return the second argument, as the first is false.
> print(false or true)
true
> print(nil or true)
true
> print(nil or "hello")
hello
This can be a very useful feature. For example, setting default values in a function (here, if the argument is false or nil, the value becomes "default"):
> function foo(x) value = x or "default"; print(value, x); end
> foo() // no arguments, so x is nil
default nil
> foo(1)
1 1
> foo(true)
true true
> foo("hello")
hello hello
The keyword not (or the equivalent exclamation operator, !) inverts a logical expression value:
> print(true, false, not true, not false)
true false false true
> print(! nil) // nil represents false
true
> print(not not true) // true is not not true!
true
> print(not "foo" ) // anything not false or nil is true
false