18.2. Calling functions and subroutines

[<<<] [>>>]

Functions and subroutines can be called two different ways. One way is to use the function in an expressions the same way as you would do with the built-in function like sin, cos or rnd. Calling a function this way you have to use the name of the function and supply parameters between parentheses.

Another way to call a function or subroutine is to use the call statement. The call statement has a very simple syntax:

CALL function_name( argument_list )

The function name is the name that stands after the keyword function or sub. The argument list is a comma-separated list of expressions. When you call a function in a call statement you can omit the parentheses, which is very convenient when you do not have arguments. Therefore the following lines are equivalent:

CALL MyFunction
CALL MyFunction()


CALL MyFunction 1,2,3
CALL MyFunction(1,2,3)

To ease readability and programmers life you can even omit the keyword CALL if the function or subroutine was already defined. Therefore you can write:

Sub MyFunction
Print "I am in my function\n"
End sub


On the other hand the following code


Sub MyFunction Print "I am in my function\n" End sub

is not valid, because the function is not defined when it is called. In such a situation you have to use the keyword CALL.

If the function or subroutine has formal arguments you can pass values inside the parentheses. Functions and subroutines can have as many arguments as you like and you can pass as many values as you like. ScriptBasic does not check that the number of actual values passed as argument is the same as the number formal arguments. If you pass more arguments than the number of the formal arguments, the last values are calculated and the result is thrown away. Have a look at the following example:

a = MyFunction(1,2,3)
a = MyFunction(1,2)
a = MyFunction(1,2,3,MyFunction("haha", "hehe","hihi"))
print a
function MyFunction(a,b,c)
local x

print a,b,c,x


end function

And the output printed to the screen:


The lines 1 to 4 are results of a function call. When we call the function the first time we pass three values to the arguments, which are named a, b and c. The values are printed correct and the value of the local variable x is undef.

The second time we call the function passing only two arguments. ScriptBasic does not complain. As we do not pass any value for the argument named c the value of it is undef.

When we call the function third time the argument evaluation calls the function itself again. Although this is the fourth argument and MyFunction has only four this argument is evaluated and this result the line 3 in the output. The result of this function call, which is undef anyway, is not used.

[<<<] [>>>]