SLUDGE

Functions (subs)


In SLUDGE, a function or "sub" is a group of instructions which make up a particular task. Each function has a name, a set of parameters (values which can be passed in) and a list of commands. A function is defined in the following way:

sub nameGoesHere (parameter1, parameter2, andSoOn) {
   # Some code
}

It is also possible to return values from a function. Functions can return any of the data types which can be stored in a variable (you can therefore use a stack if you need to return more than one value from a function).

sub addTwoNumbers (a, b) {
   return a + b;
}

sub introducePeople (aBod, anotherBod) {

   # Let's return a stack containing "A, I'd like you to meet B."
   # and "B, this is A!".

   return newStack (aBod + ", I'd like you to meet " + anotherBod + ".",
                    anotherBod + ", this is " + aBod + "!");
}

When calling a function, simply type the name of the function followed by the parameters in brackets. For example:

sub sayNumber (number) {
   say (ego, "The number is " + number + ".");
}

sub init () {

   # Let's call our addTwoNumbers function
   var total = addTwoNumbers (100, 451);

   # Now let's call our new sayNumber function
   sayNumber (total);
}

If you are calling a function which needs no parameters, make sure you still include an empty set of brackets, otherwise the function will not be called!

sub reallyImportantFunction () {
   say (ego, "It's vital that I say this!");
} 

sub init () {

   # This won't call the reallyImportantFunction...
   reallyImportantFunction;

   # But this will...
   reallyImportantFunction ();
}

More on this subject:

Passing Functions as Variables

Unfreezable Functions

spawnSub()