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

use*_*991 1 variables trace tcl proc


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

proc foo {} {
   set k {0}
   foreach a { 1 2 3 4 } {
      lappend k [ expr { [lindex $k end ] + $a } ]
   }
}
Run Code Online (Sandbox Code Playgroud)

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

Din*_*esh 5

是的,甚至局部变量也可以被追踪。它不需要是静态/全局或命名空间变量。

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
}
Run Code Online (Sandbox Code Playgroud)

输出

% 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
%
Run Code Online (Sandbox Code Playgroud)

的命令语法trace如下

跟踪变量名称 ops 命令

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

  • 大批
  • 未设置

应该将它们的第一个字母指定为arwu. 您可以使用任何您感兴趣的跟踪。我用过rwu。如果您只想跟踪读取操作,则r在其中单独使用。

参考:跟踪