将数组传递给 tcl 中的函数。只有upvar吗?

发布于 2024-09-15 02:15:25 字数 87 浏览 0 评论 0原文

据我了解,在 tcl 中,如果要将命名数组传递给函数,则必须通过被调用者体内的 upvar 命令访问调用者的上层作用域。这是在 tcl 中传递数组的唯一方法吗?

As far as I understand, in tcl if you want to pass a named array to a function, you have to access the upper scope of the caller via the upvar command within the callee body. Is this the only way to pass an array in tcl ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

下雨或天晴 2024-09-22 02:15:25

正如迈克尔指出的,有多种方法,还有一个讨论它的维基页面。只是为了在这里获得一些信息,一些选项是:

By Upvar

proc by_upvar {&arrName} {
    upvar 1 ${&arrName} arr
    puts arr(mykey)
    set arr(myotherkey) 2
}
set myarr(mykey) 1
by_upvar myarr
info exists myarr(myotherkey) => true
  • 导致调用者看到的数组更改

By array get/set

proc by_getset {agv} {
    array set arr $agv
    puts arr(mykey)
    set arr(myotherkey) 2
    return [array get arr]
}
set myarr(mykey) 1
array set mynewarr [by_upvar myarr]
info exists myarr(myotherkey) => false
info exists mynewarr(myotherkey) => true
  • 导致调用者看到的数组更改调用者看到的数组
  • 类似的机制可用于返回数组

As Michael indicated, there are several ways, plus a wiki page that discusses it. Just to have some of that information here, some options are:

By Upvar

proc by_upvar {&arrName} {
    upvar 1 ${&arrName} arr
    puts arr(mykey)
    set arr(myotherkey) 2
}
set myarr(mykey) 1
by_upvar myarr
info exists myarr(myotherkey) => true
  • results in changes to the array being seen by the caller

By array get/set

proc by_getset {agv} {
    array set arr $agv
    puts arr(mykey)
    set arr(myotherkey) 2
    return [array get arr]
}
set myarr(mykey) 1
array set mynewarr [by_upvar myarr]
info exists myarr(myotherkey) => false
info exists mynewarr(myotherkey) => true
  • results in changes to the array being seen by the caller
  • similar mechanism can be used to return an array
丢了幸福的猪 2024-09-22 02:15:25

还有其他方法,比如先将其转换为列表(通过array get数组集)。

There are other ways, like converting it into a list first (via array get and array set).

香橙ぽ 2024-09-22 02:15:25

如果您只传入数组的,则可以传入字典(提示:array get 将数组序列化为字典值)并使用 dict 命令访问其中的值。但如果您想访问实时值,upvar 绝对是最简单的。这也是一种非常快的技术;在 upvar 本身完成后,它会在变量访问期间编译为指针的额外遍历。

If you're only passing in the value of the array, you could pass in a dictionary instead (hint: array get serializes an array into a dictionary value) and use the dict command to access values in it. But if you want access to the live value, upvar is definitely easiest. It's also a very fast technique; it compiles down to an extra traversal of a pointer during variable access after upvar itself finishes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文