AS3 Concatenating Reference Not Working - actionscript-3

I'm struggling to concatenate a reference to a variable from a XML document. I'm trying to get:
chat_History.Msg.chatMessage1, chat_History.Msg.chatMessage2, chat_History.Msg.chatMessage3
It's instead over-riding the reference and turning into the value '0', '1', '2'. My code:
public function onReceivedChatData(Event:LoaderEvent)
{
var raw_user_info = LoaderMax.getContent("chatHistory");
var chat_History:XML = XML(raw_user_info);
if (chat_History.Msg)
{
trace("ReceivedChatData");
trace(chat_History);
for (var i:int = 0; i < int(chat_History.chatLength); i++)
{
var chatString:String = chat_History.Msg.chatMessage;
chatString += i.toString();
shopchatbox.shop_chat_window.text = shopchatbox.shop_chat_window.text + "\n" + chatString;
shopchatwidebox.shop_chat_window.text = shopchatwidebox.shop_chat_window.text + "\n" + chatString;
}
}
else
{
trace("chat_History XML Does Not Exist!!! Noooo :( ");
trace(chat_History);
}
}
The chatLength is 3, and it's calling the for statement 3 times correctly, however chatString isn't referencing it's variable (a string) correctly and only appears as '0', '1', '2'. I'm guessing I'm not concatenating this right and that's the problem, but I'm not sure how to do this?
Thanks!

chatString += i.toString();
That's going to give you the indexes 0, 1, 2. i just stores increments for iteration. Not the values from chat_History.Msg.chatMessage So you're adding i onto the content of chatString, not setting the variable name.
var chatString:String = chat_History.Msg.chatMessage;
chatString += i.toString();
Your code here says, take chatString, and set it to the value chat_History.Msg.chatMessage, then concatenate i as a String onto the content of chatString
If you wanted to access your variables by a variable name, I believe you'd do something like this;
var chatString:String = chat_History.Msg["chatMessage"+ String(i+1)];
So i+1 = 1, 2, 3. Which should mean you're accessing chat_History.Msg.chatMessage1, chat_History.Msg.chatMessage2 and chat_History.Msg.chatMessage3
Remove the line;
chatString += i.toString();
I'm afraid I can't test this as I don't have the XML code, but hopefully that gives you a general idea. I'm not 100% sure I've got calling a variable by a variable name correct, but it is possible to call a variable by a string name.
Edit:
After doing a little testing, the syntax appears to be correct, so that should get you the values from chat_History.Msg

Related

Is there a simple way to have a local webpage display a variable passed in the URL?

I am experimenting with a Firefox extension that will load an arbitrary URL (only via HTTP or HTTPS) when certain conditions are met.
With certain conditions, I just want to display a message instead of requesting a URL from the internet.
I was thinking about simply hosting a local webpage that would display the message. The catch is that the message needs to include a variable.
Is there a simple way to craft a local web page so that it can display a variable passed to it in the URL? I would prefer to just use HTML and CSS, but adding a little inline javascript would be okay if absolutely needed.
As a simple example, when the extension calls something like:
folder/messageoutput.html?t=Text%20to%20display
I would like to see:
Message: Text to display
shown in the browser's viewport.
You can use the "search" property of the Location object to extract the variables from the end of your URL:
var a = window.location.search;
In your example, a will equal "?t=Text%20to%20display".
Next, you will want to strip the leading question mark from the beginning of the string. The if statement is just in case the browser doesn't include it in the search property:
var s = a.substr(0, 1);
if(s == "?"){s = substr(1);}
Just in case you get a URL with more than one variable, you may want to split the query string at ampersands to produce an array of name-value pair strings:
var R = s.split("&");
Next, split the name-value pair strings at the equal sign to separate the name from the value. Store the name as the key to an array, and the value as the array value corresponding to the key:
var L = R.length;
var NVP = new Array();
var temp = new Array();
for(var i = 0; i < L; i++){
temp = R[i].split("=");
NVP[temp[0]] = temp[1];
}
Almost done. Get the value with the name "t":
var t = NVP['t'];
Last, insert the variable text into the document. A simple example (that will need to be tweaked to match your document structure) is:
var containingDiv = document.getElementById("divToShowMessage");
var tn = document.createTextNode(t);
containingDiv.appendChild(tn);
getArg('t');
function getArg(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

How do I return a value from the Function used to initialize an array in Mathematica

In this example I'm trying to create an Array of length 5 where each ellement contains the number of times .3 can be summed without exceeding 1. i.e. 3 times. So each element should contain the number 3. Here is my code:
Array[(
workingCount = 0;
workingSum = 0;
done = false;
While[! done,
workingSum = workingSum + .3;
If[workingSum > 1, done = true; workingCount, workingCount++]
])
, 5]
In the 3rd to last line there I have workingCount without a ; after it because it seems like in Mathematica omitting the ; causes the value a statement resolves to to be returned.
Instead I get this:
{Null[1], Null[2], Null[3], Null[4], Null[5]}
Why does this happen? How can I get my program to do what I want it to do? i.e. In the context of the function passed to Array to initialize it's elements, how to I use complicated multi-line functions?
Thanks in advance.
Two things:
First, one way to be able to do that in Mathematica is
Array[
Catch[
workingCount = 0;
workingSum = 0;
done = False;
While[! done,
workingSum = workingSum + .3;
If[workingSum > 1,
done = True; Throw#workingCount,
workingCount++]]] &,
5]
Second, and most important: you never should do that in Mathematica! Really.
Please visit for example the Stack Exchange site for Mathematica, and read the questions an answers there to get some grip on the programming style.
Your problem comes from the fact that you are trying to initialize your array, but are trying to do so without an explicit function call - which is what you need to do.
See here for documentation on Arrays in Mathematica:
http://reference.wolfram.com/mathematica/ref/Array.html
That aside, and minor errors (True and False have to be capitalized), this is what you want to do:
f[x_] :=
(
workingCount = 0;
workingSum = 0;
done = False;
While[done != True, workingSum = workingSum + 0.3;
If[workingSum > 1, done = True, workingCount++]
];
Return[workingCount];
);
Array[f, 5] (* The array here is generating 5 values of the return value of f[x_] *)

How to assign variables to an instance name?

I have a code in AS3 that works perfectly, but I have mane repeated methods and functions, they are the same but using different instance names, so I would like to replace the instance name with a variable to avoid re-writing too much code.
here is part of my code:
urb_mc.urb.select(0);
trace("Urb: " + urb_mc.urb.selectedIndex);
I want to replace in this case "urb" with a variable so I tryed this:
var estado = currentLabel;
trace("este es mi estado " + estado);// this is ok = "urb"
//now I need to inset the variable in my code:
String(estado)+_mc.String(estado).select(0);//thi is so wrong!
trace("Urb: " + String(estado)+_mc.String(estado).selectedIndex);//thi is so wrong!
Any idea?
Thanks in advance
Try using:
this[estado+"_mc"][estado].select(0);
trace(this[estado+"_mc"][estado].selectedIndex);
Sorry for all the edits!
Thanks for the challenge! I learned there is such a thing as a multidimensional array operator for objects.
Part 2
Try this:
var tweenNameArray:Array = ["Name1", "Name2", "Name3"]
for (var i:int = 0; i > tweenNameArray.length(); i++){
var myTween:Tween = new Tween();
myTween.name = String("myTween_" + estado + "_in"); // You may want to try .toString();
}
Then referencing the tweens should work like this:
Tween(MovieClip(this.stage.getChildByName("myTween_" + estado + "_in")).whateverMethod(); // Try with and without the MovieClip().
I will say right now, it is not recommended to do things this way.

How Do You Concatenate Arrays In Actionscript 3 When Using Different Image Files?

I've looked everywhere on the web to see if I could find an answer to this and I've looked throughout the Adobe Flash Builder help site too and I can't seem to find a concrete answer for what I'm trying to do.
It is possible to reference an array inside of an image file name, here's the scenario.
I have a list of images that only differ by the number at the end of the name (for example. orangeimg1.jpg, appleimg2.jpg, strawberryim3.jpg, etc. Is it possible when referencing the image that I could somehow reference the array in the file name rather than repeating the same code over and over again?
I have two different arrays set up one for fruit which has (orange, apple, stawberry) and I have another array with the numbers (1, 2, 3). I have jpg images for each of these combinations but how to I reference that in one line when I'm trying to refer to these images. I thought something like source = "[fruit].img.[number].jpg" would work but I'm a newbie so I'm pretty sure that isn't right.
Again I've found some information on the web but it doesn't refer to how it would work if I was coding a source for my images.
I'm really confused and would appreciate any help with this. Thanks.
Strings are concatenated using +.
var fruits:Array = ["banana", "cherry"];
var numbers:Array = [4, 2];
var source = fruits[0] + "img" + numbers[0] + ".jpg"; // bananaimg4.jpg
If you want to create multiple file names, you can use a loop:
for(var i:int = 0; i<fruits.length; i++) {
var source = fruits[i] + "img" + numbers[i] + ".jpg";
// ...
}
You probably don't need that numbers array. If those numbers are in order you could calculate the number in the loop:
for(var i:int = 0; i<fruits.length; i++) {
var source = fruits[i] + "img" + (i+1) + ".jpg";
// ...
}
Above answer is good but i am giving only some changes to make code more effective.
We can use for loop in given below format. it's optimized code:
var len:uint = fruits.length;
for(var i:int = 0; i<len; i++) {
var source = fruits[i] + "img" + (i+1) + ".jpg";
// ...
}

Losing leading 0s when string converts to array

I have a textInput control that sends .txt value to an array collection. The array collection is a collection of US zip codes so I use a regular expression to ensure I only get digits from the textInput.
private function addSingle(stringLoader:ArrayCollection):ArrayCollection {
arrayString += (txtSingle.text) + '';
var re:RegExp = /\D/;
var newArray:Array = arrayString.split(re);
The US zip codes start at 00501. Following the debugger, after the zip is submitted, the variable 'arrayString' is 00501. But once 'newArray' is assigned a vaule, it removes the first two 0s and leaves me with 501. Is this my regular expression doing something I'm not expecting? Could it be the array changing the value? I wrote a regexp test in javascript.
<script type="text/javascript">
var str="00501";
var patt1=/\D/;
document.write(str.match(patt1));
</script>
and i get null, which leads me to believe the regexp Im using is fine. In the help docs on the split method, I dont see any reference to leading 0s being a problem.
**I have removed the regular expression from my code completely and the same problem is still happening. Which means it is not the regular expression where the problem is coming from.
Running this simplified case:
var arrayString:String = '00501';
var re:RegExp = /\D/;
var newArray:Array = arrayString.split(re);
trace(newArray);
Yields '00501' as expected. There's nothing in the code you've posted that would strip leading zeros. You may want to dig around a bit more.
This smells suspiciously like Number coercion: Number('00501') yields 501. Read through the docs for implicit conversions and check if any pop up in your code.
What about this ?
/^\d+$/
You can also specify exactly 5 numbers like this :
/^\d{5}$/
I recommend just getting the zip codes instead of splitting on non-digits (especially if 'arrayString' might have multiple zip codes):
var newArray:Array = [];
var pattern:RegExp = /(\d+)/g;
var zipObject:Object;
while ((zipObject = pattern.exec(arrayString)) != null)
{
newArray.push(zipObject[1]);
}
for (var i:int = 0; i < newArray.length; i++)
{
trace("zip code " + i + " is: " + newArray[i]);
}