Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

tcl - Call procedure without full name

I have written 2 packages :
First package :

# firstpackage.tcl
namespace eval mypackage::firstpackage {}
proc mypackage::firstpackage::myproc {} {
    # ...
}
package provide mypackage::firstpackage 1.0

Second package :

# secondpackage.tcl
namespace eval mypackage::secondpackage {}
proc mypackage::secondpackage::myproc {} {
    # ...
}
package provide mypackage::secondpackage 1.0

I'm calling these 2 packages at once, like this :

# mypackage.tcl
package require mypackage::firstpackage 1.0
package require mypackage::secondpackage 1.0

package provide mypackage 1.0

Now when I call mypackage 1.0 I don't want to call the full name of my procedure like this :

package require mypackage
# set myvar [mypackage::firstpackage::myproc] works...
set myvar [firstpackage::myproc]

I thought it was possible... But I have this error : invalid command name "firstpackage::myproc"
I tried to use namespace export myproc in my 2 files (firstpackage.tcl & secondpackage.tcl) or namespace export * in mypackage.tcl but without success...
Is there a way to call my procedure without full name ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two main ways.

  1. Use namespace export myproc inside the namespace eval, and then namespace import mypackage::firstpackage::myproc in the context where you wish to use it.
  2. Do namespace path mypackage::firstpackage in your using context so that commands are additionally looked up there. (By default, all namespaces only look for commands in themself and the global namespace; namespace path inserts between those two.)

It's not recommended to do either namespace import or namespace path (on the global namespace) as part of a package definition; let the consuming code do that as that's the actual code that owns the target context. Basically, the global namespace is the application's namespace and, by convention and history only, the Tcl language's namespace as well. Library code should not normally directly make changes to the global namespace (with a few exceptions such as Tk widget instances).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...