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
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 is where commands and other code make up the function body. These commands will be executed when the function is called:
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 (
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:
/articles/Scope|scopeand its descending scopes.
nilwill be used for all missing parameters.
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:
returncommand as doing so will generate an error.
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
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.
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:
endclosure before the ending
)of a containing function or event like
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