GMS 2.3+ How do I loop over an array?

Godelinde

Member
Dear GMS2-community,

I'm trying to loop over an array using the following bit of code:

Click event object Q:

a[0] = 0;
a[1] = 3;
a[2] = 5;

for(i = 0; i < 3; ++i; )
if(instance_number(global.obj_target[a[0]])=0){
instance_create_layer(
xx,
yy,
"Instances",
global.obj_target[a])
}

But for some reason instead of creating 'global.obj_target[0]', 'global.obj_target[3]' and global.obj_target[5]', it only creates the first one.

Thanks in advance for any help or feedback.
 

rytan451

Member
For future reference, please wrap your code in code tags (like this):

[code=gml]
a[0] = 0;
a[1] = 3;
a[2] = 5;
[/code]


It makes the code look neater. For reference, the code in the OP is this:

GML:
a[0] = 0;
a[1] = 3;
a[2] = 5;

for(i = 0; i < 3; ++i; )
  if (instance_number(global.obj_target[a[0]]) = 0) {
    instance_create_layer(
      xx,
      yy,
      "Instances",
      global.obj_target[a])
  }
And your problem is this: on line 11, you're creating an instance of global.obj_target[a] rather than of global.obj_target[a[0]]. On line 6, you're only checking of an instance of global.obj_target[a[0]] exists, when you should be checking with i as the index.

Here's a corrected version of your code (cleaning up, fixing the bugs, general optimisation, and making the code more flexible):

GML:
a = [0, 3, 5]; // Only usable in GMS 2.3

var l = array_length(a); // In GMS <2.3, this is array_length_1d
var _layer = layer_get_id("Instances");

if (_layer != -1) {
  for(i = 0; i < l; ++i) {
    if (!instance_exists(global.obj_target[a[i]])) {
      instance_create_layer(xx, yy, _layer, global.obj_target[a[i]]);
    }
  }
}
 
Top