ArrayName ( ArrayIndex ) |
set color(0) purple set color(1) red set color(2) red puts "$color(0) $color(1) $color(2)" // Prints: purple ... NOTES: puts $color(0) $color(1) $color(2) // Error: puts needs 1 arg ! puts {$color(0) $color(1) $color(2)} // Prints: $color(0)... |
array size ARRAY-NAME |
returns the number of elements in the array ARRAY-NAME
set color(0) purple set color(1) red set color(2) red |
(you can ofcourse use integers as array index if you so desire !).
Such an array is called an associative array
set color(myHouse) purple set color(myCar) red set color(myChair) red puts "$color(myHouse) $color(myCar) $color(myChair)" // Prints: purple red red |
|
array names ARRAY-NAME |
set color(myHouse) purple set color(myCar) red set color(myChair) red array names color Output: myCar myChair myHouse |
There are other commands that will creat lists
|
Example:
set list2 { {jan 1} {feb 2} {march 3} } |
list "item1" "item2" ... |
You can save the return list of the list command in a variable:
set myList [list "item1" "item2" ...] |
set list3 [list abc def klm xyz] |
|
A list in Tcl is a serie of items (very much like an array of dynamic size).
lindex LIST INDEX |
lindex { abc def klm xyz } 1 Returns: def |
We still need to know how many elements are in the list so that we can use a for-loop to iterate through all elements.
llength LIST |
llength { abc def klm xyz } Result: 4 |
|
Accessing all list elements with a for command:
set LIST { ...... } |
set list1 { abc def klm xyz } for {set i 0} {$i < [llength $list2]} {incr i} { puts [lindex $list1 $i] } Output: abc def klm xyz |
foreach VARIABLE_NAME LIST BODY |
|
foreach i { abc klm xyz } { puts "Hello $i" } Output: Hello abc Hello klm Hello xyz |
|
set color(myHouse) purple set color(myCar) red set color(myChair) red set LIST [array names color] ;# get list of indices used in color[] LIST = myCar myChair myHouse |
set color(myHouse) purple set color(myCar) red set color(myChair) red set LIST [array names color] llength $LIST ;# # elements |
set color(myHouse) purple set color(myCar) red set color(myChair) red set LIST [array names color] |
set color(myHouse) purple set color(myCar) red set color(myChair) red array names color Output (list): myCar myChair myHouse |
set LIST [array names color] |