how can I refer to existing local variables building their names dynamically?
I.e.: I have
var itemA: Sprite;
var itemB: Sprite;
var itemC: Sprite;
In AS3 I could say
this["item" + x] = new Sprite();
where x could be “A”, “B” or “C”.
How can I do the same thing in Haxe?
You can use Reflect.field(object:Dynamic, fieldName:String):Dynamic
But actually for your case I might use a Map<String, Sprite>, then you can look them up by name as well as iterate through them.
Yeah, Map would be best choice in some case.
Reflect is what I was looking for, thanks!
EDIT: but, wait, let’s make an example:
var item: Sprite = new Sprite();
Reflect.field(item, "item" + itemType);
Is this correct?
Use the Map<String, Sprite>. It do what you want but by more clear way.
Ok, but is it correct how I wrote the lines of code for Reflet? I can’t get it to work with spritesheets: I get an AnimatedSpritesheet by name, but when playing it I can’t see anything.
@GiG Reflect allows you to access object’s field.
So if your class has these 3 variables doing:
getProperty(this, "item" + itemType) will give you the variable and
setProperty(this, "item" + itemType, value) will set it.
The difference between field and getProperty is that the second takes into account the getter function (if it exists), the doc says it can be slower but it’s easier to use it everywhere, and you can add a getter without having to change all the reflect code.