Hello people of StackExchange, this is my first post, as I've tried my best to solve this on my own, and I cannot find a really good solution that matches the solution I have in AS3.
AS3 Code:
//create player
R.instance({_origin: this, _updatable: 1, _saveToXML: 1, _bodyType: "DYNAMIC", _type: "o_nape_player", _sprite: "idle/CharacterIdle", _x: -32, _y: -512});
//R.instance function exposed + showing how the parameters_ get's passed through
class RInstance {
public static function create(parameters_:Object = null):Dynamic {
var instance:XxxxObject = null;
var _type:String = parameters_._type;
switch (_type) {
case "o_nape_player": instance = new O_nape_player(parameters_);
}
parameters_._origin.addToArrayObject( instance );
return instance;
}
}
//o_nape_player.as
public function XxxxObject(parameters_:Object = null) {
parameters = parameters_;
}
protected function set parameters(parameters_:Object):void {
var parameter:String;
for (parameter in parameters_) {
this[parameter] = parameters_[parameter];
}
parameters_ = null;
}
So as the title says, in Haxe, how would I, set the class's variables, based on a bag of variables that are thrown at the class ready to be unpacked?
The closest I've gotten, but this is not the result I want, as it requires setter functions:
override public function set_parameters(object:Dynamic):Void {
for (param in Reflect.fields(object)) {
try {
Reflect.callMethod(this, Reflect.field(this, "set" + param.charAt(0).toUpperCase() + param.substr(1)), [Reflect.field(object, param)]);
} catch (e:Dynamic) {
//....
}
}
}
Thank you for your time. Please, I must stress, as I just said, that is not the result I want, I want my Haxe code to line up as best as possible with my AS3 code, my AS3 code does not require setter functions, to set variables that belong to a class.
TL;DR
With all the code posted above, I can simply rephrase the question like so; How can I replicate this as simple as possible in Haxe: this[parameter] = parameters_[parameter];
The most obvious solution would be in fact to use the Reflect APIs:
function setAs(other:Test)
{
for (f in Reflect.fields(other))
Reflect.setField(this, f, Reflect.field(other, f));
}
A more complete example: Try Haxe #0a6C3.
Notes:
Reflect.getProperty and Reflect.setProperty.foo[field] = bar[field] = val) if you wrap them with the haxe.DynamicAccess abstract. It's a wrapper on top of the Reflect APIs that's a bit more convenient, specially for when you're dealing with objects with unknown structures (where you would usually need to call Reflect.hasField many times).Std.is, Std.instance and Type.typeof will be useful if typing the setAs precisely isn't feasible.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