Flurite's Scripting Tutorials

From Legacy Roblox Wiki
Jump to navigationJump to search

Prologue

Hello scripters! In this tutorial, you are going to learn the very basics of scripting! To start out, ROBLOX uses a language modified to their liking, known as Rbx.lua. Mastering this language will give you the ability to make planes, guns, and even a fun GUI-game for your place! Let's start off nice and easy right here. Just so you guys know, this tutorial is not supposed to be read in a short amount of time. Scripting takes months if not years to become good at, so I would suggest learning a section per day.

Information you need to know

  • First of all, you will need to know the ins-and-outs of ROBLOX Studio. If you don't already, visit this article:

ROBLOX Studio Info

  • In this tutorial, there will be comments, which are designated by using "--" characters. This text is just for you to understand what a specific part of my script means. Multi-line comments are done like this:
--[[This is a multi-line comment 
:P
:D]] 

Inserting a Script

There are quite a few ways to insert a script in to your game, but since you are most likely a beginner, this is the easy way:

1. In the Explorer menu, click on Workspace

2. Go to ROBLOX Studio, and at the very top of the window, you should see a line of buttons which include "File", "Edit", "View", "Insert". Click the button "Insert" and you should see a drop down menu.

3. From the drop down menu, click "Object..."

4. You should see a small window pop up with a lot of options, find the option, "Script", and double click that! You should see an object in your Explorer menu called "Script"!


Congratulations, you inserted your first script!

About the ROBLOX hierarchy

If your new to scripting, you might not know what a hierarchy is. I'll define it for you:


"A system or organization in which people or groups are ranked one above the other according to status or authority."


In ROBLOX Studio, the 'game' DataModel is the uppermost section of the hierarchy, and everything in the game is part of the 'game' hierarchy. It is the keystone of ROBLOX's structure. In this section you will learn two terms: 'descendants' and 'parents'. In Rbx.lua, a parent is what contains the object, so most objects have only one parent (besides the 'game' DataModel, which has known).


For example, when you insert a brick, it usually appears in Workspace. Therefore, the new brick's parent is Workspace! A descendant is the exact opposite of a parent.

For example, when a new brick is inserted in to Workspace, the new brick is a descendant of Workspace! There is also a term known as 'ancestor', which is similar to a parent, but goes higher up the hierarchy then the regular parent. It's kinda like a parent's parent's parent, or parent's parent's parent's parent, etc.

Getting through ROBLOX's hierarchy

Now that you know all the terms, I will teach you HOW to move through ROBLOX's hierarchy. It's actually quite simple, and all you need to do is use a '.' (period) character! Since you probably now know that Workspace is a descendant of the 'game' DataModel, then you can access Workspace by simply going like this:

game.Workspace

Simple, huh? Since ROBLOX realized that Workspace was so commonly used, they made shortcuts to it. So to access Workspace you can type any of these options:

  • game.Workspace
  • Workspace
  • workspace

P.S. You cannot use these shortcuts for any of the other direct descendants of the 'game' DataModel, like StarterPack and StarterGui.

Now to access a brick in the Workspace, you can simply use another '.' (period) character! The period character is just a general way of accessing a direct child or property of an object

game.Workspace.Brick

Make sure you use the name of the object, not the className. Now you can move anywhere through the ROBLOX hierarchy!

Properties

All objects have properties. A property is a specific 'trait' belonging to an object. For example, You can make invisible bricks by changing the brick's Transparency property. You can change how visible the brick is by changing the Transparency property of it, but every property of an object can be defined with various ways. Some are with strings, others are with numbers, etc. For the transparency property, you set the transparency to a number from 0-1, such as 0.9, 0.5, etc. The greater the transparency, the less visible it is! Since you know already learned in the previous section on how to navigate through the ROBLOX hierarchy, here is a piece of code that changes the transparency of a brick.

game.Workspace.Brick.Transparency = 0.5 --notice how I use a '.' character to get a property/child of the object

Another property for the 'Part' class (a brick's "scientific" class name) is the name. To change the name of the part, you don't use numbers, but you use a string of characters in quotes (you will learn more about strings later). Here is an example of a piece of code changing the name of a part.

game.Workspace.Brick.Name = "Brickz"

To find out what userdata the property is defined by, you can research the property on the Wiki.

Numbers and Strings

Numbers and strings are both different types of data used in Lua. Here is a quick definition of each of them.

Number: You probably know what this is, but if you don't, I will explain. A number is an arithmetical value, shown by a word or symbol, representing a particular quantity and used in counting, calculating, and for showing order in a series or for identification. This is an example of typing a number in Lua.

a = 11111122333412341234 --chances are, you won't use massive numbers like this.

When you type a number in a script, the number will turn blue (as long as it's not in a string).

String: A string is a string of characters combined. There are many formats of making a string, but the most common one is this:

"Any sort of text here" --I use double quotation marks. If you put this in a script, the string will turn purple!

And that's it! Other formats include this:

'Flurite likes papayas!' --notice how I only use single quotation marks

There are many other ways to make your string, but if you want multi-line strings, this is a common way to do it:

[[I R STRING!!!!!!!

AND I R STILL STRING!!!!]]

This is similar to multi-line comments.


Variables

Most of our newer scripters who have not gone through math classes such as pre-algebra, may not know what variables are. Variables are simply a symbol or string of characters that represents a value! Even if you have not gone through pre-algebra, you probably know how to solve a problem like this:

a = 5

a + 2 = ?

And you would probably know that a + 2 is 7. But what you might have not known is that 'a' is a variable! In this case, 'a' is the variable, and as you may be able to guess, '5' is it's value! In Rbx.lua, variables are setup almost exactly the same! In fact, if you were to put a similar piece of code in a script, it would work! Here's an example of a code:

Example
a = 5 --This is similar to the variable I gave you. This is also an example of a comment.
print(a + 2) --when I say print(a + 2), I want it to print what's inside the parenthesis to the Output window. Check your output window to see what it says!


Output:
7 --see, how it prints the result of 'a + 2'?


If copy and paste everything up to the second line of the code, you will see the result in your own output!

Congratulations, you have learned what variables are! If you have trouble grasping variables or the print() function, see the following links:

Variables

Print Function

Operators

Here are some key operators that you may want to know when using ROBLOX. This can be used as reference, but if you read through the whole thing, you won't lose anything from it.

Math Operators

  • '=': This operator is used to assign variables, as you can tell from the last section.
a = 5 --this is a variable
  • '+': This operator is used to add number values.
a = 5+2
print(a)

>7
  • '-': This operator is used to subtract number values.
a = 5-2
print(a)

>3
  • '*': This operator is used to multiply number values.
a = 5*3
print(a)

>15
  • '/': This operator is used to divide number values.
a = 6/2
print(a)

>3
  • '%': This operator is used to divide number values with a remainder.
a = 5%2
print(a)

>1
  • '^': This operator is an exponent operator.
a = 5^2
print(a)

>25

Comparison Operators

In this sub-section, I am going to be using 'if' statements. You will learn about those in the next section. For now, just read it like if it were a regular sentence. Ex: In the first example, read it like this: 'if a IS 5 then', and so on.

  • '==': This operator states that one value is equal to another.
a = 5
if a == 5 then
print('a is 5')
end

>a is 5
  • '~=': This operator states that the two values are not equal.
a = 5
if a ~= 2 then 
print('a is not 2')
end

>a is not 2
  • '>': This operator states that the first value is greater than the second.
a = 5
if a > 2 then
print('a is greater than 2')
end

>a is greater than 2
  • '<': This operator states that the first value is less than the second.
a = 5
if a < 7 then
print('a is less than 7')
end

>a is less than 7
  • '>=': This operator states that the first value is greater than or equal to the second value.
a = 5
if a >= 5 then
print('a is greater than or equal to 5')
end

>a is greater than or equal to 5
  • '<=': This operator states that the first value is less than or equal to the second value.
a = 5
if a <= 6 then
print('a is less than or equal to 6')
end

>a is less than or equal to 6

Logical Operators

In Lua, there are 3 logical operators, and, or, and not. Here is a summary of each one.

  • And operator: This operator is used to check if both values are true.
a = "Pie"
b = 1

if a == "Pie" and b == 1 then --notice how I use two equal signs to designate that one variable IS this value.
print('a is pie, and b is 1')
end

>a is pie and b is 1
  • Or operator: This operator is used to check if any of the values are true.
a = "Apple"
b = 123
c = "Banana"

if a == "Apples" or b == 123 or c == "Bananas" then
print('One of these is true, can you figure it out?')
end

>One of these is true, can you figure it out?
  • Not operator: This operator is used to find the opposite of a boolean. The opposite of true is false. The opposite of false is true.
a = true

for i = 1, 5 do
a = not a --it changes a's value to it's opposite.
print(a)
end

Congratulations, you have completed the operators section! Now you can compare different values with comparison operators, make your code more efficient with all logical operators, and do some math with some mathematical operators! If you still don't get it, you can visit this article:

Operators

Conditional Statements

In some of the previous examples in the section before, you probably saw some 'if' conditions. Like when I did:

if a == 5 then
--code
end

In this section, you will be learning about 3 of the major conditional statements of Lua, the 'if' statement, the 'elseif' statement, and the 'else' statement. This is simple guideline on how you should use these, but I will go more in depth about them later:

  • if statement -use this statement to execute some code only if a specified condition is true
  • if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement - use this statement to select one of many blocks of code to be executed

If condition

An 'if' condition simply does what it says: check if a value is another value. If conditions always need an 'end' statement to close the condition. This is the setup of an 'if' condition.

if (something == value) then

It's quite simple after you get the hang of it. Here's an example with an 'if' statement. Notice how I use two '=' signs as that designates that something IS another.

abc = 123

if abc == 123 then
print('abc is 123')
end

>abc is 123

And another example:

abc = 123
laugh = "lol"

if laugh == "lol" and abc == 123 then
print('It worked!')
end

>It worked

If..elseif Statement

Use the if..elseif statament to execute a piece of code if one of the given conditions is true. The format is much like the 'if' statement. Here's an example:

a = 3

if a == 1 then --I begin with my 'if' statement, because you can't use an 'elseif' statement if there is no corresponding 'if' statement.
   print('Hi')
elseif a == 2 then --See how the format of the 'elseif' statement is very similar to the 'if' statement's format?
   print('Hello')
elseif a == 3 then --You can use multiple 'elseif' statements in your piece of code.
   print('Hey')
end --notice how I only need one end to close all my 'if' and 'elseif' conditions.

Output:
Hey

Like the 'if' statement, you can use the 'and' and 'or' logical operators in your piece of code. Here's an example with that:

a = 3
b = 2

if a == 2 and b == 3 then
   print('Flourine')
elseif a == 3 and b == 2 then
   print('Flurite')
end

Output:
Flurite

If..elseif

Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. Here's an example of using this:

a = 3

if a == 5 then
   print('"a" is 5')
else --there is no written condition for the 'else' part. If the 'if' statement isn't true, then it automatically executes the 'else' statement
   print('"a" is not 5')
end --notice how I use an end to close this type of statement

Output:
"a" is not 5

Combinations

All these types of combinations can be combined. Here's an example:

a = 3

if a == 1 then
   print("1")
elseif a == 5 then
   print("5")
else
   print('"a" is neither 1 or 5')
end

Data Types

Main article: Data Types

Data types are special objects that are made up of using tables and nested functions (these concepts will be discussed in future sections). Some data types you already know of are numbers and strings, but there are some more complex data types that take multiple values. For example, if you want to set the position of a Part, you cannot just have this as your code:

game.Workspace.Part.Position = (0, 0, 0)

That will cause an error. Instead, you need to use the Vector3 data type. The Vector3 data type takes three arguments: x, y, and z, respectively. There are many other data types besides Vector3 such as BrickColor, UDim2, and many more. Data types can set various thing. Vector3 sets the position and size of a 3D object. UDim2 sets the position and size for a 2D object such as a GUIs.

In order to set the position or size of an object using the Vector3 data type, the .new property must be used, as that executes a function which returns three arguments: your x, y, and z values. For example, this code will set the position of a part to (5, 5, 5).

game.Workspace.Part.Position = Vector3.new(5, 5, 5)

The idea is similar for other data types and each data type has various properties and uses, so look up the documentation of the data type if you are curious about what it does.

Creating objects via script

In Rbx.lua, you don't have to use the insert menu to get a brick on to your game, but instead you can always use a script. You can simply use the Instance.new method to create any object that exists in Roblox. The method has two arguments, the first being the className of the object you are setting, and the second being where the new object is going to be parented. Here's an example of using Instance.new:

Instance.new("Part", game.Workspace) --this creates a new brick (className is part), and it is parented under Workspace

If you run this script, you should see a new part in Explorer. You can also change properties of the new part you created by defining it before.

brick = Instance.new("Part", game.Workspace) --I create the new brick and parent it under Workspace. I also, define it as the variable 'brick'.
brick.Name = "Brick" --I change the newly created part's name to "brick".
brick.Anchored = false --I change the 'Anchored' property of the brick to false
--you can edit all it's properties if you wanted

Functions

Let's say you wanted a piece of code to be executed when an event is fired, or whenever you wanted it to. One of the most common ways to do this is to use a function. This is a mini-tutorial on how custom(not built in) functions work.

Defining a function

This is the syntax of what the typical function looks like.

function ''functionname''(variable1, variable2... variableX)
   --some code
end --all functions are closed by an end

That is the basic syntax of a function! Here are a few rules about functions you should know:

  • Function names cannot have any spaces in them.
  • Function names can have uppercase and lowercase letters in them
  • The 'variables' are commonly known as arguments. Arguments are not mandatory, but if there are none, you still need the '()'
  • All functions are ended simply by using the 'end' statement.
  • The word 'function' must be spelled as it is (all lowercase letters).
  • When you define a variable in a function, it can only be used in a function. This is called a local variable. For example..


Example
--this is the function and I define the local variable 'x'.
function Hi()
   x = "Hi"
   print(x)
end

--but you cannot do this after the function closes, it will print 'nil'
print(x)


Executing a function

To execute a function, you must call it by yourself, or have it connected to an event. Since you have not learned about events yet, I will teach you how to call it yourself. This is the basic syntax on how to call a function:

''functionname''(value of variable1, value of variable2....value of variableX)

Let's say you wanted to call the function 'Hi', which I defined in the previous subsection. This is how I would do it:

function Hi()
   x = "Hi"
   print(x)
end

Hi()

Output:
Hi

This is an example of calling a function with arguments:

Example
--I'll define the function
function hola(x, y) --these are the arguments 'x' and 'y'
   print(x, y) --I will print the variables 'x' and 'y', even though they have no value. I will show you how to set their value's next.
end --I close the function

hola("Hello", "Hola") --see how I defined them? Now x = "Hello" and y = "Hola"

Output:
Hello	Hola


Methods

Methods are pre-set commands that are built in to Rbx.lua. When called, they perform an action based on the name of the method and it's arguments. Methods are built-in functions. Methods include 'Remove()', 'Clone', and many more. These functions can only be used on objects.

Calling a method

This is the basic formatting of a method:

object:methodname()

Let's say you would want to remove a brick from your game. You can use the 'Remove()' method to do this.

Example
brick = game.Workspace.Brick

brick:Remove() --see how I first stated the object, then a ':' character, then the name of the method?

--also note that an 'end' statement is not required here.


Some methods have arguments, as explained. An example of one of these methods is the 'FindFirstChild()' method. What the method does is search for a name of an object that is a child of another object. It's first argument is a string, and it's second argument is the 'Bool recursive' argument which will look through all it's descendants for the name, instead of the direct descendant. Here's an example using it.

Example
brick = game.Workspace.Brick

--pretend there is another brick that is a child of the 'brick' variable and it is named "Part"

local part = brick:FindFirstChild("Part", false) 
   if part then
      print("'Part' is a child of 'brick'")
   end

--all arguments after the first argument are optional. This is the same with functions.


To see a full list of methods, you can see this page:

List of methods

Events

Events are a type of class in ROBLOX, that are fired when a specific action occurs. For example, in a simple kill brick, you may see the .Touched event there. This event fires when an object 'touches' or collides with the brick. All events have a few methods built in to them, the most common being the ':connect()' event, which allows you to execute a function when an event is fired.

Here is a simple example using an event:

a = 5
brick = script.Parent --pretend the the script is in the brick

function touched(x) --I make my function..
   print(a, x)
end

brick.Touched:connect(touched(5)) --this is the event, along with it's method. This line is often called the 'connection' line.


Output: 
5  5

Another method of an event is 'wait()'. Unlike the regular 'wait()' function that waits for a certain amount of time, this ':wait()' method waits till the event occurs again.

Example
local otherPart = Workspace.Part.Touched:wait()

This causes the script to stop and wait for that Part to be touched by another Part.


There are many other events, such as PlayerAdded, MouseClick, Equipped, MouseButton1Clicked, and many, many more. You can find a full list of events and an in-depth description in these links:

Events list

Events (in-depth)

Loops

A loop is a way to repeat a specified piece of code multiple times. For example, if you wanted to print all the numbers from 1 to 5, you could use five prints like this:

print('1')
print('2')
print('3')
print('4')
print('5')

But you wouldn't want to do that if you wanted to count to 1000. That's when loops come in handy. There are three different loops: while, for, and repeat. I will do some explaining about each of them.

While loop

A while loop loops through a piece of code while a specified condition is true. The basic syntax of a while loop is this:

while [condition] do
   --code to execute
end

When the [condition] part is true, the following code will execute. If you place [true] as the condition, then the loop will run infinitely. BEWARE, this could cause problems with your script. Make sure that you have no important code to execute after this, because this will continue to run until you break the loop using a 'break' statement. We will talk about the 'break' statement later.

a = 1

while a == 1 do 
   print('a is 1')
   wait(3)
end --notice how we use an 'end' to close a while loop

If you test this code out, you will see that your output will have a new 'a is 1' statement every 3 seconds. When the condition turns false, the loop will automatically break, and continue with the stack of execution.

For loop

A for loop runs through a specified block of code for a designated number of times. This is the basic syntax of a for loop:

for [variable] = [beginning number], [end number], [increment (not required, the default is 1)] do
   --code to execute
end --notice how we use an 'end' to close a for loop

Here are some guidelines about what the numbers in the bracket means:

  • [variable] - This is any variable that will be changed every time the loop starts again.
  • [beginning number] - This is when you want the [variable] to start at.
  • [end number] - This is when you want the [variable] to stop changing.
  • [increment] - This is how much you want the [variable] to change with every loop. The default is 1, but it can be anything, including negative numbers

Here's a basic example of how a for loop works.

Example
for n = 1, 5, 1 do
   print(n) --this will print what the variable 'n' is
end


If you execute that script, it will print the numbers 1 through 5. Now, we will do a countdown.

Example
for n = 5, 1, -1 do
   print(n)
end


If you execute that script, it will print the numbers 5 through 1, counting down.

Repeat loop

This loop is very similar to the 'while' loop. This loop repeats it's code until it's condition is true. This is the syntax of a repeat loop:

repeat
--code to execute
until [statement is true]

This is an example of a repeat statement.

{{Example|

a = 1

repeat
a = a + 1
until (a == 5)
}}

This loop does not require an end.

Main article: Loops

Tables

A table is a way of storing information. It has a list of values that are stored in one variable. This is an example of a table:

table = {
   "string",
   1
}

As you can see, a table can hold nearly anything, and all values are setup by a comma. Here are some vocabulary terms that will be used in the section that you may not know.

  • array - A table is an array when all it's elements have numerical indexes. We will learn more about indexes later.
  • element - A value in a table or array.
  • index - An integer that identifies a value in an array.
  • value - The value is a piece of information in a table. Each value has an index.

An element in an array can be accessed by using square brackets, such as the following:

table[index]

Here's an example of accessing an element of a table.

Example
tab = {1, "Hello", 53217, "Hola"}

print(tab[3]) --this is where I access the value, notice the syntax

Output:
53217


Please note that there is no such thing as table[0], for it will return nil. You can specifically set values of the table like this:

Example
tab = {}

tab[1] = "Hello"
tab[2] = "Scripting rulez!"

print(tab[1], tab[2])

Output:
Hello	Scripting rulez!


There is a unique operator that allows us to find the number of elements in a table: '#'. Here is how you could use this operator:

tab = {"lol", 12412312, "I like piez"}

print(#tab)

Output:
3

You can make your codes more powerful with table manipulation functions. To find a full list and how they work, visit here.