Version 0 of Numbered arrays

Updated 1999-11-15 18:53:37

Richard Suchenwirth -- Tcl arrays do not preserve the order in which elements are added. You can have this behavior by assigning sortable keys that reflect the order of adding elements: Here's a quick working sketch (will lose order with the millionth element) which builds array keys of both a running ID number and an input key :

 proc array:addn {_a key value} {
   upvar $_a a
   set last [lindex [lsort [array names a]] end]
   set no [lindex [split $last ,] 0]
   if {![string length $no]} {set no 0}
   incr no
   set a([format %06.6d $no],$key) $value
 }

 array:addn foo bar testing
 testing
 array:addn foo baz testing2
 testing2
 foreach i [lsort [array names foo]] {puts $i:$foo($i)}
 000001,bar:testing                                           ~
 000002,baz:testing2

#... and here's a quick-and dirty retriever for a keyed element:

 proc array:getn {_a key} {
   upvar $_a a
   set a([array names a *,$key])
 }
 array:getn foo bar
 testing
 array:getn foo barry
 can't read "a()": no such element in array