Array elements

5 posts

Flag Post

Is there a way to limit the elements within an array? Preferably in the prototypes? I tried ‘new array(5)’ and similar things that would work for C/C++, but that just fill those five with blanks.

 
Flag Post

For the red five that is in superscript, it’s suppose to be ’ [ 5 ] ’.

 
Flag Post

In short, no. Vectors might be closer to what you’re looking for. They’re the array’s faster cousin, although it’s important to note that they only accept the object type (and any subclasses of that type) they are originally defined for.

// creates a vector with 5 null elements that will accept sprite objects
var someVector:Vector<Sprite> = new Vector<Sprite>(5);
someVector[1] = new Sprite(); // allowed
someVector[3] = new Point(); // throws a type error because a Point isn't related to a Sprite
someVector[21] = new Sprite(); // throws an out-of-range error

// vs the array created with 5 elements initially
var someArray:Array = new Array(5);
someArray[1] = new Sprite(); // allowed
someArray[3] = new Point(); // allowed, even though it's not related to sprites at all
someArray[21] = new Sprite(); // allowed, the array simply grows to accommodate for some sick reason
// I don't really use arrays in AS3 because I think they suck balls, so if I'm wrong about any of it, someone say so.
 
Flag Post
Originally posted by AshAbeAdd:

Preferably in the prototypes?

It’s not recommended to work with prototypes.

I’m not aware of a way to truly limit the size of an array in C.
Sure enough you set an amount of elements, but nothing prevents you from crossing that line. You’d have to write a function that does this.

In As3, Arrays do not have a set size and grow as you add or remove elements.
Vectors can be set to have a fixed size.

I’d just write a function that keeps the index within your desired boundaries.

 
Flag Post

If you really wanted to, you could override array, and reject anything added once size reaches a max_limit variable (which you would add to your new class).
Or as NineFiveThree mentioned, write a function to keep it in bounds,
Or, add a wrapper class that hides the internal array:

class LimittedArray
{
public var max_size:int = 0;
private var arr:Array = new Array();
public function addElement(o:Object):Bool
{
if(arr.length < max_size)
{
arr.push(o);
return true;
}
return false;
}
//add any other methods you want/need (pop, get, etc)
}

But the real question is why would you want to? AS3 along with most higher languages provide dynamic arrays because we’re no longer exposed to the underworkings where you must allocate N*size bytes for N objects, or where you have to keep track of size, or add a null pointer. If there’s a need to keep it a certain size (ie, only 10 bullets on screen), then it should be the responsibility of the adding code (a shoot function) to check the size (if bullets.size < 10, shoot()).