Blitz3D+ Command Reference

Gosub label

Parameters

label - the name of a label defined in the main program; written .name where it is defined, and without the dot here

Description

Jumps to a label and comes back when it reaches a Return.

Gosub is the old BASIC subroutine. Execution jumps to the label, runs from there, and the next Return sends it back to the line after the Gosub:

Gosub DrawStatus
...
.DrawStatus
    Text 0,0,"Score: "+score
    Return

It works, but a Function is almost always the better answer: functions take parameters, return values, and keep their variables to themselves, while a subroutine shares everything and communicates only through globals.

Gosub is main-program only. Using it inside a function is a compile error ("'Gosub' may not be used inside a function"), and labels belong to the block they are written in, so you cannot jump into or out of a function either.

Keep your subroutines below an End so the program cannot wander into one by accident; a Return that was never reached through a Gosub has nowhere sensible to go back to.

See also: Return, Goto, Function, End.

Example

; Gosub Example
; -------------

Print "The battle is won!"

; Gosub jumps to a label - the Return there brings execution back here
Gosub fanfare

Print "Back in the main program - on to the next level."

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

End

; The subroutine - placed after End so it only runs when called
.fanfare
Print "    (a triumphant trumpet fanfare plays)"
Return

Index