Version 3 of proc alias

Updated 2013-09-20 20:21:07 by pooryorick

How to make an alias for a proc

See Also

interp alias

Description

The common idiom for making an alias for a procedure is interp alias, but the byte-compiled versions of commands (not user procedures, but built-in commands) will not be used in that case. Here is an implementation of an idea suggested by MS for making aliases without, missing out on that byte-compiled command goodness:

proc alias {name target} {
    set fullname [uplevel [list namespace which $name]]
    if {$fullname eq {}} {
        return -code error "no such command: $name"
    }
    namespace eval [namespace qualifiers $fullname] \
    [list namespace export [namespace tail $name]]
    set newcmd [namespace eval [info cmdcount] {
        variable target [uplevel set target]
        namespace import [uplevel set fullname]
        rename [uplevel set name] $target
        namespace export $target
        namespace which $target
    }]
    uplevel [list namespace import $newcmd]
    uplevel [list trace add command $target delete [list apply [list {stash args} {
        namespace delete [namespace qualifiers $stash]
    }] $newcmd]]
}

Example:

alias set pset
pset answer 42
puts $answer
rename ::pset {}