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

时间:2015-09-23 15:08:09

标签: variables tcl trace 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中做到这一点? 感谢。

2 个答案:

答案 0 :(得分:3)

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

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的命令语法如下

  

跟踪变量名称ops命令

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

  • 阵列
  • 未设置

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

参考:trace

答案 1 :(得分:1)

要跟踪变量,您需要变量存在:只有在执行proc时才存在局部变量,因此跟踪变量时,在proc完成时会丢失它。在tcl中,不可能像C:那样定义“静态”变量来模拟这通常创建一个名称空间变量。

我希望我帮助过。