Reputation: 3287
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?
Upvotes: 0
Views: 1947
Reputation: 55573
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:
yes
, true
or on
is true;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.
Upvotes: 3