You can also write functions which accept any number of arguments. To do
this you have to use the ...
identifier as the last parameter. Your
function will then get a local table called arg
which contains all
parameters that were passed to your function including an element called
n
which carries the number of parameters that were passed to the function.
Please also note that the arguments will be stored in the arg
table
starting at index 0. For example, here is a function that calculates the
average of all parameters that are passed to it:
Function p_Average(...) Local pars = arg.n ; how many parameters were passed Local avg, k ; temporary locals For k = 1 To pars avg = avg + arg[k-1] ; sum up all parameters Next Return(avg / pars) ; and divide the sum by their quantity EndFunction a = p_Average(10, 20, 30, 40, 50) ; (10 + 20 + 30 + 40 + 50) / 5 = 30 b = p_Average(34, 16, 27, 39) ; (34 + 16 + 27 + 39) / 4 = 29 c = p_Average(10, 10) ; (10 + 10) / 2 = 10 Print(a, b, c) ; prints "30 29 10" |
It is important to note that the ...
identifier must be specified as the
last entry of your parameter list. You cannot do things like:
; invalid code Function p_Test(a, b, ..., c) ... EndFunction |
This will obviously not work because Hollywood could never know which
parameter belongs to c
. Using parameters before the ...
identifier
works fine though:
Function p_MinMax(ismin, ...) Local pars = arg.n ; number of parameters passed Local k If ismin = True ; find out smallest element? Local min = arg[0] ; store the smallest element here For k = 2 To pars ; iterate over all elements If arg[k-1] < min Then min = arg[k-1] ; smaller ? Next Return(min) ; and return the smallest Else Local max = arg[0] ; store the greatest element here For k = 2 To pars ; iterate over all elements If arg[k-1] > max Then max = arg[k-1] ; greater ? Next Return(max) ; and return the greatest element EndIf EndFunction a = p_MinMax(True, 4, 8, 2, 3, 10, 1, 7, 9, 5, 6) ; returns 1 b = p_MinMax(False, 4, 8, 2, 3, 10, 1, 7, 9, 5, 6) ; returns 10 |
This function will return the smallest number of the specified parameters if the first argument is True or the greatest number if the first argument is set to False.
If you need to pass all arguments over to another function, the Unpack() function can become handy. It will return all elements of a table. For example, if you want to write your own Print() function:
Function p_Print(...) Print(Unpack(arg)) EndFunction |
All arguments passed to p_Print()
will be passed over to Print() using the
Unpack() function.