FOR .. IN ..
General Form:
The FOR .. IN .. statement is used in conjunction with objects from the Collections API. It provides syntactic sugar for a FOR loop that operates elementwise over any collection that supports GetEnumerator. It should not be confused with FOR OBJECT ... IN ... NEXT OBJECT style loops.
When the FOR .. IN statement is first executed, element is set to point to the first object in the collection. If the collection is empty then execution skips to the statement immediately after the END FOR. Otherwise, program execution continues within the loop body until the END FOR statement is executed whereupon execution resumes at the top of the loop with the next element, if one exists.
Example:
DEF STRUCT Object
FLD Object_fld1
END STRUCT
DEFSUB 'fn()
LOCAL DIM element AS PTR(X$_Object)
LOCAL DIM list$_KCML_ListClass<_Object>
// Add some elements to list$
element = NEW _Object
FLD(element.Object_fld1) = 3
list$.Add(element)
element = NEW _Object
FLD(element.Object_fld1) = 1
list$.Add(element)
element = NEW _Object
FLD(element.Object_fld1) = 4
list$.Add(element)
// Print contents of list$
FOR element IN list$
PRINT $PRINTF("List contains: %d", FLD(element.Object_fld1))
END FOR
END SUB
The above listing could be rewritten using the FOR ITERATOR pattern, which provides direct access to the iterator's methods, as follows.
Example:
DEF STRUCT Object
FLD Object_fld1
END STRUCT
DEFSUB 'fn()
LOCAL DIM element AS PTR(X$_Object)
LOCAL DIM list$_KCML_ListClass<_Object>
LOCAL DIM iterator$_KCML_IteratorClass<_KCML_ListClass,_Object>
// Add some elements to list$
element = NEW _Object
FLD(element.Object_fld1) = 3
list$.Add(element)
element = NEW _Object
FLD(element.Object_fld1) = 1
list$.Add(element)
element = NEW _Object
FLD(element.Object_fld1) = 4
list$.Add(element)
// Print contents of list$
FOR ITERATOR iterator$ IN list$
element = iterator$.Element()
PRINT $PRINTF("List contains: %d", FLD(element.Object_fld1))
END FOR
END SUB
Jumping out of a FOR .. IN .. loop is allowed but should be avoided as it is considered bad programming practice and terminating loops incorrectly can cause stack overflow errors. If a program has to jump out of a loop then a BREAK statement should be used to abandon the loop entirely or the CONTINUE statement may be used skip the remaining body of the loop.
Compatibility:
FOR (ITERATOR) .. IN .. was added in KCML 7.05.See also:
FOR, FOR OBJECT ... IN ... NEXT OBJECT, BREAK, CONTINUE, RETURN CLEAR