Scripting Tips & Tricks: Basics

Hello everyone! I’m rev, and in this topic, I’ll be teaching you the basics of scripting in Roblox Studio!

You must have your Explorer and Output tab on!
To turn them on, just go to View and you’ll find them!

Introduction:


Scripting is a very important thing when developing, most of the things you do in Roblox studio must need a script for it to work! But don’t worry if you don’t know how to script very well, I can help you!

In this small tutorial, we’ll learn Variables, Common useful functions, and Loops!

Please let me know if I need to improve this post and how can I improve it!

Let’s start!

Variables


Maybe you’ve heard about variables. Variables are very useful when scripting, they can help you to make your code easy to read!

What is a variable?


A variable is a name that can hold a value inside it, It can be of any type.
Booleans, Values, Data, instances, and more. When writing variables, you need to make sure that it doesn’t include functions or statements at the beginning of the name, and they cannot include any spaces. For example:

 HOUSE --Good
 MYNAME -- Good
 if -- Not Good
 if  Redcar -- Not Good
 My house -- Not Good

example:

local MyCar = game.Workspace.Car

But there’s a difference between local variables and global variables.

A global variable can be read from other functions and/or situations

Example of global variable:

local function On()
   Value = true
end

local function false()
   Value = false
end

And a local variable can only be used inside a function/loop or other situation

Example:

local function on()
  local Value = true
end

local function off()
   Value = false  --This will give an error, since "Value" doesn't exist inside the function 'off()'   
   -- Or isn't global.
end

Examples:

Let’s begin with an example.

Let’s say that I want to script this block:
image

As you see it’s inside a folder.

Inside our script, we can call it in two different ways.

game.Workspace.Tutorials.Block -- This is a common way, but not the best

So let’s use variables and save up time!

local Block = game.Workspace.Tutorials.Block

and now we can do something like this:

Block.Transparency = 1

instead of doing:

game.Workspace.Tutorials.Block.Transparency = 1

Variables will save up a lot of time since you just have to write a simple word and not a whole location.


Basic Functions:


Functions are really used in scripting and it’s very important to learn them.

Functions are sets of instructions that can be used in a script, functions can be executed through commands, or triggered by ‘Events’ (events are signals that are send when something special happens in the game, for example, when a player touches a Block)

You can type what do you want to happen when something activates the function.

Example:

If a player touches a block, then the player will be killed.

So we can do

local function killplayer(hit) -- hit is the name that will receive the part of the body that touched the block
   if hit.Parent:FindFirstChild("Humanoid") then -- hit is the part of the body, and it's parent is the player.Character, so inside player.character we'll try to find Humanoid.
      hit.Parent.Humanoid.Health = 0 -- Setting the health for the player to 0
end

 script.Parent.Touched:Connect(killplayer) -- When block is touched, the function will be executed

Remember that you can always start with the basics, and when you learn the basics, you can increase the level.

We’ll learn the following functions:


WaitForChild()

WaitForChild() is very important when you are working on a local script (Client)

Local scripts will only work for a Client (Only work for a player)

Let’s see why!

If I put:

    local block = game.Workspace.Tutorials.Block

when this code runs in a local script, it might not work and give you an error if the Block/instance has not been replicated yet.

WaitForChild() can fix that.

WaitForChild() will wait for an instance/block to replicate in the server/client, and then, the code will run.

local Block = game.Workspace:WaitForChild("Block") -- Remember to put ""

Here we are telling the script to only focus on this block, and the script will try to wait for an instance called “Block”.

Example with NPC and a box:
(This might help you understand a little bit more)
image
Here we have our NPC, he’s waiting for the box to load. But there’s nothing inside the box.
There’s a script that will fill that box with spheres, and then the NPC will move inside the box.
image

And when it’s filled, then the NPC will get inside the box.

image

As you see, the box filled, and the NPC got inside the box! Something like this happens with wait for child.

GetChildren()

GetChildren will return every instance inside a model/part/folder/etc.

image
Let’s say that I want to call every single instance inside that model called “Spheres”.

GetChildren() Is used on Loops, don’t worry I’ll explain what’s a loop below!
Well, then we can do the following stuff!

local Spheres = game.Workspace.Tutorials.Spheres:GetChildren()

for i, v in pairs(Spheres) do
    v:Destroy()
end

As you see I have some spheres
image

Now when our script runs, this will happen.

image

as you see the whole block disappeared because we told the script to delete all the children of “Spheres”.

image

An example with blocks of GetChildren(), this might help you understand

image

As you see, we have some spheres.

The spheres are not bright, and we want to put all spheres in ‘Neon’. So if we use getchildren(). This will happen.

image
As you see, every single sphere is Neon.

GetChildren() Can be as well a replacement of doing this
local Sphere1 = script.Parent.Sphere1
local Sphere2 = script.Parent.Sphere2

GetChildren() will save you a lot of time!

FindFirstChild()

FindFirstChild() Will return the first child of any instance with the given name.

Code:

local Block = game.Workspace:FindFirstChild("Part")
Block.Material = "Neon"

Alright, so we have that code, when we run it, it will only change the material to neon on the FIRST part that the script found with the given name.

Example:

image
We have a lot of parts with the same name. We script with FindFirstChild(), and then only one of those blocks will become ‘Neon’.

image

As you see, the first block that was found by the script is the Middle block!

GetService()

GetService() Will return service with the given name, if we call any service, it will return the instance of that service.

Explanation

image

By default, we have some of those services in our Explorer, these are the most important service. But there exist more services that we can access via script.

local DataStoreService = game:GetService("DataStoreService")

So the script will access the Data Store Service.

It’s unnecessary to use GetService() when using one of the services shown in the picture.

Clone()

Clone(), as it says, will clone an instance: Model/Part/Folder/Etc.
This is a simple thing and easy to learn!

Let’s say that I want to clone a block into the workspace.

image
I’ll put the block that’s gonna be cloned into ReplicatedStorage.

Now inside a script, we can type:

local Dropper = game.Workspace.Dropper
local ReplicatedStorage = game.ReplicatedStorage
local Block = ReplicatedStorage.Block


while true do
    wait(5)
    local clone = Block:Clone() -- Will clone the block
    clone.Parent = workspace -- Will indicate the parent, we want it on workspace to see it
    clone.Position = Dropper.Position -- Will indicate the position of the cloned block
end

As we can see. The block will clone on the workspace and the position that we indicated.

image

As you see it works!


Loops


A loop will let you execute a code multiple times, there are many types of loops.
Loops will pause a thread, meaning that if you run a While true do loop at the beginning of the script and there’s code below it. The script won’t run the other code until the loop breaks.

For
The for loop lets you run a command or group of commands a set number of times.

image

You can find some of this information here!

Let’s do a code with this!

for count = 1, 10, 1 do
   print(count)
end

This will print the Count number every second.

While
While is used for infinite loops, by using true in its condition.

While true do is the most common loop with this one.

Let’s see an example.

while true do
print("This is a loop")
wait(1)

IMPORTANT: while true do should always have a delay in it, such as wait().
The script will give an exhaust error in the output. This means that the script is trying to execute the code too much, and it stopped to prevent any performance errors. When this happens, the game will lag the first seconds.

This script will print ‘This is a loop’ in the output every one second

Repeat

A repeat loop repeats until a certain condition is met. Note that the code between repeat and until is executed at least once because the conditional test is performed afterward.

Code:

local value = 18
repeat
  value = value + 1
  print("Current Value is" .. value)
until value == 25

print("Value is 25")

Breaking a loop
If you’re running a loop that won’t actually end, such as an infinite while true do loop, you can force it to end with the break commands.

local secondsElapsed = 0
local timeout = 5
while true do
  print("Looping...")
   wait(1)
   secondsElapsed = secondsElapsed + 1
  if secondsElapsed == timeout then
          break
  end
end

print("Loop ended; moving on!")

for more information, you can visit Here


I hope this information helps you understand more scripting in Roblox studio.
Please let me know if I need to improve this tutorial, or if I need to do something on this tutorial! Hope this help :smiley:

50 Likes

Usually, variables start with local

Not quite, people DO often use local variables, but there is a difference between global and local variables.

A local variable (from what I remember) is read faster than a global one. Correct me if I’m wrong though.

Local variables behave differently than global ones. Here’s some examples:

image
This is a global variable, you initialize it and give it a value. It is now a value.
It can be read from functions and other situations.

image
(Sorry for contrast in quality, someone had to take the picture over discord streams since using snipping tool removes the underline for a few moments).

The local variable is no longer recognized since it is local in the function it is in. That is the big difference between global and local variables.

(Do call the function first to make sure the global variable doesn’t return as nil).

local Block = game.Workspace:WaitForChild("Block") -- Remember to put ""

While this is correct information, you should also mention the timeout parameter.

local Block = game.Workspace:WaitForChild("Block", 10) -- Remember to put "" 

The timeout parameter gives the WaitForChild() a time to wait before it ultimately gives up on waiting. This is useful in some cases because it may cause an Infinite Yield if the part never gets created or some other reason.

In the example I showed, it waits 10 seconds before it gives up.

8 Likes

Thanks for the heads up! I’ll modify the information real quick!

7 Likes

Addition: The script will give an exhaust error in the output, meaning that the script is trying to execute the code too much that it reached to the point where it has to stop to prevent any performance errors.

You should also include that loops will pause a thread, meaning that if you start a while true do loop at the beginning of the script, the compiler wouldn’t compile the rest of the code until the loop breaks.

You shouldn’t introduce the newcomers about global Roblox Lua functions first. Start by introducing what is a function, create a function to do a certain thing and finally explain the global functions in Roblox Lua.

5 Likes

Thanks for the information! I’ll add this real quick!

2 Likes

This is wrong – digits can absolutely form part of a valid identifier. What is invalid is it starting with a digit. Basically, a valid identifier starts with any letter or underscore, followed by any amount of letters/underscores/digits.

I think you made a mistake here – false is a reserved keyword and therefore not a valid identifier.

This will say something along the lines of the variable only being used in the function body and therefore suggesting changing it to local

This code will not compile as there is a missing end.

Services are not functions – therefore cannot be called.

It’s always necessary to use :GetService, even if the service is immediately visible in the explorer by default. Some services may not immediately exist, therefore :GetService will create it if it doesn’t exist yet.

while loops execute their body while a given condition is truthy, and are not exclusively for while loops.

local i = 0

while i < 10 do
    i += 1
    print(i)
end

print(i)

Also the code snippet you provided won’t compile due to a lack of an end


I recommend getting more experience in these topics yourself before attempting to teach others :slight_smile:

There were other not-so-great practices taught in the topic, but alas, I do not have time to get into them right now. But thank you for trying!

7 Likes

No, a value can include a digit. You can do:

local variable1 = "helping"

I think your meant to say you cannot put spaces or else it won’t work.

6 Likes

Awesome man I love this intro style! I needed it

At first image have some like “local ab = false” and the other image just have the function and print() it’s not possible to print something that doesn’t exist…