actionscript 3: how to access to elements of an array created in a loop dynamically - arrays

In the library of the .fla file I have a square exported as Class "cuad" on frame 1
I want to create an Array with 100 squares so as to move them later
So I do like this:
for (var i:uint = 0; i<100;i++)
{
var cuad_mc = new cuad();
addChild(cuad_mc);
myArray.push("cuad_mc");
trace(myArray[i]);
}
I have a runtime error

The error you experience is
Error #1069: Did not find alpha propiety in the String and there is not any value predetermined
The problem comes from your line
myArray.push("cuad_mc");
What you are doing here is pushing a String Object into your Array, not the cuad Object you want. String Objects don't have Alpha values, or x values.
What you want to do is
myArray.push(cuad_mc);
cuad_mc (without the " quotation marks) is a reference to the object you just created.
This should solve your problem. I also recommend using Vectors instead of Array if you only need to store one type of Object. Like this:
var myArray:Vector<cuad> = new Vector<cuad>();
for(var i:int=0;i<100;i++){
var cuad_mc:cuad = new cuad();
addChild(cuad_mc);
myArray.push(cuad_mc);
trace(myArray[i]);
}
Vectors are just like Arrays, but they only allow one specific type, so that a situation like yours doesn't occur.

Related

How to use Array in JEXL?

Using JEXL, I am trying to initialize array and than adding elements into it, however below code gives me 'unsolvable property '0' error.
var abc=[];
abc[0]=5;
1) How can I initialize empty array and keep adding values in it?
2) Can I use it like List, where I do not need to specify size at the time of initialization ?
in JEXL syntax you can initialize objects with new function.
Other option is to add to context arraylist:
This is a working example with jexl2:
JexlEngine jexl = new JexlEngine();
String jexlExp = "var abc=new(\"java.util.ArrayList\", 1);abc[0]=5";
Expression e = jexl.createExpression( jexlExp );
List<Integer> abc = new ArrayList<>(1);
JexlContext jc = new MapContext();
//jc.set("abc", abc ); second option to add arraylist to context
Object o = e.evaluate(jc);
In JEXL, the syntax [] creates a Java array, not a List. As an array, it has a fixed size, so you cannot add values to it. However, JEXL 3.2 has a new syntax for creating an ArrayList literal. Basically, you add ... as the final element.
So in JEXL 3.2, your example could be written as:
var abc=[...];
abc.add(5);
See the JEXL literal syntax reference for more information.

Push instance name of movieClip into array using a for-loop

I have a bunch of movieclips on the stage with instance names ball1 - ball200. I was hoping I didn't have to create an array and manually set all the instance names into the array
ballArray = [ball1, ball2,ball3, etc];
I was trying to get a for loop to cycle through and add each instance name to my array like so:
function createTheArray():void{
for(var i:int = 1; i < 20;i++){
ballArray.push(ball + i);
trace(newArray[i])
}
}
But I keep getting back undefined array index's. It also tells me that I doesn't know what "ball" is. How would you use part of a instance name and combine it with the index value of the loop. So that the first time through you get ball1 as the first index value of your array?
Dragging out 200 balls onto the timeline and giving them instance names doesn't sound like much fun!
BEST OPTION:
right click the ball object and go to the properties, click "export for actionscript" and give it a unique name. (Lets call it MyBall for this example)
in your timeline code do this:
var ballArray:Vector.<MyBall> = new Vector.<MyBall>();
for(var i:int=0;i<200;i++){
ballArray.push(new MyBall());
addChild(ballArray(ballArray.length-1));
}
NEXT BEST OPTION
if all your balls are on the timeline already, you can still do the step from above (export for actionScript and give it a name) but do the following code:
var ballArray:Vector.<MyBall> = new Vector.<MyBall>();
var i:int = numChildren;
while(i--){
if(this.getChildAt(i) is MyBall) ballArray.push(this.getChildAt(i) as MyBall);
}
ANOTHER OPTION
If your balls are not all the same library objects, if you put them all as the only objects in a movie clip container (let's say you gave it the instance name ballContainer, you can still use this code so you don't have to give them instance names:
var ballArray:Vector.<DisplayObject> = new Vector.<DisplayObject>();
var i:int = ballContainer.numChildren;
while(i--){
ballArray.push(ballContainer.getChildAt(i));
}
You can use a string in brackets to get a property of an object. In your case, your object is referred to as this. So your syntax for getting a ball is this["ball"+index].
Try this:
function createTheArray():void{
for(var i:int = 1; i < 20; i++){
ballArray.push(this["ball" + i]);
}
trace(ballArray);
}
Referencing Properties by String isn't really a great practice though. If it's possible to create your balls dynamically as well, that would be a better implementation. You can create a ball MovieClip on your timeline, and select Export For ActionScript in the properties. Then you can use this code to instantiate 20 or more balls:
//add 20 balls to stage
var ballArray:Array = [];
for(var i:int = 0; i < 20; i++){
var ball:Ball = new Ball();
addChild(ball);
ballArray.push(ball);
}
trace(ballArray);

Modifying an array of dictionaries in Swift

I’m new to Swift and have been having some troubles figuring out some aspects of Arrays and Dictionaries.
I have an array of dictionaries, for which I have used Type Aliases - e.g.
typealias myDicts = Dictionary<String, Double>
var myArray : [myDicts] = [
["id":0,
"lat”:55.555555,
"lng”:-55.555555,
"distance":0],
["id":1,
"lat": 44.444444,
"lng”:-44.444444,
"distance":0]
]
I then want to iterate through the dictionaries in the array and change the “distance” key value. I did it like this:
for dict:myDicts in myArray {
dict["distance"] = 5
}
Or even specifically making sure 5 is a double with many different approaches including e.g.
for dict:myDicts in myArray {
let numberFive : Double = 5
dict["distance"] = numberFive
}
All my attempts cause an error:
#lvalue $T5' is not identical to '(String, Double)
It seems to be acting as if the Dictionaries inside were immutable “let” rather than “var”. So I randomly tried this:
for (var dict:myDicts) in myArray {
dict["distance"] = 5
}
This removes the error and the key is indeed assigned 5 within the for loop, but this doesn't seem to actually modify the array itself in the long run. What am I doing wrong?
The implicitly declared variable in a for-in loop in Swift is constant by default (let), that's why you can't modify it directly in the loop.
The for-in documentation has this:
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
In the example above, index is a constant whose value is automatically
set at the start of each iteration of the loop. As such, it does not
have to be declared before it is used. It is implicitly declared
simply by its inclusion in the loop declaration, without the need for
a let declaration keyword.
As you've discovered, you can make it a variable by explicitly declaring it with var. However, in this case, you're trying to modify a dictionary which is a struct and, therefore, a value type and it is copied on assignment. When you do dict["distance"] = 5 you're actually modifying a copy of the dictionary and not the original stored in the array.
You can still modify the dictionary in the array, you just have to do it directly by looping over the array by index:
for index in 0..<myArray.count {
myArray[index]["distance"] = 5
}
This way, you're sure to by modifying the original dictionary instead of a copy of it.
That being said, #matt's suggestion to use a custom class is usually the best route to take.
You're not doing anything wrong. That's how Swift works. You have two options:
Use NSMutableDictionary rather than a Swift dictionary.
Use a custom class instead of a dictionary. In a way this is a better solution anyway because it's what you should have been doing all along in a situation where all the dictionaries have the same structure.
The "custom class" I'm talking about would be a mere "value class", a bundle of properties. This was kind of a pain to make in Objective-C, but in Swift it's trivial, so I now do this a lot. The thing is that you can stick the class definition for your custom class anywhere; it doesn't need a file of its own, and of course in Swift you don't have the interface/implementation foo to grapple with, let alone memory management and other stuff. So this is just a few lines of code that you can stick right in with the code you've already got.
Here's an example from my own code:
class Model {
var task : NSURLSessionTask!
var im : UIImage!
var text : String!
var picurl : String!
}
We then have an array of Model and away we go.
So, in your example:
class MyDict : NSObject {
var id = 0.0
var lat = 0.0
var lng = 0.0
var distance = 0.0
}
var myArray = [MyDict]()
let d1 = MyDict()
d1.id = 0
d1.lat = 55.55
d1.lng = -55.55
d1.distance = 0
let d2 = MyDict()
d2.id = 0
d2.lat = 44.44
d2.lng = -44.44
d2.distance = 0
myArray = [d1,d2]
// now we come to the actual heart of the matter
for d in myArray {
d.distance = 5
}
println(myArray[0].distance) // it worked
println(myArray[1].distance) // it worked
Yes, the dictionary retrieved in the loop is immutable, hence you cannot change.
I'm afraid your last attempt just creates a mutable copy of it.
One possible workaround is to use NSMutableDictionary:
typealias myDicts = NSMutableDictionary
Have a class wrapper for the Swift dictionary or array.
class MyDictionary: NSObject {
var data : Dictionary<String,Any>!
init(_ data: Dictionary<String,Any>) {
self.data = data
}}
MyDictionary.data

as3 check for 2 objects with same property in array

I have an array, lets call it _persons.
I am populating this array with Value Objects, lets call this object PersonVO
Each PersonVO has a name and a score property.
What I am trying to do is search the array &
//PSEUDO CODE
1 Find any VO's with same name (there should only be at most 2)
2 Do a comparison of the score propertys
3 Keep ONLY the VO with the higher score, and delete remove the other from the _persons array.
I'm having trouble with the code implementation. Any AS3 wizards able to help?
You'd better use a Dictionary for this task, since you have a designated unique property to query. A dictionary approach is viable in case you only have one key property, in your case name, and you need to have only one object to have this property at any given time. An example:
var highscores:Dictionary;
// load it somehow
function addHighscore(name:String,score:Number):Boolean {
// returns true if this score is bigger than what was stored, aka personal best
var prevScore:Number=highscores[name];
if (isNaN(prevScore) || (prevScore<score)) {
// either no score, or less score - write a new value
highscores[name]=score;
return true;
}
// else don't write, the new score is less than what's stored
return false;
}
The dictionary in this example uses passed strings as name property, that is the "primary key" here, thus all records should have unique name part, passed into the function. The score is the value part of stored record. You can store more than one property in the dictionary as value, you'll need to wrap then into an Object in this case.
you want to loop though the array and check if there are any two people with the same name.
I have another solution that may help, if not please do say.
childrenOnStage = this.numChildren;
var aPerson:array = new array;
for (var c:int = 0; c < childrenOnStage; c++)
{
if (getChildAt(c).name == "person1")
{
aPerson:array =(getChildAt(c);
}
}
Then trace the array,

ActionScript: How to push to multidimensional arrays and later retrieve just one 'row'

I am reading a set of latitude & Longitude Coordinates that define a polygone area. They are keyed to an area ID and I retrieve them from a SQL database. So for example, Area ID 153 might have 20 coordinates and area ID 77 might have 11 coordinates. I wish to save these in a 2-D array indexed by the area ID, and where each coordinate pair is combined into one Google LatLng object. At a later point I wish to retrieve just one row i.e. the set of coordinates for one area, and send them to a function that accepts an array of coordinates and draws the polygon on a map. Here's what I have:
private var coordsFromSql:ArrayCollection = new ArrayCollection();
var polyArray:Array = new Array();
for each(var item:COORDINATES in coordsFromSql)
{
// add coordinates to the array for each Area id
polyArray[item.AREA_ID].push( new LatLng(item.LATITUDE, item.LONGITUDE) );
}
So this is where the first problem ocurrs. I don't know how to add a variable number of new items to a 2-D array into a known index. i.e considering polyArray like a 2-D spreadsheet how do I for example add values to 'row' 77 i.e. polyArray[77] ?
If I run the above code, I get runtime error #1010 'A term is undefined and has no properties'
The second part of the question is how do you extract one 'row' as a new array?
Using the above example to call a drawPolygon function, can I do this?
var polyArraySlice:Array = polyArray[77].slice();
drawPolygon(color, polyArraySlice );
It looks like your loading code is close, but not quite. In your for loop you're doing:
polyArray[item.AREA_ID].push(/*...*/)
but you never actually put anything in the array there.
So your load would probably be something like this:
var polyArray:Array = []
for each(var item:COORDINATES in coordsFromSql)
{
// add coordinates to the array for each Area id
var id:Number = item.AREA_ID;
if(polyArray[id] == null) { polyArray[id] = [] }
polyArray[id].push( new LatLng(item.LATITUDE, item.LONGITUDE) );
}
Getting a copy of the one of the individual locations would work just like you had:
var polyArraySlice:Array = polyArray[77].slice();
drawPolygon(color, polyArraySlice );

Resources