PcoWSkbVqDnWTu_dm2ix

10 min

Functions are sets of instructions that can be used multiple times in a script. Once defined, a function can be executed through a command or triggered through an /articles/events|event.

Defining Functions

A basic function declaration includes the function keyword followed by the function name and a pair of parentheses (()). Since the function’s body will be a block of code, it must be closed with the end keyword.

Between the () and end is where commands and other code make up the function body. These commands will be executed when the function is called:

Calling Functions

Once a function is defined, it can be executed by calling it (functions do not self-execute). To call a function, simply type its name followed by parentheses (()):

Function Parameters

Functions can utilize parameters for data that will be passed in. When you declare a function, you may include one or more parameter names inside the parentheses:

When calling a function with parameters, specify the values that should be passed to the function. For instance, the following function takes the two numbers passed in during each call, adds them together, and outputs the result:

Returning Values

In addition to accepting parameters, functions can also return (send back) data to the calling command. This is done through return values. Working off the example above, the following function returns the sum instead of printing it:

When a function returns a value, it can be assigned to a variable or used wherever a variable can be used. The following code illustrates this concept:

Unlike some programming languages, Lua even lets you return multiple values from a function:

Other Function Techniques

Event-Triggered Functions

Functions don’t always need to be called with a command — they can also be called through an event. See the /articles/events|Handling Events article for details.

Anonymous Functions

Functions can be created anonymously, that is without assigning them a name. This is useful when you need to call a function from the result of another function or event, for instance a delay() call or a /Players/PlayerAdded|PlayerAdded event connection:

Functions Within Tables

Since functions are a Lua data type, they can be stored in tables. This technique is commonly used in ModuleScript|ModuleScripts where the module’s table contains various functions:

Once contained in the module’s table, these functions can be called by any script which accesses the ModuleScript via require():

Tags:
  • lua
  • coding
  • function