1

How could i pass some variables/ arrays outside of procedure?

Lets say I've my procedure 'myproc' with inputparameters {a b c d e}, e.g.

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

Inside this procedure I want to calculate an array phiN(1),phiN(2),...phiN(18) out of the variables a-e which itself is a list, e.g.

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

(lets say the values 1-9 had been calculated out of the input variables a-e). And I want to calculate some other parameter alpha and beta

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

Anyway no I want to pass these new calculated variables outside of my procedure. Compare to matlab I simply would write sg like to get these variables outside of the 'function'.

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

Has anybody an idea how I can deal in tcl?? Thanks!

4

1 回答 1

2

有几种选择:

  1. 返回一个列表并lassign在外部
    使用 示例:

    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
    

    如果您返回值而不是数组,这很好。

  2. 使用upvar并提供数组/变量的名称作为参数
    示例:

    proc myproc {phiNVar a b c d e} {
        upvar 1 $phiNVar phiN
        # Now use phiN as local variable
        set phiN(1) [list 1 2 3 4 5 6 7 8 9]
    }
    
    # Usage
    myproc foo 1 2 3 4 5
    foreach i $foo(1) {
         puts $i
    }
    
  3. 使用两者的组合
    示例:

    proc myproc {phiNVar a 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 i $bar(1) {
         puts $i
    }
    

编辑:正如多纳尔所建议的,也可以返回一个字典:

dict 是一个 Tcl 列表,其中奇数元素是键,偶数元素是值。您可以使用 将数组转换为 dict,array get然后使用 将 dict 转换回数组array set。您也可以使用dict本身。
例子

     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 get phiN] $alpha $beta]
    }

    lassign [myproc 1 2 3 4 5] phiNDict alpha beta
    array set bar $phiNDict
    foreach i $bar(1) {
         puts $i
    }
    # Use the [dict] command to manipulate the dict directly
    puts [dict get $phiNDict 1]

有关更多想法(这是关于数组,但也适用于值),请参阅此 wiki 条目

于 2013-04-18T14:39:26.213 回答