Globals in Functions

Monkey Forums/Monkey Programming/Globals in Functions

Volker(Posted 2011) [#1]
Globals in Functions are not possible in monkey?
Function Timemeasure(go:Int)  
	Global t:Int
end function	

worked fine in Blitzmax but throws an 'Error parsing global' in monkey.


Tibit(Posted 2011) [#2]
While I don't think there is a way you can place a global inside a function, you can place it outside the function but inside the same module, would not that give the same result? or if you want it to be global within the function, use a Local instead.


Volker(Posted 2011) [#3]
To be more specific, I do often things like this:

Function Timemeasure(go:Int) ' true=start, false=end time measuring
	
	Global t:Int	
	If go = True ' start measuring
		t = Millisecs()
		Return
	End If
	If go = False
		Print"Time measured: " + (Millisecs() - t) + " millisecs"	
	End If
End Function



Then I use Timemeasure(true) before the code I want to test for speed
and a Timemeasure(false) after the code.
This will not work with local. I can define it outside the function,
but then it's global for the whole module.


ziggy(Posted 2011) [#4]
Shouln't it be much more cleaner this way:
Class Timemeasurer

	Private
	Global intTime:Int = 0
	Public

	Function Start()
		intTime = Millisecs()
	End

	Function Stop()
		Print"Time measured: " + (Millisecs() - intTime) + " millisecs"	
	End

End

So you just call Timemeasurer.Start and Timemeasurer.Stop ? This way it's still clean and self-contained.


Volker(Posted 2011) [#5]
Fine. No need to create a new object. Will do it that way.