If you have anything that you think that I need to add, please say so. Feel free to ask questions if you don't understand something. I will do my best to answer you. Oh, and when you see things in bold, they are not full examples, but small snippets to help you understand what I am talking about.
If you cannot seem to figure out what a function is, then read this.
What is a function? How do I use one?
Functions are pretty easy to understand once you get the hang of them. What they do is allow you to create "shortcuts" or "custom commands" in your program. They can help you to accomplish many things, for they are very flexible. You can also put different values into functions. For example, if you wanted to make a tall red ghosted box, you could write:
Make object box 1,10,50,10
color object 1,rgb(255,0,0)
ghost object on 1
Or, you could make a function that would do it, like this:
Function MakeTallRedBox(OBJECT)
Make Object Box OBJECT,10,50,10
Color Object OBJECT,rgb(255,0,0)
ghost object on OBJECT
endfunction
And to use or "call" that function, just write:
MakeTallRedBox(1)
And then you will see a tall red box with the object number 1.
To make or "declare" a function, all you need to do is to write FUNCTION, and then right after that, you can write the name of your function or custom command. Note that the name can have no spaces and it cannot have the same name of a normal command. For example, you can't name your function "SYNC", becasue there is already a command named SYNC built into DarkBasic. However, when you write FUNCTION, you need to make a space between the word FUNCTION and the name of the function, that way it can tell the actual command FUNCTION and the name of your function apart. Why do functions need names? Well, if they didn't have names, then how would you call them? The name of our function above is MakeTallRedBox. What's the name of this function (open the snippet for the answer):
Function DarkBasicIsTheBest(OBJECT)
Make Object Cube OBJECT,10
endfunction
The name is: DarkBasicIsTheBest
All it does is make a 10x10x10 cube.
Inbetween FUNCTION and ENDFUNCTION is where you write what the function actually does. You use ENDFUNCTION to say that the function is over. So, this function:
Function CreateCube(OBJECT)
Make Object Cube OBJECT,10
endfunction
would create a cube using the object number specified in the variable OBJECT. You'll learn about that variable OBJECT on the next line
You may be wondering what the () and the word OBJECT are doing there. well, it's those () and what's in them that makes functions so special.
You can place a variable in those (), and so whatever you put in there when you call the function will be placed in that variable for the function to use. Going back to our Tall red cube example. You may have noticed that I put a 1 in the () when I called the function. Well, when I made the function, the variable called OBJECT was in those (). In this case, when the function refers to the variable OBJECT, it is refering to the number 1, because when I called the function I replaced the word OBJECT with the number 1. When I said:
Make object box OBJECT,10,50,10
in the function, I was really saying
Make Object box 1,10,50,10
because I had put a number 1 in the () when I called the function. If I had put a 2 in those () when I called the function, the function would really be saying this:
Make Object box 2,10,50,10
instead of
Make Object box OBJECT,10,50,10
because I had put a 2 in the variable OBJECT, the variable OBJECT now represents the number 2.
So basically, in order to place a value inside a variable for a function, you must put a value in the variable's place when you call the function.
Of couse, you could have a function that needs no input at all, like this one:
Function SetupGame()
sync on
sync rate 60
autocam off
endfunction
And you'd call that like this:
SetupGame()
Because you don't need to pass anything into the function, you can just leave the () blank.
Returning Values
Did you know that functions can return values? Well, they can! Creating functions that return values can be very useful, especially when trying to deal with long maths. For example, if you wanted ot find out what a number times 5 minus 3 plus 9 plus half of our original number minus 1/4 of the original number was, you could write:
N=5 `where N is our number
N=N*5-3+9+(N/2)-(N/4)
That's fine. But, what if you wanted to do it for 4 different numbers that were not in order? Say those numbers were 2 5 8 and 10. You could write:
N=2
Answer=N*5-3+9+(N/2)-(N/4)
N=5
Answer=N*5-3+9+(N/2)-(N/4)
N=8
Answer=N*5-3+9+(N/2)-(N/4)
N=10
Answer=N*5-3+9+(N/2)-(N/4)
but that's long and annoying! So, why not make a function for it:
Function DoComplexMath(N)
Answer#=N*5-3+9+(N/2)-(N/4)
endfunction Answer#
Notice the "Answer#" after endfunction. That is the value or variable that you want to return. If I don't want to return anything, I would just leave that blank, like all of the prior examples. So, if I wrote
HeyThisIsTheAnswer#=DoComplexMath(5)
then the answer to the math problem that was done in the function would be put inside the variable called "HeyThisIsTheAnswer#". Understood? And you don't need to return integer variables, nor do you need to pass them in. You can pass and return ANY kind of variable that you want. That "DoComplexMath" function returns a REAL number or a FLOAT (notice the "#" sign after the variable name "Answer"). This function is faster to use because instead of doing this:
N=2
Answer=N*5-3+9+(N/2)-(N/4)
N=5
Answer=N*5-3+9+(N/2)-(N/4)
N=8
Answer=N*5-3+9+(N/2)-(N/4)
N=10
Answer=N*5-3+9+(N/2)-(N/4)
You can just do this:
Result#=DoComplexMath(2)
Result#=DoComplexMath(5)
Result#=DoComplexMath(8)
Result#=DoComplexMath(10)
It's much cleaner.
And keep in mind that functions can only return one value, not 2, not 3, not 4. Just 1. If you want to return more values, you may want to look into GLOBAL variables (DBPro) or ARRAYS (DBC and DBPRo). But you CAN pass multiple values into functions.
Passing Multiple Values Into Functions
In our MakeTallRedBox function, we had only one value going into the function. Let's change that so that we have to specify two values: The Object number and the height of our tall red box. This is our old function:
Function MakeTallRedBox(OBJECT)
Make Object Box OBJECT,10,50,10
Color Object OBJECT,rgb(255,0,0)
ghost object on OBJECT
endfunction
That creates a tall red box with a height of 50. Let's change that. To insert multiple values into a function, all you need to do is add another variable in the part where you make the function. You separate these variables using commas (,). So, if we wanted to store the height in a variable called HEIGHT, and the object number in one called OBJECT, we would write this at the start:
Function MakeTallRedBox(OBJECT , HEIGHT)
There. Now we need to specify 2 values for our function to work: The Object number and the height. Here is the rest of our function:
Function MakeTallRedBox(OBJECT , HEIGHT)
Make Object Box OBJECT,10,HEIGHT,10
Color Object OBJECT,rgb(255,0,0)
ghost object on OBJECT
endfunction
Now, we can specify the height of our box. So, if I called the function like this:
MakeTallRedBox(1,65)
If would make a tall red box with a height of 65. Please note that when calling functions that have multiple input values (or whatever you want to call them) you must put them in the same order as you did when you declared the function. When we declared our MakeRedBox function, we had said:
MakeTallRedBox(OBJECT , HEIGHT)
with the object number first, and the height second. So, if we called the function like this:
MakeTallRedBox(65,1)
Then what would that do? Take a guess. The answer is in that code box. Open it after you've guessed.
It would make a cube with an object number of 65 and a height of 1!
We put it in the wrong order, that's why!
And there you have it. Functions can accept as many input values or "parameters" as you like! You could give it 5 values, like this if you wanted!
Function AddAllTheNumbers(One,Two,Three,Four,Five)
Answer=One+Two+Three+Four+Five
endfunction Answer
That function would add up all of the numbers that you specify!
However, there is a limit to the amount of parameters that you can specify. The limit is 255. But who wants to keep track of 255 parameters anyway!? You probably couldn't even fit that many on 1 line, so this shouldn't concern you
USEFUL FUNCTION INFO
Just so you know, unless a variable was declared global earlier in the program, all variables that are used within functions are considered "Local" variables. This means that if you gave a variable called "PotsAndPans" a value of 50 outside of a function, and then in a function you used the same variable and gave it a value of 10, it would only be equal to 10 within the function. It would still be 50 outside of it. Furthermore, a variable used inside a function will not save its value for the next time that it is called. Meaning that, if you said
PotsAndPans=PotsAndPans+10
within a function, the variable would go to 10, of course, but as soon as the function ended it would go back to 0. So, the next time that function was called, it would just boost the value back up to 10, not to 20 because tha variable's value was not saved. But you
can pass arrays and global variables through functions. however, if you modify them outside of a function, then they will be changed by that as well as what happens to them within the functon. For example, if I had a variable called "PotsAndPans" again, but it was global this time, and I did this to it outside of the function:
PotsAndPans=50
and then in the function I did this:
PotsAndPans=15
Then "PotsAndPans" would turn out to be 15, because it is global. The same applies to Arrays, but Arrays are ALWAYS global.
Alright, time for one of my favorite things about functions: you can pass variables into them! Remember how we were always passing numbers into functions? Well, we can also pass the contents of a variable into a function! Say we had our MakeTallRedBox function again. It would be like this:
Function MakeTallRedBox(OBJECT , HEIGHT)
Make Object Box OBJECT,10,HEIGHT,10
Color Object OBJECT,rgb(255,0,0)
ghost object on OBJECT
endfunction
And we could call it like this:
MakeTallRedBox(1,60)
That's one way you could do it. Another way is that you could also use variables! Say we wanted whatever was in the variable ObjectNumber to be the object number of out tall red box. To do that, you would do something like this:
ObjectNumber=3
MakeTallRedBox(ObjectNumber,60)
That would make a tall red box with an object number of 3 and a height of 60. Why an object number of 3? Because that's what is in that variable ObjectNumber that we passed into the function. Now, the contents of the variable OBJECT in our function is turned into the contents of the variable ObjectNumber that we passed in! Say we wanted to pass in a height variable as well. Then, we would do this:
ObjectNumber=3
VariableHeight=55
MakeTallRedBox(ObjectNumber,VariableHeight)
And it would make a tall red box with an object number of 3 and a height of 55.
And one last thing. It's sort of off topic, but oh well. There is one more command that you must be aware of. It's called EXITFUNCTION. It works kind of like the EXIT command for loops. It will forcibly leave the function before it's supposed to end. So, if you put it at the start of a function, it will leave the function before anything happens. so, calling this function:
function MakeACube(Object)
exitfunction
Make Object cube Object,10
endfunction
Would result in nothing, because you would have left the function before the cube was even made!
But like ENDFUNCTION, you can put a return value on EXITFUNCTION as well. You'd do it in the same way as you would ENDFUNCTION. Here's an example of EXITFUNCTION returning a value:
function Add(One,Two,Three)
Sum=One+Two
exitfunction Sum
Sum=One+Two+Three
FinalSum=Sum
endfunction FinalSum
That function would return the sum of the first two numbers because it wouldn't have gotten the chance to add all of the numbers, just the first two would have been added.
A FEW LAST NOTES:
-Arrays can be passed through functions and be changed, because they are always gloabl
-Global variables (only in DBP) can be passed through functions and be changed.
-TYPES (DBP) cannot be declared in functions.
-Arrays CAN be declared in functions.
-When decclaring a function, it's best to do it after all of your loops are done. You should declare all functions in that same area, one by one. They should get declared somewhere where they will not gone over by the compiler or the thing that reads your code. Function declarations should not be run. However, you SHOULD run functions calls. Treat function calls like normal commands.
EXAMPLES
=Only works in DBPro.
=Works in DBPro and DBC.
Some of the responses contain additions to this tutorial.
- Global Variables And Functions
rem ******************************************
rem EXAMPLE 1- Global Variables And Functions
rem ******************************************
rem SETUP DEMO
Sync on
Sync Rate 0
rem Make our variable global.
Global TestVariable
rem Set it to 50 to begin with.
TestVariable=50
rem Print the contents of our variable at the moment.
sync : print "Our variable is equal to ",TestVariable : sync
rem Wait for you to press a key.
wait key
rem Wait a little bit so you can take your hand off of the key.
wait 200
rem Print what we are about to do.
sync : print "Let's run it through our function and change its value to 25."
rem wait for a key press.
wait key
rem give you time to release the key.
wait 200
rem Make the variable equal 25 using our function.
ChangeVariable(25)
rem Print the new contents of the variable
sync : print "Now our variable is equal to ",TestVariable : sync
rem Wait for you to press a key.
wait key
rem End the program
end
rem Declare our functions after the program has ended, that way the declaration will not get run.
Function ChangeVariable(Amount)
rem Assign the variable the proper amount.
TestVariable=Amount
rem End of the function.
endfunction
- Arrays and Functions (similar to global variable example)
rem ******************************************
rem EXAMPLE 2- Arrays And Functions
rem ******************************************
rem SETUP DEMO
Sync on
Sync Rate 0
rem Create our array.
Dim Array(1)
rem Set it to 46 to begin with.
Array(1)=46
rem Print the contents of our array at the moment.
sync : print "Our array is equal to ",Array(1) : sync
rem Wait for you to press a key.
wait key
rem Wait a little bit so you can take your hand off of the key.
wait 200
rem Print what we are about to do.
sync : print "Let's run it through our function and change its value to 34."
rem wait for a key press.
wait key
rem give you time to release the key.
wait 200
rem Make the variable equal 34 using our function.
ChangeArray(34)
rem Print the new contents of the array.
sync : print "Now our array is equal to ",Array(1) : sync
rem Wait for you to press a key.
wait key
rem End the program
end
rem Declare our functions after the program has ended, that way the declaration will not get run.
Function ChangeArray(Amount)
rem Assign the array the proper amount.
Array(1)=Amount
rem End of the function.
endfunction
- Tall Red Box I
rem *************************************
rem EXAMPLE 3- MakeTallRedBox in action I
rem *************************************
rem Setup Demo
sync on
sync rate 60
autocam on
Randomize Timer()
rem Make this variable equal to a random number between 1 and 10.
RandomNum=1+rnd(9)
rem Call our MakeTallRedBox function and make the object a random number between 1 and 10.
MakeTallRedBox(RandomNum)
rem Begin a loop that ends when you press enter.
repeat
rem Print some text to the screen
Text 0,0,"HERE IS OUR TALL RED GHOSTED BOX. THE OBJECT NUMBER IS "+str$(RandomNum)
Text 0,50,"PRESS ENTER TO EXIT."
rem Refresh screen
sync
rem Exit the loop when you press ENTER.
until returnkey()
rem End the program so we don't hit a function declaration mid-program.
end
rem Declare the function.
Function MakeTallRedBox(OBJECT)
rem create a tall box using the specified object number (as specified in the function call)
Make Object Box OBJECT,10,50,10
rem Color it red.
Color Object OBJECT,rgb(255,0,0)
rem Make it ghosted
ghost object on OBJECT
rem end of function.
endfunction
EDIT: Alright, more examples:
Putting strings into functions.
rem *****************************************
rem EXAMPLE 4- PASSING STRINGS INTO FUNCTIONS
rem *****************************************
rem Place The print cursor at 0,0.
set cursor 0,0
rem Use our doubleprint function to print two lines of text using the print command. We just put the text in, and it prints it!
DoublePrint("Woah I can't fit all I have to say on one line.","Hey, another line. This is great! Thank you doubleprint function! PRESS A KEY TO EXIT.")
rem Wait for the user to press a key in order to exit.
suspend for key
rem End the program.
end
rem Declare our function after the program has ended so we don't "Hit a function declaration mid-program".
Function DoublePrint(Text1$,Text2$)
rem Print our first line of text. It will say whatever was put in the variable Text1$
Print Text1$
rem Print our second line of text. It will say whatever was put in the variable Text2$
Print Text2$
endfunction
I hope this helped!
P.S. SEE TDK MAN'S POST FOR MORE INFO.