le_wofl
le_wofl

Reputation: 303

Haxe - use string as variable name with DynamicAccess

I am trying to use a string ('npcName') as a variable name. So far I have tried casting dialogMap into a DynamicAccess object, but it gives me the error 'Invalid array access' when I try this:

    var npcName:String = 'TestNPC';
    var casted = (cast Registry.dialogMap:haxe.DynamicAccess<Dynamic>);
    var tempname = casted[root.npcName[0].message];
    trace(tempname);

'dialogMap' is an empty map which I want to fill like so:

Registry.dialogMap['message'] = root.npcName[0].message;

How can I use npcName, a string, in the above line of code? Is there a way to transform the string into something usable? Any help would be appreciated.

Upvotes: 3

Views: 731

Answers (1)

Mark Knol
Mark Knol

Reputation: 10143

The haxe.DynamicAccess doesn't have array access (like map[key]), but is an abstract type for working with anonymous structures that are intended to hold collections of objects by the string key. It is designed to work with map.get(key) and map.set(key). It is basically a nicer wrapper around Reflect.field and Reflect.setField and does some safety checks with Reflect.hasField.

    var variable = "my_key";
    var value = 123;

    var dynamicMap = new haxe.DynamicAccess<Dynamic>();
    dynamicMap.set(variable, value);

I'm noticing you are doing very much cast and dynamic, so untyped code, which is a bit of contradiction in a typed language. What is the actual type of dialogMap?

Not sure you are aware of it but, Haxe has its own maps, which are fully typed, so you don't need casts.

    var map = new Map<String, Int>();
    map[variable] = value;

I think this article helps understanding how to work with dynamic (untyped) objects.

Tip; for testing such small functionalities you can doodle around on the try.haxe site : http://try.haxe.org/#4B84E

Hope this helps, otherwise here is some relevant documentation:

Upvotes: 3

Related Questions