Hamster-Skripte: functions (defined)
Creations of own function
Sub <identifier> (< variable-craft >)
Sub <identifier>
Beginning and declaration of own function with the name <identifier>. The name must with one of the marks ("A"... "Z", "a"... "Z") begin. Other marks also may the figures ("0"... "9") and the underlined ("_") contain.
If the function has parameter, these must be declared with Kommata separated in clips:
TestSub (1, "two", 3)
Quit
Sub TestSub ($a, $b, $c)
Print (" TestSub was called with " + $a + "," + $b + "and" + $c)
Endsub
To hand over a return value to the appealing place in the script and to leave at the same moment the procedure, the order "return" can be applied:
Print (TestSub (1, "two", 3))
Quit
Sub TestSub ($a, $b, $c)
Return (" TestSub was called with " + $a + "," + $b + "and" + $c)
Endsub
If no return value is fixed the function ends with the order "endsub" and the return value 0.
Parameter delivery " by value " / " by reference "
Standard is the parameter delivery " by value " i.e. of the function a copy of the appealing variables will hand over and changes in these copies within the function do not have an effect on the originals variables beyond the function:
Var ($a)
$a = 1
TestSub ($a)
Print ($a) * - > 1 (invariably by TestSub)
Quit
Sub TestSub ($x)
$x = 42
Endsub
If a variable " by reference should be handed over " to a function, is to the variable name with the declaration of the function a star "*" voranzustellen. Through here the parameter variable is retransferred at the end of a function in the originals variable:
Var ($a)
$a = 1
TestSub ($a)
Print ($a) * - > 42 (changed by TestSub)
Quit
Sub TestSub (* $x)
$x = 42
Endsub
Indication: the parameter delivery " call by reference " is simulated(shammed) in the hamster by copying the variables instead of by same memory addresses! This can lead under circumstances to side stocks!
Validity area of variables
All variables declared in a function are locally to the function. If the function is finished, the variables declared within the function are deleted.
The global variables which have been declared outside by functions, can be used within functions if within the function no variables with same names were declared.
Var ($a)
$a = 1
Print ($a) * - > 1
TestSub
Print ($a) * - > 42
Quit
Sub TestSub
Print ($a) * - > 1
$a = 42
Print ($a) * - > 42
Var ($a) * worldwide $a is from now on " out of scope "
$a = 666
Print ($a) * - > 666
Endsub