12.4 Return values

If your function returns one or more values it is required to specify these values in parentheses. These are required because otherwise the parser would treat them as separate statements. Consider the following code:

; wrong code!
Function p_Max(a, b)
    If a > b Then Return a
    Return b

The Hollywood parser would interpret this code in the following way:

Function p_Max(a, b)
    If a > b Then Return   ; if a > b, then return no value !!
    a                      ; execute function a() !!
    Return                 ; return no value !!
    b                      ; execute function b() !!

You see that this does not make much sense. The parentheses are obligatory because Hollywood allows you to type as many commands as you wish in one line without any delimiters. And Hollywood allows you to call functions that do not accept arguments without specifying parentheses. Therefore a statement like Return a is converted into two statements, namely Return and a(). If you want to return the variable a you have to write Return(a). The correct version of our p_Max() function thus has to look like this:

Function p_Max(a, b)
    If a > b Then Return(a)

By using the parentheses you signal to Hollywood that the variables a and b belong to the Return() calls and are not separate functions.

If a function returns more than one value but you want to have only the first return value, you need to put a pair of parentheses around the function call. This will cast the result of this function to one single value. For example, the following function returns three values:

Function p_ThreeVals()
    Return(1, 2, 3)

If you pass this function now to a function that accepts a multiple number of arguments, e.g. DebugPrint() all three return values will be passed to DebugPrint() as well:

DebugPrint(p_ThreeVals()) ; prints "1 2 3"

If you want DebugPrint() to receive only the first return value of p_ThreeVals() you need to put parentheses around the p_ThreeVals() call so that it looks like this:

DebugPrint((p_ThreeVals()))  ; prints "1"

Functions cannot only return numbers, but also strings, tables and even other functions. For example, the following code is completely legal:

Function p_Return_a_Table()
    Return({1, 2, 3, 4, 5})
a = p_Return_a_Table()
DebugPrint(a[3])         ; prints 4

In practice, you will probably not use this feature very much but you should know that it is at least possible to have functions that return tables or other functions. Another example:

Function p_Return_Func()
    Return(Function(s) DebugPrint(s) EndFunction)
myfunc = p_Return_Func()
myfunc("Hello World!")   ; calls DebugPrint("Hello World!")

Show TOC