Previous
Switch Loop 
Next
File Handling in Tcl/Tk 
Tcl/Tk Tutorial - Create GUI using Tk with Tcl Language
Procedures

Procedures

In some languages they call it functions. In others they call it subroutines. Yet others call it methords. In TCL we call it Procedures. I know that there are subtle and humanly indistinguishable changes between those words - but who cares?

Syntax:
proc procedure_name arguments ?args? body

I like this syntax better...
proc procedure_name { arguments ?args? } {
body
}

The proc command creates a new Tcl procedure by any name, replacing any existing command or procedure there may have been by that name. Whenever the new command is invoked, the contents of body will be executed by the Tcl interpreter. Arguments can be specified to the procedure. It consists of a list, possibly empty, each of whose elements specifies one argument. Each argument specifier is also a list with either one or two fields. If there is only a single field in the specifier then it is the name of the argument; if there are two fields, then the first is the argument name and the second is its default value.

For this command I will give a C++ example and the TCL example...

In C++

int plus(int a, int b)
 {
 int ans=a+b;
 return ans;
 }
In TCL

proc plus {a b} {
set ans [expr $a+$b]
return $ans
}

The given arguments can be a number, a string, a list, a human being - in short, anything. I still have not understood how to give a human being as the argument - but I firmly belive that it is possible.

The defined functions can be called by using its name. The arguments are listed after the name. An example for using the above function.


#Function Plus
proc plus {a b} {
set ans [expr $a+$b]
return $ans
}

set sum [plus 1 2]
label .txt -text "Sum of 1 and 2 is $sum"
pack .txt
Previous
Switch Loop 
Next
File Handling in Tcl/Tk 
Subscribe to Feed