How can I have a string list in ActionScript-3 ? I don't want to just use an array and always check for type or be type vulnerable. If I could make arrays type specific that would help me. In C# I can do:
List<string> list = new List<string>();
list.Add("hello world");
string str = list[0];
I wished I could do more or less the same in AS-3.
You can use the Vector type, like this:
var list:Vector.<String> = new <String>[];
// or new Vector.<String>();
list.push("hello world");
var str:String = list[0];
Note that AS3's Vector class lacks some functionality found in C#'s List<T> like Remove(), and includes some functionality you would find in other classes of C# such as pop(), typically found in Stack<T>.
In AS3 you can use Vector datatype.
See More info on Vector data type
Vector class works the same way as you need.
See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html.
Related
Am I overcomplicating this? Since I recently learned that with std::vector you can use the [] operator and it will add the entry if missing.
I have something a little more detailed:
using WeekendFutureItemHistMap = std::map<CString, std::vector<COleDateTime>>;
using WeekendFutureHistMap = std::map<WeekendHistAssign, WeekendFutureItemHistMap>;
WeekendHistAssign is just an enum class.
In my function I am populating it this way:
if (m_mapScheduleFutureHist[eHistAssign].find(strName) != m_mapScheduleFutureHist[eHistAssign].end())
m_mapScheduleFutureHist[eHistAssign][strName].push_back(datAssign);
else
{
m_mapScheduleFutureHist[eHistAssign].emplace(strName, std::vector<COleDateTime>{datAssign});
}
According to the std::vector operator[] it states:
Returns a reference to the element at specified location pos. No bounds checking is performed.
As a result it seemed the right thing to do is test for the existing first as done.
Did I overcomplicate it?
std::vector<int> v;
v.resize(100);
v[0]=1;
v[1]=10;
...
I am trying to write a class in Haxe supporting array like access using the [] operator such as:
var vector = new Vec3();
trace(vector.length); // displays 3
vector[0] = 1; // array like access to the class, how?
vector[1] = 5.6; // more array access
vector[2] = Math.PI; // yet more array access
The problem is I don't know how to define a class such that it allows the [] operator. I need this class, rather than using an Array<Float> or List<Float> because there is some trickery going on with it to support my animation system which references to parts of vectors using storyboards (see http://www.youtube.com/watch?v=ijF50rRbRZI)
In C# i could write:
public float this[index] { get { ... } set { .... } }
I've read the Haxe documentation and found ArrayAccess<T>, but the interface is empty. That is I don't understand how to implement it, or if I just implement ArrayAccess<Float> ... what method on my class would be called to retrieve Float at said index?
Haxe doesn't support operators overload (yet) so you will have to use a get/set pair. You can use inline if the magic that happens inside your methods need to be optimized for speed.
Preface: I'm working with Processing and I've never used Java.
I have this Processing function, designed to find and return the most common color among the pixels of the current image that I'm working on. the last line complains that "The method color(int) in the type PApplet is not applicable for the arguments (String)." What's up?
color getModeColor() {
HashMap colors = new HashMap();
loadPixels();
for (int i=0; i < pixels.length; i++) {
if (colors.containsKey(hex(pixels[i]))) {
colors.put(hex(pixels[i]), (Integer)colors.get(hex(pixels[i])) + 1);
} else {
colors.put(hex(pixels[i]),1);
}
}
String highColor;
int highColorCount = 0;
Iterator i = colors.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if ((Integer)me.getValue() > highColorCount) {
highColorCount = (Integer)me.getValue();
highColor = (String)me.getKey();
}
}
return color((highColor);
}
The Processing docs that I'm looking at are pretty sparse on the HashMap so I'm not really sure what's going on inside it, but I've been augmenting what's available there with Java docs they point to. But I'm not really grokking what's happening with the types. It looks like the key in the HashMap needs to be a string and the value needs to be an integer, but they come out as objects that I have to cast before using. So I'm not sure whether that's causing this glitch.
Or maybe there's just a problem with color() but the docs say that it'll take a hex value which is what I was trying to use as the key in the HashMap (where I'd rather just use the color itself).
Now that I've talked through this, I'm thinking that the color() function sees the hex value as an int but the hex() function converts a color to a string. And I don't seem to be able to convert that string to an int. I guess I could parse the substrings and reconstruct the color, but there must be some more elegant way to do this that I'm missing. Should I just create a key-value-pair class that'll hold a color and a count and use an arraylist of those?
Thanks in advance for any help or suggestions you can provide!
I'll dig deeper into this, but an initial thought is to employ Java generics so that the compiler will complain about type issues (and you won't get runtime errors):
HashMap<String,Integer> colors = new HashMap<String,Integer>();
So the compiler will know that keys are Strings and elements are Integers. Thus, no casting will be necessary.
I didn't figure it out, but I did work around it. I'm just making my own string from the color components like:
colors.put(red(pixels[i]) + "," + green(pixels[i]) + "," + blue(pixels[i]),1)
and then letting the function drop a color out like this:
String[] colorConstituents = split(highColor, ",");
return color(int(colorConstituents[0]), int(colorConstituents[1]), int(colorConstituents[2]));
This doesn't really seem like the best way to handle it -- if I'm messing with this long-term I guess I'll change it to use an arraylist of objects that hold the color and count, but this works for now.
With the introduction of things like duck typing, I would love it if I compose object methods on the fly, besides extension methods. Anybody know if this is possible? I know that MS is worried about composing framework on the fly, but they seem to be dipping their toes in the water.
Update: Thanks to Pavel for clarifying. For example, say I return a new dynamic object from LINQ and would like to add some methods to it on the fly.
In light of the updated answer, you're actually not looking for "dynamic methods", so much so as "dynamic objects" - such that you may add new properties and methods to them at runtime. If that is correct, then in .NET 4.0, you can use ExpandoObject in conjunction with dynamic:
dynamic foo = new ExpandoObject();
foo.Bar = 123; // creates a new property on the fly
int x = foo.Bar; // 123
// add a new method (well, a delegate property, but it's callable as method)
foo.Baz = (Func<int, int, int>)
delegate(int x, int y)
{
return x + y;
};
foo.Baz(1, 2); // 3
You can have "dynamic methods" too, with expression trees, and once you obtain a delegate for such a method, you can also create a callable method-like property out of it on an ExpandoObject.
For use in LINQ queries, unfortunately, you cannot use object initializers with ExpandoObject; in the simplest case, the following will not compile:
var foo = new ExpandoObject { Bar = 123; }
The reason is that Bar in this case will be looked up statically as a property of ExpandoObject. You need the receiver to be dynamic for this feature to kick in, and there's no way to make it that inside an object initializer. As a workaround for use in LINQ, consider this helper extension method:
public static dynamic With(this ExpandoObject o, Action<dynamic> init)
{
init(o);
return o;
}
Now you can use it thus:
from x in xs
select new ExpandoObject().With(o => {
o.Foo = x;
o.Bar = (Func<int, int>)delegate(int y) { return x + y; };
});
Yes, there is: Generating Dynamic Methods with Expression Trees in Visual Studio 2010
This was already possible with the aid of DynamicMethod and/or MethodBuilder. Not sure if that counts for being "worried", as it has been around for a while now, though it requires a dynamic assembly in most scenarios (DynamicMethod can be used without, though).
this question feels like it would have been asked already, but I've not found anything so here goes...
I have constructor which is handed a string which is delimited. From that string I need to populate an object's instance variables. I can easily split the string by the delimited to give me an array of strings. I know I can simply iterate through the array and set my instance variables using ifs or a switch/case statement based on the current array index - however that just feels a bit nasty. Pseudo code:
String[] tokens = <from generic string tokenizer>;
for (int i = 0;i < tokens.length;i++) {
switch(i) {
case(0): instanceVariableA = tokens[i];
case(1): instanceVarliableB = tokens[i];
...
}
}
Does anyone have any ideas of how I do this better/nicer?
For what it's worth, I'm working in Java, but I guess this is language independant.
Uhm... "nasty" is in the way the constructor handles the parameters. If you can't change that then your code snippet is as good as it may be.
You could get rid of the for loop, though...
instanceVariableA = tokens[0];
instanceVariableB = tokens[1];
and then introduce constants (for readibilty):
instanceVariableA = tokens[VARIABLE_A_INDEX];
instanceVariableB = tokens[VARIABLE_B_INDEX];
NOTE: if you could change the string parameter syntax you could introduce a simple parser and, with a little bit of reflection, handle this thing in a slightly more elegant way:
String inputString = "instanceVariableA=some_stuff|instanceVariableB=some other stuff";
String[] tokens = inputString.split("|");
for (String token : tokens)
{
String[] elements = token.split("=");
String propertyName = tokens[0];
String propertyValue = tokens[1];
invokeSetter(this, propertyName, propertyValue); // TODO write method
}
Could you not use a "for-each" loop to eliminate much of the clutter?
I really think the way you are doing it is fine, and Manrico makes a good suggestion about using constants as well.
Another method would be to create a HashMap with integer keys and string values where the key is the index and the value is the name of the property. You could then use a simple loop and some reflection to set the properties. The reflection part might make this a bit slow, but in another language (say, PHP for example) this would be much cleaner.
just an untested idea,
keep the original token...
String[] tokens = <from generic string tokenizer>;
then create
int instanceVariableA = 0;
int instanceVariableB = 1;
if you need to use it, then just
tokens[instanceVariableA];
hence no more loops, no more VARIABLE_A_INDEX...
maybe JSON might help?
Python-specific solution:
Let's say params = ["instanceVariableA", "instanceVariableB"]. Then:
self.__dict__.update(dict(zip(params, tokens)))
should work; that's roughly equivalent to
for k,v in zip(params, tokens):
setAttr(self, k, v)
depending on the presence/absence of accessors.
In a non-dynamic language, you could accomplish the same effect building a mapping from strings to references/accessors of some kind.
(Also beware that zip stops when either list runs out.)