Topic outline

  • Functions (Funktiot)

    Also known as procedures or subroutines (aliohjelma) in many languages. They are a way to structure your programs to meaningful wholes for the sake of readability, and to avoid unnecessary copypasting of the same code over and over (you can also break your sketch to multiple files and have functions there separately). Like variables, functions too have a name, type and a scope. In addition to that they may have a return value and parameters. We’ve already defined two functions, setup and draw. We can create other functions exactly the same way:

    void myfunc()
    {
      println("Here we go!");
    }

    The function can be called by giving its name and parenthesis: myfunc(); This is exactly what we’ve been doing when we write things like size(640,480); or smooth(); How to make a simple function: simplefunction.pde

    Parameters

    Parameters are a way to pass information to functions. When defining a function the parameters go inside the parentheses: type and name. Inside the function they are visible as any variables.

    void printsum(int a,int b)
    {
      print(a+b);
    }

    A complete example with parameters: parameters.pde

    Return value

    When the type of a function is void, it doesn’t return anything back to the caller. In many cases we need to get something back, such as information about whether there was a problem. If we define a function with a type (e.g. int), we can return things from it with return. Return will also stop the function and jump back to the caller. See returnvalue.pde

    Homework

    Modify your previous smiley face sketch so that the face is drawn by a function which takes the x/y location as parameters. When the mouse button is pressed, call the function from draw with mouseX and mouseY, which lets you paint with the face as follows:

    Smileypaint

    Example solution: smileypaint.pde