Question

I have a function like this:

proc test { {isSet "false"} } {
   if {isSet  == "true"} {
    # do something
   }
}

but when I call this proc, how to pass false or true:

test "false" or test false?
Was it helpful?

Solution

You're doing it wrong (ignoring the fact you're using bare word isSet in your if conditional expression which won't work). Instead do

proc test {{isSet "false"}} {
   if {$isSet} {
       # do something
   }
}

This will allow you to call your test proc however you wish:

test 0
test 1
test [expr {1 == 0}]
test yes
test false
test "no"
test {true}
test "off"

etc…

The underlying idea is that the Tcl interpreter will try to interpret the value contained in the isSet variable as a value of a boolean type; there's a set of rules for it to do that:

  • A value 0 of integer type is false.
  • A value different from 0 of integer type is true.
  • Everything else is first converted to a string and then
    • A string literally equal to one of yes, true or on is true;
    • A string literally equal to one of no, false or off is false.

The rules applied for interpreting a string as a boolean are described in the Tcl_GetBoolean() manual.

And you're making another mistake in your assumptions: Tcl does not have explicit string and boolean types (as it's typeless) so "false" and false are exactly the same things to the Tcl interpreter at the time it parses your script as double quotes and curly braces are used in Tcl for grouping, not for specifying types of literals (and Tcl does not have literals). So I would recommend to start from the tutorial to get better grip on these ideas.

The types I mentioned when I described interpreting of values as boolean are internal to Tcl values and are not user-visible — yes, internally Tcl caches "native" representation of values so when you do set x [expr {1 + 2}], internally the value assigned to x will have an integer type but this is really an implementation detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top