Each typename
Parameters
| typename - the name of a type declared with a Type block |
Description
|
Used with For to loop over every object of a custom type. The form is For b.bullet = Each bullet ... Next. On each pass the variable points at the next object in that type's list, in the order the objects sit in the list, and the loop ends when there are none left. This is the heart of type-based game code. One For Each loop moves every bullet, another ages every particle, another runs the AI for every enemy. Because the loop knows nothing about how many objects there are, the same code works with three on screen or three hundred. Deleting the current object inside the loop is safe and expected - see Delete - which lets you update and cull in a single pass. Creating new objects while iterating is riskier, because they are appended to the end of the same list and the loop will reach them in this pass; if a bullet spawns bullets you can loop for a very long time. Collect new objects in a second pass, or set a flag the loop checks. For Each walks the list front to back. To go the other way, or to control your own position, use First, Last, After and Before with a While loop instead. See also: For, Next, Type, Delete, First, Null. |
Example
; Each Example ; ------------ ; A squad of enemies, kept in a Type collection Type Enemy Field name$ Field hp End Type Spawn("Scout",20) Spawn("Grunt",50) Spawn("Brute",80) Print "The squad before the medic arrives:" ShowSquad() ; For ... Each visits every Enemy in the collection, one at a time For e.Enemy=Each Enemy e\hp=e\hp+10 Next Print "" Print "After healing every squad member by 10 hp:" ShowSquad() Print "" Print "Press any key to close the example" WaitKey End ; Create one enemy and set its fields Function Spawn(n$,hp) e.Enemy=New Enemy e\name=n$ e\hp=hp End Function ; Print every enemy in collection order Function ShowSquad() For e.Enemy=Each Enemy Print " "+e\name+" ("+e\hp+" hp)" Next End Function
Index