Tcl 访问循环项 item 的内容

Tcl access contents of a loop item item

我创建了基于数组的变量,然后用该数组的结果填充该变量,并尝试在循环中访问该变量以替换字符串中的文本。

我有一个数组

mookie profile:alias:0 mookie
mookie profile:class:0 hacker
mookie profile:inventory:0 DigitalHackerDevice
mookie profile:inventory:1 BootDisk
mookie profile:inventory:2 HackThePlanet99

然后我得到所有数组并存储它

#get_userSprite is defined via an HTML form so "mookie" for this example
set array "[lsort -dictionary [array names $get_userSprite]]" 

我有一个用键(别名,class,库存)填充 $ 的循环

foreach item $array {

set datastoreKey [lindex [string map {":" " "} $item] 1] ;#alias, class, inventory

#using the array string profile:alias:0 get the item
set array_string [getItem $get_userSprite $item] ;#get the result for profile:alias:0 returns "mookie"

lappend $datastoreKey "$array_string" ;# this then creates variables with the result of that.

#$alias eq mookie
#$class eq hacker
#$inventory eq item1,item2,item3
} ;#close loop

我可以确认这些已填充

puts $class ;# returns mookie
puts $alias ;# returns merchant
puts $inventory ;# returns DigitalHackerDevice, item1, item2

我还存储了我希望访问的三个字段的列表

if { $datastoreKey ni $myList } { lappend myList [list $datastoreKey] } else { puts "Don't append" }

所以 myList 现在包含:别名 class 库存

我有一个 tagswap 程序,它用字符串替换变量中的“单词”

proc tagSwap {craft values} { return [string map $values $craft] } ;#Preforms morph of words.

所以

foreach item $myList {

puts $item ;#alias class inventory
set swaps [tagSwap $string [list "$item" "$item"]] 
} ;#end loop

我对如何访问 $alias 的内容以将字符串中的单词“alias”替换为“mookie”感到目瞪口呆,因为 $item 是“alias”,它用那个替换它等等对于其余的。 Class、库存等

您的结果与您提供的输入数据不匹配。忽略这一点,您的问题似乎可以归结为:我有一个变量“item”,其中包含另一个变量的名称。如何转储其他变量的值?

虽然这可以使用 puts [set $item] 完成,但通常更容易更改代码以使用数组成员而不是标量变量。

因此,请使用 lappend datastore($datastoreKey) "$array_string" 而不是 lappend $datastoreKey "$array_string"。然后获取项目的价值只是一个问题:puts $datastore($item)

这也避免了任何项目名称与您在代码中使用的变量发生冲突的风险。