Retrieves elements sequentially from a list.
Description
$LISTNEXT sequentially returns elements in a list. You initialize ptr to 0 before the first invocation of $LISTNEXT. This causes $LISTNEXT to begin returning elements from the beginning of the list. Each successive invocation of $LISTNEXT advances ptr and returns the next list element value to value. The $LISTNEXT function returns 1, indicating that a list element has been successfully retrieved.
When $LISTNEXT reaches the end of the list, it returns 0, resets ptr to 0, and leaves value unchanged from the previous invocation. Because ptr has been reset to 0, the next invocation of $LISTNEXT would start at the beginning of the list.
Note:
Because ptr is an index into the internal structure of list, the list should not be modified while $LISTNEXT is being used on it. Modifying list may make the ptr value invalid and cause the next invocation of $LISTNEXT to issue a <FUNCTION> error.
You can use $LISTVALID to determine if list is a valid list. An invalid list causes $LISTNEXT to generate a <LIST> error.
When $LISTNEXT encounters an omitted list element (an element with a null value), it returns 1 indicating that a list element has been successfully retrieved, advances ptr to the next element, and resets value to be an undefined variable. This can happen when encountering an omitted list element, such as the second invocation of $LISTNEXT on list=$LB("a",,"b"), or with any of the following valid lists: list=$LB(), list=$LB(UndefinedVar), or list=$LB(,).
$LISTNEXT("",ptr,value) returns 0, and does not advance the pointer or set value. $LISTNEXT($LB(""),ptr,value) returns 1, advances the pointer, and set value to the null string ("").
Example
The following example sequentially returns all the elements in the list. When it encounters an omitted element, the $SELECT returns the default value “omitted”:
SET list=$LISTBUILD("Red","Blue",,"Green")
SET ptr=0,count=0
WHILE $LISTNEXT(list,ptr,value) {
SET count=count+1
WRITE !,count,": ",$SELECT($DATA(value):value,1:"omitted")
}
WRITE !,"End of list: ",count," elements found"
QUIT
$LISTNEXT and Nested Lists
The following example returns three elements, because $LISTNEXT does not recognize the individual elements in nested lists:
SET list=$LISTBUILD("Apple","Pear",$LISTBUILD("Walnut","Pecan"))
SET ptr=0,count=0
WHILE $LISTNEXT(list,ptr,value) {
SET count=count+1
WRITE !,value
}
WRITE !,"End of list: ",count," elements found"
QUIT