This commit is contained in:
Joe 2026-02-02 12:08:47 -06:00
parent a9b4f8e83b
commit e6efc04756
8494 changed files with 495610 additions and 0 deletions

View file

@ -0,0 +1,105 @@
---
title: Code a function
description: What a function is, and how to code a function in Luau
next: /tutorials/fundamentals/coding-2/use-parameters-and-events
prev: /tutorials/fundamentals/coding-1/parents-and-children
---
**Functions** are sets of instructions that can be used many times in a script. There are pre-made functions (also called methods) like `print()` and `Library.task.wait()` that are built into most programming languages. Coders can also create their own custom functions for code they want to use more than once, but don't feel like writing over and over. In Luau, this is done by typing:
`local function nameOfTheFunction()`
Functions can be thought of like a recipe. They're both lists of specific instructions. For example, you could use a function to teach a robot how to make spaghetti. First, make a `local function` that lists the steps to prep the meal. Then, whenever you want dinner, just say, "Robot, run makeSpaghetti()".
The steps to make dinner might look like this:
1. Boil water
2. Add pasta
3. Cook 15 minutes
4. Add sauce
5. Serve on a plate
While the code version might look like something like this:
```lua
local function makeDinner()
-- List of instructions
end
-- Tell the code to run
makeDinner()
```
## Create a function
To practice, your first function will print your favorite food in the Output window. First set up the script you're going to use, if you don't remember how, here's a reminder:
1. Create a new script in **ServerScriptService**.
2. Rename the script _FunctionsPractice_.
3. Delete `"Hello World"`.
4. Add comment at the top. For example: `-- Prints your favorite food`
Next, you create and name the function. All functions should have names that help you remember what their purpose is. Functions names are camelCased, with the first letter lowercase and next words capitalized.
Examples: `addPoints()`, `restartGame()`, `rainFlamingLlamas()`
- Type `local function printFood()`, then press <kbd>Enter</kbd> on your keyboard. It should autocomplete the function to look like:
```lua
local function printFood()
end
```
<Alert severity="warning">
Type `end` yourself if the code doesn't autocomplete for some reason. If the function doesn't have an `end`, your code won't run.
</Alert>
### Add code to functions
All of the code for your function has to be typed between the lines `local function printFood()` and `end`. Any code not between those two points won't run when the function does.
```lua
local function printFood()
-- Code here runs when the function is called
end
-- Code here will not run
```
Information that is inside the function, or can be used by the function, is in **scope**.
- Between `local function printFood()` and `end`, use `print()` to state your favorite food.
```lua
local function printFood()
print("Curry!")
end
```
<Alert severity="success">
As you typed, your code should have indented automatically. This makes it easier for you and others to see the start and end of a function. If it didn't auto indent, you can press <kbd>Tab</kbd> at the beginning of the line to quickly indent it.
</Alert>
### Tell the function to run
There's one more thing we need to do before the function will work, and that's to tell it to run, also known as **calling** a function. Functions won't run until they are called. To call a function, type the function's name including the `()`.
1. Under `end`, type `printFood()`.
```lua
local function printFood()
print("Curry!")
end
printFood()
```
2. Test the code. Your favorite food should appear in the [Output](../../../studio/output.md) window.
### Troubleshooting tips
If your code doesn't run, check for errors such as the following:
- Check that `print("Your Food Here")` is between `local function printFood()` and `end`.
- Make sure that your food is a string, with quotations on `"each side"`.
- Check that the function is called after it's been created. `printFood()` should be below `end`.

View file

@ -0,0 +1,69 @@
---
title: Functions and events
description: Landing page for chapter on coding functions in Luau and using events on Roblox.
next: /tutorials/fundamentals/coding-2/code-a-function
prev: /tutorials/fundamentals/coding-1/parents-and-children
---
### Series description
Use functions and events to make code run when you want, as often as you want. With functions and events you can set up traps, buttons, health pickups, and more.
Covered in this course are functions, parameters, arguments, and returning values.
### Objectives and prerequisites
<table>
<tbody>
<tr>
<td width="20%"><b>Learning Objectives</b></td>
<td>
Learn to place code into reusable chunks called functions.
Understand what it means for code to be "in scope".
Set up events within an experience and use them to tell the functions when to run.
Practice using functions and events to create traps and buttons.
</td>
</tr>
<tr>
<td><b>Prerequisites</b></td>
<td>
Basic knowledge of Roblox Studio such as moving and rotating parts.
Previous experience creating Script objects and using variables, properties, and strings.
</td>
</tr>
</tbody>
</table>
### Series Contents
<table>
<thead>
<tr>
<th>Article</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>[Code a function](../coding-2/code-a-function.md)</td>
<td>Set up chunks of code in a way that only runs when you tell it to run.</td>
</tr>
<tr>
<td>[Use parameters and events](../coding-2/use-parameters-and-events.md)</td>
<td>How to code a function when you don't have all of the information yet.</td>
</tr>
<tr>
<td>[Parameters practice - buttons](../coding-2/parameters-practice-buttons.md)</td>
<td>Practice using events and parameters by making a bridge appear in-world with the push of a button.</td>
</tr>
<tr>
<td>[Multiple parameters and arguments](../coding-2/multiple-parameters-and-arguments.md)</td>
<td>Pass multiple pieces of information into a function at once.</td>
</tr>
</tbody>
</table>

View file

@ -0,0 +1,157 @@
---
title: Multiple parameters and arguments
description: Pass multiple pieces of information into a function in Luau using arguments and parameters.
next: /tutorials/fundamentals/coding-3/landing
prev: /tutorials/fundamentals/coding-2/parameters-practice-buttons
---
Functions can actually have more than one parameter, allowing for multiple arguments (pieces of information), to be passed into the function. An example might be assigning a player to a team. Here you would need a parameter to pass in the player, and a parameter to pass in which team to assign them to.
To set up multiple parameters, separate the parameter names with a comma.
```lua
local function assignTeam(playerName, whichTeam)
end
```
## Practice with multiple parameters
To practice working with multiple parameters, create a function that sorts objects into trash or recycling.
- The **first** parameter will be trash, which will be destroyed.
- The **second** parameter will be for recycling, which will be made shiny and new again.
### Set up the function
First set up the function with multiple parameters and then test your work.
1. Create a new script in **ServerScriptService**.
2. Code a new function named `sortGarbage()` with two parameters, `trash` and `recyclable`.
3. At the bottom of the script, call the function.
4. Quickly check the code so far using a print statement inside the function.
```lua
local function sortGarbage(trash, recyclable)
print("garbage test")
end
sortGarbage()
```
### Use multiple parameters
Inside the function, parameters can be used similar to variables. In this example, `trash` is destroyed and then `recyclable` is given sparkles using a Particle Emitter.
1. Delete the print statement, and use Instance.new() to create a new Particle Emitter as shown. This will be used to give recyclables their sparkle.
```lua
local function sortGarbage(trash,recyclable)
-- Create a new Particle Emitter
local sparkle = Instance.new("ParticleEmitter")
end
sortGarbage()
```
<Alert severity="success">
`Datatype.Instance.new()` can also be used to create objects such as Fire, folders, and parts.
</Alert>
2. Destroy whatever is passed in through the trash parameter the same as if trash were any other variable.
```lua
local function sortGarbage(trash,recyclable)
local sparkle = Instance.new("ParticleEmitter")
-- Destroy the trash
trash:Destroy()
end
sortGarbage()
```
3. Parent the Particle Emitter to the recyclable.
```lua
local function sortGarbage(trash,recyclable)
local sparkle = Instance.new("ParticleEmitter")
-- Destroy the trash and make recyclables shiny
trash:Destroy()
sparkle.Parent = recyclable
end
sortGarbage()
```
## Pass values through parameters
Time to take out the trash! With the parameters set up, the functions are ready to take in information.
1. Create two objects using basic parts to represent things you might throw away. One should be trash and one recyclable. Make sure they have unique names.
2. At the top of the script, add variables for the objects you created. These will be your arguments.
```lua
local Workspace = game:GetService("Workspace")
local cementBlock = Workspace.Cement
local glassBottle = Workspace.GlassBottle
```
3. At the bottom of the script, where `sortGarbage()` is called, pass in each argument.
```lua
local Workspace = game:GetService("Workspace")
-- Objects to use as arguments
local cementBlock = Workspace.CementBlock
local glassBottle = Workspace.GlassBottle
--Destroys trash and cleans up recyclables
local function sortGarbage(trash,recyclable)
local sparkle = Instance.new("ParticleEmitter")
trash:Destroy()
sparkle.Parent = recyclable
end
-- Pass in the arguments
sortGarbage(cementBlock, glassBottle)
```
4. Test your code. The object passed in first will be destroyed. The second object will sparkle.
## Order of parameters
Typically, arguments are matched to parameters based on the order they're passed in. For instance, the first argument is used for the first parameter. The second argument is used for the second.
In our example, there are two parameters. Whatever gets passed in first will always be trash, and the second will always be recyclable.
```lua
--Destroys trash and cleans up recyclables
local function sortGarbage(trash,recyclable)
local sparkle = Instance.new("ParticleEmitter")
trash:Destroy()
sparkle.Parent = recyclable
end
--Goes in order. Cement is destroyed and the glass bottle is recycled
sortGarbage(cementBlock, glassBottle)
--GlassBottle is destroyed and cementBlock is recycled
sortGarbage(glassBottle, cementBlock)
```
If you were to only pass in only one argument, that argument would be treated as trash. If you were to pass in three arguments, nothing would happen to the third argument because there is no third parameter.
## Summary
Parameters are placeholders through which values can be passed into functions. Arguments are the values that get passed through the placeholder. You can create multiple parameters by separating their names with commas. When calling functions, the order that values get passed into the receiving function determines which parameter they're used.

View file

@ -0,0 +1,111 @@
---
title: Parameters practice - buttons
description: Practice connecting functions to events by creating a button that activates a bridge.
next: /tutorials/fundamentals/coding-2/multiple-parameters-and-arguments
prev: /tutorials/fundamentals/coding-2/use-parameters-and-events
---
Buttons can be used by players to unlock new areas, give points, and reveal treasure. Whenever a player touches a button, it should give some feedback to let players know it's being interacted with, like change colors or make sounds.
In this example, the button will be used to activate a bridge. When the button has been pressed, it'll turn green and players will be able to use the bridge. If the player hasn't pressed the button, they'll fall through the bridge when they try to walk on it.
## Make a bridge
Start off by setting up the bridge.
1. Create an area in your environment where players will need a bridge.
2. Create a part for the bridge and rename it Bridge.
3. Select the bridge, in the Properties window:
- Change **Transparency** to .5. For Transparency, 0 is visible, 1 is invisible.
- Check **Anchor**.
- Uncheck **CanCollide**.
4. When you test the experience, the bridge should be misty looking and people shouldn't be able to walk on it yet.
<img src="../../../assets/education/coding-2/transparent-bridge.jpg" width="80%" />
## Create the button
Now that the bridge is set up, create the button.
1. Create a new part named _Button_.
2. Change the button color to red.
3. **Anchor** the button.
4. Move the button so it's slightly floating and not touching anything. This is so to make sure the `Touched` event doesn't accidentally fire.
<img src="../../../assets/education/coding-2/red-button.jpg" width="80%" />
## Make the button interactive
This time, instead of using the `Class.BasePart.Touched|Touched` event to create a trap, you'll use it to create a button that makes the bridge usable. To make the bridge collidable, use the code `bridge.CanCollide = true` within a custom function that runs when a player touches the button. You know everything else you need to complete the following steps.
Try to figure it out yourself before looking at the code solution.
1. Insert a new **script** into the button named _ActivateBridge_.
2. Delete `Hello World`.
3. Create variables for the bridge and for the button.
4. Create a **local function** that does the following the button is touched:
- Prints `"button touched"`.
- Changes button's color from red to green when touched.
- Changes bridge's transparency to 0 to make it visible.
- Makes the bridge usable by using the code `bridge.CanCollide = true`
5. Connect the function to the button's `Touched` event.
6. Test the script and make sure the bridge appears when the button is touched.
Code Solution
Below is one possible code solution
```lua
-- Insert this script into button
-- Turns the button green when something touches the button.
local button = script.Parent
local bridge = workspace.Bridge
local function buttonPressed()
print("button touched")
button.Color = Color3.fromRGB(0, 170, 0)
bridge.Transparency = 0
bridge.CanCollide = true
end
button.Touched:Connect(buttonPressed)
```
### Troubleshoot your code
**Issue: The bridge is already solid when the experience starts.**
Make sure that the parts are Anchored and not touching anything. The parts might touch something, like terrain or another part, and cause the buttonPressed() function to fire accidentally.
**Issue: You get an error in the Output window saying: "Bridge is not a valid member of Workspace"**
Check the following:
- The naming of your bridge. The bridge in your script must be named exactly like in the Explorer.
- That `part.Touched:Connect(buttonPressed)` is outside the `buttonPressed()` function.
### Optional code challenge
The script in this lesson can also be used to keep doors that keep players out of specific areas. Practice your coding skills and do the following:
- Create a door part.
- Create a button further away from the door.
- Change the script in this lesson so it makes the door change transparency and so the player can't collide with it.
Your version might look something like this:
```lua
local button = script.Parent
-- Reminder: Replace the name of the part, Gate, with the one in your project
local gate = workspace.Gate
local function buttonPressed()
print("button touched")
-- Changes button to red to give player feedback
button.BrickColor = BrickColor.Red() -- CHANGE THIS
-- Make the gate invisible
gate.Transparency = 1
-- Makes it so the player can walk through the gate
gate.CanCollide = false
end
button.Touched:Connect(buttonPressed)
```

View file

@ -0,0 +1,124 @@
---
title: Use parameters and events
description: How to pass information into functions using parameters and arguments. Also covers connecting functions to events.
next: /tutorials/fundamentals/coding-2/parameters-practice-buttons
prev: /tutorials/fundamentals/coding-2/code-a-function
---
Normally, functions can only use the information they have coded within them. Sometimes however, you might not know in advance what that information will be, or you want to be able to reuse the same function with multiple pieces of similar information. For example, if you wanted to use a function to display the name of the person who finished an obby course the fastest in giant letters to everyone. You won't know the name of the future winner until the race is finished.
**Parameters** are placeholders for information you want to give to the function at a later time. They're like windows that allow you to **pass** information to the function.
## Use parameters and events to set up a trap
This script will create a trap part that destroys whatever touches the part, including other parts. You'll have to use a parameter to set it up. Be careful to anchor the trap where it doesn't fall and destroy things unintentionally.
### Create a new part
A part needs to be set up that will destroy anything that touches it.
1. Create a new part that's not touching anything. If it's touching something it might go off too soon.
2. In the Explorer, rename the part:TrapPart.
3. **Anchor** the part.
### Set up the script
Use what you know about variables and the experience hierarchy to reference the trap part.
1. Add a new script into the trap part. Rename the script _TrapScript_.
2. Delete Hello World and add a descriptive comment.
3. Under the comment, create a new variable which finds the script's parent.
```lua
-- Destroys whatever touches the parent
local trap = script.Parent
```
### Create a function with a parameter
The trap will use a function to destroy whatever touched the part. To work, the function needs to know what touched the part. And that means using parameters. Parameters are typed inside the `()` that comes after a function's name. They look like this:
```lua
local function functionName(parameterName)
end
```
The actual information that gets passed through the parameter is called an **argument**. You'll create a new function called `onTouch()` with a parameter called `objectTouched` that will track whatever touches the trap and then destroy the touching part.
1. Create a local function. It can be named anything, but this lesson will use `onTouch`
```lua
local trap = script.Parent
local function onTouch()
end
```
2. Inside the `()`, type a name for the parameter. This lesson will use objectTouched.
```lua
local trap = script.Parent
local function onTouch(objectTouched)
end
```
3. Between `local function onTouch()` and `end`, create a print statement. You'll use this to check if something is touching the part in the next section.
```lua
local trap = script.Parent
local function onTouch(objectTouched)
print("Something touched the trap")
end
```
### Use an event to call the function
We want the function to run whenever something touches the part. To make that happen, connect the function to the `Touched` event. **Events** are things that happen in the experience. Like a player touching a part or losing health. When a function is connected to an event, the function runs whenever the event happens.
The `Touched` event fires whenever one part touches another part and can be used to create buttons, traps, and other objects that players interact with.
1. Beneath the function's `end`, type `trap.Touched:Connect(onTouch)`
```lua
local trap = script.Parent
local function onTouch(objectTouched)
print("Something touched the trap")
end
-- Connect the function to the Touched event
trap.Touched:Connect(onTouch)
```
2. Click Test and then touch the part. Check for your test print statement: `Something touched the trap`. If you can't see the string in the Output window, check the following:
- Make sure the string "Something touched the part!" is between local function onTouch() and end.
- Check that Touched is capitalized.
3. Now that the function is correctly set up, use it to destroy whatever touches the part. Inside the function, after the string, type `objectTouched:Destroy()` The completed code should be:
```lua
local trap = script.Parent
local function onTouch(objectTouched)
print("Something touched the trap")
-- Destroy the touching object
objectTouched:Destroy()
end
trap.Touched:Connect(onTouch)
```
4. Test again and see what happens when the part is touched. Your avatar should end up missing feet or arms. If the part touches the avatar's head or neck, it might even be completely destroyed.
<video controls src="../../../assets/education/coding-2/parameters-and-events_trap.mp4" width="80%"></video>
## Summary
Parameters are used to pass information that would be normally out of scope (where a function can't see it), into a function. Meanwhile, events are special signals that go off inside of the experience when something important happens. Different objects have different events. Functions can be connected to events so that they are called each time the event gets fired. This little script connected a function to the trap's `Class.BasePart.Touched|Touched` event, and passed in what was touching the trap through the parameter.