Tcl's variables do not have datatypes at all. All of them can hold any value.
Tcl's values have types, but the type system is largely hidden from scripts, and it is normal for people to say that everything is a string (because strings are the supertypes of all other value types in Tcl). Your code is not supposed to rely on the types of values either, as long as the value that you have can be coerced to the correct type, which is done automatically by Tcl's various operations (e.g., list operations coerce to list types, arithmetic operations coerce to numeric types). The most recent such coercion is cached in the value; this enables most operations to be actually fairly fast.
You can look up what the current opinion of the Tcl system of the type of a value is with the tcl::unsupported::representation
command, which is a debugging only operation. Be aware that the type might not always be what you expect; the system has a different concept of typing to you.
set a 10
set b { I love Tcl }
set c "Hello"
# Print the representations; these are all of LITERALS
puts [tcl::unsupported::representation $a]
puts [tcl::unsupported::representation $b]
puts [tcl::unsupported::representation $c]
# Now actually use the values in ways that do type forcing...
set a [expr {$a << 0}]
set b [lrange $b 0 end]
set c [string range [append c \u1234] 0 end-1]
# Print the representations again
puts [tcl::unsupported::representation $a]
puts [tcl::unsupported::representation $b]
puts [tcl::unsupported::representation $c]
Example output (from my machine):
value is a pure string with a refcount of 4, object pointer at 0x7fad2df273d0, string representation "10"
value is a pure string with a refcount of 4, object pointer at 0x7fad2df26e30, string representation " I love Tcl "
value is a pure string with a refcount of 4, object pointer at 0x7fad2df29860, string representation "Hello"
value is a int with a refcount of 2, object pointer at 0x7fad2df2a3a0, internal representation 0xa:0x7fad2df29a40, no string representation
value is a list with a refcount of 2, object pointer at 0x7fad2df27790, internal representation 0x7fad30826510:0x0, no string representation
value is a string with a refcount of 2, object pointer at 0x7fad2df29440, internal representation 0x7fad30826210:0x0, no string representation
The last line is particularly weird, but it's because we have converted from UTF-8 to (approximately) UTF-16.
Again, DO NOT MAKE YOUR CODE TYPE-DEPENDENT. The behaviour and format of commands in the tcl::unsupported
namespace is subject to change without prior announcement. The representation of values is subject to change without prior announcement (and is not part of the Tcl API). If you're writing C code to work with representations, you write it as:
- Is it my known representation already?
- If not, can I convert the string form to the representation I support?