I'm looking for a way to do something like this in Haxe:
function foo(...args)
{
for (arg in args)
{
...
}
}
Someone around here who can help me?
This question is very old, so, I'm answering as a documentation. Rest arguments are supported in Haxe since 4.2:
function logAll(...arguments : String)
{
for(arg in arguments)
trace(arg);
}
Haxe doesn't have rest arguments, mostly because those are untyped by nature, and the language should help going typed to have safest code. Typed code can be checked and also optimized by the compiler. More errors compile-time, less errors run-time.
Still the same result of rest arguments can be somehow achieved in a few ways, depending on what you are looking for; does the function only receive values or also objects?
The most straightforward way is using the Any type and Reflect:
function loop(props:Any)
{
for (prop in Reflect.fields(props))
{
trace(prop, Reflect.field(props, prop));
}
}
// usage:
loop({name: "Jerson", age: 31});
You can just use an array with values, therefore you also need to use an array when you use it:
static function loop(values:Array<Any>)
{
for (i in 0...values.length)
{
trace(i, values[i]);
}
}
//usage:
loop(["Jerson", 31]);
If you dislike this array in the implementation, you can also use this wonky function, which I wouldn't advice, but just to give an idea.
function loop<A,B,C,D,E,F>(?prop1:A, ?prop2:B, ?prop3:C, ?prop4:D, ?prop5:E, ?prop6:F)
{
var props:Array<Any> = [prop1,prop2,prop3,prop4,prop5,prop6];
for (i in 0...props.length)
{
trace(i, props[i]);
}
}
// usage:
loop3("Jerson", 31);
Try these examples here: https://try.haxe.org/#Be3b7
There are also macros for rest arguments, which can be nice if you are familiar with macros. Note that this will trace while compiling and doesn't generate the trace in the output source at the moment.
import haxe.macro.Expr;
macro static function loop(e1:Expr, props:Array<Expr>)
{
for (e in props)
{
trace(e);
}
return macro null;
}
// Usage:
loop("foo", a, b, c);
Best advice of course is just don't go dynamic much to keep type-safety, but this should keep you going.
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