MG Mud User | 88f1247 | 2016-06-24 23:31:02 +0200 | [diff] [blame^] | 1 | CONCEPT |
| 2 | varargs |
| 3 | |
| 4 | DESCRIPTION |
| 5 | A function uses "varargs", short for "variable arguments", if |
| 6 | it intentionally may be called with less or more arguments |
| 7 | than formally specified. |
| 8 | |
| 9 | The proper order to define a function call is: |
| 10 | |
| 11 | [ modifier ] [ varargs ] [ return type ] function( args...) |
| 12 | |
| 13 | Any other order will result in an error. |
| 14 | |
| 15 | |
| 16 | Given a function definition like this: |
| 17 | |
| 18 | void fun (string arg1, int arg2, int arg3) |
| 19 | |
| 20 | fun() has to be called with exactly three parameters: one |
| 21 | string and two integers. |
| 22 | |
| 23 | |
| 24 | If the function is defined as |
| 25 | |
| 26 | varargs void fun (string arg1, int arg2, int arg3) |
| 27 | |
| 28 | it is possible to call the function with just arg1, or arg1 |
| 29 | and arg2. The remaining unspecified arguments (arg2 and arg3, |
| 30 | resp. arg3) are in these cases assumed to be 0. |
| 31 | |
| 32 | |
| 33 | To pass more arguments than specified, the functions last |
| 34 | parameter must be defined as following: |
| 35 | |
| 36 | void fun (string arg1, int arg2, varargs int * arg3) |
| 37 | |
| 38 | This allows fun() to be called with two or more arguments. |
| 39 | The arguments, except those assigned to the other parameters, |
| 40 | in this case arg1 and arg2, and collected into an array which |
| 41 | is then passed as arg3. For example |
| 42 | |
| 43 | fun("foo", 1) -> arg3 == ({ }) |
| 44 | fun("foo", 1, 2) -> arg3 == ({ 2 }) |
| 45 | fun("foo", 1, 2, 3) -> arg3 == ({ 2, 3 }) |
| 46 | |
| 47 | The type of the varargs argument has to be an array of the |
| 48 | expected type (int*, object*, string*, ...); in this example, |
| 49 | only integers are allowed. To accept arguments of any kind, |
| 50 | define the parameter as 'varargs mixed' or 'varargs mixed*'. |
| 51 | |
| 52 | To 'flatten' the received argument array in your own function |
| 53 | calls, use the efun apply(); e.g.: |
| 54 | |
| 55 | apply(#'call_out, "bar", 1, arg3) |
| 56 | |
| 57 | or the 'flatten arguments' operator: |
| 58 | |
| 59 | call_out("bar", 1, arg3...) |
| 60 | |
| 61 | The two varargs variants can of course be combined: |
| 62 | |
| 63 | varargs void fun (string arg1, int arg2, varargs int* arg3) |
| 64 | |
| 65 | defines a function which may be called with any number of |
| 66 | arguments. |
| 67 | |
| 68 | |
| 69 | HISTORY |
| 70 | The possibility to pass more arguments than formally specified |
| 71 | was introduced in 3.2.1@132. Before, the excess arguments were |
| 72 | silently ignored. |
| 73 | |
| 74 | SEE ALSO |
| 75 | pragma(LPC), apply(E), modifiers(LPC) |