How to pass unlimited number of arguments to function (js)?

I know I can just pass an array and cycle thru it, but I’m sure there is a better way.

Unless you need an unlimited/variable number of arguments of different types or the arguments need to have default values I am not sure why the array won’t work. Can you post code/example where you need this? Thanks.

An array WILL work, but I’d prefer not to pass an array.

Let’s say I created a sum function/class. I’d rather do:

sum(5,10,12,17);

as opposed to:

sum(Array(5,10,12,17));

I’m sure it’s possible, because some of the native functions take unlimited args.

The .Net keyword ‘params’ can do this for you:
http://msdn.microsoft.com/en-us/library/w5zay9db(VS.71).aspx

I don’t think this will work for JS, so the class containing the function with the variable argument list will need to be written in C#.

Thanks, I’ll look into that, but I’d prefer to work in JS if possible.

When you create an array or hashtable in javascript, you’re technically passing an unlimited amount of args, so I assume it’s technically possible.

Not sure if this works in Unity but in normal JS this will work:

function sumThem() {
  var sum = 0;
  for ( var i = 0; i < arguments.length; i++ ) {
    sum += arguments[i];
  }

  return sum;
}

sum(1,2,3,4,5,6,7,8,9);
sum(3988,203);

When you call a function in JS there is a variable called argument holding the arguments to that function. Again, not sure if this will work in Unity but I hope it helps.

The fact that you can use a certain feature in JS, does not mean you can create classes with that feature using JS.

For example, output parameters (like the hitInfo parameter of Physics.Raycast) can be used using JS, but you cannot create a function with output parameters yourself, since the syntax required for that is simply not part of the scripting language.

The bottom line is: if you want to create classes with more advanced .Net programming features like generics, output parameters, structs, properties or your ‘params’ function, you will need to switch to C#. Fortunately none of these features are required, there is always a way around them. Like in your case, just simply passing an array if you want an arbitrary number of parameters.

I’m having a similar problem, but this time I can’t pass an Array.
I am trying to make a relatively simple Networking system able to send up to infinite amount of arguments over the network, changeable by the user and networkView.RPC does not take arrays. I did read in the doc’s that a function took object[ ], maybe that is the answer???
btw the networking system works, it’s just the customization that I’m having problems with :slight_smile: