AS3: Casting to Vector - actionscript-3

I am trying to create a vector from unknown class, but it fails, any ideas about how to do it?
This is what i tried:
var vector:Vector = new Vector(); // throw exception
function base():void{
var vector:Vector.<String> = createVector(String);// throw classCastException
}
function createVector(cls:Class):*{
var array:Array = new Array();
for(var i:int = 0; i < 10; i++){
var element:cls = new cls();
array.push(element);
}
return Vector(array);
}

Vector is expecting a parameter type so you can't do this like you want, but using getQualifiedClassName to get class info you can construct a string that will enable you to call the Vector. constructor using getDefinitionByName :
Ex.
// get class parameter name
var className:String=getQualifiedClassName(String);
// get the Vector class object for the given class
var o:Object=getDefinitionByName("__AS3__.vec::Vector<"+className+">");
// call the constructor
var v:*=o.prototype.constructor(["hello", "world"]);
So your function can be written as:
public function createVector(cls:Class):*{
var cn:String = getQualifiedClassName(cls);
var o:Object = getDefinitionByName("__AS3__.vec::Vector.<"+cn+">");
var array:Array = [];
for(var i:int = 0; i < 10; i++){
var element:* = new cls();
array.push(element);
}
return o.prototype.constructor(array);
}
live example at wonderfl:
http://wonderfl.net/c/pkjs

Based on #Patrick answer I found a working solution.
Check it out:
function createVector(cls:Class):*{
var className:String = getQualifiedClassName(cls);
var vectorClass:Class = getDefinitionByName("__AS3__.vec::Vector.<"+className+">") as Class;
var vector:* = new vectorClass(10);
for(var i:int = 0; i < 10; i++){
var element:MyClass = new cls(); // may be Object or Object extends cls
vector[i] = element;
}
return vector;
}

Related

AS3. MouseEvent click in (for) loop function

am need here onClick one of the movieclip loop_Task.addChild(tee) trace the tee.task_id.text which one is clicked from the list for ex. this
output be like
(List Clicked : 100)
(List Clicked : 101)
or onClick passed the item data it's already clicked to new class screen
here is my code
public function resultHandlerList_items(event:SQLEvent):void
{
// TODO Auto-generated method stub
var result:SQLResult = selectStmt1.getResult();
var numResults:int = result.data.length;
for (var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
var tee:listview_mc = new listview_mc
loop_Task.addChild(tee)
tee.y = 270*i
tee.task_id.text = row.Tid
tee.task_tit.text = row.Ttitles
tee.task_stime.text = row.Stime
tee.task_subject.text = row.Subject
tee.addEventListener(MouseEvent.CLICK, onClickList)
}
function onClickList(e:MouseEvent):void{
trace("List Clicked : " + e.currentTarget)
}
}
in the first thanks to #Organis He give me the way to fix my code and he give me info about how to talk with the compiler with exactly how to make the compiler understand your code this code the fix (e.currentTarget as listview_mc) and now this my code after fixing and i do take a public var String and pass it to other Class
public function resultHandlerList_items(event:SQLEvent):void
{
// TODO Auto-generated method stub
var result:SQLResult = selectStmt1.getResult();
var numResults:int = result.data.length;
for (var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
var tee:listview_mc = new listview_mc
loop_Task.addChild(tee)
tee.y = 270*i
tee.task_id.text = row.Tid
tee.task_tit.text = row.Ttitles
tee.task_stime.text = row.Stime
tee.task_subject.text = row.Subject
tee.addEventListener(MouseEvent.CLICK, onClickList)
}
function onClickList(e:MouseEvent):void{
trace("List Clicked : " + (e.currentTarget as listview_mc).task_id.text)
ts_id = (e.currentTarget as listview_mc).task_id.text;
sport._sport.Remove_Home_Sc(e);
trace("done")
}
}

how addChild is being used in below AS3 code?

For addChild(iconObject) (second line inside function startAmoebaAttack()), can anyone explain me where will iconObject be added in? because it doesn't have any object or array before addChild like iconObject.addChild(newSoldier);
private var iconObject:Sprite;
public function startAmoebaAttack() {
iconObject = new Sprite();
addChild(iconObject);
createSoldierIcon();
}
public function createSoldierIcon(){
soldierIcon = new Array();
for(var i:uint = 0; i<soldierLeft; i++){
var newSoldier:SoldierIcon = new SoldierIcon();
newSoldier.x = 65 + i *24;
newSoldier.y = 590;
iconObject.addChild(newSoldier);
soldierIcon.push(newSoldier);
}
}
It will automatically run it in this's context (same as this.addChild(iconObject)). In your case this is descendant of DisplayObjectContainer .

AS3 Event Handler stuck in infinite loop

I have a problem with my event handler. I am trying to use URLRequest to load some data from a database. But it's stuck in an infinite loop. Any suggestion of why is it looping, even after all the data is loaded?
The result is pushed into an array.
Code:
public function Listingdetailinfo()
{
somedata = SearchVectorTest.lists;
SrSend = new URLRequest("http://testurl/requestimage.php");
SrSend.method = URLRequestMethod.POST;
Arvariables = new URLVariables ;
SrSend.data = Arvariables;
SaLoader = new URLLoader();
SaLoader.dataFormat = URLLoaderDataFormat.TEXT;
Arvariables.data1 = somedata[0];
SaLoader.load(SrSend);
SaLoader.addEventListener(Event.COMPLETE,Asandler);
function searchVOs( pic:String )
{
this.pic = pic;
}
function Asandler(event:Event):void
{
trace(event.target.data);
// retrieve data from php call
var resultString:String = event.target.data;
trace(event.target.data);
// parse result string as json object and cast it to array
var resultArray:Array = JSON.parse(resultString) as Array;
var len:int = resultArray.length;
trace(resultString);
// create vector of SearchVO
var searchVOs:Array = new Array();
// get the length of the result set
var i:int;
for (i=0; i<len; i++)
{
searchVOs[i] = new Listingdetailinfo();
searchVOs[i].pic = resultArray[i].pic;
myArray.push(searchVOs[i].pic);
}
}
}
I assume your code represents the constructor of Listingdetailinfo class. The reason of your "infinite loop" is that you are creating new instances of this class in
searchVOs[i] = new Listingdetailinfo();

Error joining AS2 with AS3

I have problems joining two scripts into one.
This is main part of the script: AS3.
And this is already joined script.
And here is part of the code that I need to import (AS2) :
stop();
var banners:Array = new Array();
var imagePaths:Array = new Array();
var links:Array = new Array();
var bodyTexts:Array = new Array();
var imageTime:Number;
var numberOfBanners:Number;
var isRandom:String;
var showHeader:String;
var bannersXML:XML = new XML();
bannersXML.ignoreWhite = true;
bannersXML.load("banners.xml");
bannersXML.onLoad = function(success) {
if (success) {
trace("XML LOADED");
imageTime = parseInt(this.firstChild.firstChild.firstChild)*1000;
numberOfBanners = parseInt(this.firstChild.childNodes[1].firstChild);
isRandom = this.firstChild.attributes["isRandom"];
showHeader = this.firstChild.childNodes[2].attributes["showHeader"];
var bannerSequence:Array = new Array();
if (isRandom == "true") {
//Make a random sequence
while (bannerSequence.length<numberOfBanners) {
newRandomNumber = random(numberOfBanners);
//Make sure that the random one chosen is not already chosen
for (var i = 0; i<=bannerSequence.length; i++) {
if (newRandomNumber != bannerSequence[i]) {
alreadyThere = false;
} else {
alreadyThere = true;
break;
}
}
//Add only random values that aren't in the array
if (!alreadyThere) {
bannerSequence.push(newRandomNumber);
}
}
} else {
for (var i = 0; i<numberOfBanners; i++) {
bannerSequence.push(i);
}
}
}
//Read XML in the Random Order Chosen
for (var i = 0; i<numberOfBanners; i++) {
banners.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].firstChild.firstChild.toString());
bodyTexts.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].childNodes[1].firstChild.nodeValue);
imagePaths.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].childNodes[2].firstChild.nodeValue);
links.push(this.firstChild.childNodes[2].childNodes[bannerSequence[i]].childNodes[3].firstChild.nodeValue);
}
play();
};
//Start the image counter at 0
var imageCounter = 0;
I get erorr in this part of the code
function doRandArray(a:Array):Array {//make random array
var nLen:Number = a.length;
var aRand:Array = a.slice();
var nRand:Number;
var oTemp:Object;
for (var i:Number = 0; i < nLen; i++) {
oTemp = aRand[i];
nRand = i + (random(nLen – i));
aRand[i] = aRand[nRand];
aRand[nRand] = oTemp;
}
return aRand;
}
When I run it, I get an error in this place:
nRand = i + (random(nLen – i));
Scene 1, Layer 'Layer 1', Frame 1, Line 265 1084: Syntax error: expecting rightparen before i.
as2 random(random(nLen – i)); is generate 0,1,...nLen-i-1. not floating only int value.
correct as3 code is int(Math.random()*(nLen-i)); or Math.floor(Math.random()*(nLen-i));
as2: random()
as3: Math.random()
In ActionScript 3 the random function is a little bit different from what it was in as2 code, just change the offending line to:
nRand = i + Math.random()*(nLen-1);
This should fix all errors and work just the same.
EDIT: as #bitmapdata.com indicated, for this to run the same as in as2 the random value must be truncated (stripped of its decimal values). Besides the couple of possibilities he suggested, I would personally just change nRand's type to uint on declaration:
var nRand:uint;
You can also change the iterator type to var i:uint. Less memory usage is always good ;)

How to create a series of class instances in a for loop, as3

In my library I have a bunch of classes named tip1, tip2, tip3, tip4...and so on. Is it possible to create one instance of each on the stage using a for loop? I tried this but it didn't seem to work.
var tips:int = 12;
for(var i:int = 1; i<=tips; i++){
var tipName:String = "tip"+i
var tip:MovieClip = new tipName();
tip.name = "tip" + i
tip.x = stage.width;
tip.y = 0;
addChild(tip);
}
Any help would be appreciated. Thanks!
You were missing the "getDefinitionByName" part.
// Up top
import flash.utils.getDefinitionByName;
// Down below
var tips:int = 12;
for (var i:int = 1; i < tips; ++i ) {
var myClass:Class = getDefinitionByName('tip' + i) as Class;
var tip:Object = new myClass();
tip.name = "tip" + i;
....
}
Instead of
var tip:MovieClip = new tipName();
Try (written from memory)
var clazz:Class = getDefinitionByName(tipName) as Class;
var tip:MovieClip = new clazz();
Also, you generally want to use stage.stageWidth instead of stage.width, since the latter will return the stage bounding box width (which might not be the same as the area the swf file covers).