Updated 2017-09-08 22:29:46 by Hi

Richard Suchenwirth 2005-09-08 - A colleague asked for how to step through Tcl procedures. It didn't take me long to cook up this example, which provides an interactive prompt at which you can inspect the situation in the stepped proc (reinvented from Steppin' out :):
 proc step {name {yesno 1}} {
    set mode [expr {$yesno? : "remove"}]
    trace $mode execution $name {enterstep leavestep} interact
 }

 proc interact args {
    if {[lindex $args end] eq "leavestep"} {
        puts ==>[lindex $args 2]
        return
    }
    puts -nonewline "$args --"
    while 1 {
        puts -nonewline "> "
        flush stdout
        gets stdin cmd
        if {$cmd eq "c" || $cmd eq ""} break
        catch {uplevel 1 $cmd} res
        if {[string length $res]} {puts $res}
    }
 }

#----------------------------Test case, a simple string reverter:
 proc sreverse str {
    set res ""
    for {set i [string length $str]} {$i > 0} {} {
        append res [string index $str [incr i -1]]
    }
    set res
 }
#-- Turn on stepping for [[sreverse]]:
 step sreverse

 sreverse hello

#-- Turn off stepping (you can also type this command from inside interact):
 step sreverse 0
 puts [sreverse Goodbye]

#-------------------------------------------- gives in a tclsh:

 {set res {}} enterstep -->
 ==>
 {for {set i [string length $str]} {$i > 0} {} {
        append res [string index $str [incr i -1]]
    }} enterstep -->
 {string length hello} enterstep -->
 ==>5
 {set i 5} enterstep -->
 ==>5
 {incr i -1} enterstep -->
 ==>4
 {string index hello 4} enterstep -->
 ==>o
 {append res o} enterstep -->
 ==>o
 {incr i -1} enterstep -->
 ==>3
 {string index hello 3} enterstep -->
 ==>l
 {append res l} enterstep -->
 ==>ol
 {incr i -1} enterstep -->
 ==>2
 {string index hello 2} enterstep -->
 ==>l
 {append res l} enterstep -->
 ==>oll
 {incr i -1} enterstep -->
 ==>1
 {string index hello 1} enterstep -->
 ==>e
 {append res e} enterstep -->
 ==>olle
 {incr i -1} enterstep -->
 ==>0
 {string index hello 0} enterstep -->
 ==>h
 {append res h} enterstep -->
 ==>olleh
 ==>
 {set res} enterstep -->
 ==>olleh
 eybdooG