Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2d array

Status
Not open for further replies.

jlynch1

Technical User
Dec 20, 2001
100
0
0
IE

How can I create a 2d array in tcl.
I want to store 2 values for every index.

eg
index 0 contains values 1 & .203

 
Sample procedures:

proc D2 {} {
set x 0
array set arr {}

while {$x < 200} {
set arr($x,&quot;2D&quot;) [list [expr $x + 1] [expr $x * $x]]
incr x
}
parray arr
treat_as2D arr
return
}

proc treat_as2D {aname} {
upvar 1 $aname name

foreach elem [array name name] {
puts &quot;$elem vals = 1: [lindex $name($elem) 0] 2: [lindex $name($elem) 1]&quot; }
return
}

And of course you can use the array indexes in very interesting ways as well.

HTH
 
To set myarray(0) with 1 & .023 :
set myarray(0) [list 1 .203]
or (if the two numbers are constant):
set myarray(0) {1 .203}

To get 1 from myarray(0):
set value [lindex $myarray(0) 0]
To get .203 from myarray(0):
set value [lindex $myarray(0) 1]

The value assigned to myarray(0) is a list.
The command 'list' creates a list.
The command 'lindex' gets the nth value inside the list.

myarray is not realy an array but an associative array.
If you prefer you can use a structured index:
set myarray(0,0) 1
set myarray(0,1) .203

set value $myarray(0,0) (-> 1)
set value $myarray(0,1) (-> .203)

If you append the values in the index order, you can also use only lists (can be more efficient):

set mylist {}
lappend mylist [list 1 .203]
set value [lindex [lindex $mylist 0] 0] (-> 1)
set value [lindex [lindex $mylist 0] 1] (-> .203)

For more information:

HTH

ulis
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top