DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 1.10 Exiting a Function

1.10.1 Problem

You want to exit a function.

1.10.2 Solution

Functions terminate automatically after the last statement within the function executes. Use a return statement to exit a function before reaching its end.

1.10.3 Discussion

The return statement exits the current function, and the ActionScript interpreter continues the execution of the script that initially invoked the function. Any statements within the function body that follow a return statement are ignored.

function myFunction (  ) {
  return;
  trace("Never called");
}

myFunction(  );
// Execution continues here after returning from the myFuction(  ) invocation.

In the preceding example, the return statement causes the function to terminate before performing any actions, so it is not a very useful function. More commonly, you will use a return statement to exit a function under certain conditions. This example exits the function if the password is wrong:

function checkPassword (password) {

  // If password is not "SimonSays", exit the function.
  if (password != "SimonSays") {
    return;
  }

  // Otherwise, perform the rest of the actions.
  gotoAndStop ("TreasureMap");
}

// This function call uses the wrong password, and so the function exits.
checkPassword("MotherMayI");

// This function uses the correct password, and so the function jumps to the 
// TreasureMap frame.
checkPassword("SimonSays");
    [ Team LiB ] Previous Section Next Section