Input Fields

Blitz3D Forums/Blitz3D Beginners Area/Input Fields

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

The main difference between Global and Local variables is the scope - that is, the range of code where the variable retains its value.

When a variable is declared as Local, its scope is limited to the function - or the part of the code - where the variable were declared.

Consider this example:
test() ;call a test function
Print "MyLocal outside the function: " + MyLocal ;prints 0 because MyLocal scope is only inside the function

function test()
local MyLocal = 5
Print "MyLocal inside the function: " + MyLocal ;prints 5
end function


So, when you need a local variable, just for calculations an the like, then use Local.

Instead, when you need a variable to be accessed in every point of your code - that is, in every function and every place of your code - then use Global declaration.

A variable can be declared Global only in the main part of your code - that is, you can't declare a Global variable inside a function.

Time for another example:
Global MyGlobal$ = "mintybreath"
;call a test function
print MyGlobal; prints "mintybreath"
test()
print MyGlobal ;prints "Hello mintybreath"

function test()
MyGlobal = "Hello " + MyGlobal ;updates the global variable
end function


To summarize: use Global when you need a global scope for your variable. Example: score, player name, speed, etc.

Use Local when you need to compute some value which is only temporary needed.

Don't forget also Costants. A Costant does not change its value, and it's also global by default - that is, you can access it in every piece of your code, exactly like a global variable. But the Costant value can't be changed:
Const PI# = 3.14
print "PI outside the function = " + PI; prints 3.14
test() ;call our lovely test function

;uncomment the next line to generate a compile error: a constant value can't be changed
;pi = pi + 1 ;generates a compile error.

function test()
print "PI inside the function = " + PI ;prints 3.14
end function

Hope this helps,
Sergio.