在 proc 的局部变量上使用 TCL 跟踪

using TCL trace on a local variable of a proc


假设我有这个 TCL 代码(这是一个简单的例子):

proc foo {} {
   set k {0}
   foreach a { 1 2 3 4 } {
      lappend k [ expr { [lindex $k end ] + $a } ]
   }
}

我想跟踪 proc foo 中的 k 变量,就像我跟踪它一样,无论它是全局变量还是命名空间变量。在 TCL 8.5 中我该怎么做?
谢谢

是的,即使是局部变量也可以被追踪。它不需要是 static/global 或命名空间变量。

proc trackMyVar {name element op} {
    # In case of array variable tracing, the 'element' variable will specify the array index
    # For scalar variables, it will be empty
    if {$element != ""} {
        set name ${name}($element)
    }
    upvar $name x
    if {$op eq "r"} {
        puts "Variable $name is read now. It's value : $x"
    } elseif {$op eq "w"} {
        puts "Variable $name is written now. New value : $x"
    } elseif {$op eq "u"} {
        puts "Variable $name is unset"
    } else {
        # Only remaining possible value is "a" which is for array variables 
        # For array variables, tracing will work only if they have accessed/modified with array commands
    }
}


proc foo {} {
    # Adding tracing for variable 'k'
    trace variable k rwu trackMyVar
    set k {0}
    foreach a { 1 2 3 4 } {
        lappend k [ expr { [lindex $k end ] + $a } ]
    }
    unset k; # Just added this to demonstrate 'unset' operation
}

输出

% foo
Variable k is written now. New value : 0
Variable k is read now. Its's value : 0
Variable k is written now. New value : 0 1
Variable k is read now. Its's value : 0 1
Variable k is written now. New value : 0 1 3
Variable k is read now. Its's value : 0 1 3
Variable k is written now. New value : 0 1 3 6
Variable k is read now. Its's value : 0 1 3 6
Variable k is written now. New value : 0 1 3 6 10
Variable k is unset
%

trace的命令语法如下

trace variable name ops command

这里,'ops'表示感兴趣的操作,是以下一项或多项的列表

  • 数组
  • 阅读
  • 未设置

应将其首字母指定为 arwu。您可以使用任何您感兴趣的方式进行跟踪。我用过rwu。如果您只想跟踪读取操作,请在其中单独使用 r

参考:trace