Question
Alan Nguyen · Mar 21

# How to write a For Loop

Hello,

I have a variables X="1,4,6,8,9,12" and I want to write a For loop with this variable in similar with the loop below:

For Y=1,4,6,8,9,12 {

Write Y,!

}

Can someone help? Thank you.

**Product version:**IRIS 2021.2

Something like this would do it

`for i=1:1:$LENGTH(X,",") { w $PIECE(X,",",i),! }`

You beat me to it @Chris Stewart!

`set X="1,4,6,8,9,12" for i=1:1:$L(X,",") set Y=$p(X,",",i) write Y,!`

Thank you. Can we use the variable X instead of using $L(X,”,”)?

not directly - this is grabbing the Length ($Length()) of the variable X, using "," as a delimiter of the string. So the counter 'i' will run from 1 to the length of X, and then each iteration will grab the next piece of the string (, delimited again)

`set x="1,4,6,8,9,12" while x>0 {write +x,! set x=$piece(x,",",2,*) }`

x only !

creative!

another option is to use a list

`set x=$listfromstring("1,4,6,8,9,12") SET ptr=0 WHILE $LISTNEXT(x,ptr,y) { WRITE !,y }`

You can also treat each integer as a string. This would work if your list was small but would be annoying if you had a larger list. It's probably better suited for text strings and not integers treated as strings, but it is an option!

`USER>for y="1","4","6","8","9","12" { w y,! } 1 4 6 8 9 12`

Or use embedded Python

`for x in [1,2,3,4,5,6,7,8]: print('this is x: '+repr(x))`

Similar to Robert solution but using for:

`set x="1,4,6,8,9,12" for write !,+x set x=$p(x,",",2,*) quit:x="" 1 4 6 8 9 12`

Most of the ObjectScript examples above (but not the Python example) take O(n**2) time (i.e., quadratic time) where 'n' is number of values in X. This happens because the $PIECE(X,",",i) starts searching from the beginning of the string or because shortening the string X with

set x=$p(x,",",2,*)

will copy the string 'x' multiple times with the first element deleted before each copy.

The ObjectScript example from Timo Lindenschmid using $LISTNEXT takes O(n) time (linear time). This can be important if $L(X,",") is 1000 or more because such a list with 1000 elements will require about 500,000 scans of "," characters or about 500,000 copies of string characters.

Rich Taylor's Python example should also take linear time.

Another solution would be to build a %DynamicArray object and then iterate through its contents.

Finally, you could build a multi-dim ObjectScript array and iterate through the subscripts with $ORDER. This is method closest to using standard MUMPS/ANSI M/ObjectScript features.

It seems, nobody likes the execute command... once celebrated, now frowned upon

`set x="11,22,33,""Done""" xecute "for i="_x_" write i,!" 11 22 33 Done`

😏