PreviousNext

The while Loop

The while loop behaves like the while loop in C. It takes two arguments: an expression and a script (called the body). When the expression evaluates to non-zero, the while command executes the body and then reevaluates the expression, continuing the loop until the expression evaluates to 0. The syntax for a while loop is:

while expression body

The following example procedure uses a while loop to search through each element in a list for a pattern. As long as the list size contains more than zero elements ($size > 0), the procedure continues looping.

proc _dcp_list_find {search_list pattern} {

set found_items ""
set size [llength $search_list]

while { $size > 0 } {
set size [expr $size - 1]
set index [lsearch $search_list $pattern]
if { $index == -1 } {
return $found_items
}
lappend found_items [lindex $search_list $index]
set search_list [lreplace $search_list $index $index]
}
}