Comments
Comments allow us to add explanations and notes to our code. When scripts are executed all comments are completely ignored.
Single-Line Comment
You can use the hotkey Ctrl + /
in Roblox Studio to create a comment on the current line.
-- This is a single-line comment
local score = 100 -- This single-line comment is at the end of a line
Multi-Line Comment
--[[
This is a multi-line comment.
You can write multiple lines of comments here.
]]
Variables
Variables are used for storing data of different types.
local nameOfVariable = "valueOfVariable"
local
is the scope of the variable.nameofVariable
is the name of the variable."valueOfVariable"
is the value of the variable.
Data Types
A variable’s type is based off its value. The type of a variable is important as it enables us to know how we can use that variable. For instance, you can only perform math operations on two number variables.
Primitive Types
The following are standard Luau types, which are also commonly used in other programming languages.
Type | Example | Info |
---|---|---|
string | “StringType” | Characters surrounded by " , ' , or ` s |
number | 10.5 | Any number including whole numbers & decimals |
boolean | true | true or false . Similar to yes or no |
table | {} | Array or Dictionary |
function | function() | A function |
nil | It means “nothing” or “does not exist” |
String
You can combine two strings putting two periods (..
) between the strings.
local newString = "Hey I'm".." pretty cool!" -- Hey I'm pretty cool!
Using backticks (`
) when creating a string is another easy way of combining strings.
local firstString = "Hey I'm"
local newString = `{firstString} pretty cool!` -- Hey I'm pretty cool!
Number
You can perform math operations with two numbers by using any arithmetic symbols between the numbers.
local newMath = 5 + 10 -- 15
Boolean
You can use a conditional statement to create a boolean.
local newBool = 5 + 10 == 15 -- true
Roblox Types
Roblox adds to their plethora of custom types often, but you always view the most up to date list here!
Examples
Simple
local numberVariable = 10
local stringVariable = "100"
local booleanVariable = true
local nilVariable = nil
local nilVariable2
local tableArrayVariable = {"2", 3, true}
local tableDictionaryVariable = {first = "2", 2 = "3rd", third = "two"}
Advanced
local numberVariable = 1_000 -- _ can be used within a number to improve readability of larger numbers
local stringVariable = "100".." and two"
local stringVariableTwo = `Here's another string and the first string: {stringVariable}`
local booleanVariable = numberVariable == 1_000
local nilVariable = nil
local nilVariable2 = nilVariable or nil
Functions
Functions are reusable blocks of code that perform specific tasks.
-- Defining a function
function greetPlayer(playerName)
print("Hello, " .. playerName)
end
-- Calling a function
greetPlayer("Alice")
Conditional Statements
We can use conditionals to perform an action based on a specified scenario.
Conditionals are written in the following format:
local number = 10
if number == 10 then -- Can be thought of as 10 = 10
print(true)
elseif number < 15 then -- Can be thought of as 10 is less than 15
print(true)
else -- Can be thought of as any other 'condition' besides the previous two
print(false)
end
Conditionals are read from top to bottom. For example, first number == 10
is read, since this is true print(true)
will run, and nothing more will happen. If we want number < 15
to be checked, we must use a number between 11
and 14
so that number == 10
will NOT be true.
Relational Operators
We commonly use relational operators to create conditionals.
if 10 == 10 then -- Can be thought of as 10 = 10 (True)
print(true)
end
Symbol | Comparison | Example | Result |
---|---|---|---|
== | Equal to | 1 == 2 | False |
~= | Not equal to | 1 ~= 2 | True |
< | Less than | 1 < 2 | True |
<= | Less than or equal to | 1 <= 2 | True |
> | Greater than | 1 > 2 | False |
>= | Greater than or equal to | 1 >= 2 | False |
Logical Operators
We can also use logical operators to create slightly more complex conditionals.
if not 10 == 10 or not 1 == 1 then -- Can be thought of as 10 ~= 10 or 1 ~= 1 (False)
print(true)
end
Symbol | Comparison | Example | Result |
---|---|---|---|
not | Cannot be true | not 1 == 2 | True |
or | Either can be true | 1 == 2 or 1 == 1 | True |
and | Both need to be true | 1 == 2 and 1 == 1 | False |
Tables
Tables are used to store a collection of data.
Arrays
Arrays are used to store a collection of values in a specific order. Elements in an array are indexed with integers starting at 1.
local fruits = {"apple", "banana", "cherry"}
Adding values to an Array
We can use the table.insert
function to add values to the end of an array.
table.insert(fruits, "grape")
Removing Values from an Array
We can use the table.remove
function to remove a value by index.
local fruits = {"apple", "banana", "cherry"}
table.remove(fruits, 2) -- Removes "banana"
Using Values from an Array
We can use elements from an array by using their index.
local fruits = {"apple", "banana", "cherry"}
local firstFruit = fruits[1] -- "apple"
Dictionaries
Dictionaries are used to store key-value pairs. These could be thought of as storing variables, where they key would be the variable’s name and the value would be the variable’s value.
local player = {
name = "Bob",
score = 75
}
Adding Values to a Dictionary
You can add values to dictionaries by indexing it with the dot operator and then specifying the new key and value.
player.level = 10
Removing Values from a Dictionary
You can remove values from dictionaries by setting the value of the key to nil
.
player.score = nil -- Removes the "score" key and value
Using Values from a Dictionary
You can use values from dictionaries simply dot indexing it with the specific key.
local playerName = player.name -- "Bob"
Loops
Loops allow us to execute a block of code repeatedly.
For Loops
For loops are the most commonly used loops. We use these when we know the total number of iterations in advance or if we want to iterate through a table.
Numeric For Loop
for i = 1, 5 do
print(i) -- Prints numbers from 1 to 5
end
Iterating over an Array
Elements are stored inside of an array in a specific order start from the index of 1. As we iterate through the following array the elements will be printed in the following order: apple
, banana
, cherry
.
local fruits = {"apple", "banana", "cherry"}
for index, value of fruits do
print(index, value) -- Prints the index beside the fruit
end
Iterating over a Dictionary
One important thing to keep in mind is that key value pairs are stored inside of dictionaries in no specific order. That means as we iterate through the dictionary, the score 75
pair could be printed before the name bob
pair.
local player = {
name = "Bob",
score = 75
}
for key, value of player do
print(index, value) -- Prints the key beside the value
end
While Loops
While loops are used when the number of iterations isn’t known in advance but is based on a condition.
The following while loop will iterate until the counter
variable becomes 5.
local counter = 1
while counter <= 5 do
print(counter) -- Prints numbers from 1 to 5
counter = counter + 1
end
Controlling Loops
We can modify the behavior of loops such as stopping them early or skipping the current iteration by using control statements.
Break
The break
statement is used to stop the loop prematurely.
for i = 1, 10 do
if i == 5 then
break -- Exits the loop when i equals 5
end
end
local counter = 10
while true do
if counter == 10 then
break -- Exits the loop during the first iteration
end
print(true) -- Will never be printed as the iteration is stopped before this is reached
end
Continue
The continue
statement is used to skip the current iteration.
local fruits = {"apple", "banana", "cherry"}
for index, value of fruits do
if value == "banana" then
continue
end
print(value) -- Only apple and cherry will be printed
end
Loop Tips
Infinite Loops
There are occasions where you may want a code block to be executed during the entire duration of your game being active. This is possible by using a while loop and never breaking the condition. The simplest way to do this is by setting true
as the condition.
Depending on the situation we might be able to avoid using an infinite loop by instead using event driven programming. It’s often recommended to avoid infinite loops because they can easily be misused and really stagger your game’s performance.
while true do
print(true) -- This will never stop being printed
end
Yielding in Loops
It’s almost always recommended to use the task.wait
function inside of a while loop to prevent performance impacts. This function allows us to yield or temporarily stop the loop after each iteration.
while true do
print(true) -- True will infinitely be printed each second
task.wait(1) -- Yield / pause control for 1 second
end
Symbols
Symbol | Name | Usage |
---|---|---|
~ | Tilde | |
/ | Slash | |
! | Exclamation mark | |
# | Hashtag | |
– | Dash | |
() | Brackets / Parenthesis | |
{} | Curly Braces | |
[] | Square Brackets | |
; | Semicolon | |
: | Colon | |
% | Percent | |
^ | Caret | |
* | Asterisk | |
& | And symbol | |
– | Hyphen / Minus / Dash | |
| | Pipe | |