"For each" problem with types

Blitz3D Forums/Blitz3D Beginners Area/"For each" problem with types

Spikenspan(Posted 2003) [#1]
Here's the example code:

Type t1
Field num1
End Type

a.t1 = New t1
a\num1 = 11

b.t1 = New t1
b\num1 = 33

For b.t1 = Each t1
DebugLog "num1=" + b\num1
Next


Here's the debug log output:

num1=11
num1=33


One would assume that the output in the debug log would be "num1=33" only, since the iteration only concerns "b". It looks like the FOR..EACH command loops through all instances of a given type, regardless of the variable used.

Is there a way to limit the scope of the FOR..EACH command to one variable?


GfK(Posted 2003) [#2]
You can do this:
For N = 1 to 10
  A.t1 = new t1
  A\num1 = rand(0,100)
Next
That code uses variable A ten times to add ten items to the t1 type collection, so the collection contains ten items.

If you then do this:
For N = 1 to 10
  B.t1 = new t1
  B\num1 = rand(0,100)
Next

...the t1 type collection will now contain 20 items.

In a nutshell, it doesn't matter what variable you use - A, B, whatever, as they're all added to the T1 type collection in the end, and using more than one variable to do it is a waste, really.

If you need to distinguish between one and the other, then you can either create another type (t2, for instance), OR you can add a further Field to your existing type.
Type t1 
  Field num1 
  Field Class
End Type
You can then iterate through the whole type collection with a For...Each loop, analyse the contents of the 'Class' field, and execute the appropriate bit of code.
For A.t1 = Each t1
  If A\Class = 1
    ;Do something
  EndIf
  If A\Class = 2
    ;Do something else
  EndIf
Next



Spikenspan(Posted 2003) [#3]
It explains everything. I simply assumed TYPE to be just like STRUCT in c. Thanks a lot for the reply!


dynaman(Posted 2003) [#4]
That got me at first too, pretty powerful when you are used to them though.


Tricky(Posted 2003) [#5]
I was confusing it with the "STRUCT" as well (which I used to call "RECORDS", as a ex-Pascal coder)...

Using it like STRUCT is possible, but not really preferable


(tu) sinu(Posted 2003) [#6]
gfk's got it down exactly right.
types are great when you understand them fully.