Forum Discussion

dragonflymr's avatar
dragonflymr
Icon for Cirrostratus rankCirrostratus
Dec 21, 2015

table and sort order

Hi,

From my simple test it seems that keys are listed (for example in foreach loop) in the order they were created so key created first is listed as last and key created as last first (at least with for indef indef keys).

Is that so or maybe coincidence or flaw in my test routine?

I asking this in context of deleting x number of oldest keys (when keys are indef indef). Side question is if only way to do that is to iterate through all keys and start deleting when counter hits given threshold - something like that:

 

set s [table keys -subtable master -count]

set keys_to_be_del 10

set start_del [expr {$s - $keys_to_be_del}]

set i 1

foreach k [table keys -subtable master] {

    if {$i > $start_del} {

        table delete -subtable master $k
    }

    incr i
}

 

Of course above will only work correctly if my assumption is correct 🙂

Piotr

 

3 Replies

  • Hi Piotr,

     

    did a quick test and can confirm your observations. The order of the contained keys is based on the creation time.

     

    Intresting catch... :-)

     

    (+1 kudo)

     

    Cheers, Kai

     

  • Just beginners luck :-)

     

    What do you think about code - is that OK or could be improved - except reducing vars usage?

     

    Piotr

     

  • Hi Piotr,

    there is always a little danger if someone tries to use creative codings and explores undocumented stuff. So be prepared that this behavior may change with later updates...

    But to answer your question....

    I guess your code can be improved by using the [lrange] command to filter the relevant key names before passing the retrived [list] to the [foreach] loop. But I haven't tested out the performance differences...

     

    set keys_current [table keys -subtable master -count]
    set keys_to_remove 10
    
    foreach key [lrange [table keys -subtable master] [expr { $keys_current - $keys_to_remove + 1 }] $keys_current] {
        table delete -subtable master $key
    }
    

     

    Cheers, Kai