开发者

Can we create a list of arrays and how?

开发者 https://www.devze.com 2023-03-20 22:30 出处:网络
I want to create a list and each element of it is an array, similarly to an array of structs in C language.

I want to create a list and each element of it is an array, similarly to an array of structs in C language.

Can it be done in TCL and how if it can? thanks very much!

I did some try but it failed...

tcl>set si(eid) -1
tcl>set si(core) 0
tcl>set si(time) 0
tcl>lappend si_list "$si"
Error: can't read "si": variable is arra开发者_如何学Pythony


You can't create a list of arrays, but you can create a list of dicts which is functionally the same thing (a mapping from keys to values):

set mylist [list [dict create a 1 b 2] [dict create a 4 b 5]]
puts [dict get [lindex $mylist 1] a]

To do it as arrays you need to use [array get] and [array set] to change the array into a string:

set si(eid) -1
set si(core) 0
set si(time) 0
lappend si_list [array get si]

And to get it back out

array set newsi [lindex $si_list]
puts $newsi(eid)

dicts let you work on the {name value} lists directly.


One way to do this on versions of Tcl that don't include dict is to use upvar.

To do this, add the names of the array variables to your list:

    set si(eid) -1
    set si(core) 0
    set si(time) 0
    lappend si_list "si"

Then to get your array back, do this:

    upvar #0 [lindex $si_list 0] newsi
    puts $newsi(eid)


You could also use the ::struct::record package from tcllib for something like that.

0

上一篇:

:下一篇

精彩评论

暂无评论...
验证码 换一张
取 消