1

lets say I want:

proc set_valid {} {
    set valid 1
    puts "$printme"
}

proc valid_start {} {
    set valid 0
    set printme "ABC"
    valid_stop
    return valid
}

that valid_start will return 1, Can I use it some how without upvar? that all variables will be shared between the procs?

I just want to have the following instead,

proc valid_start {} {
    set valid 0
    set printme "ABC"
    ####
    set valid 1
    puts "$printme"
    ####
    return valid
}

Just to be able to repeat some lines of code just like "source" do to a .tcl file but to a specific code block in the same .tcl , Can I do that?

2 Answers 2

3

Every procedure has its own local variables; to refer to the local variables of a caller procedure you must use upvar (or uplevel to run a command to manipulate them in the right scope).

proc set_valid {{printme "the message"}} {
    upvar 1 valid valid
    set valid 1
    puts "$printme"
}

The global and variable commands are very similar, but are (typically) used to refer to global variables and current-namespace variables respectively instead.

With that procedure definition, you can then do:

proc valid_start {} {
    set valid 0
    set printme "ABC"
    # Stuff...

    set_valid $printme

    # I guess you want to return the variable contents, not the name?
    return $valid
}

You could also transfer the printme variable by the same mechanism (see below), but I recommend keeping the number of “magically available” variables to a minimum; it's much clearer and more maintainable if variables are sent by value, sent by explicitly-passed name, or declared at the top with global or variable (where appropriate).

proc set_valid {} {
    # Emphasising that local variable names are different to the caller's names
    upvar 1 valid abc printme def
    set abc 1
    puts "$def"
}
proc valid_start {} {
    set valid 0
    set printme "ABC"
    # Stuff...
    set_valid
    return $valid
}

If you're wanting your procedure to work like something sourced right there, use uplevel 1.

proc set_valid {} {
    uplevel 1 {
        set valid 1
        puts "$printme"
    }
}

That's how you do macro-like things. If you need to do code generation in this, the list command is extremely useful. Ask another independent question here on Stack Overflow if you want to learn more.

2

You coud try to play with the command info and eval to realize what you're trying to do. But in a software engineering view I would not recommand doing that, you're kind of beating the purpose of a function

proc proc1 {} {
    set valid 1
}

proc proc2 {} {
    set valid 0
    set code [info body proc1]
    eval $code
    puts $valid
}

proc2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.