Functions: Difference between revisions
>JulienDethurens |
m Text replacement - "<SyntaxHighlight code="lua">" to "<syntaxhighlight lang="lua">" |
||
(31 intermediate revisions by 3 users not shown) | |||
Line 4: | Line 4: | ||
== Introduction == | == Introduction == | ||
Functions perform specific tasks. Some functions are already [[Function Dump|predefined]], and some functions you create yourself. [[Method|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. | {{type|function|Functions}} perform specific tasks. Some {{type|function|functions}} are already [[Function Dump|predefined]], and some {{type|function|functions}} you create yourself. [[Method|Methods]] are also an example of {{type|function|functions}} for specific objects. The idea behind most {{type|function|functions}} is either to check or modify something, or to save yourself some time by avoiding repeating code. {{type|function|functions}} are also used to define code that you don't want to call immediately. | ||
== Using Functions == | == Using Functions == | ||
The basics of writing a function is actually pretty easy. | The basics of writing a {{type|function}} is actually pretty easy. | ||
< | <syntaxhighlight lang="lua"> | ||
function twoPlusTwo() -- Function name | function twoPlusTwo() -- Function name | ||
x = 2 + 2 -- Variable | x = 2 + 2 -- Variable | ||
Line 16: | Line 16: | ||
twoPlusTwo() -- This is how you call a function. Once called it will run your block of code from before. | twoPlusTwo() -- This is how you call a function. Once called it will run your block of code from before. | ||
</ | </syntaxhighlight> | ||
Everything between | Everything between '''function''' and '''end''' sets what your {{type|function}} will do. Here, you are: | ||
* Declaring a function by 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. | * Declaring a {{type|function}} by the name of {{`|TwoPlusTwo}}. You can name a {{type|function}} anything you want, but typically, you'll want to give it a name relevant to its purpose. | ||
* Assigning a value of 2+2 to {{`|x}} | * Assigning a value of 2+2 to {{`|x}} | ||
* Printing {{`|x}} | * Printing {{`|x}} | ||
It's important to note that your function won't run/execute until you specifically | It's important to note that your {{type|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 {{type|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: | When calling a {{type|function}}, the code bookmarks where you started and returns to the bookmark after the {{type|function}} executes. For example, examine this code: | ||
{{code and output| | |||
code= | |||
function firstfunction() | function firstfunction() | ||
print("We are in 'firstfunction'") | print("We are in 'firstfunction'") | ||
Line 44: | Line 45: | ||
main() | main() | ||
|output= | |||
We are in 'firstfunction' | |||
We are in 'main' | |||
We are in 'secondfunction' | |||
}} | |||
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(). | 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(). | ||
Line 51: | Line 57: | ||
{{main|Arguments and Parameters}} | {{main|Arguments and Parameters}} | ||
When a function is called, the caller can set some variables within the function. Properly, these variables are called "parameters", although they are often referred to as arguments as well. The values that these variables are set to are called "arguments". For a nice example, I'll demonstrate a short little function that adds its arguments together, and displays the result in the output. | When a {{type|function}} is called, the caller can set some variables within the {{type|function}}. Properly, these variables are called "parameters", although they are often referred to as arguments as well. The values that these variables are set to are called "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 {{type|function}} that adds its arguments together, and displays the result in the output. | ||
{{code and output|code= | {{code and output|code= | ||
Line 66: | Line 72: | ||
}} | }} | ||
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. | If you call a {{type|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 === | === 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 | Sometimes when using {{type|function|functions}}, you'll want to get a value out of them. Let's take another look at the Add {{type|function}} before, but this time, instead of printing the sum, we'll use '''return'''. | ||
{{code and output|code= | {{code and output|code= | ||
Line 79: | Line 85: | ||
end | end | ||
x = | x = add(5, 2) | ||
print(x) | print(x) | ||
Line 89: | Line 95: | ||
When return is called, a couple things happen: | When return is called, a couple things happen: | ||
* The | * The {{type|function}} stops executing; notice how "Sum Found" wasn't printed. This is useful for preventing execution of code in a {{type|function}}. | ||
* The {{type|function}} becomes somewhat like a variable, holding the value(s) returned. Examine this code to understand this idea better: | |||
{{code and output | |||
|code = | |||
function addNumbers(num1, num2) | |||
return num1 + num2 | |||
end | |||
a = addNumbers(3, 5) | |||
print(a) | |||
|output = | |||
8 | |||
}} | |||
=== Functions as Variables === | === 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: | In Lua, {{type|function|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: | ||
{{code and output| | {{code and output| | ||
Line 104: | Line 122: | ||
}} | }} | ||
Similarly, they can be passed as arguments to other functions. | Similarly, they can be passed as arguments to other {{type|function|functions}}. | ||
This can also be done to custom made functions. Examine this code: | This can also be done to custom made {{type|function|functions}}. Examine this code: | ||
{{code and output| code= | {{code and output| code= | ||
Line 119: | Line 137: | ||
=== Event Triggered Functions === | === 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. 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 an event - typically referred to as a | {{type|function|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 {{type|function}} to be called when a player enters a game. The event that corresponds to this scenario is the [[PlayerAdded (Event)|PlayerAdded]] event. You would write your {{type|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 an event - typically referred to as a '''connection line'''. | ||
< | <syntaxhighlight lang="lua"> | ||
function | function PlayerAdded(p) | ||
print(p.Name) | print(p.Name) | ||
end | end | ||
game.Players.PlayerAdded:connect( | game.Players.PlayerAdded:connect(PlayerAdded) | ||
</ | </syntaxhighlight> | ||
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 | Notice how although I set an argument when writing the {{type|function}}, I didn't include it when setting the {{type|function}} to be called. That's because we don't want the {{type|function}} to be called when we bind the event handler - we want the {{type|function}} to be called when the event happens. In this case, the {{type|function}} is being treated as a variable. Most events call their event handlers with arguments. In the case of the PlayerAdded event, the handler is called with a single argument - the player who joined the game. | ||
=== Anonymous Functions === | === Anonymous Functions === | ||
Line 135: | Line 153: | ||
{{main|Anonymous Functions}} | {{main|Anonymous Functions}} | ||
Functions can also be created anonymously, that is, without assigning them a name. These are occasionally known as lambda expressions. | {{type|function|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 function [[expression]] | For example, the following syntax is a {{type|function}} [[expression]] | ||
< | <syntaxhighlight lang="lua"> | ||
function() print("hi") end | function() print("hi") end | ||
</ | </syntaxhighlight> | ||
This isn't a valid statement by itself, but is instead a value that can be used in place of a function name. | This isn't a valid statement by itself, but is instead a value that can be used in place of a {{type|function}} name. | ||
For example: | For example: | ||
< | <syntaxhighlight lang="lua">hi = function() print("hi") end</syntaxhighlight> | ||
Is the same as: | Is the same as: | ||
< | <syntaxhighlight lang="lua">function hi() print("hi") end</syntaxhighlight> | ||
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 [[Function_Dump/Roblox_Specific_Functions#Delay.28Float_t.2C_Function_f.29_or_delay.28Float_t.2C_Function_f.29|Delay]] function; | Anonymous {{type|function|functions}} are often used as a shorthand where a {{type|function}} is passed as an argument to another {{type|function}}. A good example of this is the [[Function_Dump/Roblox_Specific_Functions#Delay.28Float_t.2C_Function_f.29_or_delay.28Float_t.2C_Function_f.29|Delay]] {{type|function}}; | ||
< | <syntaxhighlight lang="lua"> | ||
Delay(1, function() | Delay(1, function() | ||
print("I've waited 1 second now") | print("I've waited 1 second now") | ||
end) | end) | ||
</ | </syntaxhighlight> | ||
Notice the Delay function's closing parenthesis is after the "end" for the function. | Notice the Delay {{type|function}}'s closing parenthesis is after the "end" for the {{type|function}}. | ||
Another common place where anonymous functions are used is when connecting event handlers | Another common place where anonymous {{type|function|functions}} are used is when connecting event handlers | ||
< | <syntaxhighlight lang="lua"> | ||
game.Players.PlayerAdded:connect(function(p) | game.Players.PlayerAdded:connect(function(p) | ||
print(p.Name) | print(p.Name) | ||
end) | end) | ||
</ | </syntaxhighlight> | ||
===Recursion=== | |||
{{main|Recursion}} | |||
Recursion, in programming, is the process of repeatedly calling the same function from the bottom up. 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 == | == Functions Within Tables == | ||
Since a function is just another type, they can be stored in tables like other types. | Since a {{type|function}} is just another type, they can be stored in {{type|table|3=tables}} like other types. | ||
< | <syntaxhighlight lang="lua"> | ||
tab = {} | tab = {} | ||
function tab.func( arg ) | function tab.func( arg ) | ||
Line 175: | Line 198: | ||
end | end | ||
tab.func(1) | tab.func(1) | ||
</ | </syntaxhighlight> | ||
This is the same as: | This is the same as: | ||
< | <syntaxhighlight lang="lua"> | ||
tab = { | tab = { | ||
func = function( arg ) | func = function( arg ) | ||
Line 186: | Line 209: | ||
} | } | ||
tab.func(1) | tab.func(1) | ||
</ | </syntaxhighlight> | ||
== Methods == | == Methods == | ||
{{see also|Object-Oriented Programming}} | {{see also|Object-Oriented Programming}} | ||
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: | A method is a special {{type|function}} that operates on the {{type|table}} that contains it. This is what Roblox uses for its objects. Lua provides a special syntax for methods: | ||
< | <syntaxhighlight lang="lua">tab:method(args)</syntaxhighlight> | ||
This is equivalent to: | This is equivalent to: | ||
< | <syntaxhighlight lang="lua">tab.method(tab, args)</syntaxhighlight> | ||
Notice that the table is used both to get the function and as an argument. | Notice that the {{type|table}} is used both to get the {{type|function}} and as an argument. | ||
You can declare methods directly: | You can declare methods directly: | ||
< | <syntaxhighlight lang="lua"> | ||
tab = {} | tab = {} | ||
function tab:method( args ) | function tab:method( args ) | ||
print( "I'm a method from " .. tostring(self) .. " with args " .. tostring( args ) ) | print( "I'm a method from " .. tostring(self) .. " with args " .. tostring( args ) ) | ||
end | end | ||
</ | </syntaxhighlight> | ||
Which is the same as: | Which is the same as: | ||
< | <syntaxhighlight lang="lua"> | ||
tab = {} | tab = {} | ||
tab.method = function( self, args ) | tab.method = function( self, args ) | ||
print( "I'm a method from " .. tostring(self) .. " with args " .. tostring( args ) ) | print( "I'm a method from " .. tostring(self) .. " with args " .. tostring( args ) ) | ||
end | end | ||
</ | </syntaxhighlight> | ||
== See Also == | == See Also == | ||
Line 221: | Line 244: | ||
*[[In-Depth Scripting Guide]] | *[[In-Depth Scripting Guide]] | ||
[[Category: Data | [[Category: Data types]] |
Latest revision as of 06:18, 27 April 2023
Introduction
Functions perform specific tasks. Some functions are already predefined, and some functions you create yourself. 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. functions are also used to define code that you don't want to call immediately.
Using Functions
The basics of writing a function is actually pretty easy.
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 sets what your function will do. Here, you are:
- Declaring a function by 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.
- Assigning a value of 2+2 to x
- Printing x
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 set some variables within the function. Properly, these variables are called "parameters", although they are often referred to as arguments as well. The values that these variables are set to are called "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; notice how "Sum Found" wasn't printed. This is useful for preventing execution of code in a function.
- The function becomes somewhat like a variable, holding the value(s) returned. 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 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 an event - typically referred to as a connection line.
function PlayerAdded(p)
print(p.Name)
end
game.Players.PlayerAdded:connect(PlayerAdded)
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 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 function expression
function() print("hi") end
This isn't a valid statement by itself, but is instead a value that can be used in place of a function name.
For example:
hi = function() print("hi") end
Is the same as:
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
Recursion, in programming, is the process of repeatedly calling the same function from the bottom up. 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 table like other types.
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