Blitz:Procedures

From Amiga Coding
Revision as of 17:17, 23 July 2015 by Daedalus (talk | contribs)
Jump to: navigation, search

Blitz Basic / AmiBlitz supports the concept of procedures, which are like separate "modules" in your code that can be treated like statements or functions. In effect, this allows you to create your very own commands for situations where suitable commands don't exist in the standard Blitz libraries. Using procedures and functions helps keep your code tidy and easy to read, which in turn helps to avoid introducing bugs into your code.


Using Procedures

Two types of procedures are available: Statements and Functions. Similarly to the built-in statements and functions, these are more or less the same except that statements don't return a value whereas functions do. They can be used anywhere in you code *after* their position in the source, so it's generally a good idea to have them near the top. Using procedures is similar to using built-in commands, however there are a couple of differences:

  • Procedures always curly brackets around their arguments, for example:
DrawMySprite{x,y}
  • Procedures must have the curly brackets after their name, even if there are no arguments. For example:
ClearBoard{}


Declaring Statements

To create a statement, the Statement...End Statement commands are used, with the statement code in between. Curly brackets are required after the Statement, even if arguments are not required. For example: Statement ShowMyMessage{}

 NPrint "This is my first statement!"

End Statement This statement will show the message every time it is called in your code. Up to 6 arguments can be added in the curly brackets, separated by commas: Statement PrintWelcome{name$, messagecount}

 NPrint "Welcome ", name$
 NPrint "You have ", messagecount, " message(s) waiting"

End Statement


Declaring Functions

Functions are declared similarly to statements, however they require an extra line of code in order to provide the return value. The command Function Return value is used to exit the function and return the value. Value can be any primitive type of information, and can be a constant or a variable. For example: Function AddUp{a, b}

 result = a + b
 Function Return result

End Function This function will return the sum of the two numbers provided as arguments when it is called. Note: It is important to ensure that the data type that is returned by the function is what is expected by your code. Returning a string is going to cause problems if your main code tries to use the result in a maths operation! To enforce proper variable type matching, use Syntax 2 near the top of your code.


Calling Procedures