Debugging Tcl Script with commandloop

Besides using puts to debug my Tcl script, I also like this technique, which set up a break point within my script. There are times when I cannot use that technique, I use the commandloop command to create an impromptu break point.

Before we get started, let me clarify that the purpose of commandloop is not for debugging, but that is what I am using it for. Consider the following block of code:

    # Given a number x, double it
    proc double {x} {
        upvar 1 x xValue
        set xValue [expr {$xValue * 2}]
    }

Those who knows Tcl can spot the bug right away, but for argument sake, let’s pretend that the bug was well hidden and I need to set a break point to debug the procedure double. I can accomplish this goal using the commandloop command:

    package require Tclx
	
    # Given a number x, double it
    proc double {x} {
        upvar 1 x xValue
        commandloop
        set xValue [expr {$xValue * 2}]
    }

During execution, commandloop will halt the code and display the ‘%’ prompt. At this point, I can execute any Tcl command to debug the problem:

    $ tclsh db.tcl 
    %set x
    n
    %set xValue
    Error: can't read "xValue": no such variable
    %exit

    $ 

In the capture above, the script stopped just after the upvar line and displayed the ‘%’ prompt. I then issue some Tcl commands to debug and finally was able to pinpoint the problem–the upvar line should have been:

    upvar 1 $x xValue

One thing to note, unlike the aforementioned solution, commandloop has one disadvantage: upon typing exit, the script will exit right away, ignoring the rest of the script. However, in a crunch, this command provides a quick way to set break point to debug my script.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s