TCL获取我所在的proc名称

Nar*_*rek 12 tcl proc

如何知道我所处的过程的名称是什么.我的意思是我需要这个:

proc nameOfTheProc {} {

    #a lot of code here
    puts "ERROR: You are using 'nameOfTheProc' proc wrongly"
}
Run Code Online (Sandbox Code Playgroud)

所以我想获得"nameOfTheProc"但不是硬代码.因此,当有人更改proc名称时,它仍然可以正常工作.

bmk*_*bmk 13

您可以info level针对您的问题使用该命令:

proc nameOfTheProc {} {

    #a lot of code here
    puts "ERROR: You are using '[lindex [info level 0] 0]' proc wrongly"
    puts "INFO:  You specified the arguments: '[lrange [info level [info level]] 1 end]'"
}
Run Code Online (Sandbox Code Playgroud)

使用内部,info level您将获得当前所在的过程调用深度级别.外部将返回过程本身的名称.

  • `[info level [info level]]`可以写成`[info level 0]`... (3认同)

kos*_*tix 6

实现你的问题隐含的正确的惯用方法是使用return -code error $message这样的:

proc nameOfTheProc {} {
    #a lot of code here
    return -code error "Wrong sequence of blorbs passed"
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您的过程将完全按照Tcl命令执行的方式执行,因为它们对所调用的内容不满意:它会在调用站点导致错误.


Jac*_*son 5

如果运行Tcl 8.5或更高版本,info frame命令将返回一个dict而不是一个列表.所以修改代码如下:

proc nameOfTheProc {} {
   puts "This is [dict get [info frame [info frame]] proc]"
}
Run Code Online (Sandbox Code Playgroud)