Here author Steve Vink introduces us to the wonders of functions. This is a shorter version of the tutorial, the full length verison can be downloaded - details at the end.

A function is a self-contained operation. You tell it what to do; it does it; end of story. Functions, as clever as they are, don't remember anything. If you call it twice, it will have no recollection of what it did the first time. Far from being a drawback, this is where the power lies. Load, run and look at example 1, which demonstrates that when incrementing a variable in a function, it resets itself every time. If you are unfamiliar with functions, and how they are called, this example will also introduce the syntax to you.

Newsletter article, and project download:

http://www.thegamecreators.com/data/newsletter/newsletter_issue_27.html#9

Language: 
Dark Basic Pro
Code: 
remstart
 Functions Example 3
 In the first example, our value remained static, no matter how many times we incremented it.
 By passing in the value as a paremeter, and receiving it back again afterwards,
 the value can be retained.  In a real programming situation, you might use this
 feature of functions to calculate a new character position, 
 evaluate health based on numerous factors (or parameters), or simply perform a 
 long-winded calculation that is "tidier" in the form of a function.
remend

` Basic Setup
`******************************************************
	set display mode 640,480,16
	sync on: sync rate 10
	

` Main routine
`******************************************************
	` Call the function Counter() 1000 times
	for looping = 1 to 1000
		cls
		MainValue = Counter(MainValue)
		center text 320, 200, "Main Code : I have looped " + str$(looping) + " times"
		center text 320, 420, "Press 'Esc' to Exit"
		if escapekey() then end
		sync
	next looping
	

` End Program
`******************************************************
	end




`******************************************************
` Functions
` Functions always appear after the main body of your code.
` Although there is an "end" statement above for completeness,
` it is not essential.  Your functions will NOT run, until
` you call them explicitly.  This is the first major difference 
` between Subs and Functions.
`******************************************************


function Counter(MyValue)
	
	` Increment the value of n, and display
	inc MyValue, 1
	center text 320, 240, "Function : I have incremented MyValue, it's value is now " + str$(MyValue)
	
endfunction Myvalue

0
No votes yet