Roblox > Scripting Lessons >

Lesson 7: Organizing Into Functions

Functions are a great way to break down large, complicated tasks into several smaller ones. Functions are delclared like this:

function name(argument1, argument2, ...)
-- insert actions here
end

"name" in this example, is the name of the function. Arguments are variables that are fed into the function. To execute the function that was just created you would do this:

name(1, "string", variable)

That will run the function and give it the arguments 1, "string", and variable. Functions can also return values into their calling function. For example:

function getArea(length, width, height)
return (length * width * height)
end

This function takes the arguments length, width, and height, and returns their values multiplied together. A good way to think of this would be to think of the function in the eqation as being the value that it returns. For example:

if (getArea(3, 1, 2) == 6) then -- This is a true statement because 3 times 1 times 2 is equal to 6.
-- insert actions here
end

If there is anything about this that you didn't get PM me or Post on the Forums.

<- Previous Lesson  Next Lesson ->
Updated on Apr 23, 2010 by Ajedi32 (Version 6)
comments powered by Disqus