0

I have TCL code:

namespace eval gen {
    proc generate { } {
        set language "C"
        namespace eval current_file_generation_info {
            variable language $language
        }
    }
}

At line variable language $language I am trying to set variable language in namespace current_file_generation_info to the value of variable language inside procedure generate. My code gives me error something like "language variable does not exists" and I understand why it does so.

So my question is, how can I set the variable language in namespace current_file_generation_info equal to variable language inside generate procedure?

2 Answers 2

1

The simplest way is to just name the target namespace in the variable call, but if you do that, you should make the namespace as a separate step (if it is possible to call the code at a point when the NS wasn't already created).

namespace eval gen {
    proc generate { } {
        # Make the namespace by running an empty script in it
        namespace eval current_file_generation_info {}
        # Initialise the variable
        variable current_file_generation_info::language "C"
    }
}

Otherwise, you could do:

namespace eval gen {
    proc generate { } {
        namespace eval current_file_generation_info \
                [list variable language "C"]
    }
}

Hint: the list command is very good at generating substitution-free scripts that call a single command.

Sign up to request clarification or add additional context in comments.

1 Comment

Which is the best way to use current_file_generation_info::language variable from other namespace?
1
namespace eval gen {
    proc generate { } {
        set language "C"
        set [namespace current]::language $language
    }
    generate
    variable language
    puts $language
}

It would be clearer to avoid using the same variable name for a local var and a namespace var

namespace eval gen {
    proc generate { } {
        variable language
        set _language "C"
        set language $_language
    }
}

or just omit the local var

namespace eval gen {
    proc generate { } {
        variable language
        set language "C"
    }
}

1 Comment

In your example the language variable is created in gen namespace in the procedure that is in gen namespace. I need to create variable language in the current_file_generation_info namespace form procedure that is in gen namespace.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.