This is how to make user defined functions...|
A function is a group of lines of code, that can be called apon whenever needed.
An example function call is:- ShowText(0,0,"Hi there!", 3000);
This calls the function ShowText with the parameters 0, 0, "Hi there!" and 3000...
ShowText is defined like so:-
function ShowText(x,y,txt, ms)
var font = GetSystemFont();
font.drawText(x, y, txt);
Now as you can see, ShowText actually takes parameters of x, y, txt and ms...
But in calling ShowText like:- ShowText(0, 0, "Hi there!", 3000) we've substituted x, y, txt and ms
with the values 0 for x, 0 for y, "Hi there!" for txt and 3000 for ms.
We could call ShowText and make it look exactly like:- ShowText(x, y, txt, ms)
Simply by doing something like this:-
var x = 0, y = 0, txt = "Hi there!", ms = 3000;
ShowText(x, y, txt, ms);
Ok, thats that done with. Now, lets return a value from our functions.
var me = GetRandomText.arguments;
Huh?! No parameters are defined though?!
Yeah, you can pass more parameters into a function than the defined parameters...
A defined parameter list looks like:- ShowText(x, y, txt, ms)
ShowText has 4 parameters defined it its header.
But in the body of the function, you could access
ShowText(x, y, txt, ms, ?, ??, ???, ... etc) by thinking of them as:-
ShowText.arguments == x
ShowText.arguments == y
ShowText.arguments == txt
ShowText.arguments == ms
ShowText.arguments == ?
ShowText.arguments == ??
ShowText.arguments == ???
ShowText only exists within the ShowText function!
ShowText.arguments is an array of the parameters passed to the function.
So basically, GetRandomText randomly returns one of its parameters.
Lets throw it into the ShowText function as the txt parameter.
ShowText(16, 16, GetRandomText("Hey!", "Hi there!", "Yo!"), 3000);
This will show some random text on the screen for 3000 milliseconds...
Now lets show how to create your own functions...
This is a function with no parameters, that returns nothing:-
This is a function with one parameters, that returns twice the parameter:-
return (2 * x);
Final issue with functions, scope.
If a variable is created within a function, it is destroyed when the function ends.
Its scope is local to the function that defined it.
A variable that is defined outside a function, is not destroyed when the function ends.
Its scope is global, and all functions can access and modify its value.
In this example gVar is global, and temp is local...
var gVar = 25;
var temp = 30;
Thats its folks, soon, I will cover loops and special statements, like if, with, etc...