object as array

Started by KiraHaraReturns, Wed 20/02/2019 12:07:22

Previous topic - Next topic

KiraHaraReturns

to manage the code easier, I decided to put some objects in an array, which works fine, I love it. But to avoid possible bugs, I would like to implement a query if a particular array index is out of bounds. What I need is a check if an array is null or not. Any ideas?

Snarky

There are two things you need to check:

1. Is the index valid? Trying to look up objectArray[-1] or objectArray[2378432] in a 32-item array will crash. So for objectArray[i], always ensure that (i>=0 && i<ARRAY_SIZE). You can do this as an explicit if-check, or simply write the code to ensure it won't ever have any other values (for example a for-loop from 0 to <ARRAY_SIZE).

2. Is the array entry non-null? Simply check this directly. For example:

Code: ags
    if(objectArray[i] != null)
    {
      // Do stuff
    }

KiraHaraReturns

here's what I've got:

Khris

Like Snarky said, you need to ensure that the index is inside the array's bounds yourself.
AGScript doesn't have try..catch, so there's no way around this.

KiraHaraReturns

I got it, the size given is equal to the upper bound -1, now everything's clear and works pretty well, THANKS

Snarky

This is a consequence of array numbering starting at 0. For example, if an array is size 2, the valid indices are 0, 1.

KiraHaraReturns

is there a method to get the size of an array?

Snarky

No, AGS doesn't currently have that.

For arrays you create, you should simply keep track of the size yourself. (The best way is often to #define a constant that you set the array size to and check against later. That way you can change it later without having to change it everywhere in the code.)

For arrays provided by AGS, there's usually a function or property that holds the array size. For example, the size of the character[] array is Game.CharacterCount.

Crimson Wizard

Quote from: Snarky on Wed 20/02/2019 13:58:09
For arrays you create, you should simply keep track of the size yourself. (The best way is often to #define a constant that you set the array size to and check against later. That way you can change it later without having to change it everywhere in the code.)

Or store it in the variable, if array may be of varied size.

Adding "array.Length" property is a long standing feature suggestion, but it still haven't been done...

SMF spam blocked by CleanTalk