vasili111
vasili111

Reputation: 6930

TCL. How to check if procedure exists?

I need to check if procedure func1 exists and result (if exists 1 if not 0) put in variable proc_ststus_var . How can I do it?

Upvotes: 2

Views: 8923

Answers (3)

Andrew Stein
Andrew Stein

Reputation: 13140

info procs ?pattern? will give you the basic building block for what you want:

% proc foo {} {}
% info procs foo
foo
% info procs bar
% 

Something like:

% proc procExists p {
   return uplevel 1 [expr {[llength [info procs $p]] > 0}]
}
% procExists foo
1
% procExists bar
0

Upvotes: 10

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

Note that if you check if a procedure with certain meta characters (*, ?) exists, info commands might return the wrong result.

So to check if a procedure exists, use either namespace which or check the result of info commands:

if {[llength [namespace which $cmdname]]} {
    ...
}
if {$cmdname in [info commands $cmdname]} {
    ...
}

Tcl's unknown uses the namespace which approach.

Upvotes: 8

Leo
Leo

Reputation: 6570

you can try something like

set commandExists [ info commands "mycommandname" ];

Upvotes: 4

Related Questions