5. Functions, keyboard, images

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

Keyboard

Like with the mouse, the simplest way to read the keyboard is to check the global variable keyPressed. If it’s true, key will contain the pressed key. It can be either a character in single quotes or a special value such as ENTER or BACKSPACE. However, when you get serious about it, both the mouse and keyboard are better supported using event handlers such as mouseClicked. A simple keyboard example: keyboard.pde. An advanced example of the use of event handlers: eventhandlers.pde

PImage

PImages let us load and display bitmap images (jpg/png/gif/tga). You can add images to your sketch through Sketch – Add File. You can also download them directly from URLs, but then they obviously won’t work, if you don’t have an Internet connection. Example images for today: player.jpg and football.png. How to load images and display them on screen: images.pde

This entry was posted in Processing. Bookmark the permalink.