# Functions

Oct 09 2019, 4:36 PM PST 10 min

Functions provide developers with a useful way of creating a code block and giving that code block, or sequence of commands, a name. When a developer wishes to perform that sequence of commands, they can refer to it by name, rather than cutting-and-pasting the code block over-and-over.

Some functions are predefined for us in the `Global_namespace`, and some functions are created by developers. Methods are also an example of functions for specific objects. The idea behind most functions is either to check or modify something or to save yourself some time by avoiding repeating code.

## Definition

Functions can be confusing from a conceptual standpoint. These analogies may help you.

A function as a subroutine - You can think of a function as a “subroutine,” or a block of code, that can be executed again and again. This helps us to reduce needless replicating code throughout our scripts to perform the same sequence of tasks over and over.

``````function YouCanRepeatMe()
print("Hi.!")
print("I like saying hi!")
print("Hi there!")
end

YouCanRepeatMe()
YouCanRepeatMe()
YouCanRepeatMe()
YouCanRepeatMe()
``````

You can see here, that, instead of repeating the lines inside of the function 12 times, they are stated only, but invoked 4 times in a row. This is a subroutine. By giving the subroutine a name, the code you write can also become a lot easier to read as our function names can be more semantic and descriptive.

A function as a, well, function - If you have studied algebra in school, then you are probably familiar with the notation `f(x) = x*2`. This notation communicates something very important: you input a number, in this case, `x`; then the function multiplies that number by 2. Functions on Roblox can work the same way: you input a variable, and then receive output that varies depending upon the input.

### Using Functions

The basics of writing a function are actually pretty straight-forward.

``````function twoPlusTwo() -- Function name
x = 2 + 2          -- Variable
print(x)           -- Print variable's value
end                   -- End

twoPlusTwo()          -- This is how you call a function. Once called it will run your block of code from before.
``````

Everything between `function` and `end` defines what your function will do. Let’s break it down:

• We declare a function with the name of `TwoPlusTwo`. You can name a function anything you want, but typically, you’ll want to give it a name relevant to its purpose. Note that the name must follow the same naming conventions as variables.
• We assign a value of 2+2 to the variable `x`
• We print `x` to the console.

It’s important to note that your function won’t run/execute until you specifically call it. That’s what the last line - `TwoPlusTwo()` - does. If you delete this line, nothing will get printed to your screen, because, as previously stated, the function won’t run.

When calling a function, the code bookmarks where you started and returns to the bookmark after the function executes. For example, examine this code:

If you check your output, notice how it will execute `main()`, then put a bookmark where you called `firstfunction()`, execute `firstfunction()`, print “We are in main”, bookmark it where you called `secondfunction()`, and lastly, execute `secondfunction()`.

#### Using Arguments and Parameters

When a function is called, the caller can pass to the function one or more values to be used by the function when processing the request. The values are placed into variables with their own unqiue name. The variables are also called “parameters”, or “arguments.”

The parameters in a function are always local to the function and are only used in the function’s scope and its descending scopes. For a nice example, I’ll demonstrate a short little function that adds its arguments together, and displays the result in the output.

If you call a function and enter too many arguments, the excess ones will be ignored, on the other hand, if you forget any, the value of nil will be given to all missing arguments.

#### Using Return

Sometimes when using functions, you’ll want to get a value out of them. Let’s take another look at the Add function before, but this time, instead of printing the sum, we’ll use return.

When return is called, a couple things happen:

• The function stops executing; also note that you cannot have any statements immediately after return or you will receive an error.
• The function becomes somewhat like a variable, holding the value(s) returned. Like this you can “set” a variable to what the function returns.
• Examine this code to understand this idea better:

#### Functions as Variables

In Lua, functions are first class objects. This means that they are treated as an expression, like `"Testing"`, and can be stored in a variable. For example:

Similarly, they can be passed as arguments to other functions.

This can also be done to custom made functions. Examine this code:

#### Event Triggered Functions

Functions don’t have to be called by writing out a command. They can be called by an action known as an event. For example, say you want your function to be called when a player enters a game. The event that corresponds to this scenario is the `Players/PlayerAdded` event. You would write your function as usual. But then instead of calling it the same way as before, you’d treat it as an event handler, and bind it to an event - typically referred to as a connection line.

``````function PlayerAdded(p)
print(p.Name)
end

``````

Notice how although I set an argument when writing the function, I didn’t include it when setting the function to be called. That’s because we don’t want the function to be called when we bind the event handler - we want the function to be called when the event happens. In this case, the function is being treated as a variable. Most events call their event handlers with arguments. In the case of the `Players/PlayerAdded` event, the handler is called with a single argument - the player who joined the game.

#### Anonymous Functions

Functions can also be created anonymously, that is, without assigning them a name. These are occasionally known as lambda expressions.

For example, the following syntax is a valid way to define a function.

``````function() print("hi") end
``````

This isn’t a useful statement by itself because the function is declared, but we have given ourselves no way to invoke the function. To do that, we assign the function to a variable.

For example:

``````hi = function() print("hi") end
``````

This is functionally equivalent to the following:

``````function hi() print("hi") end
``````

Anonymous functions are often used as a shorthand where a function is passed as an argument to another function. A good example of this is the `Delay` function:

``````Delay(1, function()
print("I've waited 1 second now")
end)
``````

Notice the Delay function’s closing parenthesis is after the “end” for the function.

Another common place where anonymous functions are used is when connecting event handlers

``````game.Players.PlayerAdded:Connect(function(p)
print(p.Name)
end)
``````

#### Recursion

In programming “recursion” is the process of a function calling itself. Recursion is often used in place of loops. An advantage to using recursion over loops is its simplicity and the main disadvantage is that large recursions could cause heavy use of memory, and on Roblox, lag.

### Functions Within Tables

Since a function is just another type, they can be stored in tables like any other data type.

``````tab = {}
function tab.func( arg )
print "I'm in a table"
end
tab.func(1)
``````

This is the same as:

``````tab = {
func = function( arg )
print "I'm in a table"
end
}
tab.func(1)
``````

### Methods

A method is a special function that operates on the table that contains it. This is what Roblox uses for its objects. Lua provides a special syntax for methods:

``````tab:method(args)
``````

This is equivalent to:

``````tab.method(tab, args)
``````

Notice that the table is used both to get the function and as an argument.

You can declare methods directly:

``````tab = {}
function tab:method( args )
print( "I'm a method from " .. tostring(self) .. " with args " .. tostring( args ) )
end
``````

Which is the same as:

``````tab = {}
tab.method = function( self, args )
print( "I'm a method from " .. tostring(self) .. " with args " .. tostring( args ) )
end
``````

Tags:
• lua
• function