variables/arrays from tcl procedure -


how pass variables/ arrays outside of procedure?

lets i've procedure 'myproc' inputparameters {a b c d e}, e.g.

myproc {a b c d e} {      ...     (calculate arrays, lists , new variables) } 

inside procedure want calculate array phin(1),phin(2),...phin(18) out of variables a-e list, e.g.

set phin(1) [list 1 2 3 4 5 6 7 8 9]; 

(lets values 1-9 had been calculated out of input variables a-e). , want calculate other parameter alpha , beta

set alpha [expr a+b]; set beta  [expr c+d]; 

anyway no want pass these new calculated variables outside of procedure. compare matlab write sg these variables outside of 'function'.

[phin,alpha,beta] = myproc{a b c d e} 

has idea how can deal in tcl?? thanks!

there several options:

  1. return list , use lassign outside
    example:

    proc myproc {a b c d e} {     set alpha [expr {$a+$b}]     set beta [expr {$c+$d}]     return [list $alpha $beta] }  lassign [myproc 1 2 3 4 5] alpha beta 

    this fine if return values, not arrays.

  2. use upvar , provide name of array/variable argument
    example:

    proc myproc {phinvar b c d e} {     upvar 1 $phinvar phin     # use phin local variable     set phin(1) [list 1 2 3 4 5 6 7 8 9] }  # usage myproc foo 1 2 3 4 5 foreach $foo(1) {      puts $i } 
  3. use combination of both
    example:

    proc myproc {phinvar b c d e} {     uplevel 1 $phinvar phin     set alpha [expr {$a+$b}]     set beta [expr {$c+$d}]     set phin(1) [list 1 2 3 4 5 6 7 8 9]     return [list $alpha $beta] }  lassign [myproc bar 1 2 3 4 5] alpha beta foreach $bar(1) {      puts $i } 

edit: donal suggested, is possible return dict:

a dict tcl list odd elements keys , elements values. can convert array dict array get , convert dict array array set. can use dict itself.
example

     proc myproc {a b c d e} {         set alpha [expr {$a+$b}]         set beta [expr {$c+$d}]         set phin(1) [list 1 2 3 4 5 6 7 8 9]         return [list [array phin] $alpha $beta]     }      lassign [myproc 1 2 3 4 5] phindict alpha beta     array set bar $phindict     foreach $bar(1) {          puts $i     }     # use [dict] command manipulate dict directly     puts [dict $phindict 1] 

for more ideas (this arrays, apply values well) see this wiki entry.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -