Functions
Functions
Functions
Variables are the basic building block of truly functional programs. They allow us to reserve a place to
store data, so that we can write formulas and expressions in our code without necessarily having the
actual values yet.
Conditional Logic is often what's taught next, and In my last lesson I said that would be covered next,
but I have different theories about that. I personally think Functions are better to learn next, so that's
what we're about to tackle.
That description doesn't tell you much, so let's jump right into an example.
Defining Functions
function sayHello() {
console.log("Hello!");
}
Save it, reload your game with F5 and go into the console.
type the following
sayHello()
Go back to your plugin document and add a line below the console.log("Hello!"); statement.
On that line, type the following
console.log("Goodbye!");
function sayHello() {
console.log("Hello!");
console.log("Goodbye!");
}
Save your document, refresh your project and call the sayHello function in the console again.
This time, it should print out both statements, "Hello!" and "Goodbye!"
So what's the point here? Do we need a function to say hello and goodbye to us? Well, no, not
In JavaScript, there are many different constructs that are set up in a simlar way to functions. A set of
parenthesis, followed by a set of curly braces. You'll see this now, and more from here on out. But know
this. Your code to execute, that goes inside of the curly braces. That means after the { and before the }
It's a good practice to have your keyword function, the name, the parenthesis and the opening curly
brace all on one line. The closing curly brace should be on it's own line, and an empty line in between.
This is pretty much how you should start all function declartions.
Anyway, right now your function should look something like this
function addToVar () {
Now, this function is valid. It is considered complete. It doesn't do anything, but it is defined correctly. If
you want, save your doc, refresh your project and type the first half of the function name into the
console. Intellisense will list the function, meaning it was successfully defined.
Now, we will add some code to it, but first, let's talk about the single most important practice in coding.
Commenting. You wouldn't believe how quickly your own code can become unrecognizable after just
days of having not read it.
Commenting lets you write notes to yourself or other scripters, right there in the script. Comments
won't be read by the program, so you can add them wherever you want without fear of messing your
code up. Let's write a single line comment above the function, to describe what it's supposed to do.
On the line above your function, (make a new line if you have to), type the following
//Function to increase Game Variable 1 by 20
Now, it's pretty obvious what we're going to be doing with this function. The comment makes it clear in
plain English. Sometimes the syntax of JavaScript doesn't make it super clear to someone (even the
scripter themselves) exactly what is happening. Comments alleviate that.
Always write comments, and always write them assuming an idiot would need to understand them. I
mean it. You'll probably forget to do this in the beginning, because you're trying to remember
everything. But you'll start using them eventually, so why not try to make it a habit now?
Inside of the curly braces, we put our code to execute. On the empty line between the braces, type the
Just a quick explanation, hopefully you remember what the above code does from the last lesson on
Variables. However, if you don't, it's using the script call for Game Variables, calling variable 1, and
setting it's value to the currrent value + 20.
Save your document, refresh your game and go to the console. type
addToVar()
and hit Enter.
And nothing seems to happen. The console spits out a line that says 'undefined'. That will make sense
later on in this lesson.
But was it successful? Did it actually work? Well, we didn't get an error, so it kind of seems that way.
Still, we should be sure.
Time to check the value of Game Variable 1. In the console, type
$gameVariables.value(1)
and hit Enter.
Assuming it started at 0, the value returned should now be 20.
There's been times where a full day had passed since I'd opened RMMV, and I launched my game,
opened the console, pressed up and still had access to the last lines I had typed.
You can do this as many times as you'd like, but it makes me think…wouldn't it be easier to just
incorporate those two calls into the function?
Rather than have to keep typing them both to test them. I know I'm going to want to verify that the
increase worked properly, so it makes sense. Maybe I could do
There, now every time you call the addToVar function, it will both add 20 to the variable, and print out
the value to the console.
Functions have the innate ability to use the keyword return to literally 'return' from the function with a
piece of data. There are a lot of reasons for this, but rather than come up with them, we have one right
here.
When you type into the console, it's like you're typing inside of the console.log() parenthesis.
Don't read to much into that, just know that the console is there for programmers, not for players of the
game. It's here to help you test. So it tries to return data whenever possible.
//
//Function to increase Game Variable 1 by 20
function addToVar() {
$gameVariables.setValue(1, $gameVariables.value(1) + 20);
return $gameVariables.value(1);
}
We would get the same effect as the other method. Not really much less typing, but logging to the
console is just for verification, for you to test stuff. More often than not, your functions will perform
some calculations, check some conditions, and return some kind of data as a result.
Another important thing to note is that the return statement terminates the function. Once the
computer reads that line, it leaves the function, and if there is a piece of data to the right of return, like
in the example above, it will return with that data.
If some of what I just said doesn't make sense right away, don't worry. You'll see this all the time, and it
will make sense, trust me.
If you haven't already, save your document, refresh your game, and test out your function. Now when
you type
addToVar()
and hit Enter, you see your result right away. After typing it once, you can just hit Up and then Enter a
bunch of times to keep running it.
You're seeing the value because you're running the function in the console. Therefore, since a value is
being returned by something, the console wants to show it to you.
That's not really what return is for, though. It's often used for assignment.
Assigning a value is just storing it, remember? If you think about how to assign a value to a variable, it's
pretty simple: variable name first, followed by = assignment operator, followed by value to be assigned.
Well, when a value is returned, such as with our addToVar function, it can be assigned to a variable.
Try this out. In the console, we'll create a new variable, and assign it the value returned from our
function
After you enter that, type the name of the result variable into the console, and you'll see it holds the
value that was returned when the function ran last.
If you run the addToVar function on it's own, you'll see it keeps increasing, just like it's supposed to. But
now, if you check the result variable, it still has that previous value.
That's because it was the value that was returned when it was assigned.
The point to take away from this is that returned values can be assigned to other variables, which will
come in handy quite often.
Functions are very flexible. You haven't seen all they can do. Before anything else, type the following
into your .js document on a new line
//Multiply a number by 2
function timesTwo(num) {
return num * 2;
}
timesTwo(10)
and hit Enter.
You've also probably noticed some other instances of typing into the parenthesis of what seem like
functions. Such as $gameVariables.value(1)
or $gameVariables.setValue(1, $gameVariables.value(1) + 20)
or console.log("Anything you log")
When you define a function, you can define arguments. An argument is a variable that belongs to a
function. It only exists in the function, you can't refer to it outside of the function. They allow you to
pass data to the function, so that it can use it for various reasons.
Inside of the function, I can use the arguments in a forumula or statement, just like a variable.
So I used a return statement, because I want this data to…be returned, of course.
I multiplied num by 2, and that value is what gets returned.
Arguments give you a ton of flexibility, because it allows functions to behave differently on the fly, and
you'll see plenty of reasons as you learn why arguments make your life easier, and give you way more
power in writing functions.
You can have more than one argument. You can have as many as you like, but it's best not to make too
many.
Here's an example of a function with three arguments
function madLib(a, b, c) {
return "I am a " + a + " with one " + b + " and a fistful of " + c;
}
If you saved this, and tested it in the console, with the following example
Now, you'll learn more about handling arguments later, but for right now, you'll need to supply all three
arguments when you call this function. It is possible to make arguments behave as 'optional', however
right now, know that you'd need to use all three for this to work properly. Otherwise, if you don't supply
one or more arguments, that argument will return 'undefined', in the mad Lib.
Also a not, arguments are called in the order they are declared. The first argument you supply when you
call will be assigned to the first argument defined in the function definition.
You can create variables inside of functions that aren't arguments. Arguments are defined in the
parenthesis, an separated by a comma.
Local variables, ones that have a limited 'scope', are defined the way other variables are defined, but
they must be inside of the curly braces of the function.
Once a function is finished running, local variables stop existing. This is a good way to save memory, but
that will be discussed more later, and something you'll learn as you go.
Here's an example of a more fleshed out but still pretty simple function. You can try it out yourself, don't
worry if you don’t understand it, but don't be surprised if you learn a few things. If you run this function
in the console, take a look at the game screen after you do.