Clearing arrays, as3

32 posts (showing 1-20)
TheDeveloper

Market Level 0Community Level 3
233 posts

Lets say I have 10 different arrays, and for whatever reason I wish to simply clear / empty them all of all their elements. Is there a quick way I can do this without having to reference each array? A sort of "emptyAllArrays();" option?

posted 2015-03-17T13:24:17-07:00
bluebox

Market Level 6Community Level 3
334 posts

no, each is a variable. I think you have to make your own solution for that.

Default operation that is able to redefine all variables of such type would be dangerous weakness.

posted 2015-03-17T14:14:25-07:00 | edited 2015-03-17T14:15:29-07:00
djstatika

Market Level 10Community Level 7
1254 posts

when you create the arrays, add them to an array of arrays, then loop through that

posted 2015-03-17T16:18:47-07:00
FGL_Porter

FGL AdminCommunity Level 16
427 posts

^ Exactly what he said. Create a function for creating arrays, and just put the functionality in there. That way when you say something = createArray(), all of the extra work is done for you and contained within the function.

posted 2015-03-20T03:26:25-07:00
JohnBlackburne

Market Level 3Community Level 10
2184 posts

You can just set the length of each to zero to quickly empty each. E.g.

array1.length = array2.length = array3.length = ... = array10.length = 0;

You are referencing each array but in a minimal way. Putting them in an array and looping through it would achieve the same but for a small number of known arrays the above works just as well.

posted 2015-03-21T18:31:20-07:00
FGL_Porter

FGL AdminCommunity Level 16
427 posts

I'm not 100% positive, but isn't there some sort of increasing / exponential delay for each additional setting? For isntance:

a = b = c = d is far less cpu intensive than a = b = c = d = e = f = g = h

I'm not sure how much this is, or if it applies to setting a value, but I definitely recall reading about it pertaining to if statements and the number of conditionals.

posted 2015-03-21T19:23:12-07:00
DelaniStudio

Market Level 2Community Level 5
370 posts

For array with 100 elements (benchmarks in ms, the lower the less time needed):

// best performance (benchmark: 1157)
array.length = 0;
// lower performance (benchmark: 1554)
array = [];
// even lower performance (benchmark: 3592)
array.splice(0);

posted 2015-03-21T19:28:17-07:00
TheDeveloper

Market Level 0Community Level 3
233 posts

So essentially there is no way to simply clear all arrays without having to reference them individually "somewhere". Even if I were to place them all into one big array which I used to control them, I would still need to reference them individually in order to push them into said array. What I was looking for was a solution where I could just empty every array I have without at any point having to reference them individually. 

Like how "SoundMixer.stopAll();" will just stop all audio without me having to ever reference any sound individually.

It is clear after reading all these replies that sadly no such function exists, never mind :/

posted 2015-03-21T20:48:46-07:00 | edited 2015-03-21T20:49:05-07:00
bluebox

Market Level 6Community Level 3
334 posts

'TheDeveloper' title and questions like that schouldn't appear in that same post ;)

posted 2015-03-21T21:24:06-07:00 | edited 2015-03-21T21:24:23-07:00
FGL_Porter

FGL AdminCommunity Level 16
427 posts

The thing is, SoundMixer.stopAll() must be referencing them, it's just all behind the scenes. When you register a sound, it's being added to an array of some sort. The really simple solution is just to stop creating arrays the usual way, and create an array with a function that returns the array, then do all of the dirty work in that function.

posted 2015-03-21T23:04:47-07:00
FGL_Dave

FGL AdminCommunity Level 4
285 posts

Yup, use the Factory pattern if you want that degree of control. I do feel like we're glossing over a very important part of this here though - you say 'for whatever reason', but it's likely that if you need to do this on any large scale there's a design problem somewhere; maybe the reasoning should be considered to lead to a better solution?

For example: Is this for resetting the game state? Your game should ideally be designed so that just clearing the entities (or game objects - which should ideally be one array in a 'world' type object, each with their own children that they are individually responsible for) and possibly resetting some independent game state variables should be enough to do the job you're after here. If you're having to clear arrays within game objects from some 'god' object or place, you're probably not writing decent code!

Stable, maintainable code relies on being able to trace a path of execution and know what the effect of any given function might be (with minimal side effects). Clearing every array from somewhere in your game logic contradicts this - it may seem faster and easier to do it like that, but that's the sort of thing that leads to large scale difficult refactoring down the line!

posted 2015-03-22T16:59:16-07:00 | edited 2015-03-22T17:06:00-07:00
TheDeveloper

Market Level 0Community Level 3
233 posts

On Mar 21, 2015, FGL_Porter said:

The thing is, SoundMixer.stopAll() must be referencing them, it's just all behind the scenes.

Whether it's behind the scenes or a full in your face Broadway production it doesn't matter to me, I can just type "SoundMixer.stopAll();" and all the sounds stop, and I don't have to think about it again. That sort of functionality is what I was looking for when it came to clearing arrays, a simple command that I can type in that does the job, and that's it. I don't want to have to build it myself, like I didn't have to build anything to get "SoundMixer.stopAll();" to stop all audio.

On Mar 21, 2015, FGL_Dave said:

A whole bunch of stuff you can read above ^^^^^^^

My point of view or attitude towards coding is this, either you write something that works, or you write something that doesn't work. Punisher0504 pointed out 3 different ways to clear an array of its elements, all 3 different options achieve the same result, and although array.length = 0, is faster then array.splice(0), it is extremely unlikely that you will find a browser based flash game where the difference in performance is noticeable by anyone, (let alone the target audience).

The point I'm trying to make is that I don't care about writing what anyone would consider "decent code", I only care about writing code that works, (and when I say "works" I mean in the proper sense, executes what you want it to execute, doesn't cause any noticeable drop in performance (for example, clearing 1 array with array.length = 0, is faster then array.splice(0), but performance wise you won't notice the difference), doesn't break any other function, etc etc etc) and speed. And when I say speed, I mean the less I need to type the better.

So when I say "for whatever reason", I mean just that, for whatever reason that could possibly arise where I have multiple arrays that I want to just clear, can I do this with a simple short command? The answer is "no", there exists no "clear all arrays" function in Flash, and if I wanted to do something like this I would have to take the time to write it myself.

I appreciate all of the different replies, and the time everyone has taken to read my message and respond, but really that's all anyone needed to say, "no that functionality doesn't exist, but you could write something yourself".

posted 2015-03-22T18:45:44-07:00 | edited 2015-03-22T18:51:01-07:00
FGL_Porter

FGL AdminCommunity Level 16
427 posts

The reason it doesn't just magically exist already, is because it doesn't make design sense. It makes sense to stop all sounds, which is why the systems were created in the first place - clearing every array does not make sense, that's why it does not exist, just as there is no way to set every Boolean to false, nobody does that.

As for the code, I wrote this in about 5 minutes. It may need minor syntax changes (wrote it very quickly in notepad++), but the gist of it is here:

[as3]
private var masterArray:Array = new Array();

private function createArray():Array {
    var theArray:Array;
    theArray = new Array();
    masterArray.push(theArray);
    return theArray;
}

//implementation
someVar = createArray();

private function clearMasterArray():void {
    for(var i:int = 0; i < masterArray.length; i++) {
        masteryArray[i].length = 0;
    }
}[/as3]

 

posted 2015-03-23T02:21:27-07:00
djstatika

Market Level 10Community Level 7
1254 posts

You can just set the length of each to zero to quickly empty each. E.g.

array1.length = array2.length = array3.length = ... = array10.length = 0;

I didnt know you could just set them to 0! Thanks. I'm gonna change all my code right now

For array with 100 elements (benchmarks in ms, the lower the less time needed):

// best performance (benchmark: 1157)
array.length = 0;
// lower performance (benchmark: 1554)
array = [];
// even lower performance (benchmark: 3592)
array.splice(0);

Helpful, thanks

posted 2015-03-23T10:54:30-07:00
djstatika

Market Level 10Community Level 7
1254 posts

As for the code, I wrote this in about 5 minutes. It may need minor syntax changes (wrote it very quickly in notepad++), but the gist of it is here:

For a laugh i tried extending Array. Create a new class:

[as3]
package
{
    public dynamic class ArrayPlus extends Array
    {
        private static var allArrays:Vector.<Array> = new Vector.<Array>();
        
        public function ArrayPlus():void
        {
            super();
            
            allArrays.push(this);
        }
        public static function clearAll():void {
            for (var i:int = 0; i < allArrays.length; i++) 
            {
                allArrays[i].length = 0;
            }
        }
    }
}[/as3]

Then you can use it by creating an arrayplus like this:

[as3]
var testArray1:ArrayPlus = new ArrayPlus();[/as3]

and then using it like a normal array

[as3]
testArray1[0] = 1;
testArray1.push(3);
trace(">>"+testArray1[1]);[/as3]

When you want to clear all:

[as3]
ArrayPlus.clearAll();
trace(">>"+testArray1.length);[/as3]

posted 2015-03-23T11:07:52-07:00 | edited 2015-03-23T12:24:50-07:00
TheDeveloper

Market Level 0Community Level 3
233 posts

FGL_Porter said:

... clearing every array does not make sense, that's why it does not exist, just as there is no way to set every Boolean to false, nobody does that.

That's a silly statement, surely it cannot be beyond you to imagine a scenario where you have a small program (like a flash game) that contains more then one array, and at some point you wish to clear them all? If I tried hard enough I'm sure I could easily think of a situation where you have more then one boolean and for whatever reason you wish to set them all to false. To say "nobody does that" is I guess true, as the functionality doesn't exist, so nobody can actually do it (unless they build their own function), but to imply that nobody would ever want to do it is clearly false.

posted 2015-03-23T12:08:36-07:00
FGL_Dave

FGL AdminCommunity Level 4
285 posts

TheDeveloper said:

FGL_Porter said:

... clearing every array does not make sense, that's why it does not exist, just as there is no way to set every Boolean to false, nobody does that.

That's a silly statement, surely it cannot be beyond you to imagine a scenario where you have a small program (like a flash game) that contains more then one array, and at some point you wish to clear them all? If I tried hard enough I'm sure I could easily think of a situation where you have more then one boolean and for whatever reason you wish to set them all to false. To say "nobody does that" is I guess true, as the functionality doesn't exist, so nobody can actually do it (unless they build their own function), but to imply that nobody would ever want to do it is clearly false.

But it needs some way to know *which* variables you want to clear. That's why you have to reference them. Without knowing which variables to clear, it'd be leading to an easy design trap as I described above, and it'd contribute to making your code unmaintainable (at which point, serious developers would start to dislike the language and begin to avoid it). It may seem like a convenient function to someone who doesn't care about code design, but design is equally (if not more!) important than performance. Giving developers the option to clear all 'user' variables of a specific type would allow for some really bad practice.

The SoundMixer is a different scenario; here it makes sense as the SoundMixer controls resources of a specific type, and stopping all sounds is a pretty natural and obvious operation that only affects objects within the SoundMixer class. That's good design - it makes sense, it's predictable and as you say it's a handy function.

However, just arbitrarily being able to clear all arrays that the user has made would very quickly and easily lead to chaos in almost every case! What about that one array you have tucked away somewhere that is incredibly important and should never be cleared, but you coded it 3 weeks ago while tired and drunk, and have now completely forgotten about it's existence? You clear all arrays - bam, you probably have hundreds of subtle (or maybe not so subtle) bugs in your code - your game would very likely be completely broken :) And even if it isn't, what if you make another game using this codebase 12 months down the line (a sequel, because the game did well) and forgot that all of your arrays get cleared somewhere while adding a new feature? Now, you have to spend more time tracking down where that happens and working around it!

Just because the player doesn't see your code, doesn't mean your code is not important. There's a limit to code design's usefulness, sure, but I feel like you're limiting yourself in a lot of ways by only caring about performance! Check out LongAnimals, he can crank out games faster than almost anyone - I bet he has good, maintainable code where it counts. Good code = more money for you, and less time spent making that money. The only barrier is a bit of extra effort required on your part to learn how to write good code :)

I appreciate all of the different replies, and the time everyone has taken to read my message and respond, but really that's all anyone needed to say, "no that functionality doesn't exist, but you could write something yourself".

But it's an interesting discussion that could be worth so much more than that (to you or future readers)!

posted 2015-03-23T12:22:35-07:00 | edited 2015-03-23T12:29:53-07:00
TheDeveloper

Market Level 0Community Level 3
233 posts

FGL_Dave said:

But it's an interesting discussion that could be worth so much more than that (to you or future readers)!

Okay that's fine, it's good to talk (as they use to say on those retro BT adverts). I would say this though, if you have a program where you need to clear all of your arrays bar one, then you wouldn't use the "clear all arrays" option (if it existed), the same way I don't use "stop all sounds" when I don't actually want to stop all of the audio, just specific tracks.

The analogy where you could return to some code having forgotten that somewhere you are clearing all of your arrays could apply to anything. I could just as easily return to some code and forget that somewhere I've stopped all of the sound. It wouldn't be difficult to trouble shoot, likewise it wouldn't be difficult to trouble shoot a problem where you have forgot that you are clearing all of your arrays.

However, just arbitrarily being able to clear all arrays that the user has made would very quickly and easily lead to chaos in almost every case!

It wouldn't though, let's just imagine this scenario; you have a game where you have a "bullets" array, and an "enemies" array. The game is done (either the user quit to the main menu, or they beat it, or whatever, it's game over, finished). You now want to clear both of these arrays, how would a clear all arrays function (remember you only have these two) break your stuff? You're gonna' clear them both anyway, so how would this function cause chaos to this specific program as it is?

The most important thing when it comes to coding Flash games is "does the code work", and "speed" (how quick you can knock the code out). That's it really, whether "serious" coders use the platform doesn't matter to me, if the platform exists and spits out a file format that has value is all that is relevant.

Best practice or the "proper way" means nothing really. If the code works then it's good, and you can sell the game and make money. The success of someone like LongAnimals has a lot more to do with the quality of his games, and his professional approach to the industry, then it has to do with his actual in game code. That's the truth.

(And I might be ML0 on here but I've been living off of Flash games since 2008, not that that means anything, but "in before anyone says you're ML0 and have no idea what you're on about").

posted 2015-03-23T13:29:16-07:00 | edited 2015-03-23T13:34:42-07:00
djstatika

Market Level 10Community Level 7
1254 posts

Best practice or the "proper way" means nothing really. If the code works then it's good, and you can sell the game and make money

Yes, but in this case you are arguing between something quick and something quick. In the time youve spent arguing about this you could have done it. People have done it for you here

The point of programming is that if you want something that's not provided by default, you can add it yourself. I explained above how you can extend the array class to do exactly what you are asking for. Although, personally I agree with the others that I wouldnt want to do this.

You're gonna' clear them both anyway, so how would this function cause chaos to this specific program as it is?

It will cause problems because it also clearing the other array deep in your code that you had forgotten you had added before, creating new bugs that you have no idea where they are coming from.

Such a function might save you writing out 5 lines of code, but can potentially waste loads of time with strange unexplained bugs. Thats what AS2 used to be like...

posted 2015-03-23T14:14:32-07:00 | edited 2015-03-23T14:20:02-07:00
TheDeveloper

Market Level 0Community Level 3
233 posts

djstatika said:

 ..It will cause problems because it also clearing the other array deep in your code that you had forgotten you had added before ...

There is no other array hidden away that has been forgotten about, there is just what was explained, and that's all. And it's clear that having a function that clears them in one go wouldn't cause any problems.

In the time you've spent arguing about this you could have done it.

Yes, at this point the discussion has passed the initial "problem", I think now we are just arguing principles of how people approach coding, and that's what I was typing about at that point.

Thats what AS2 used to be like...

AS2 was bloody great! Well, in some areas, the performance was shit but it was cool how you could just throw stuff together in seconds and it would work, you didn't even need to define variables, it was amazing!

posted 2015-03-23T14:59:11-07:00