Lesson 12: Returning from Functions

I’ve missed a small bit about Functions out from these lessons which is crucial to understand what’s happening when using interfaces/methods… and when it comes to writing your own structs.

You can get the result of a function by making sure the last line returns the value you want.

fn MultiplyThese varA varB =
 (
 varA * varB
 )
a = MultiplyThese 10 10

The above code is going to assign a to the result of the MultiplyThese function to the variable a, so 10 * 10, a == 100.

Lets look what adding another line in will do….

fn MultiplyThese varA varB =
 (
 varA * varB
 50
 )
a = MultiplyThese 10 10

The second line of the function is 50 so this is what it will return to us regardless of what varA * varB actually gives us. We can force the function to return the value from the 1st line by using return.

fn MultiplyThese varA varB =
 (
 return varA * varB
 50
 )
a = MultiplyThese 10 10

A second return value will override the first, this is useful for if test/case clauses.

fn MultiplyThese varA varB
 (
 return varA * varB
 if varB == 0 do return 1
 )

You could also make sure the value that is returned is what you want by declaring the local variable at the end of your function.

fn MultiplyThese varA varB
(
   local endResult
   endResult = VarA * VarB
   if varB == 0 do endResult = 1
   endResult
 )

It’s important to understand how functions return values and the scopes of these when using recursive functions, which I’ll explain in another lengthy post.

Advertisements

About davewortley

Somewhere between an artist and a programmer, I like technical things, but being creative. I love problem solving and coming up with elaborate solutions. This blog is where I shall share ideas, tips, tutorials and anything that amuses me.
This entry was posted in Lessons, MaxScript. Bookmark the permalink.

5 Responses to Lesson 12: Returning from Functions

  1. David says:

    Very good! Don’t take long between posts – I know sometimes work can be overwhelming, though.
    Anyway, good to have you posting again, David!

    Like

  2. Thank you! Very helpful

    Like

  3. Johanes says:

    Good stuff, thank you for these lesson and gotcha posts!

    Like

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