Updated 2011-05-04 07:04:34 by oehhar

True or False. Tcl has no separate Boolean type, like in C, the integers 0 (false) and 1 (true - in fact any nonzero integer) are used.

NEM: Although expr will also accept "true" and "false" (and "yes"/"no"..) as Boolean values.

1S In fact, there's no separate Integer type in Tcl as well -- everything is a string. A proper boolean value is either a proper integer, with, like in C, zero meaning false and non-zero meaning true, or one of the following: yes, no, true, false, on, or off.

RS The canonical forms however, like expr produces them, are 1 and 0.

See Boolean Logic or Integers as Boolean Functions.

  Boolean and the comparision operators '''==''' and '''!='''

HaO 2011-05-02 Comparisions with == or != do not work with booleans not in canonical form:
% expr {true == 1}

This issue may be avoided using the bool() function to bring strings in boolean canonical form:
% expr {bool(true) == bool(1)}

This is only recommeded if two variables contain boolean data.
expr {bool($b1) == bool($b2)}

otherwise, one would use:
expr { $b1 }
expr { ! $b1 }

MG The string is command also recognises booleans:
proc trueorfalse {str} {
if { ![string is boolean -strict $str] } {
return -1; # not a boolean
return [string is true $str]
% trueorfalse foo
% trueorfalse yes
% trueorfalse off

HaO Yes, correct, another way to get a value in canonical boolean form is:
string is true -strict $b

hv Here is my little script which lists which token is true, false, or neither:
# Which token is considered true/false?
set tokens {-2 -1 0 1 2 yes no Yes No YES NO on off On Off ON OFF
true false True False TRUE FALSE Y N OK FAIL}
set trueTokens {}
set falseTokens {}
set neitherTokens {}
foreach token $tokens {
if {[string is true -strict $token]} {
lappend trueTokens $token
} else {
if {[string is false -strict $token]} {
lappend falseTokens $token
} else {
lappend neitherTokens $token
puts "True: $trueTokens"
puts "False: $falseTokens"
puts "Neither: $neitherTokens"

True: 1 yes Yes YES on On ON true True TRUE Y
False:0 no No NO off Off OFF false False FALSE N
Neither: -2 -1 2 OK FAIL

AMG: Why does [string is boolean] reject "2" when it valid to use "2" anywhere a Boolean is expected?

Also, in addition to the strings tested above by HV's code, [string is boolean] accepts all capitalizations of: t, tr, tru, f, fa, fal, fals, ye, and of. Notably, o is not accepted, since it is a common prefix shared by on and off.