Equivalent to #define in tcl?

Is there a command in tcl equivalent to C ++ #define? I saw ways to implement “define” using the proc function overload, I just wanted to know if anyone knew a weirder way.

+3
source share
4 answers

Tcl has a mechanism that allows you to define aliases for procedures in the interpreter.

If you

proc foo {one two three} {do something with $one $two $three}

and you find that you always pass $ a and $ b as the first two arguments, you can write:

interp alias {} foo_ab {} foo $a $b

And now you can say:

foo_ab $d   ;# same as "foo $a $b $d"
foo_ab $e   ;# same as "foo $a $b $e"

Example:

proc foo {one two three} {puts [join [list $one $two $three] :]}
set a Hello
set b World
interp alias {} foo_ab {} foo $a $b
foo_ab example  ;# prints "Hello:World:example"

The empty braces in the command interp aliassimply mean the current interpreter. You can do a lot of fun with the help of subordinate translators.

+4
source

interp alias a b :

interp alias {} foo_ab {} foo $a $b

, :

proc foo_ab args {
    global a b
    uplevel 1 [list foo $a $b {*}$args]
    # Or this in older Tcl: uplevel 1 [list foo $a $b] $args
}

8.5 apply:

interp alias {} foo_ab {} apply {args {
    global a b
    uplevel 1 [list foo $a $b {*}$args]
}}

8.6 , tailcall:

interp alias {} foo_ab {} apply {args {
    global a b
    tailcall foo $a $b {*}$args
}}

, :

interp alias {} foo_ab {} namespace inscope :: {foo $a $b}

, Tcl 8. *.

+4

proc, d, e (, ), .

proc foo {a b c {d ""} {e ""} }.....

, args, , args, .

   proc foo {a b c args } {
     foreach bar $args {
       #do whatever...
     }
   }

Brian

+2

If "takes the same arguments" means that you are repeating the same values ​​for $a, $band $cthen you need to use global variables instead of function parameters. Store the values ​​in them before calling the function, and then your function call is simplified to foo $d, etc.

+1
source

Source: https://habr.com/ru/post/1792261/


All Articles