ObjectScript Reference
$LISTNEXT
|
|
Retrieves elements sequentially from a list.
Synopsis
$LISTNEXT(list,ptr,value)
$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(NULL), or
list=$LB(,).
$LISTNEXT and Performance
Using
$LISTNEXT to return a large number of elements from a list is substantially more efficient than using
$LIST to perform the same operation.
The following example rapidly accesses the elements in
mylist:
SET ptr=0
WHILE $LISTNEXT(mylist,ptr,value) {
/* perform some operation on value */
}
It is substantially faster than the following equivalent example:
FOR i=1:1:$LISTLENGTH(mylist) {
SET value=$LIST(mylist,i)
/* perform some operation on value */
}
$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
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
Content Date/Time: 2019-02-16 22:40:03