tclvmd

Tcl foreach loop not finding second variable


I am sure this has been asked here before but I can't seem to find any link that can help me with my particular problem.

I am using tcl scripting within vmd to do a quick analysis.

package require pbctools
set wat [atomselect top "segid HETA"]
set pbcbox [pbc get -now]
set Lz [lindex [lindex $pbcbox 0] 2]
set Qwat 0
puts [$wat get charge]
foreach i{$wat get z} j{$wat get charge} {set $Qwat [expr $Qwat + $j * ($i + 0.5 * $Lz) / $Lz]}
#puts $Qwat

When I run this script, I get the error: enter image description here Where atomselect 0 shows that it set wat fine, 100.608742 is the length of the box Lz and it is finding the charge for each atom (there are 4 atoms each with a negative charge).

However it is failing on this foreach loop where I am wanting it to iterate by location and charge at the same time. So line 1 in list 1 and line 1 in list 2. I have tried each syntax iteration I could think of but I cannot seem to get this expression to work within the foreach loop.

What am I doing incorrectly here?


Solution

  • The problem is that you are missing some whitespace for Tcl to understand what you want.

    As a result foreach i{$wat get z} j{$wat get charge} {} creates 3 variables (assuming $wat is "atomselect0"):

    1. "i{atomselect0", with a value of "get"
    2. "z}", with a value of "j{atomselect0"
    3. "get", with a value of "charge}"

    As you can see, there is no variable "j". My guess of what you want is probably something along the lines of:

    foreach i [$wat get z] j [$wat get charge] {
        set $Qwat [expr {$Qwat + $j * ($i + 0.5 * $Lz) / $Lz}]
    }
    

    (Except for some unusual circumstances, it's usually advisable to brace your expressions. So I made that change too, although it wasn't strictly necessary.)