Names are strings. Or rather a string is a name because it is used as a name. And $
in Tcl means “read this variable right now”, unlike in some other languages where it really means “here is a variable name”.
The $blah
syntax for reading from a variable is convenient syntax that approximately stands in for doing [set blah]
(with just one argument). For simple names, they become the same bytecode, but the $…
form doesn't handle all the weird edge cases (usually with generated names) that the other one does. If a command (such as set
, lappend
, unset
or incr
) takes a variable name, it's because it is going to write to that variable and it will typically be documented to take a varName (variable name, of course) or something like that. Things that just read the value (e.g., llength
or lindex
) will take the value directly and not the name of a variable, and it is up to the caller to provide the value using whatever they want, perhaps $blah
or [call something]
.
In particular, if you have:
proc ListRangeBy {from to {by 1}} {
set result {}
for {set x $from} {$x <= $to} {incr x $by} {
lappend result $x
}
return $result
}
then you can do:
llength [ListRangeBy 3 77 8]
and
set listVar [ListRangeBy 3 77 8]
llength $listVar
and get exactly the same value out of the llength
. The llength
doesn't need to know anything special about what is going on.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…