Hamster-Scripts: Functions (self-defined)

Creating a function

sub <identifier>( <variable-list> )

sub <identifier>

Starts a user-defined function named <identifier>, which has to start with a letter ("A"..."Z", "a"..."z"). Further characters may also contain digits ("0"..."9") or underscores ("_").

If the function has parameters, they have to be noted as a comma-separated list of variables within parenthesis:

	TestSub( 1, "two", 3 )
	quit

	sub TestSub( $a, $b, $c )
	   print( "TestSub called with " + $a + ", " + $b + " and " + $c )
	endsub

Each function has a return-value which can be set by "return", which additionally exits the function immediately:

	print( TestSub( 1, "two", 3 ) )
	quit

	sub TestSub( $a, $b, $c )
	   return( "TestSub called with " + $a + ", " + $b + " and " + $c )
	endsub

If no return-value is given, it is always set to 0 by a final "endsub", which is just an equivalent to "return( 0 )".

Please note, that the "endsub" in the example above is not really needed, as the function was already left by the previous "return". It's just there to make the script more "readable" and it's a good idea to a) always note it at the very end of a function and b) only there.

Parameters by value / by reference

By default, all parameters of a function are "called by value", which means, that their values are copied to their counterparts given in the parameter-list of the "sub". The values of the variables used for calling the "sub" are left unchanged:

	var( $a )
	$a = 1
	TestSub( $a )
	print( $a )  # -> 1 (unchanged by TestSub)

	quit

	sub TestSub( $x )
	   $x = 42
	endsub

If a variable in the parameter-list of a function is preceded with a "*", this value is "called by reference", which means, that the function directly uses the variable the function was called with. So if the function changes the value of the parameter variable, the value of the calling variable is changed as well:

	var( $a )
	$a = 1
	TestSub( $a )
	print( $a )  # -> 42 (changed by TestSub)

	quit

	sub TestSub( *$x )
	   $x = 42
	endsub

Scope of variables

All variables declared within a function are local to this function. When the function is left again, they are deleted.

Global variables (i.e. declared outside of any function) are accessible within the function, unless a variable with the same name is created in it:

	var( $a )

	$a = 1
	print( $a )  # -> 1

	TestSub
	print( $a )  # -> 42

	quit

	sub TestSub

	   print( $a ) # -> 1
	   $a = 42
	   print( $a ) # -> 42

	   var( $a )   # global $a is from now on "out of scope"
	   $a = 666
	   print( $a ) # -> 666

	endsub

[Hamster Ys Documentation]