TCL 中的类 C 数组

C-Like Array in TCL

我正在将程序从 C 移植到 TCL,我正在尝试在 C 中实现类似于数组的数据结构。我需要它做的两件主要事情是

我会在运行时间之前就知道数组的大小,并且这个大小在整个程序中应该是不变的(所以是静态的)。是否有符合此要求的数据结构?

如果重要的话,我正在使用 TCL 8.6

编辑:我还需要能够从函数中 return 数据结构。

tcl array (some examples) or the tcl dict 命令都可以满足您的需要。

对应的数据结构为list。它满足您的所有要求。如果您希望它具有固定大小,您可以 "pre-allocate" 像这样:

set data [lrepeat 8 {}]

创建八个空隔间。

它是有序的,您可以通过索引(从 0 开始)访问每个元素,并且可以将其值传递给 procedures/functions 和 return。您可以使用例如遍历它foreachfor,还有很多列表操作命令。


虽然 list 是最接近 C 数组的 Tcl 数据容器,但可以使用 arraydict 来模拟固定大小、直接访问、有序的容器。

# allocation
set listdata [lrepeat 8 {}]
array set arraydata {0 {} 1 {} 2 {} 3 {} 4 {} 5 {} 6 {} 7 {}}
set dictdata [dict create 0 {} 1 {} 2 {} 3 {} 4 {} 5 {} 6 {} 7 {}]
# or
set dictdata {0 {} 1 {} 2 {} 3 {} 4 {} 5 {} 6 {} 7 {}}

# access (write, then read)
lset listdata 5 96
lindex $listdata 5 ;# -> 96
set arraydata(5) 96
set arraydata(5) ;# -> 96
dict set dictdata 5 96
dict get $dictdata 5 ;# -> 96

# return from procedure
# (not possible with arraydata, arrays are shared using either
# scope manipulation or namespaces)
return $listdata
return $dictdata

# traversal
for {set i 0} {$i < 8} {incr i} {puts [lindex $listdata $i]}
# or
foreach elem $listdata {puts $elem}
for {set i 0} {$i < 8} {incr i} {puts [lindex $arraydata($i)]}
dict for {idx val} $dictdata {puts $val}

文档:array, dict, for, foreach, incr, lindex, lrepeat, lset, puts, return, set