Declaring Local and Global in a function

BlitzMax Forums/BlitzMax Programming/Declaring Local and Global in a function

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.

Hi,

This topic's first post shows:
Strict
Do()

Function DO()
	Global x
	Do2()
	Print x
	
	Function Do2()
		x:+1
	End Function
End Function
If I declare x as local, it won't compile as the x in Do2() won't be recognised.
Imagine this:
'code

Function F1 ( )
  Local L
  'code

  Function F2 ( )
    'code
  EndFunction
EndFunction
Imagine your main programme calls F1 and F1 calls F1 a second time, so L exists twice, one time for each instance of F1. And if now F2 get's called it doesn't know which L to use, that's why this is simply impossible.

It depends on how the variable's are stored in memory:
Globals are stored at a constant position in the process's memory, so each function instance can access them; locals in contrast are stored on the stack, that means every function instance only knows the position of its own locals, there's no way to get the locals of other function instances.

You could work around this by using a global to store the position of the local, so if F1 gets called you store the position of the local in the global: "globalvar=varptr localvar" and inside F2 you can access to it using: "globalvar[0]"
Another way to do this would be that you pass the local variable as "by reference" variable to the sub function.

This problem isn't compiler specific, it's just a question about how the stack actually works.