|Powered by QM on a Rpi server|
KnowledgeBase 00030: QMBasic FOR Statement Extensions
This article was originally published as a Tip of the Week.
Probably all applications use the FOR statement to go around a loop some number of times. QM provides two useful variants that can simplify programming.
Processing a List of Values
Sometimes a developer wants to execute a loop for a set of values of the control variable that cannot be created from the standard syntax. QM has a variation of the form
FOR I = 1, 17, 23 statements NEXT IAlthough the example above uses constant values, the items in the list can be expressions that will be evaluated at the point when the value is copied to the control variable. The value in the control variable on leaving the loop will be the final item in the list unless the loop exits prematurely by use of WHILE, UNTIL, EXIT, etc.
Processing All Elements of a List
Developers frequently need to process each element of a dynamic array. QM can do this with a statement of the form
FOR EACH VAR IN LIST statements NEXT VARwhere LIST contains the list of items to be processed, each of which will be assigned to VAR in turn. The delimiter between each item in LIST may be any of the mark characters. The list is copied to a temporary variable at the start of the loop so that changes made to the LIST variable inside the loop have no effect on its behaviour.