Sunteți pe pagina 1din 7

Functions

Monday, August 12, 2019 5:50 PM

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.

Conditional Logic is what makes complex possible.


However, Functions are what makes programming bearable.
A short way to describe functions is 'a block of code', that you can name. Then, anytime you want to run
that code, you just use it's name.

That description doesn't tell you much, so let's jump right into an example.

Defining Functions

Go to your plugin document and, on a new line, type the following:

function sayHello() {
console.log("Hello!");
}

Save it, reload your game with F5 and go into the console.
type the following

sayHello()

and hit Enter.

You'll see the string "Hello!" printed out to the console.

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!");

Now, you function should look like this:

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

New Section 2 Page 1


So what's the point here? Do we need a function to say hello and goodbye to us? Well, no, not
necessarily and certainly not right here and now. The point is to show you a basic function definition, as
well as where the code goes.

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 }

Let's define another function, one piece at a time.


Go back to your .js document, make a new line, and create a function. The first thing you do is type the
keyword function
Hit the spacebar once after the word function, and then write the name you'd like to give the function.
Just like variables, you can name functions whatever you'd like. As such, it's best to keep the names
relevant to the function's purpose.

Let's name this function addToVar


Insert another space after the name, and put a set of parenthesis ()
After the parenthesis, put a pair of curly braces {}
Place your cursor inside of the curly braces, and press enter twice.

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

New Section 2 Page 2


Inside of the curly braces, we put our code to execute. On the empty line between the braces, type the
following

$gameVariables.setValue(1, $gameVariables.value(1) + 20);

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.

So now, your function should look like this


//Function to increase Game Variable 1 by 20
function addToVar() {
$gameVariables.setValue(1, $gameVariables.value(1) + 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.

So it worked. Let's run it again.


Now you could either type the line again, or you could use the 'history' of the console.
Simply press the up key while the text cursor is active and blinking on the console.
If you press it again, it will bring up the line you typed before that. You can do this for a good while. I
don't know what the cutoff point it.

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.

Whichever way you prefer, run the addToVar function again.


Then call the value of Game Variable 1 again, to verify that the number increased again.

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

//Function to increase Game Variable 1 by 20


function addToVar() {
$gameVariables.setValue(1, $gameVariables.value(1) + 20);
console.log($gameVariables.value(1));
}

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.

New Section 2 Page 3


the value to the console.
Now you could save this, and try it out, and see that it works. However, there's a shorter, easier
statement to use, that is more appropriate for the situation.

The return keyword

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.

When there isn't any data to return, it simply returns 'undefined'.


However, if we went into our function, and changed it to look like this

//
//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 RETURNED VALUE

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

New Section 2 Page 4


var result = addToVar();

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.

DEFINING ARGUMENTS IN A FUNCTION

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;
}

Save, refresh your game, then in the console type

timesTwo(10)
and hit Enter.

The console prints out 20


Put in any number you want, between the parenthisis and run it again. You can probably tell what it's
doing.

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.

In the timesTwo function definition, inside of the parenthesis I wrote num.


That was me defining an argument, called num. I could have called it whatever. x, placeholder,
myNumber, yourFriendSteve. As always, name it something relevant, and short if you can help it. I name
it num, because this whole function is mean to return a number you pass it, multiplied by 2.

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.

New Section 2 Page 5


DEFINING MULTIPLE ARGUMENTS

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

madLib("jerk", "nipple", "unicorns")

You would get


"I am a jerk with one nipple and a fistful of unicorns"
Fun stuff.

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.

A Final Note About Functions

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.

Try this example function

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.

//Return the HP of a character with a specific id, in a user-friendly string.


function findHPString(id){
var hp;
var name;

//Find HP and Name of character with matching id


hp = $gameActors.actor(id).hp;
name = $gameActors.actor(id).name();

New Section 2 Page 6


$gameMessage.add(name + " currently has " + hp + " health left.");
}

New Section 2 Page 7

S-ar putea să vă placă și