Welcome, guest | Sign In | My Account | Store | Cart

How to obtain the name of a procedure from within it.

Tcl, 5 lines
1
2
3
4
5
proc myProc {args} {
    set procName [lindex [info level 0] 0]
    puts "You called \"$procName\""
    puts "The full call was \"[info level 0]\""
}

[info level n] returns information about a specific level in the callstack of procedures, namely the name of the command in that level and its arguments. This information is in a list and the name of the command is the first element. Level 0 refers to the currently executing procedure.

2 comments

Richard Suchenwirth 22 years, 7 months ago  # | flag

Some fixes. The proc as shown would constantly return "myProc", as it is asked for its name. Also, "puts" should be left to the caller. I propose to rewrite it as

proc myName {} {lindex [info level 1] 0}

A practical application is in an overloaded widget procedure.

David Snyderman 22 years ago  # | flag

Is this more useful? Would the following name return proc be of more use?

proc myname {} {

    set level [expr [info leve] - 1]

    return [lindex [info level $level] 0]

}



Perhaps accompanied by:



proc calledby {} {

    set level [expr [info leve] - 2]

    if { $level > 0 } {

        return [lindex [info level $level ] 0]

    } else {

        if { [string length [info script] ] > 0 } {

            return [info script]

        } else {

            return [info nameofexecutable]

        }

    }

}
Created by Jeff Hobbs on Thu, 21 Jun 2001 (MIT)
Tcl recipes (162)
Jeff Hobbs's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks