In Haxe, I am trying to access an object's value via a variable. In JavaScript you use [ ] to access it, but in Haxe this doesn't work and comes back with an error:
String should be Int
Array access is not allowed on { x : Int, name : String }
I need help with the last line of code:
var room = { x: 10, name: 'test' };
trace(room.name); // this works returns 'test'
// how do I reference foo to return 'test' as the above result.
var foo = "name";
var results = room[foo]; // need fixing
What you're trying to do is called Reflection, and the way to do that in Haxe is via the Reflect API:
var results = Reflect.field(room, "name");
If you want to access a static field instead, pass the Class<T> as the first argument instead of an instance:
class Foo {
public static var bar = 0;
}
var bar = Reflect.field(Foo, "bar");
For properties with a getter, you'll want to use getProperty() instead.
Note: Reflection is generally considered bad practice as it moves errors from compile- to runtime and is inherently type-unsafe. There are usually better ways to solve a problem, but it's hard to recommend a concrete solution here without more context.
You could alternatively use haxe.DynamicAccess. This is particularly useful if your object is the result of haxe.Json.parse, or by other means a Dynamic.
However, since your example (indirectly) types room, some conversion is needed and you'll still loose typing (you'll have "values" with different types and will need to settle on <Dynamic>):
var foo = "name";
var access = (cast room:haxe.DynamicAccess<Dynamic>);
trace(access[foo]);
(full example)
If your use case has a typed structure that can be converted into a String -> T map or if you're already dealing with dynamics, this is a good fit; otherwise, Reflect or untyped are simpler and therefore better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With