Updated 2016-02-15 18:06:43 by dbohdan

How to make an alias for a proc

See Also  edit

interp alias
includes this alias in its proc module

Description  edit

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. Below is an implementation of an idea suggested by MS for making aliases without, missing out on that byte-compiled command goodness.

PYK 2014-06-23: I just noticed that kruzalex had already provided a similar command on the namespace page. I've taken some inspiration from his implementation and modified the code below.
proc alias {alias target} {
    set fulltarget [uplevel [list namespace which $target]]
    if {$fulltarget eq {}} {
        return -code error [list {no such command} $target]
    set save [namespace eval [namespace qualifiers $fulltarget] {
        namespace export}]
    namespace eval [namespace qualifiers $fulltarget] {namespace export *}
    while {[namespace exists [
        set tmpns [namespace current]::[info cmdcount]]]} {}
    set code [catch {set newcmd [namespace eval $tmpns [
        string map [list @{fulltarget} [list $fulltarget]] {
        namespace import @{fulltarget}
    }]]} cres copts]
    namespace eval [namespace qualifiers $fulltarget] [
        list namespace export {*}$save]
    if {$code} {
        return -options $copts $cres
    uplevel [list rename ${tmpns}::[namespace tail $target] $alias]
    namespace delete $tmpns 
    return [uplevel [list namespace which $alias]]

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