Variadic parameters for a function.

Hello

I'd like to create a function that can accept parameters to pass them to the invoke call of the Method class. Is it possible? 

Here is an pseudo example.

class MyInvoker {
    private var _method;
    function initialize(m) {
        _method = m;
    } 
    function myInvoke(parameters...) {
        _method.invoke(parameters...)
    }
}

Thanks.

  • Not possible with Monkey C

    What you can do is have

    function myInvoke0() {}

    function myInvoke1(a) {}

    function myInvoke2(a,b) {}

    etc......

    The max number of parameters is 8 IIRC.

  • Can you get the behavior you're looking for by passing in an array?

  • Use an array or pass null for unused parameters (and test in the function).

    (I wouldn't do the one function for each number of args.)

  • I'm not sure what the exact use case is here, but if you can't modify the signature of the function(s) to be invoked, you could combine the two approaches, given that, as Jim pointed out, there is a max number of arguments in Monkey C. (I've run into it before, although I don't remember if it was 8 or not.)

    class MyInvoker {
        private var _method;
        function initialize(m) {
            _method = m;
        } 
        function myInvoke(argArray) {
            var size = argArray.size();
            if (size == 0)
                _method.invoke()
            else if (size == 1)
                _method.invoke(argArray[0])
            else if (size == 2)
                _method.invoke(argArray[0], argArray[1])
            //...
            else if (size > 8) {
                throw new MyInvokerException(); // define this somewhere else
            }
    
        }
    }

    I guess I'm not sure if I understand why Method.invoke() can't be called directly here. It is too bad that invoke() takes an arbitrary number of arguments but none of the code we write can do the same. But in the pseudo-example, if you exposed _method publicly (either with a getter function or as a public member), couldn't you just call invoke() directly?

    However, I guess one advantage of the array approach is that arguments in an array can be stored, manipulated and passed around for later use.