Blitz3D+ Command Reference

Global variable[=value][,variable2[=value2],...]

Parameters

variable - the variable's name, with an optional type tag ($, #) or custom Type

value (optional) - starting value; 0, 0.0, "" or Null (default) depending on the type

Description

Declares a variable that every part of the program can see.

Blitz has two kinds of variable. Anything you assign inside a Function belongs to that function alone and disappears when it returns. A Global belongs to the whole program, so the main loop and every function share the one copy. Score, lives, the level number, the player's entity handle, the current game state - these are the things worth making global.

Give a starting value on the same line if you like: Global score = 0, lives = 3. Custom types work too: Global player.Ship = New Ship.

Globals can only be declared in the main program - a Global inside a function is a compile error - but that declaration can sit anywhere in it, and it is common to gather them all at the top of the file where they are easy to find.

Here is the classic trap. A variable you assign in the main program without saying Global is NOT global; it is local to the main program. Use the same name inside a function and you get a brand new, empty variable of your own, and the assignment quietly goes nowhere. If a function seems to be ignoring your value, this is almost always why. Declaring the variable Global fixes it, and building the file with Dialect "secure" makes the compiler point out variables that were never declared.

Arrays are the exception: an array made with Dim is already visible everywhere and never needs a Global.

See also: Local, Const, Dim, Function, Dialect.

Example

; Global Example
; --------------

; A Global variable is visible everywhere - including inside functions
Global score=0

AddScore(100)
AddScore(250)
AddScore(50)

Print ""
Print "Final score: "+score

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

End

; The function reads and changes the Global score directly
Function AddScore(points)
    score=score+points
    Print "Scored "+points+" points - total is now "+score
End Function

Index