-=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- (c) WidthPadding Industries 1987 0|106|0 -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=-
SoCoder -> Article Home -> Advanced Techniques


 
Pixel_Outlaw
Created : 02 July 2025
Edited : 03 July 2025

[BMX] Custom For Loop Iterators



Here is an example of how to implement your own Iterator for BlitzMax NG for loops.
I've never seen somebody do this so I present it here.

The For loops are designed this way and left open to the user such that you can make your own kind of iterator.
This is a very common technique in other languages too. Especially C++, Java, C#, Rust - Anything with loops and an iterator interface.

Beyond simple generators like below, it also provides a mechanism to use For loops with any new type of collection you define (think things like Red/Black trees, R-Trees etc)


 

Comments


Thursday, 03 July 2025, 17:39
realtime
not a blitz max user. vibe coding asking AI to create the grid iterator



sample use:

Thursday, 03 July 2025, 17:53
Pixel_Outlaw
That's exactly the idea for another type.
Looks to compile and pass. (but the AI seems to have made a logic mistake for 0,0)

Somebody making a 3D game might even add a z. Turning what would be 3 nested loops into a single iterator to populate a cube.
It's a lot of code, but you only ever need to define it once to replace a bunch of nested stuff forever.

This could even be extended to provide an offset x and y.
Well done.



Thursday, 03 July 2025, 18:20
Pixel_Outlaw
Looks a the fix is just to prime the x with -1 instead of 0. Then it works just fine. (It will then iterate 0 through N - 1)

If you want inclusive iteration then the MoveNext method changes a bit.

Becomes



Result: (with the inclusive tweak)


Now, what a powerful thing it would be to define an iterator to create things like Bezier curves.
The user doesn't even need to know how it works, he just feeds it a new BezierCurve iterator and gets his <n> Points back.

Another idea for an Interator might take a collection and only return the "even" indexes etc. All kinds of fun to be had.
Languages that let you extend the basic loops are quite nice.