Introduction to User-Defined Functions

Prev Next

Introduction

B4P provides means to define your own procedures and functions, assign plausible names for them and call them up like standard B4P functions. Following control flow functions are available to define your own functions:

  • define procedure(): The user-defined function can only be called as a procedure in statements. Even if provided, return values are discarded.
  • define function(): The user-defined function can only be called inside expressions where the returned value is used.
  • define procedure and function(): The user-defined function can be called as both procedure in statements and functions inside expressions.

All three functions expect a block (inside braces) containing the code. Variables created inside are local variables. Parameters are available as pure input parameters, output parameters, bi-directional I/O parameters, and references to variables so the whole sub-structure containing thee the members can be accessed. Return values can be provided with the return() function call.

Additional procedure and function names can be defined on the same implementation. The local variable function name[] is visible inside the code block and can be used to provide distinguished functionality for every additional procedure and function name. For more info, see

Fore more details, see the section on user-defined functions.

       define function( hypotenuse, { { x, numeral }, { y, numeral } } )
       {
           return( sqrt( x[]*x[] + y[]*y[] ) );
       }

       define procedure( say hello ) { echo("Hello !"); }

       say hello;
       echo( hypotenuse(3,4) );  //  5
       echo( hypotenuse(5,12) ); // 13
       echo( hypotenuse(8,15) ); // 17
       echo( hypotenuse(1,1) );  //  1.41...   
Hello !
5
13
17
1.4142135624
Try it yourself: Open LAN_Features_Introduction_to_User-Defined_Functions.b4p in B4P_Examples.zip. Decompress before use.