Casting Data Types From XML To AS 3.0
Hey guys,
I was just wondering if it's possible to cast standard AS 3.0 data types other than Number, int, uint and String from XML. I experimented with this:
ActionScript Code: var xml:XML = <root_node> <number_node>12.9876</number_node> <int_node>321654</int_node> <string_node>this is a string</string_node> <boolean_node>false</boolean_node></root_node>;var number_node:Number = xml.number_node;var int_node:int = xml.int_node;var string_node:String = xml.string_node;var boolean_node:Boolean = xml.boolean_node;trace(number_node); // returns 12.9876trace(int_node); // returns 321654trace(int_node * number_node); // returns 4177513.4904trace(string_node); // returns this is a stringtrace(boolean_node); // returns true (AS 3.0 default)
If it's only numbers and strings, would it be possible to use remoting and and something like AMFPHP, WebOrb, Zend Framework, etc. with MySQL to store other datatypes? Is there an easy solution?
ActionScript.org Forums > ActionScript Forums Group > ActionScript 3.0
Posted on: 11-04-2008, 11:56 PM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Mx.data.components - Unable To Declare Data Component Types In External Class Files
Hi all,
FlashMX 2004, v7.2:
I am trying to declare instances of data-components (DataSet and DataHolder) in external classfiles, but Flash can't find the sourcefiles for any of the data component classes in the classpath.
According to the help-files, the classname for the DataHolder component is:
Code:
mx.data.components.DataHolder
Similarly, the classname for the ComboBox component is:
mx.controls.ComboBox
Code:
mx.data.components.DataHolder
In the following, the ComboBox gets declared, and the DataHolder generates a "Class can't be loaded" error:
Code:
class my_class extends MovieClip {
var my_cbox:mx.controls.ComboBox;
var my_data:mx.data.components.DataHolder;
function my_class() {
// constructor function
}
}
Sure, it fails because there is no "components" folder in the mx.data folder (at least on my system), and I have been unable to find any DataHolder.as file anywhere either, even though the documentation gives examples that reference the mx.data.components-folder for various data components. I even tried re-installing to make sure I had not accidentally deleted any classfiles, but still no luck.
Am I missing something really obvious here? Does anyone know how to successfully import, declare or otherwise make use of data-components in external class files? Any help greatly appreciated.
Data Types (I Think ?)
I have a question that is causing a serious problem. It has to do with classes, data types( I think?) and
data from XML.
Lets say I have the following function IN A CLASS FILE
Code:
public function RectangleTile(cx:Number, cy:Number, rw:Number, rh:Number) {
super(cx,cy);
rectWidth = rw;
rectHeight = rh;
createBoundingRect(rw, rh);
}
Right... ok so I create a new instance of it with the variables that are to be passed to it.
Code:
_root.engine.addSurface (new RectangleTile (300, 200, 100, 400));
Ok, this works as expected, and does EVERYTHING I want it to do (properly) but.......
If i take data from an XML file such as this :
Code:
<myXML>
<rect x="300" y="200" w="100" h="400" />
</myXML>
I parse it like this......
Code:
var myXML:XML = new XML();
myXML.ignoreWhite = true;
myXML.onLoad = function() {
trace ("test") //It outputs this
with (_root) {
x = myXML.firstChild.firstChild.attributes.x;
y = myXML.firstChild.firstChild.attributes.y;
w = myXML.firstChild.firstChild.attributes.w;
h = myXML.firstChild.firstChild.attributes.h;
this.engine.addSurface (new RectangleTile(x,y,w,h)); /*
THIS DOES NOT WORK FOR SOME REASON!!
*/
}
}
myXML.load ("xmlFile.xml");
So really, my question is, is there anything different about the variables parsed in XML, and the
variables that are just defined in _root ?
My guess is maybe the data-types, cause on the function in my Class file, i was using strict data-typing.
It works when i just call the function in _root, by just entering numbers, but when i use variables
parsed from XML, it doesnn't do anything.
If anyone knows what data-type that I would be dealing with, it would be a great help.
Also... I am not even sure if data-typing is my problem
Thanks in advance for any help, I won't be on for about 8-10 more hours.
XML Data Types & If Statements
I'm having trouble getting my conditional statement to recognize the value of an XML item, and I assume it is due to a data typing issue. For example,
Code:
myVar = _root.questionList.firstChild.childNodes[0].childNodes[4].childNodes;
trace(myVar); // here, myVar traces as the letter "c".
if (myVar == c) {
trace("it equals c"); // This never traces
}
if (myVar == "c") {
trace("it equals c"); // This never traces
}
if (String(myVar) == c) {
trace("it does"); // This never traces
}
trace(typeof(myVar)); // this reports "object"
What am I missing?
Can I Use Custom Data Types
Hi:
Please bear with me I'm coming from the C++ environment and I'm trying to learn AS 3.0. In the C++ one can easily define and group data into custom data types (using struct or typedef). So I'm wondering if that is possible in AS 3.0 as well?
Something when I could define a single variable, say:
Code:
struct CustomType{
var i1:int;
var i2:String;
}
and then:
Code:
var v:CustomType;
v.i1 = 1;
v.i2 = "Hello world";
XML To Array, Data Types
I've been creating Arrays from XML documents and I think I'm missing something with how the values are typed. For instance, if I create an Array from a simple XML structure like:
<test>1</test>
<test>2</test>
When I populate the Array with these values, sometimes they act like numbers but sometimes they don't. For instance, I can set a Number variable equal to one of these values and it seems to work. But if I try to add or subtract I get the non a number thing. Also, if I run a typeof() on these, they are objects, not numbers.
So I may have answered my own question here, but can anyone confirm - do I need to indicate the data types when they get put in the Array? How would I do that? Thanks in advance.
XML To Array, Data Types
I've been creating Arrays from XML documents and I think I'm missing something with how the values are typed. For instance, if I create an Array from a simple XML structure like:
<test>1</test>
<test>2</test>
When I populate the Array with these values, sometimes they act like numbers but sometimes they don't. For instance, I can set a Number variable equal to one of these values and it seems to work. But if I try to add or subtract I get the non a number thing. Also, if I run a typeof() on these, they are objects, not numbers.
So I may have answered my own question here, but can anyone confirm - do I need to indicate the data types when they get put in the Array? How would I do that? Thanks in advance.
Using XML Data - Question About Types
Hello
What's the best way to integrate xml data so that it is treated as a number
I can declare the following
var val:Number;
and then read the value in from a .xml file
If I do this in the following example, flash seems to convert newVal to a string when I want a number
I assume this is because val is a value read in from a .xml file:
var newVal:Number=0;
for(var i;Number=0;i<10;i++){
newVal+=5+val;
trace(newVal);}
How can I get flash to treat val as a number and yield a numeric result rather than a string of numbers
Xml, Arrays And Data Types
I'm making a website for a DJ. He wants a calendar on it which will show people when he has a show booked so that they don't bother calling him asking for days when he's busy. This sounded simple enough. I built all the calendar, an SQL database to store the days currently booked and an PHP page to get the data from the database and format it into XML for Flash to read.
The calendar is set up as a movieclip for the year which contains movieclips for each month which, in turn, contain movieclips for each day. Like this: http://www.dynamicentry.co.uk/stuff/calendar.jpg. Each has an instance name 'y2009' for the 2009 year movieclip, 'd04' for the 4 day of a month... So the 1st January 2009 would be 'y2009.m01.d01'. Each of the day movieclips has a blank version on frame 1 and a version with 'Booked' stamped accross it on frame 2. So inorder for a day to show as booked, we need to move it from frame 1 to 2.
So I make the XML file (i'll just post the result since the PHP query to get the data works fine):
Code:
<?xml version="1.0"?>
<bookings>
<books day = "y2009.m01.d01"/>
</bookings>
So far, so good. I've got the reference I need to make a booking on January 1st 2009. Then I wrote the Flash side:
Code:
var bdayarray:Array = new Array();
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoaded);
var xml:XML;
function onLoaded(e:Event):void {
xml = new XML(e.target.data);
var cl:XMLList = xml.books;
for (var i:Number=0; i<cl.length(); i++) {
bdayarray.push(cl[i].attribute("day"));
}
for (var n:Number=0; n<bdayarray.length; n++) {
var cd;
cd = bdayarray[n];
cd.gotoAndStop(2);
}
}
loader.load(new URLRequest("bookings.php"));
Looks good to me. No luck though. I did a few traces and got some results. When I traced bdayarray[0] after the populating it in the first loop, I got 'y2009.m01.d01' like I was expecting. Surely this is fine, as that would make the line 'cd.gotoAndStop(2);' mean 'y2009.m01.d01.gotoAndStop(2);' like I want. But then I tried tracing 'y2009.m01.d01' and got '[object daybox_18]'.
Uh oh. I think I know what the problem is. I think the XML is coming though as the wrong type of data, possibly as a string rather than as a reference to the object I want. Does anyone know how I can convert the XML data into what I actually need it to be?
Thanks in advance for any help.
Declare Data Types Within An Object?
Hi all. I am creating an object like this:
Code:
var myObject:Object = new Object();
When I add new properties to the object, some will be numbers and others strings.
Is this syntax correct, or do I need to declare the data type for each property?
Code:
myObject.userName = "Joe Smith";
myObject.passed = "yes";
myObject.previousUser = "no";
myObject.programScore = 78;
myObject.screenName = "0301";
Didn't know if I should declare string, boolean and numeric data types within an object or not.
Thank you.
MaryAnne
Problem With Data Types? I Am Not Sure Need Some Advice.
I moved this to the Actionscript 2.0 thread as i am working in mx04 and had misposted in the incorrect forum
Link to new post;
http://www.actionscript.org/forums/s....php3?t=134241
hopefully i will see a response in the proper forum.
J
Problem With Data Types? Im Not Sure Whats Up
Hi all
I've posted this on another forum (were-here) but that place seems all but abandoned. Not sure what happened, it used to be a kicken forum.
Anyways i am building an image gallery, i have written a script that is supposed to go through and unload the movieClip for each of the thumbnails that were loaded. Here is the function;
Code:
var itemVar = "item";
function clearAndLoad () {
for (var i=0; i<item_count; i++) {
var currThumb = itemVar + i;
unloadMovie (item_mc.currThumb);
}
loadXml ();
};
This does not unload any of the thumbs on stage but when i change the function and just target a specific Thumbnail it works and removes the one i targeted ie;
Code:
var itemVar = "item";
function clearAndLoad () {
for (var i=0; i<item_count; i++) {
var currThumb = itemVar + i;
unloadMovie (item_mc.item0);
}
loadXml ();
};
Is this a datatype issue? I have tried changing var currThumb to var currThumb:Object = .... as well as trying the String type.
I dont what could be going wrong, a trace of currThumb seems to output the correct values as well item0 thru item5 (in this case there were six thumbs)
can anyone shed some light on this for me?
Thanks
J
Function Accepting Two Data Types
Hey all,
I want to have a function that can accept either a string or a movie clip and executes slightly differently depending on which is passed to it, but not really different enough to warrant a whole 'nother function. I have tried two functions called the same but with different parameters and it didn't work. Thanks
--Surgery
Declare Variable Data Types
From my understanding, there is no need to declare variables data type like String, Number, Array for it to function. For example:
var abc:String = "abcde";
var abc:Number = 1234;
var abc:Array = new Array();
We can write it in easier way and it is still working.
abc = "abcde";
abc = 1234;
abc = new Array();
So, what is the purpose and benefit to declare the variable specific data type?
Complex Data Types From PHP To Flash
Does anyone know of any really easy and effective ways to move complex data types from PHP into FLASH and vice-versa? A while back I made an attempt to recreate PHP' serialize() function in actionscript but it was really difficult and performance was poor.
I'm able to do it fairly easily for one dimensional arrays indexed by numbers, but when I have to pass either an object (or several objects) or when i have to pass a nested array of arbitrary complexity (such as a data tree) then I get bogged down.
I have a little experience dealing with XML in flash (working with the tree component) but it seems like so much effort when i am dealing with a new data type.
Does anyone know of any pre-packaged components or code (in actionscript and complimentary part in php) that might be useful?
Problem With Abstract Data Types
Hey everyone...
I'm new to OOP with Actionscript, and i guess i understand the basics, but the following costed me half the day and i still don't understand it:
I have two classes, Node.as and Player.as.
I have this public function in my Node class:
Code:
public function getName():String {
return nodeName;
}
Now in the constructor of my Player class, i want to access this function:
Code:
public function Player(startNode:Node) {
trace ("node: " + startNode.getName());
}
The interesting part of my main actionscript:
Code:
var q:Node = new Node("q", 150, 225);
var player:Player = new Player(q);
My constructor always traces "node: undefined".
So did i make a stupid mistake somewhere or is it just not possible to use classes in this way?
AS3 - [AMV2] Primitive Data Types
I wasn't sure where to post this question because there doesn't seem to be a suitable forum for it, so I've plopped it in the ActionScript forum for now.
I'm currently learning how to read/write ActionScript Byte Code (ABC) so that I will be able to read/write SWF files. The primitive data types used within the ABC format are a bit odd so I just need to confirm that I am using them correctly.
The u32 data type is described by Adobe like this:
"The type u32 represents variable-length encoded 32-bit unsigned integer value."
Simple enough... until we get to the part about reading and writing u32 values:
"The variable-length encoding for u32 uses one to five bytes, depending on the magnitude of the value encoded. Each byte contributes its low seven bits to the value. If the high (eighth) bit of a byte is set, then the next byte of the abcFile is also part of the value."
Now I'm assuming that the high (eighth) bit of each byte is the first bit in the bit sequence, so the X in the following byte would be the high bit... X0000000.
This is the code I am currently using to read a u32 value:
Code:
var value:uint = 0;
while( true )
{
var byte:uint = source.readUnsignedByte();
value += byte & 127;
if( ( byte >> 7 & 1 ) == 0 )
{
break;
}
}
I'm just looking for someone to tell me if that is the correct way to read the value because I seem to be getting some strange values returned.
Also, this is what Adobe say when it comes to signed values:
"In the case of s32, sign extension is applied: the seventh bit of the last byte of the encoding is propagated to fill out the 32 bits of the decoded value."
Is it possible for someone to give that to me in Layman's Terms because it isn't making much sense to me at the moment.
Thanks.
[F8] Saving And Loading Complex Data Types
I have a need to turn a collection of complex data types into a string that can be saved using a server side php script then be able to load it back again.
I don't want to change the PHP script at all?
this is an example:
PHP Code:
myArray[5]={mo:"mike", me:{moor:"morges", meat:"mooe", ahdjsfkg:"agsdl"}};
don't forget the array!
TYVM
Mistron
Sending Complex Data Types To Amfphp With As3
Hello,
Has any one figured out a good way to send complex data types to amfphp yet? It seems like the functionality to send Arrays, Objects, and custom classes up stream has become a little tricky in AS3.
The problem, as I understand it, is that the basic complex data types in AS3, like Array and Object, have become "looser" and now behave more like a custom class then a true data type.
My first thought was to treat like a custom class in amfphp, but according to the instructions here: http://amfphp.org/docs/classmapping.html , It requires the use of Object.registerClass which is not in the standard Actionscript library any more.
I could probably get an array up there by serializing it w/ .toString() then explode() it in php, but this not an ideal solution due to the processing overhead and added development time to create custom serializers for my Objects.
Have any of you crafty fellows out there come up with anything yet? If so, I would appreciate greatly any and all suggestions. Even if its just a hunch.
Thanks for your time!
...aaron
PS: Here is some code I've been playing with that will demonstrate the issue.
AMFPHP Service
PHP Code:
<?php
//AMFPHP VERSION 1.2
class TestService {
function TestService() {
// Define the methodTable for this class in the constructor
$this->methodTable = array(
"testMethod" => array(
"description" => "This is a description",
"access" => "remote"
)
);
}
function testMethod ($data) {
ob_start();
var_dump($data);
$buffer = ob_get_contents();
ob_end_flush();
return $buffer;
}
}
?>
Flex 2 Sample App
Code:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
public function callRemoteMethod():void {
var gateway:NetConnection = new NetConnection( );
var responder:Responder = new Responder(handleResponse, handleError);
gateway.connect('http://localhost/amfphp/gateway.php');
var temp:Object = {var1:"Hello", var2:"World"};
gateway.call( "TestService.testMethod", responder, temp );
}
private function handleResponse( result:Object ): void {
idText.text = result.toString();
}
private function handleError( result:Object ): void {
idText.text = result.toString();
}
]]></mx:Script>
<mx:VBox width="100%" height="100%">
<mx:Button label="GO" click="callRemoteMethod()"/>
<mx:TextArea id="idText" width="100%" height="100%" />
</mx:VBox>
</mx:Application>
A few examples:
Object:
var temp:Object = {var1:"Hello", var2:"World"};
Response:
Error #2044: Unhandled NetStatusEvent:. level=error, code=NetConnection.Call.BadVersion
Array:
var temp:Array = [1, 2, 3];
Response:
Same
But if I do this:
var temp:Array = [1, 2, 3];
gateway.call( "TestService.testMethod", responder, temp.toString() );
Response:
string(5) "1,2,3"
---
Thanks for taking the time to read all this. I'm looking forward to your ideas!
=D
Array, Object, List...? Data Types Help
I'm making a game and it requires me to maintain hundreds of lists of objects.
Elements are frequently removed from these lists, and the entire lists are frequently sorted and scanned.
My Question: What is the most efficient data type for my needs?
Arrays work, but in order to remove an item I must scan the entire array for the matching object and then splice the object out. Here's an example of the type of function I'm using to remove an object from the list. Keep in mind that all of my game elements are provided a unique id for use with such searches.
Code:
public function removeArrayElement(id:int){
var arraylength:int=myArray.length;
for(var i:int=(arraylength-1);i>=0;i--){
if(arraylength[i].id==id){
myArray =myArray.slice(0,i).concat(myArray.slice(i+1));
return;
}
}
}
This works but there's got to be a better way.
It seems that Objects would represent a more efficient way since I could access an element without a loop, but there is no way that I know of to remove an element or to return all of the contents of one at once.
I've seen some information in the AS3 Language Reference about ArrayCollections and iLists etc, but I really am not quite sure how to use them, and I'm not sure if they would suit my purposes.
My goals again.
Maintain Lists of Objects where I may:
1#Add a Class of arbitrary type;
2#Remove an Element efficiently by reference or ID(can not be index position)
3#Retrieve the whole list of contents as references.
I've plenty of other work to do on the game so there's no real hurry, but this is in the back of my mind as something that I want to streamline, and I haven't been able to find any good information on the subject.
If no better way is known to this forum then I'd at least appreciate some reassurance that the way I'm doing it is about as good as other people may have tried.
Thanks -Rory-
.NET Web Service Interoperability Data Types For Flash
I'm implementing a web service which will be used by clients from different platforms. I would like to define .NET properties instead of public members for all my return data objects.
Can clients from all flash consume return data in the web service which is generated from .NET data class which only contains public properties?
Second, what types of data cause trouble for interoperability?
cheers and thanks for your help.
.NET Web Service Interoperability Data Types For Flash
I'm implementing a web service which will be used by clients from different platforms. I would like to define .NET properties instead of public members for all my return data objects.
Can clients from all flash consume return data in the web service which is generated from .NET data class which only contains public properties?
Second, what types of data cause trouble for interoperability?
cheers and thanks for your help.
Kirupa's Abstract Data Types Tutorial
Its been a while since my last post, i've been very busy with my school and work that i barely have time to open flash.
Here's my Question:
Can somebody tell if its posible to make an edge just one way and how ?
An example of what im asking for its like this:
Let's pretend i have 3 nodes: a, b and c, and 3 edges "a-b", "b-c", and "c-a"
if i select a and c the path selected is "c-a" instead of "a-b", "b-c".
Importing Multiple Data Types From A Text File
I have a text file where I want to pull out multiple variables of different types.
Take for example the following
GalleryActive = true;
ImageDirectory = "Interior";
subGallery[1] = Before;
subGallery[2] = Construction;
subGallery[3] = After;
Images[1] = 15; // number of images in sub gallery "Before"
Images[2] = 10; // number of images in sub gallery "Contruction"
Images[3] = 17; // number of images in sub gallery "After"
MainHeader = "The Gradow Estate";
SubHeader = "Exploring the Interior";
I have pulled arrays out of a file before with parsing, but this was only an array and not multiple variables including arrays. Can anyone help me with this? I'm not even sure if this is a good listing convention. Basically I need to import this data from a text file and I was wondering if anyone could show me some sample code for this?
Thank you in advance.
2 Basic Questions - Data Rates And File Types
Greetings! Started using flash to help my boss with his website and he's asked me two questions I don't know the answer to!
1. What is the opportune data rate for the general population for videos when using flash? He has a small production company and most of the people he is selling to have cable if not T1+. I've advised a data rate of 300 kbps (but that would have to include audio too )... does that seem right to you?
2. It currently takes a VERY long time for me to export a movie to test it and see how it all works and looks. Currently all of the pictures in the system are in .PSD format. If I were to make these all JPEGs and swap them all out for these smaller files would this help reduce export time at all?
Thanks so much!
Trigger Code Hinting On Strict (or Strong) Data Types
Hey!
I've seen Lee get back the code hints whenever his is typing some code on the timeline. For instance
var bmp:BitmapData = new BitmapData(foo._width, .... get back code hints here!, ...... );
What is the command/key stroke to get those back? I tried hitting control-spacebar like the livedocs say, but that only works if no params have been entered.
Any help?
cheers.
:)
"In(Object){...}" Function? Data Types For Object Variables?
I can create an object and use dot syntax to create, or reference, variables inside of it.
But how can I specify the data types of these variables?
Also, is there some way I can enter the namespace of the object over a number of lines via {}s instead of using repetitive dot syntax?
Thanks in advance.
AS3: Casting
What is the difference between the following two statements?
ActionScript Code:
oBj1 = XML(oBj2);
and
ActionScript Code:
oBj1 = oBj2 as XML;
TIA, Eugene
Casting
Hi. Why does the attached lines return true, all three of them?
I understand the first returning true, I could even understand the second (strictly from the documentation it's ok to return true, but I think the "as" word is misleading), but I definitely don't understand why the third one is true.
Could some one explain me the exact semantics of those thing?
Thanks,
FaQ
Attach Code
var a:Sprite = new Sprite();
trace(a is Sprite, " = a is Sprite");
trace((a as DisplayObject) is Sprite, " = (a as DisplayObject) is Sprite");
trace(DisplayObject(a) is Sprite, " = DisplayObject(a) is Sprite");
Type Casting
I have an input box where I want to put a number value that begins with zero. "016" I then put this value into an array and it drops the zero. I want the number value to be treated like a string. I have tried using the myText.toString() function, and the String(myText) constructor, but it still takes off the zero at the begining. does anyone have any ideas, or has anyone experienced this before?
Web Casting And Forums?
Hi folks, I need a pointer in the right direction here!
I have to setup a live webcam and a stills webcam on 10min refresh, aslo I need to make a forum page all in flash mx2004, can anyone point me in the direction of some good tutorials that I can just dive into?
Any help greatly appriciated.
Cheers.
Casting To Integer - What's Going On?
Look at this piece of code:
---------------------
alint = "0060";
trace (int(alint));
---------------------
this gives the value 48.
-48!?!? Where does that come from?
Help appreciated!
Casting An Array To An Int
I have this trace statement that reads out a array of an sql database-
trace(re.result._items[row][name]);
It prints this
2
8 *
3
1
5 *
2
0
5 *
1
I am trying to pull out the numbers with a * and make them seperate int's. Whats the best way to do this? Thanks in advance!
Casting To Integer?
Hi,
I am new to actionscript .
How do I cut off the decimal part of a Number to get only an integer.
I want to display % complete of an upload, and I want for example
75.43% to read 75%
So there is no integer type in ActionScript 2? only Number?
Is there some way to cast the darn thing ?
Or how do i do it?
-thanks
Type Casting
Is there any way to convert String to Number? Flash doesn't convert it automaticly in my code. I used .valueOf but I didn't work.
Instanceof And Casting; Anyone?
I'm setting up a nice event-handling class for taking care of the WebServiceConnector. I'm trying to do a clean cast of the result object, so I can get it back into type safety before handing it off to whatever class asked for it.
This (and variations thereof) is what I've been trying for a while now:
Code:
private function resultListener(res:Object)
{
if(res.target.results instanceof Boolean)
{
var return:Boolean = Boolean(res.target.results);
}
else if(res.target.results instanceof String)
{
var return:String = String(res.target.results);
}
else if(res.target.results instanceof Number)
{
var return:Number = Number(res.target.results);
}
else if(res.target.results instanceof Array)
{
var return:Array = Array(res.target.results);
}
else if(res.target.results instanceof Object) //(should) always true
{
var return:Object = Object(res.target.results);
}
}
None of these if-clauses are ever true. I would suspect - at the very least - that "instanceof Object" would be a catch-all, but it isn't. So... what type is results?
Do you have any idea as to how I can create this function - casting the result to a known AS-type?
Casting To Boolean From XML
How would you get Flash to recognise a value passed via XML as a boolean true/false...
Ive tried casting it to force it to be Boolean, which I think ive done correctly as:
ActionScript Code:
var run:Boolean = Boolean(xmlData.run.text())
Ive also tried removing the .text() however it always goes true, anyone know what i'm doing wrong...?
XML Node And Casting To Int
Just came across a strange behaviour in my Flex app when casting a xml node value to int.
Code:
//The attibute is set to '2'
var selectedCodeId:int = int(selectedFilterTreeNode.@codeId); //gave 2
var selectedCodeId:int = selectedFilterTreeNode.@codeId as int; //gave 0
Anyone seen this before?
SharedObject Casting
I'm storing a custom class object in a local SharedObject file, and then later trying to retrieve it. When I try to retrieve it, I get the following error:"Type Coercion failed: cannot convert Object@10547d59 to AS3.accounting.UserAccount."
The "@10547d59" changes every time obviously since it is just a temporary type name.
The 'basic' code to save the object is this:
ActionScript Code:
public function createUser(name:String, password:String):Boolean{
var users:Object = userAccounts.data.users;
if(!users) users = new Object();
if(users[name]) return false;
user = new UserAccount(name, password);
users[name] = user;
userAccounts.setProperty("users", users);
userAccounts.flush();
return true;
}
The 'basic' code to load the object is this:
ActionScript Code:
public function findUser(name:String, password:String):Boolean{
var users = userAccounts.data.users;
if(!users || !users[name]) return false;
user = users[name];
return true;
}
The object being sent-to the file is of type UserAccount, and the data retrieved is attempting to be placed in a UserAccount object, but the retrieved data doesn't seem to remember what type it was, and since Object is higher in the inheritance hierarchy it won't naturally convert it for me.
If you have any ideas, please feel free to share them. Otherwise, when I figure out the best solution I'll post it below.
FLVMovie Casting
Hi there...
I'm new to the hole AS3 stuff... so sorry if the question is kind of silly.
For the Question:
I created my own FLVMovie Class:
Code:
package {
import flash.events.MouseEvent;
import fl.video.FLVPlayback;
public class FLVMovie extends FLVPlayback{
public function FLVMovie(){
this.addEventListener(MouseEvent.CLICK,clickHandler);
}
public function clickHandler(btn){
trace('movie click');
this.stop();
}
}
}
No for the question itself.... I have a existing FLVPlayback on the Stage... is there a way to convert / cast it into a FLVMovie so it has the Click event handler?
thx...
Casting MC To FLVPlayback
I need to create a FLVPlayback component dynamically, but it seems I can't cast the MovieClip returned by attachMovie to FLVPlayback class, it always return null. If I create a new document, it works well. I think this problem happen when I tell Flash to export classes at frame 2, but my component is being attached at frame 3. Is there a way to export classes for frame 2 and still being able to cast the Component?
Casting Error In CS 3
Hi guys,
I maintain an API for which have a huge chunk of its code loaded dynamically from the server. This is all fine and dandy until I try to parse costume class instances back and forward between the current file and the loaded remote API file.
Basically I get a cast error as below:
TypeError: Error #1034: Type Coercion failed: cannot convert Nonoba.api.net::Connection@408e47e1 to Nonoba.api.net.Connection.
My initial ida for a solution was to simply just accept :* and do
var conn:Connection = parsedObject as Connection
but this results in a null value
Any ideas?
Casting Woes
Imagine a quick scenario;
_thumbs is a Sprite, inside it is a custom class called "thumb1" (extends MovieClip) and inside that is a sprite called "nail". Nail is a libraryitem. Nail has a child called blocker (that's in the library item already).
Now, this works fine;
ActionScript Code:
var t = _thumbs.getChildByName("thumb"+i);var sx = t.getChildByName("nail");TweenMax.to(sx.blocker,1,{yada});
Wheras this works fine, I can't for my life figure out how to cast these variables. If I try making them DisplayObjects or Sprites or MovieClips or whatnot it all throws error with either implicit coercion or reference to a undefined method getChildByName
Grateful for any insight.
Casting Vs. Converting
hey, thought it might be useful to some to see these tests i ran:
ActionScript Code:
private function testTypeConversions () :void {
var i:int = 10;
trace("int as String:"+(i as String)); //null
trace("String(int):"+String(i)); //"10"
trace("int.toString():"+i.toString()); //"10"
var num:Number = 0.5;
trace("Number as String:"+(num as String)); //null
trace("String(Number):"+String(num)); //"0.5"
trace("Number.toString():"+num.toString()); //"0.5
var str:String = "2.3";
trace("String as int:"+(str as int)); //null
trace("int(String):"+int(str)); //2
trace("parseInt(String):"+parseInt(str)); //2
trace("String as Number:"+(str as Number)); //null
trace("Number(String):"+Number(str)); //2.3
}
the moral of the story here is that AS2-style casting:
ActionScript Code:
Type(value)
can actually convert primitives to a different datatype, while AS3-style casting:
ActionScript Code:
value as Type
will not convert (and will return null if the cast is invalid).
while it may be tempting, then, to just stick with AS2-style casting, i'm pretty sure it's preferable to use AS3-style casting and conversion functions like toString, parseInt, and parseFloat. that's more in keeping with other OO languages.
also, as a side note, the AS3 language reference actually refers to AS2 casting functions as conversion functions. that's what they do...don't (do what i did and) confuse them with casting via 'as'!
Casting A String To An Object
I'm having trouble passing an object parameter using a string concatenation in a for loop...
in the for loop, I duplicate movieClips, copying a movie called "glass" and try to register it's speeds with the register() function below.
for (i = 1; i <= numObjects; i++) {
duplicateMovieClip(glass,"glass" + i, i);
register("glass" + i,20,20,20);
}
function register(object, xspeed, yspeed, rspeed) {
objects.push(object);
object._xspeed = xspeed * (2 * Math.random() - 1);
object._yspeed = yspeed * (2 * Math.random() - 1);
object._rspeed = rspeed * (2 * Math.random() - 1);
}
unfortunately, when passing tmp as "glass" + i, register thinks its a string, not an object. The object appear on stage, but doesn't move. If I hard code register() passing in as register(glass2,20,20,20) it does move.
How do I cast the string I pass in as an object?
Casting (like In Java?) Or Help In This Thing
hi guys,
how do you cast, like you do in Java?
string = (String)(skaljeasjkle)
..
or, you can just help me to do this
you see, i have a class Q. i named my instances of these q0, q1, q2 to qn.
in this class Q, i have vars question, a0, a1, a2, a3.
i want flash to read the Q (q0, q1, q2, qn) depending on the counter at a moment in time. for example...
var temp = (Q)(q + "" + counter);
//so i can access the qn's vars..
trace(qcounter.a1);
i THINK you can do something like that in Java but even there i'm already rusty.
if i don't use this method, i'll have a HUGE if statement.. or switch. and of course, i wouldnt want to do that.
Type Casting Problem
Hello gurus,
I have a problem:
while loading a number from a variable in a text file, into a script, i found that the number is not really a number but a string or a character. But i need it as a number to perform some operation. Can you please help me on how to convert that??
Type Casting To A Class Name
I'm trying to type cast an item in an array (inventoryList) to a Class, so I can addChild the movieClip to the stage. The items in the inventory 'carrotIcon and passportIcon' - I also have movieClips of the same name in the library with their own classes.
It works when I just change the line to 'addIconName = new carrotIcon()' for example. Maybe the answer is that I should use something else than 'Class' as the type cast. I've tried MovieClip to no avail.
var itemName:*;
var inventoryList:Array = new Array();
inventoryList.push("carrotIcon");
inventoryList.push("passportIcon");
for (var i:int = 0; i < (inventoryList.length); i++)
{
itemName = Class(inventoryList[i]); //this is the line I'm having problems.
addIconName = new itemName();
addChild(addIconName);
}
Thanks for looking!
Joe
|