Blitz3D+ Command Reference

Function name ( [parameter[,parameter2,...]] )

Parameters

name - the function's name, with an optional type tag ($ for a string result, # for a float, or a custom Type)

parameter (optional) - a parameter declaration, written like a variable and optionally followed by = and a constant default value

Description

Declares a function - a named block of code you can call from anywhere in the program.

A function is the tool for cutting a game into pieces you can think about one at a time: UpdateEnemies(), DrawHUD(), Distance#(x1,y1,x2,y2). Functions only run when they are called, and control returns to the line after the call when they finish.

The brackets are always required, even for a function that takes nothing: Function DrawHUD(). Give the name a tag to return something other than an integer - Function Distance#(x1#,y1#,x2#,y2#) returns a float, Function PlayerName$() returns a string. Parameters may have defaults, which must be constants: Function Spawn(x,y,hp=100) can then be called as Spawn(10,20).

When you are ignoring the result you can drop the brackets and call it like a command: Spawn 10,20.

Variables inside a function are its own. Values from the main program do not leak in, so pass what you need as parameters and use Global for the handful of things everything shares. Arrays made with Dim and objects of a custom Type are visible everywhere, so those need no special treatment. Because each call gets its own locals, a function can safely call itself.

Return hands a value back and leaves immediately. Running off the end at End Function returns 0, 0.0, "" or Null depending on the return type.

Functions can only be declared in the main program, so they cannot be nested inside one another; write them one after the other, usually below the main loop. One sharp edge: naming a function after a Blitz command replaces that command everywhere in your program, and there is then no way to reach the original - a Function LoadImage that calls LoadImage calls itself until it runs out of stack.

See also: End Function, Return, Global, Local, Gosub.

Example

; Function Example
; ----------------

; Call our damage function for two different attacks
Print "The goblin swings a rusty sword ..."
Print "    Damage dealt: "+Damage(6,8)

Print "The knight swings an enchanted axe ..."
Print "    Damage dealt: "+Damage(25,8)

Print ""
Print "Press any key to close the example"
WaitKey

End

; Function defines a reusable routine - it only runs when called.
; The values passed in arrive as the parameters base and armour.
Function Damage(base,armour)
    ; Armour soaks up part of the blow, but a hit always deals at least 1
    If base<=armour Then Return 1
    Return base-armour
End Function

Index