Home > Uncategorized > GlowScript Tutorial 6: Functions

GlowScript Tutorial 6: Functions

You want to do cool stuff with numerical calculations, right?  Well, you can only go so far before you need to learn about functions.

Actually, functions aren’t anything new.  You have already used functions like mag() and norm().  Let’s make our own function.  Take a look at the following simple program.


When you run that, it should look like this:


This function is created in line 3 with “def”.  Test is the name of the function and x and y are the two parameters that you pass to it.  Anything indented after the def statement is part of the function.  The “return” line tells the function what to give back when you call it.

Maybe that sounds confusing.  Of course this “test” function is sort of silly.  How about I make a function that recreates the magnitude of a vector.  It would look like this.


Be aware that I have to use a unique name for this function.  I couldn’t call it “mag” since that’s already used.  Anything inside the function (like tempmag) only exists inside the function.  I can give three different things to the function when I call it.

  • A variable that is a vector (like A or B).
  • A vector – like vec(-1,3,4)
  • or a scalar (like 3).

Here is what happens when I run this program.


It appears that the first three times the function works correctly.  When you give it a scalar, the function basically replies “dude.  I don’t know what you are doing.”  Your function uses the components of a vector.  If you don’t give it a vector, it won’t work.  The output says “NaN” which stands for “Not a Number”.

Ok, one more function.  What if I want to sum the numbers up to a certain number.  For instance, if I gave it 4, I would want it to calculate 1+2+3+4 = 10.  Here is that function.


I guess I should have talked about loops first.  Right?  I feel dumb now although I technically DID talk about loops in previous tutorials when we used the “while” loop.  Here is another kind of loop, he “for” loop.  This “for” loop makes values of i for everything in n.  Here is a super simple loop example.


Running gives this:


You can use any variable instead of “i” – but it will start from the value 0.  That’s why my dumb counting function adds i+1 to the sum for each loop.  Maybe it was a bad example of a function.

In the next tutorial we will do some physics using functions.

GlowScript Tutorial 7: Useful Projectile Motion

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: