Welcome to my Scripting Tutorial, i’ll expand it overtime, for now, let’s get started
About me
Hello, i’m Ideal, i code in Roblox for 7 years now and i wanted to share my knowledge
When i started, there were no tutorials in my language (I’m Polish) apart of few very basic ones, i really like how the roblox changed, and this time there are tutorials, including this one
Before we start, i dedicate this tutorial to my friend, Apro87 who is beginner and needs that help
Tutorials List:
A) Lua basics
- Before we start
- Variables
- Operators&Basic math
- Conditional Statements
- Functions
- Loops
- For loop
- Tables
- Math library
- Basic Code Organisation
- Types
B) Roblox’s Api
- Instances and their methoods
- Parts manipulation
- 3D Vectors
- Events
- Detectors
- CFrames
- Attributes
- Vector math: Linear Interpolation
- Services
- Enums
- Filtering: Client vs Server
- Introduction to local scripts
- Basic gui programming
- Tween Service - Better lerping
- Client and Server rules
- Tools
- User Input Service - Detecting key presses
- Run Service - Physical simulations & smooth movement
- Remotes & Bindables - Scripts connection
- Modular scripting
- Data Storage - Saving stuff
- PCalls - Safe functions
- Teleport Service - Teleportation between places
- Raycasting - Advanced collision detection
- Micro Modules - Code sorting strategy
- OOP - Code organisation strategy
- Collection Service - Game optimization
- Tips and advices about coding
C) Advanced Coding
- Metatables
- Advanced CFrame Math
- Math over Code
- Advanced Code Organisation
- Path Finding Service - Smart NPCs
- Strings
- Perlin Noise
- How to create Grids
- Where to go next?
- Important tips for future jorney
Now, let’s begin our jorney!
Lua basics
1. Before we start
Soo, before we start, you need to know how to use Roblox Studio, and how Explorer and Propertiess works!
If you are 100% sure that you meet those requirements, then, let’s start
First of all, we need to do 2 things, first is to insert new script, for now we will put them in workspace to make it simple
Second thing is to open Output tab, it’s console where we can write messages using scripts
To open output navigate to VIEW section and then find Output it’s near explorer and propertiess
When we have everything ready, we can start coding by opening our Script
You should see:
print("Hello world!")
What is this? you may ask, let’s Run our game to see what will happen
as you can see, there is "Hello world!" message on the output
Print methood is using to output any text, as long as it’s inside quotes, there is also Warn methood that works the same, the difference is the color of text will be orange
warn("There is an error!")
Both methoods are very usefull, Prints and Warns can be used for debugging, analysing other scripts, testing and many more things
Apart of those two methoods that you learned, i want to show you another very usefull thing, Comments
-- this is single-line comment
--[[
this is multi-line comment
]]
Comments are part of your script that can’t be read by machine, soo you can use them to safely describe what each section does, they allows you to make your code cleaner and more sorted
The last thing, always remember about Upper-Case letters, one letter can make very, i mean very big mistake!
Thanks for reading first part
2. Variables
Welcome to second tutorial, today we will learn about Variables
What are they? what they are used for?
Variables are containers of data, there are few types of data, we will talk about them in a moment, first, how to create a Variable?
local var
local is key that allows us to define variable, in this case we named our Variable “var”,
it can be made from any normal letters, remember that Variables must have unique names!!!
Yea, Variables must have unique name, otherwise they will be Overwritten
Overwrite is situation when we change our Variable’s current value to other value
Yea, but what are those values are???
Values are some type of data that Variable holds, there are few common types:
- Number
- String (Text)
- Boolean (true/false)
- Object (other Roblox object)
- Table
Now, when we know our types, we can make real Variables
local NumberA = 5 -- Number
local Text = "Hello everyone!" -- String
local Debounce = true -- Boolean
local Part = workspace.Part -- Roblox's object
local Pets = {} -- Table
As you can see, this is how we create our Variable
Then how to overwrite it???
It’s as simple as creation of one, here’s how:
local Number = 5 -- number variable
Number = 7 -- we change Number's value to 7
One last thing, we can create empty variables, their type is nil
local target -- empty variable, it can be assigned
--[[Some code...]]
target = Dog -- after some code we can assign target to other Variable or Object
alternatively, we can set current variable to empty one
local Part = workspace.Part -- Variable that stores Object
--[[Some code...]]
Part = nil
Note: Those --[[Some code...]] comments are only to replace real code, soo showcase would look better
Thanks, this was all for today’s tutorial, have a nice day! Godbye!
3. Operators&Basic math
Welcome to next tutorial, today we will take look at Operators and Basics of math, let’s start!
When we know that Variables can be Overwritten and also assigned to other Variable, we can start doing some real things with them
local a = 5
local b = 3
We have two numbers, and we want to get third number that will be Sum of a and b
How we can achieve that???
This is where Operators come to help us, they are Mathematical symbols that performs some operation on numbers or other objects
local a = 5
local b = 3
local c = a + b
print(c)
When you will Run the game, on the output, value of c will show
there are 5 most used mathematical operators:
(+) addition
(-) subtraction
(*) multiplication
(/) division
(%) modulo - reminder of division
Changing Variable by it’s own value, it’s very usefull when we want to create some Coins system or shop where we take only specific amount of Player’s currency
local PlayerCoins = Player.Coins-- number of coins player currently have
local ItemPrice = 400
--[[We detect when player purchases an item]]
PlayerCoins.Value = PlayerCoins.Value - ItemPrice
This will decrease value of Coins by 400
Eventually you can make it shorter:
PlayerCoins.Value -= ItemPrice -- works the same, simply shorter
You can do that with any of operators mentioned above
It’s everything today, Thanks for reading, Godbye!
4. Conditional Statements
Welcome, today we will learn Conditional Statements
what are they? and what they do?
you will see in a moment :}
Soo, before we start, we need to know what Logic Gates are, they are common in games and they are important part of computer building, in Roblox, we have 3 main gates:
- Or Gate
- Not Gate
- And Gate
You may ask, what they do?
Logic gates are used to compare if more advanced Condition is True or False
But first, we need talk about Conditions
local a = 5
local b = 3
local c = a + b
Let's say we have to check if number c is 8 or not, this is how we can do this
local a = 5
local b = 3
local c = a + b == 8
print(c)
If you run this code, you will get True, try to change a or b and you will get False
As you can see, after our equation there are two equals signs
Yes, there are two equal signs, because it’s Condition, double equal sign symbol is equation statement, it’s also boolean, soo we can have True or False
There are few other logic operators:
(>) a greater than b
(<) a smaller than b
(>=) a greater or equal b
(<=) a smaller or equal b
(~=) a is not equal to b
Also, we can create more advanced statements, with help of our Logic Gates
local a = 4
local b = 3
local c = 2
local d = 1
local e = a + b >= 5 and c + d ~= 3
print(e)
Run the game, if a + b is greater or equal 5 and c + d is not equal 3, then it will return True
As you can see, we combined two statements using Logic Gate this is very usefull, we can make checks with this, but there is one thing that will connect all of it
local a = 4
local b = 3
local c = 2
local d = 1
local e = a + b >= 5 and c + d ~= 3
if e then
print("Our equation is correct")
else
print("Sadly, our equation is incorrect")
end
What are this??? what are ends, and those if thing???
Great question, soo i’ll provide answer, If Statement is lua element, that allows us to control the flow of information, this mean, we can detect if something is correct and then run code depending on situation
This second statement, Else is usually used alongside with If, it runs it’s code when every statement above failed
We can also add ElseIf to control more situations
local a = 5
local b = 3
local c = 2
if a + b > c then
print("a + b is greater than c")
elseif a - c == b then
print("a - c is equal to b")
else
print("probably other scenario")
end
You can observe that code runs in specific order, from top to bottom, every statement is considered after another's fail, remember that
IMPORTANT NOTE: to make your code redable, inside every If Statement code should be moved by pressing TAB key, this will make your code look a lot better!
At the end, i want to add that you should always take look at those namings and other stuff like that, it’s very easy to make mistake, luckily Output and Print methoods will help you with debbuging
you can place Prints before each If Statement to check when code failed, and try to fix it
This was all for today, thank you for your attention, have a nice day!
5. Functions
Welcome everyone, today we will learn about Functions
I’m sure that most of you had functions in math classes, if not, don’t worry, in Lua functions are completely different
But what are they?
Functions are part of code that have some task, usually they are tools that you use to optimize and simplify your code
function example()
print("Hey!")
end
example()
After running the game, you can see "Hey!" on the output
Soo, what this Function does? it simply print some text
Therefore, you can use Functions to make your code more redable, but what about using them as tools?
function getSpeed(Street:number,Time:number):number
return Street/Time
end
local CarSpeed = getSpeed(40,20)
print(CarSpeed)
After running game, we will see 2 units of speed, because in 20 seconds, we travelled 40 units of distance
Note: I used this strange :number
, those are types, you can use them to make your code more cleaner, you can put many things there, for now you don’t need this
First, talk about this Function’s structure, it have Name that we call, it have Arguments inside brackets, and Return value which is optional, sometimes we give some Arguments only to make function use them to complete it’s task
Outside of function, we made new Variable and we Called Function, we gave Arguments
and printed the Return value
Sometimes we can use local functions, if we don’t have to use Function in other Function or Line above it, here is cleaner example:
Hello() -- function can be called in lines above it's first creation
--[[we mention our function for the first time]]
function Hello()
print("Hello everyone!")
end
Hello() -- it will give an error, local function can't be called outside it's scope
local function Hello()
print("Hello everyone!")
end
Hello() -- will be Ok, function is called after it was defined in this scope
Soo, now you know what is difference between local and normal functions, you should use both of them, but in specific situation, one is better than the other
Note: Scopes are parts of code that share their variables, If Statement is great example of scope, everything between Statement and End is scope
Today we learned about very usefull component, before we end
Exercise:
Create function that checks if given power is too low, good or too high and return if it can be used safely or not
Thanks for today, have a nice day, Godbye!
6. Loops
Welcome, today we will learn about Loops, this is part 1 of this tutorial
First, theory
For now, you could call something once, before it will turn into 1000 lines of “Hello world!” prints, now we will meet Loops they, as the name suggests, they repeat code inside of them
IMPORTANT NOTE:
task.wait(1/10) -- roblox api methood that allows us to wait x seconds before executing code
If we don’t want to make our computer explode, put this before End in every loop, it even can be 0 seconds, but it have to be there
There are 3 basic lua loops:
- For loop
- Repeat loop
- While loop
while true do
print("Infinite loop!")
task.wait(1)
end
While loop is infinite loop, that will run to the point when statement(true in this case is infinite) will change to false
local a = 5
local b = 3
while a + b > 20 do
print("Still running...")
a += 1
task.wait(0)
end
Loop will run about 12 times before statement will be False, then it will stop
At the end, While Loop is loop that repeats code until it’s statement will become False
But now, if While Loops are infinite, then what repeat loops are?
Repeat loop is almost the same,
ALMOST!!!
local a = 5
local b = 3
repeat
print("Hi")
a += 1
until a + b > 20
It will run the code until statement will be True
But, it’s the same as While Loop! only inverted!
Not exacly, in While Loops statement is checked before running code
On the other hand, Repeat Loop will always run code at least once, before it’s statement will become True and break the loop
Last thing, one keyworld that will help you a lot
while True do
print("Nothing happened")
if SomeThingHappened == true then
print("Something happened!")
break
end
task.wait(1)
end
break keyworld ends the loop, you can’t write anything in scope after it, break ends the loop
Now you should practice your coding, in next part we will consider more advanced topics!
Thanks for today, soon i’ll create part 2 of this tutorial, for now have a nice day, Godbye!
7. For loops
Welcome, today we will learn about For Loops it’s part 2 of previous tutorial, soo read it before this one, let’s begin
You know that Loops allows us to repeat code inside them, but only if the statement of the loop is True or False depending on loop’s type
For Loop is different, it’s statement is not True or False, it’s rather pre-defined
For Loop is loop that repeats x number of times and then stops, it doesn’t require you to break it or change conditions
for i = 1, 10 do
print(i) -- will print numbers from 1 to 10, i is loop counter that changes every time loop runs code
end
But what it does??? it doesn't look like previous ones
Yea, this is the case why it’s part 2
This type of loop have one variable, it’s loop counter, the most common name of it is “i” or “_” but you can use any String for that, still those 2 are the best to use
loop counter changes every time, it can grow or decrease, we can also change default value of growth (it’s 1) to any that we want
for i = 1, 10, -1 do
print(i) -- will print numbers from 10 to 1
end
Note: For clear explanation, third argument (in case above -1) is optional, default value is 1
for i = 0, 1, 0.1 do
print(i) -- will print fractions from 0 to 1, it's step is 0.1 soo 0.1,0.2,0.3...
end
Note: In for loops you usually don’t need to add task.wait()
because they are not infinite
Ok, soo if For Loop is used to repeat things X times, and it changes it's counter, where we can use it???
For Loop is interestingly the mostly used loop in entire Roblox, it’s used alongside with Tables to create data structures and frameworks
For Loop is heavily connected to Tables, we will consider them in third part of this tutorial
Thanks for reading, have a nice day!
8. Tables
Welcome, today we will learn about Tables, this is third and the last part of loops tutorial
When we know what For Loop does, as it counts numbers and repeats code X times, we can use this to our advantage, see Tables are simply sorted lists of Variables
What does it mean???
Tables are lists of elements, those elements have 2 propertiess:
Key & Value
local arr = {
[1] = 5,
[2] = 3,
[3] = 4
}
print(arr) -- will print {...} that can be expanded, then you can see table's **Keys** and **Values**
What??? this is the strangest thing ever!
Maybe it looks like, but, it’s pretty simple, Tables holds elements, those elements have Key that is position where element’s Value is assigned
Note: you don’t have to write those numbers in [ ], Lua will automatically add Keys to Values like this:
local arr = {
5, -- Key is 1
4, -- Key is 2
3 -- Key is 3
}
Note: Keys can be represented as Strings, then table behaves like an array, remember that there can be only one Key with the same number | name
local arr = {
[1] = 5,
[1] = 3, -- will throw an error!!!!
[2] = 2
}
--[[Keys can be represented as Strings, below see example of table that stores fruit counts]]
local fruits = {
["Oranges"] = 5,
["Apples"] = 3,
["Lemons"] = 4
print(fruits)
}
Now we will learn how to manipulate Tables
First, there is library for that in Roblox, but it’s usually better to use other methoods to make your code more efficient
One of those methoods is indexing, indexing is simply assigning Keys to Values
local arr = {} -- empty array (table with keys&values)
arr[1] = 5 -- we assign value of 5 to key number 1
arr[2] = 4
arr[3] = 2
print(arr)
We can index with Strings
local arr = {} -- empty array
arr["Oranges"] = 5 -- we assign value of 5 to key that represents Oranges
arr["Apples"] = 3
print(arr) -- prints our list of fruits on the output
print(arr["Oranges"]) -- will print Value of this Oranges
After all of those things with tables, can we do something else?
Yes of course
Now we will meet new type of loop
For Loops as you know have counter that changes every time it runs, and tables can have numerical Keys, we can connect both of them to read all Values using For Loop
local arr = {
"Apple",
"Pear",
"Lemon",
"Orange",
"Cherry"
}
for i = 1,5 do
local Fruit = arr[i] -- every time fruit will be the same as our array's values
print(Fruit) -- Apple, Pear, Lemon, Orange, Cherry
task.wait(1)
end
Run the code and you'll see that every 1 second a different fruit name is printed, the same as in array's order
Is there any option to make this shorter???
Yes, a little bit, it’s where new type of Foor Loop comes in handy
local arr = {
"Red",
"Blue",
"Yellow"
}
for i, Color in arr do
print(i,Color) -- prints Key which is named "i" and Color
end
After running the game, you can see that it printed number and then color
For in loop repeats it's code for each table elements, if there are 50 elements, there will be 50 repeats, if there are 1000 elements, there will be 1000 repeats and soo on
To show you better example, i added String Keys in place of numbers
local arr = {
["Color1"] = "Red",
["Color2"] = "Blue",
["Color3"] = "Yellow"
}
for i, Color in arr do
print(i,Color)
end
As you can see, "i" is now name and it's printed like order in our array
To end this, i want to add that there are two tricks to make your life easier
First, if you want remove something from table, simply make:
arr[Key] = nil -- assigns Value of nil to Key, soo table removes this Key
arr[Key] = newValue -- also you can overwrite Key's Value
IMPORTANT NOTE: For next trick, you can assign Key’s Value to 1 if you need something to be checked but not used is usually stored as key, soo it can be easily checked
Second, is how to detect if some object is present or not
For cleaner explanation, let’s say we have Players list that contains player’s nick as Key that are inside round, and we want to perform some action, but only if player is playing
To do that we can use arrays with Keys only! in this type of array, every key have Value of 1 because Value is not important in this case
local Players = {
}
--[[Some code that adds players in game]]
--[[Some event that calls function to check if player is in game]]
if Players[Player.Name] then -- checks if Player's name is on the list
return true
else
return false
end
Why is this methood good???
Trying to find if Table have some Key or not is easier for computer than looping through entire array and searching if value is present, also Value of 1 that is not used is very small amount of data, almost nothing
Soo to summarize everything:
- Loops are piece of code that repeats some task, depending on loop it might be different how
- For Loops repeat code X times that was set by programmer
- Tables are lists of elements that contain Key and Value
- Key is identificator that can be used to find specific element’s Value inside table
- Keys can be either numbers or strings
- There is special For Loop that loops through every table’s element
- Loops can be breaked either by using break or by changing it’s Running Statement
- There is methood where we use only Keys to store data required to be checked if it’s there or not
Thank you very much for reading my tutorial about Loops and Tables, in next tutorial we will learn about math library and how to use it, have a nice day, Godbye!
9. Math library
Welcome, today we will learn about basic functions of math library
This time, it’s very short tutorial, math library allows you to perform more advanced mathematical operations
Before we will take look into few of them, there are 3 other operators that i didn’t mentioned:
(-) Unary minus, negates value in front of it
(^) Exponentation
(//) Floor division, Rounds result to nearest full number that is less or equal result
Ok, now we can start talking about library
Usually library is collection of methoods or functions provided by programming language or plugins, math library is Roblox’s collection of math functions
How to use it?
local SOMENUMBER = math.FUNCTION() -> Result
Above is example how to call it, in this case we want variable that is result of math library function
List of most used functions:
math.random(min,max)
> returns pseudo-random value between min and max numbers
math.rad(angle in degree)
> transforms degree to radians
math.deg(angle in radians)
> transforms radians to degree
math.abs(number)
> returns distance of number from 0
math.sign(number)
> returns -1, 0, 1 depending if number was positive, negative or equal zero
math.clamp(number,min,max)
> limits given number between min and max, and eventually changes to max if number is greater or to min if is less than given range
math.floor(number)
> rounds number to largest full number that is less than it
math.ceil(number)
> rounds number to smallest full number that is greater than it
math.round(number)
> rounds number with math rule (if number is less than 0.5, works like floor, if it’s greater or equal, then like ceil)
math.pow(number,power)
> works like number^power (2^2 = 4, 2^3 = 8, 2^4 = 16…)
math.sqrt(number)
> works like number^1/2
Trigonometry functions and Inverse Trigonometry functions
Apart of those methoods, there are few others, also there are 2 mathematical constants:
math.pi
> returns value of π
math.huge
> returns very huge number
Remember that i wanted to show you simplified version of the most common methoods, few describtions can be difficult for some people, if you want more explanation, then
all methoods can be found here: math | Documentation - Roblox Creator Hub
What can we use this library for?
There are variety of ways, many genres of games use them, here are few examples:
- Shooters
- Building games
- Vechicle games
- Minigames
and more!
Thanks for reading, have a nice day, Godbye!
10. Basic Code Organisation
Welcome, today we will learn about Code Organisation, those are tips from my experience, let’s start
Soo, comments are used to describe code, you can use them as decoration too, here’s some propositions:
local Model = script.Parent
local RunService = game:GetService("RunService")
local Debris = game:GetService("Debris")
local CollectionService = game:GetService("CollectionService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage.Remotes.Event
local remoteFunction = ReplicatedStorage.Remotes.Function
local Part = Model.Parts.Part -- very normal part
local Gun = Model.Weapons.Gun -- super new Blaster
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--[[Function that does something]]
local someFunction = function(argument,number,car):{}
car.Position = Vector3.new(5,5,5)
argument += 2
number = argument * car.Position.X
return {number,number*2,argument*car.CFrame.LookVector}
end
--------------------------------------------------------------------------
--[[Function that register rocks]]
local function rock(rock,name):"new"
local new = name.." and "..rock
return new
end
Of course this function makes no sense, but it’s example, we use different symbols to make our code redable, we use headers and describtions to decorate our code, soo it’s clean
Also another very easy thing is to use TAB to move code to the right, as you can see, every scope have one Tab, this mean code inside function, will be moved, code inside loop inside function will be moved even further
local function Something()
for i = 1, 10 do
if i > 5 then
print("Hi")
else
print("Wait")
end -- scope 3
end -- scope 2
end -- scope 1
Apart of that, the hardest part, NAMING, for this i can’t really show example, simply try to name Functions, Variables, Objects and everything else depending on it’s functionality
For instance function that calculates bullet’s trajectory should be called CalculateBulletTrajectory
or maybe value of car’s speed should be called CarSpeed
, so it can be understood easily
Types are another thing that should be considered, more about them in next tutorial
Another quick thing, use space to separate important stuff, variables should be separated from objects, or stuff related to something specific should be separated from other things
This is more advanced tip, and also short, you can replace certain Roblox’s Api stuff with math, math is usually more efficient and use less performance, those are more specific cases and advanced topics, but keep that in mind
Follow good practices, you can find them on forum, here are some links:
IMPORTANT NOTE: Always be open to alternatives, roblox advances quickly, and adds new ways to make everything better
Those were few tips for making your code cleaner and better organised, you should use them to become better
Thanks for reading, have a nice day, Godbye!
11. Types
Welcome, today we will learn about Types, this is our last Lua tutorial
Soo, i used Types few times, they are simply what Type of thing is Variable
There are many types, i mentioned 4 basic ones:
- numbers
- booleans
- strings
- tables
There are of course tens of Roblox’s own Types like Instances, Parts, Constraints and more
Types are used to organise code and to describe specific variables, let’s say we want to make 10 different values required for system to run, and we want player who don’t know programming to change them, we simply add types and player will know what type of stuff to write in
local speed : number = 50
local isFuelInfinite : boolean = true
local carName : String = "Super car"
We can create our own custom types
type rock = Part -- custom types have to be equal currently existing ones
type custom = "Custom Type" -- using string type to create new type, usefull in some cases
Can we detect if object's type is equal to type that we looking for?
Yes, to do this we use typeOf methood
local part = workspace.Part
if typeOf(part) == "Part" then
print("Part is Part... what?")
end
Types can be used for some logic code or checks, but for the most time you will use them as visuals
Thanks for today, i believe i helped you learn Lua, i have Roblox’s Api tutorials in plan, stay tuned, have a nice day, Godbye!
Our next tutorial: Scripting Manual Part 2