0% found this document useful (0 votes)
14 views65 pages

Roblox Lua Scripting Book

This document is a comprehensive beginner's guide to Roblox Lua scripting, aimed at children aged 9 and above. It covers essential programming concepts such as variables, functions, loops, and events, with practical examples and quizzes to reinforce learning. The guide also includes a full game project to help readers apply their knowledge in creating a playable game.

Uploaded by

funx9618
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views65 pages

Roblox Lua Scripting Book

This document is a comprehensive beginner's guide to Roblox Lua scripting, aimed at children aged 9 and above. It covers essential programming concepts such as variables, functions, loops, and events, with practical examples and quizzes to reinforce learning. The guide also includes a full game project to help readers apply their knowledge in creating a playable game.

Uploaded by

funx9618
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ROBLOX LUA

SCRIPTING
From Zero to Game

The Complete Beginner's Guide — Ages 9+

Variables · Functions · If Statements · Loops · Events · Instances · And More

Made for kids who want to build real Roblox games — explained in plain English, no confusing
tech talk. Every chapter has examples, tips, quizzes, and a vocabulary section.

Covers: print · arithmetic · variables · data types · booleans · local · functions · parameters · return · instance properties ·
if/elseif/else · loops · events · touched events · humanoid · leaderboards · and operators
Chapter

Table of Contents
Everything you will learn in this book

Setting Up Roblox Studio


Chapter 1
Getting Studio ready, creating your first script, output window

Your First Line of Code — print()


Chapter 2
What print does, printing text, printing numbers

Arithmetic Operations
Chapter 3
+ - * / % — doing math in Lua

Variables
Chapter 4
What variables are, naming rules, storing values

Data Types
Chapter 5
Strings, Numbers, Booleans — the three types you need to know

local — The Golden Rule


Chapter 6
Why local matters and when to use it

Functions
Chapter 7
Writing reusable blocks of code, calling functions

Parameters
Chapter 8
Passing information into functions

return
Chapter 9
Getting values back out of functions

Instance Properties
Chapter 10
[Link], BrickColor, Size, Anchored and more

If Statements
Chapter 11
Making your code make decisions

elseif — Multiple Conditions


Chapter 12
Checking more than two things
Logical Operators: and / or / not
Chapter 13
Combining conditions

Loops
Chapter 14
for loops, while loops — repeating code

Events
Chapter 15
Touched, PlayerAdded, Chatted — reacting to the game

The Humanoid
Chapter 16
Health, taking damage, killing players

Leaderboards
Chapter 17
Tracking coins, kills, points on a leaderboard

Comments
Chapter 18
Writing notes in your code

Advanced Tips & Tricks


Chapter 19
Clean code habits, debugging, common mistakes

Full Game Project


Chapter 20
Putting it all together into a real playable game

Scripting Reference Sheet


Quick lookup for everything covered in this book
Chapter 1

Setting Up Roblox Studio


Your coding environment

Before you write a single line of code, you need to set up Roblox Studio. Think of Studio as your
workshop — it's where everything happens. Don't worry, it's completely free and easy to install!

Step 1 — Download Roblox Studio


Go to [Link] in your browser and sign in with your Roblox account. Once you're
logged in, look for the Download Studio button and install it like a normal app.

Step 2 — Create a New Project


Open Studio. You'll see a list of templates. Click Baseplate — this gives you a flat empty world to
build on. Perfect for learning!

Step 3 — The Most Important Panels


Studio has lots of panels. You only need to know two for now:

• Explorer — Shows everything in your game — parts, scripts, players — like a file tree on the
right side.
• Output — Shows messages from your code. If you print something, it appears here. Go to
View at the top and click Output if you can't see it.

Step 4 — Creating Your First Script


• In the Explorer panel, find ServerScriptService
• Click the + button next to it
• Type Script and press Enter
• Double-click the Script that appears to open the code editor
• Delete the default text inside it
■ Where do scripts go?
Always put your scripts inside ServerScriptService. Scripts placed here run automatically
when the game starts. If your script is somewhere else, it might not run at all!
Scripts inside Parts only run when specifically told to — we'll cover that later.

Step 5 — Run Your Game


Click the big Play button at the top of Studio to run your game. Any results from your code will
appear in the Output window at the bottom. Click the Stop button when you're done testing.

■■ Important!
Any changes you make to the game WHILE it's playing are TEMPORARY. They disappear
when you stop. Always stop the game before editing your scripts!

■ Quiz Time!

1. Where should you put your scripts in Roblox Studio?


Answer: Inside ServerScriptService

2. What panel shows everything in your game like a file tree?


Answer: The Explorer panel

3. What button do you press to run your game?


Answer: The Play button at the top

4. Where do you see results from your print() code?


Answer: In the Output window

■ Vocabulary
Roblox Studio — The free app you use to build and script Roblox games
Explorer — The panel that shows everything inside your game
Output — The panel that shows messages from your running code
ServerScriptService — The folder in Explorer where you put your scripts
Baseplate — A starter template — a flat empty world to build on
Chapter 2

Your First Line of Code — print()


Showing messages in the Output window

Every programmer in the world learns print first. It's the simplest thing you can do — it shows a
message in the Output window. Players can't see it, only YOU can. Think of it as a way to talk to
yourself while coding.

Your Very First Script


Type this into your script and press Play:

print("Hello, Roblox!")

You should see Hello, Roblox! appear in the Output window. That's it — you just wrote your first
line of Lua code!

How print() Works


Let's break it down word by word:

• print — A built-in command that Lua already knows. It shows something in Output.
• () — The parentheses are where you put what you want to show.
• "Hello!" — The text you want to print. Always wrapped in quotation marks.

Printing Different Things


print("Hello!") -- prints text

print(100) -- prints a number

print(true) -- prints true

print("I am", 13, "years old") -- prints multiple things

When you print multiple things separated by commas, they all appear on the same line with
spaces between them.
■ Pro Tip — Use print to Debug!
Whenever your game isn't working correctly, add print() statements everywhere to check
what's happening. For example:
print("health is:", health) -- check what value health has
This is called debugging — every real developer does it all the time!

Common Mistakes with print


Print("hello") -- WRONG! capital P breaks it

print(hello) -- WRONG! no quotes = lua thinks hello is a variable

print("hello" -- WRONG! missing closing bracket

print("hello") -- CORRECT!

■■ Lua is Case Sensitive!


print is correct. Print with a capital P is WRONG and will cause an error.
Same goes for everything in Lua — capitalize matters everywhere!

■ Quiz Time!

1. What does print() do?


Answer: Shows a message in the Output window

2. Can players see what you print?


Answer: No! Only you (the developer) can see it

3. What is wrong with: print(Hello)?


Answer: Hello has no quotes around it — Lua thinks it is a variable

4. How do you print two things at once?


Answer: Use a comma: print("I am", 13)

5. What is it called when you add print() to find bugs?


Answer: Debugging
■ Vocabulary
print() — A built-in Lua function that shows messages in the Output window
Output window — The panel at the bottom of Studio where print results appear
Debugging — The process of finding and fixing bugs in your code using tools like print()
Function — A named command that does something — print is a function
Parentheses — The () brackets — used to pass information into a function
Chapter 3

Arithmetic Operations
Math in Lua — it's just like school math!

Lua can do math just like a calculator. You already know +, -, *, / from school. There's one extra
operator called modulus (%) which gives you the remainder. Let's go through all of them!

The Five Operators


Operator Name Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 4 2.5

% Modulus 10 % 3 1

Using Arithmetic with print()


print(10 + 5) -- shows: 15

print(10 - 5) -- shows: 5

print(10 * 5) -- shows: 50

print(10 / 4) -- shows: 2.5

print(10 % 3) -- shows: 1

What is Modulus (%) ?


Modulus gives you the leftover after division. Like when you share 10 sweets between 3 friends
— each gets 3, and you have 1 left over. That leftover is the modulus!
print(10 % 3) -- 10 divided by 3 = 3 remainder 1 -> shows: 1

print(15 % 4) -- 15 divided by 4 = 3 remainder 3 -> shows: 3

print(20 % 5) -- 20 divided by 5 = 4 remainder 0 -> shows: 0

■ Real Game Use of Modulus


In Roblox games, modulus is used to check if something is even or odd:
if number % 2 == 0 then -- if there is no remainder, the number is even
It's also used for things like every 10th player getting a reward!

Order of Operations
Just like in school, Lua follows BODMAS/PEMDAS. Multiplication and division happen before
addition and subtraction. Use brackets () to control the order:

print(2 + 3 * 4) -- shows 14 (not 20!) because * happens first

print((2 + 3) * 4) -- shows 20 because brackets are first

■ Quiz Time!

1. What does 25 % 4 equal?


Answer: 1 (25 divided by 4 = 6 remainder 1)

2. What symbol is used for multiplication in Lua?


Answer: * (asterisk)

3. What does print(100 / 4) show?


Answer: 25

4. What does print(2 + 3 * 4) show and why?


Answer: 14 — because * happens before +

5. What is modulus useful for in games?


Answer: Checking if a number is even/odd, giving rewards every Nth event
■ Vocabulary
Operator — A symbol that performs an operation — +, -, *, /, %
Arithmetic — Math operations — adding, subtracting, multiplying, dividing
Modulus (%) — Returns the remainder after division
BODMAS — The order of operations: Brackets, Orders, Division, Multiplication, Addition,
Subtraction
Chapter 4

Variables
Boxes that store information

A variable is like a labeled box. You put something inside it, give it a name, and whenever you
need that thing, you just say the label name and Lua grabs it for you.

Your game needs to remember things — how much health a player has, how many coins they
collected, what their name is. Variables are how that happens.

Creating a Variable
local coins = 50

Three parts to every variable:

Part What It Is Example

local Keeps the variable in this script (always use this!) local

coins The name YOU made up — the label on the box coins

50 The value stored inside the box 50

Using Variables
local coins = 50

print(coins) -- shows: 50

print("coins:", coins) -- shows: coins: 50

■■ No quotes when printing variables!


print(coins) -- correct! shows the VALUE inside the box
print("coins") -- wrong! just prints the word coins, not the value

Variables Can Change


That's literally why they're called variables — the value can vary (change)!

local health = 100

print(health) -- shows: 100

health = 50 -- change it! (no local this time)

print(health) -- shows: 50

health = 0

print(health) -- shows: 0

■ Why no local the second time?


You only write local when you FIRST create a variable.
After that, you just use the name directly to update it.
Writing local again would create a SECOND variable with the same name — confusing!

Math with Variables


local coins = 0

print(coins) -- shows: 0

coins = coins + 10 -- add 10 to whatever coins currently is

print(coins) -- shows: 10

coins = coins + 10

print(coins) -- shows: 20

coins = coins * 2 -- double the coins

print(coins) -- shows: 40

coins = coins + 10 means: take whatever is in coins, add 10 to it, then put the result back into
coins.

Variable Naming Rules


• Names can only contain letters, numbers, and underscores _
• Names CANNOT start with a number
• Names are case-sensitive: coins and Coins are two different variables!
• No spaces in names — use camelCase like playerName or underscores like player_name
• Make names descriptive — playerHealth is better than just h

-- GOOD variable names

local playerName = "Alex"

local maxHealth = 100

local coinCount = 0

-- BAD variable names (will cause errors!)

local 1player = "Alex" -- starts with a number

local my name = "Alex" -- has a space

■ Quiz Time!

1. What is a variable?
Answer: A named storage box that holds a value

2. What keyword should you always put before a new variable?


Answer: local

3. What does coins = coins + 5 mean?


Answer: Take whatever is in coins, add 5, save it back

4. Is playerName the same as playername?


Answer: No! Lua is case-sensitive — they are different variables

5. What is wrong with: local 2score = 0?


Answer: Variable names cannot start with a number

■ Vocabulary
Variable — A named storage box that holds a value which can change
local — Keyword that keeps a variable inside its script
Assignment — Giving a variable a value using =
camelCase — Writing names like playerHealth — lowercase first, capitals for new words
Case-sensitive — Uppercase and lowercase letters are treated differently — coins != Coins
Chapter 5

Data Types
Strings, Numbers, and Booleans

Every value in Lua has a type. Think of it like different kinds of containers — a glass for water, a
plate for food, a box for toys. You wouldn't put soup in a toy box!

The three main types you'll use in Roblox are: Strings, Numbers, and Booleans.

1. Strings — Text
A string is any piece of text. Always wrapped in quotation marks. If it has quotes around it, it's a
string — even if it looks like a number!

local playerName = "Alex" -- string

local weapon = "Sword of Doom" -- string

local fakeNumber = "100" -- this is also a STRING (has quotes!)

print(playerName) -- shows: Alex

■■ Strings with quotes vs Numbers


"100" is a STRING — you cannot do math with it!
100 without quotes is a NUMBER — you CAN do math with it.
print("50" + 50) -- ERROR! Cannot add string and number

String Concatenation — Joining Text


You can join strings together using .. (two dots):

local firstName = "Alex"

local lastName = "Smith"

local fullName = firstName .. " " .. lastName

print(fullName) -- shows: Alex Smith


local level = 5

print("You are level " .. level) -- shows: You are level 5

2. Numbers
Numbers in Lua have no quotes. They can be whole numbers (integers) or decimals (floats).

local health = 100 -- whole number (integer)

local speed = 16.5 -- decimal number (float)

local damage = -25 -- negative number

-- You can do math with numbers

local total = health + damage

print(total) -- shows: 75

3. Booleans — True or False


A boolean is the simplest data type. It can ONLY be true or false. Think of it as a yes/no switch.

local isAlive = true -- player is alive

local hasWeapon = false -- player has no weapon

local doorIsOpen = false -- door is closed

local isRunning = true -- player is running

Booleans are perfect for on/off states in your game. Later with if statements, you'll check these to
make decisions!

-- CORRECT boolean usage

local isAlive = true -- no quotes, lowercase

-- WRONG! These will break your code

local isAlive = True -- capital T is wrong!

local isAlive = "true" -- this is a STRING, not a boolean!

Quick Reference — All Three Types


Type Example Has Quotes? Use For

String "Alex" YES Names, messages, text

Number 100 NO Health, coins, scores

Boolean true NO On/off states, alive/dead

■ Quiz Time!

1. What type is "hello"?


Answer: String — it has quotation marks

2. What type is 42?


Answer: Number — no quotes

3. What type is true?


Answer: Boolean — can only be true or false

4. What is wrong with local isAlive = True?


Answer: Boolean must be lowercase: true not True

5. How do you join two strings together in Lua?


Answer: Use .. (two dots): "Hello" .. " " .. "World"

■ Vocabulary
Data Type — The kind of value a variable holds — string, number, or boolean
String — Text wrapped in quotation marks
Integer — A whole number with no decimal point — 1, 42, 100
Float — A decimal number — 3.14, 16.5, 0.5
Boolean — A value that is either true or false — nothing else
Concatenation — Joining strings together using the .. operator
Chapter 6

local — The Golden Rule


Why you should always use local

You've been typing local before every variable. Let's actually understand why!

Scope — Where Variables Live


Imagine your school has classrooms and hallways. Things inside a classroom can only be used in
that classroom. Things in the hallway can be used by everyone.

Variables work the same way in Lua. local variables stay in their own classroom (the script or
block they were created in). Variables WITHOUT local go into the hallway — any script can access
them.

local coins = 50 -- local variable: lives in this script only

score = 100 -- global variable: ANY script can see it

Why Always Use local?


• Safety — other scripts can't accidentally change your variable
• Speed — Lua runs local variables faster than global ones
• Best practice — every professional Roblox developer uses local
• Avoid bugs — two scripts using the same global name can cause weird bugs

■ Simple Rule
Just ALWAYS put local before every variable you create.
Never think about it — just always type local first.
local coins = 50 <-- always like this!

Scope Blocks
Local variables also have 'block scope' — they only exist inside the block they were created in.
This becomes important with if statements and loops:

local x = 10 -- x lives in this whole script

if true then

local y = 20 -- y only lives INSIDE this if block

print(x) -- works fine: x = 10

print(y) -- works fine: y = 20

end

print(x) -- works fine: x = 10

print(y) -- ERROR! y does not exist out here

■ Quiz Time!

1. What keyword keeps a variable inside its script?


Answer: local

2. What is a global variable?


Answer: A variable without local — any script in the game can see it

3. Why is local faster?


Answer: Lua accesses local variables more efficiently than global ones

4. If you create a local variable inside an if block, can you use it outside?
Answer: No — it only exists inside that block

■ Vocabulary
local — Keyword that limits a variable to the script or block it is created in
Global variable — A variable without local — visible to all scripts (avoid these!)
Scope — Where a variable can be accessed — local scope means only within the
block/script
Block — A section of code between a keyword and end, like an if block or function body
Chapter 7

Functions
Reusable blocks of instructions

A function is like a recipe. You write the instructions once, give them a name, and then you can
follow that recipe anytime just by calling its name. You don't rewrite the recipe every time — you
just say 'make the pizza!'

Why Do We Need Functions?


Imagine you want to show a player's stats every time they respawn. Without functions, you'd write
the same code over and over:

-- Without functions -- terrible! same code repeated

print("name: Alex")

print("health: 100")

print("coins: 50")

-- player respawns...

print("name: Alex")

print("health: 100")

print("coins: 50")

-- player respawns again...

print("name: Alex") -- writing the same thing AGAIN

With a function, you write it ONCE and call it whenever you need it:

-- With a function -- much better!

local function showStats()

print("name: Alex")
print("health: 100")

print("coins: 50")

end

showStats() -- first spawn

showStats() -- respawn

showStats() -- another respawn

Function Structure
local function greetPlayer()

print("Welcome to the game!")

print("Good luck!")

end

greetPlayer() -- call it here!

Breaking it down:

Part Meaning

local function Always start with this — local keeps it in the script, function tells Lua what this is

greetPlayer The name YOU made up — call it anything descriptive

() Empty brackets for now — we'll put parameters here later

the code inside The instructions that run when the function is called

end ALWAYS needed to close the function

greetPlayer() This is the CALL — this is what actually runs the function

Define vs Call — Two Steps


There are always TWO steps with functions:

-- STEP 1: Define (write the instructions)

local function sayHello()


print("Hello!")

end

-- Nothing has happened yet! You just wrote the recipe.

-- STEP 2: Call (actually run it)

sayHello() -- NOW it runs! Output shows: Hello!

sayHello() -- run it again!

sayHello() -- and again!

■■ Forgetting to Call
The most common beginner mistake is defining a function but forgetting to call it!
If nothing shows in Output, check that you actually called your function below the definition.

■ Quiz Time!

1. What keyword pair always starts a function?


Answer: local function

2. What always closes a function?


Answer: end

3. What are the two steps to using a function?


Answer: 1) Define it, 2) Call it

4. What do the () after the function name do when calling?


Answer: They tell Lua to actually RUN the function now

5. What is the difference between defining and calling a function?


Answer: Defining stores the instructions. Calling actually runs them.

■ Vocabulary
Function — A named block of reusable instructions
Define — Writing a function — creating the instructions (local function name()...end)
Call — Running a function — telling Lua to execute it (name())
Body — The code written between the function's () and its end — the actual instructions
Chapter 8

Parameters
Passing information into functions

Right now your functions always do the same thing. Parameters let you give functions different
information each time you call them. Think of a vending machine — the machine is the function,
and the button you press is the parameter!

Without Parameters — Same Every Time


local function greetPlayer()

print("Welcome, Alex!")

end

greetPlayer() -- always says Alex, cant change it

With Parameters — Different Every Time


local function greetPlayer(name)

print("Welcome,", name)

end

greetPlayer("Alex") -- Welcome, Alex

greetPlayer("Suri") -- Welcome, Suri

greetPlayer("Jordan") -- Welcome, Jordan

Same function, different results every time! That's the power of parameters.

How Parameters Work — Step by Step


local function greetPlayer(name) -- name is an EMPTY BOX
print("Welcome,", name)

end

greetPlayer("Suri") -- fills the box with "Suri"

-- inside: name = "Suri"

-- so prints: Welcome, Suri

■ Parameter = Empty Box


When you write a parameter in the brackets (name), you're creating an empty box.
When you CALL the function with a value greetPlayer('Suri'), you fill that box.
Inside the function, the parameter works exactly like a regular variable!

Multiple Parameters
Separate multiple parameters with commas. Values must be passed in the SAME ORDER!

local function playerStats(name, health, coins)

print("name:", name)

print("health:", health)

print("coins:", coins)

end

playerStats("Alex", 100, 50)

-- name = "Alex"

-- health = 100

-- coins = 50

playerStats("Suri", 75, 200)

-- name = "Suri"

-- health = 75

-- coins = 200
■■ Order Matters!
playerStats("Alex", 100, 50) -- correct: name, health, coins
playerStats(100, "Alex", 50) -- WRONG! now name=100 and health="Alex"!
Always pass values in the same order as the parameters were defined.

■ Quiz Time!

1. What is a parameter?
Answer: An empty box in a function's brackets that gets filled when you call the function

2. If a function has 3 parameters, how many values must you pass when calling it?
Answer: 3 — one for each parameter

3. What does greetPlayer("Suri") do to the name parameter?


Answer: It fills the name box with the string Suri

4. What happens if you pass values in the wrong order?


Answer: Each value goes into the wrong parameter — your code will behave incorrectly

■ Vocabulary
Parameter — A variable in a function's brackets — acts as an empty box waiting to be filled
Argument — The actual value you pass into a parameter when calling a function
Multiple parameters — More than one parameter, separated by commas: function name(a,
b, c)
Chapter 9

return
Getting values back out of functions

You know how functions DO things? Sometimes you want a function to not just do something, but
also give you back an answer. That's what return does.

Think of it like this: you ask your friend 'what is 10 + 20?' Your friend calculates it and says 'it's 30!'
They RETURNED the answer to you. Without return, they'd just think about it silently and never
tell you!

Without return — answer stays inside


local function addNums(a, b)

local result = a + b -- calculated but never given back!

end

addNums(10, 20) -- runs but you have no way to use the answer

With return — answer comes out


local function addNums(a, b)

return a + b -- gives the answer back out!

end

local answer = addNums(10, 20) -- catch the answer in a variable

print(answer) -- shows: 30

-- or print directly without storing

print(addNums(5, 7)) -- shows: 12

Real Roblox Example — isAlive Function


local function isAlive(health)

if health > 0 then

return true -- player is alive

else

return false -- player is dead

end

end

local alive = isAlive(100)

print(alive) -- shows: true

local alive2 = isAlive(0)

print(alive2) -- shows: false

■ Two Ways to Use return Values


1. Store in a variable: local result = addNums(10, 20)
2. Use directly: print(addNums(10, 20))
Use option 1 when you need the value multiple times.
Use option 2 when you just want to see it once.

■ Quiz Time!

1. What does return do?


Answer: Sends a value back out of the function to whoever called it

2. What is the difference between print and return?


Answer: print shows something on screen. return gives a value back to be used in code.

3. Can you use return inside an if statement inside a function?


Answer: Yes! This is very common in Roblox

■ Vocabulary
return — Sends a value back out of a function so it can be used elsewhere
Return value — The value that a function returns
Chapter 10

Instance Properties
Controlling Roblox parts with code

Everything you see in a Roblox game — bricks, walls, parts, the baseplate — is called an
Instance. Every instance has properties — characteristics like color, size, position, and whether
it's anchored.

You can change these properties with code! This is where scripting starts to feel like real game
development.

Finding a Part in Your Script


Before you can change a part's properties, your script needs to find it. Think of [Link]
as an address:

-- The full address: game -> Workspace -> YourPartName

local part = [Link]

-- You can also write it like this (same thing)

local part = [Link]

The name after Workspace. must EXACTLY match the part's name in the Explorer panel. Capital
letters matter!

Changing Properties
local part = [Link]

-- Change color

[Link] = [Link]("Bright red")

-- Change size (width, height, depth)

[Link] = [Link](10, 5, 10)


-- Anchor the part (stop it from falling)

[Link] = true

-- Make it transparent (0 = solid, 1 = invisible)

[Link] = 0.5

-- Move it to a position

[Link] = [Link](0, 10, 0)

-- Can it be collided with?

[Link] = false

Common BrickColors
BrickColor Name BrickColor Name BrickColor Name

"Bright red" "Bright blue" "Bright green"

"Bright yellow" "White" "Black"

"Lime green" "Hot pink" "Cyan"

"Orange" "Dark orange" "Reddish brown"

Vector3 — 3D Positions and Sizes


Roblox is a 3D world, so positions and sizes have THREE values: X, Y, Z.

[Link](X, Y, Z)

-- X = left/right

-- Y = up/down

-- Z = forward/backward

[Link] = [Link](10, 5, 10) -- 10 wide, 5 tall, 10 deep

[Link] = [Link](0, 5, 0) -- center, 5 studs up, center

Creating New Parts with Code


You can also CREATE parts from scratch using [Link]:

local newPart = [Link]("Part", [Link])

[Link] = [Link]("Bright blue")

[Link] = [Link](5, 5, 5)

[Link] = [Link](0, 10, 0)

[Link] = true

[Link] = "MyNewPart"

■ Why store in a variable?


Without a variable you'd have to write [Link] every time!
With a variable:
[Link] = ... (short and clean)
[Link] = ... (short and clean)
[Link] = ... (short and clean)

■ Quiz Time!

1. What is an Instance?
Answer: Any object in Roblox — parts, scripts, GUIs, etc.

2. What is a property?
Answer: A characteristic of an instance — like BrickColor, Size, Anchored

3. How do you find a part called 'Floor' in Workspace?


Answer: local floor = [Link]

4. What does [Link](X, Y, Z) represent?


Answer: A 3D position or size with left/right, up/down, forward/backward values

5. What does Anchored = true do?


Answer: Stops the part from falling due to gravity
■ Vocabulary
Instance — Any object in Roblox — parts, scripts, models, GUIs
Property — A characteristic of an instance that you can read or change
BrickColor — The color of a Roblox part — set using [Link]('Color Name')
Vector3 — A 3D value with X, Y, Z components — used for Position and Size
Anchored — A property that stops a part from being affected by gravity
Transparency — How see-through a part is — 0 is solid, 1 is invisible
[Link] — Creates a brand new instance of any type in your game
Chapter 11

If Statements
Making your code make decisions

Right now your code just runs top to bottom, doing the same thing every time. If statements let
your code make decisions. This is where things get exciting because now your game can react
differently to different situations!

Real Life Examples


• If you have enough coins then buy the sword
• If health is 0 then the player dies
• If player touches the door then open it
• If score is above 100 then give a badge

The Structure
if condition then

-- code that runs if condition is true

end

Always three things: if, then, and end. The code in the middle only runs if the condition is true.

Real Example
local health = 100

if health == 100 then

print("Full health!")

end

-- == means CHECK if equal (not = which means STORE)


■■ = vs ==
= means STORE a value: local coins = 50
== means CHECK if equal: if coins == 50 then
This is the most common beginner mistake — mixing them up!

Adding else — What if it's False?


local health = 50

if health == 100 then

print("Full health!")

else

print("You are hurt!")

end

-- health is 50, not 100, so else runs

-- Output: You are hurt!

Comparison Operators
Operator Meaning Example

== Equal to if health == 100 then

~= NOT equal to if health ~= 0 then

> Greater than if coins > 50 then

< Less than if health < 20 then

>= Greater than or equal if score >= 100 then

<= Less than or equal if level <= 5 then

Checking Booleans
local isAlive = true
-- Long way:

if isAlive == true then

print("Player is alive")

end

-- Short way (same thing!) -- from your book's Script Tip:

if isAlive then

print("Player is alive")

end

-- Checking for false:

if not isAlive then

print("Player is dead")

end

■ Script Tip — Shorter Boolean Checks


Just as your book showed: if (scriptingIsAwesome) then is the same as
if (scriptingIsAwesome == true) then
You can omit the == true part for booleans! It's cleaner and every
professional Roblox developer writes it this way.
■ Quiz Time!

1. What are the three keywords every if statement needs?


Answer: if, then, end

2. What is the difference between = and ==?


Answer: = stores a value. == checks if two values are equal.

3. What does else do?


Answer: Runs a block of code when the if condition is false

4. What does ~= mean?


Answer: Not equal to

5. If health = 30, what does if health >= 50 then print("ok") end do?
Answer: Nothing — 30 is not >= 50 so the print is skipped

■ Vocabulary
if statement — A block of code that only runs when a condition is true
condition — An expression that evaluates to true or false
else — The code that runs when the if condition is false
comparison operator — A symbol that compares two values: ==, ~=, >, <, >=, <=
boolean expression — Any expression that results in true or false
Chapter 12

elseif — Multiple Conditions


Checking more than two possibilities

Sometimes you need more than just true or false. What if there are three, four, or five different
possibilities? That's where elseif comes in!

The Structure
if condition1 then

-- runs if condition1 is true

elseif condition2 then

-- runs if condition1 is false AND condition2 is true

elseif condition3 then

-- runs if condition1 and 2 are false AND condition3 is true

else

-- runs if ALL conditions above are false

end

Real Example — Health Zones


local health = 45

if health >= 75 then

print("Healthy!")

elseif health >= 40 then

print("Getting hurt...")

elseif health >= 10 then


print("Critical health!")

else

print("You are dead!")

end

-- health is 45, so:

-- health >= 75? No.

-- health >= 40? YES! Prints: Getting hurt...

-- (stops checking after finding a true condition)

■ It Stops at the First True Condition


Lua checks from top to bottom and STOPS when it finds the first true condition.
Once one branch runs, all the others are skipped — even if they would also be true!
So always put your most specific conditions first.

Grading System Example


local score = 82

if score >= 90 then

print("Grade: A")

elseif score >= 80 then

print("Grade: B") -- this runs! 82 >= 80

elseif score >= 70 then

print("Grade: C")

elseif score >= 60 then

print("Grade: D")

else

print("Grade: F")

end
■ Quiz Time!

1. What does elseif let you do?


Answer: Check multiple conditions one after another

2. If condition1 is true, does Lua check condition2?


Answer: No — it stops at the first true condition

3. Do you always need an else at the end?


Answer: No — else is optional

4. A player has 85 health. What prints?


Answer: if health>=90: No. elseif health>=75: Yes — prints whatever is in that branch

■ Vocabulary
elseif — An additional condition checked only if all previous conditions were false
else — The final fallback — runs if no if or elseif condition was true
branch — One of the possible paths through an if/elseif/else block
Chapter 13

Logical Operators: and / or / not


Combining multiple conditions

Sometimes one condition isn't enough. What if you need to check TWO things at once? That's
what and, or, and not are for!

and — Both Must Be True


Just like your book shows with the rain example: 'if it is raining AND I have my coat...'

local isRainingOutside = true

local haveMyCoat = true

if isRainingOutside == true and haveMyCoat == true then

print("Im fine, I have my coat!")

end

-- Both must be true for the if to run

-- If either is false, it does not run

-- Roblox game example

local health = 80

local hasWeapon = true

if health > 50 and hasWeapon then

print("Ready to fight!")

else

print("Not ready yet")

end
or — At Least One Must Be True
local hasKey = false

local isAdmin = true

if hasKey or isAdmin then

print("Access granted!") -- runs because isAdmin is true

end

not — Flips True to False


local isDead = false

if not isDead then

print("Player is alive!") -- not false = true, so this runs

end

-- Same as:

if isDead == false then

print("Player is alive!")

end

~= Operator — Not Equal


From your book — the ~= operator means NOT equal to:

local myFavoriteColor = "Blue"

if myFavoriteColor ~= "Green" then

print("myFavoriteColor does NOT equal Green")

end
■ Quiz Time!

1. What does and require?


Answer: BOTH conditions must be true

2. What does or require?


Answer: At least ONE condition must be true

3. What does not do?


Answer: Flips true to false and false to true

4. What does ~= mean?


Answer: Not equal to

5. If hasKey is false and isAdmin is false, does hasKey or isAdmin run?


Answer: No — neither is true

■ Vocabulary
and — Logical operator — both conditions must be true
or — Logical operator — at least one condition must be true
not — Logical operator — flips true to false and false to true
~= — Not equal to — opposite of ==
Chapter 14

Loops
Repeating code automatically

Loops let your code repeat itself. Imagine you want to count from 1 to 100, or give every player a
coin every second, or keep checking if a door should open. Without loops you'd write the same
code hundreds of times!

for Loop — Repeat a Specific Number of Times


-- Count from 1 to 5

for i = 1, 5 do

print("Count:", i)

end

-- Output:

-- Count: 1

-- Count: 2

-- Count: 3

-- Count: 4

-- Count: 5

Breaking it down: for i = 1, 5 means 'start at 1, keep going until 5'. i is the counter variable — it
increases by 1 each time. do and end wrap the code to repeat.

for Loop with a Step


-- Count by 2s

for i = 0, 10, 2 do

print(i) -- 0, 2, 4, 6, 8, 10
end

-- Count backwards

for i = 10, 1, -1 do

print(i) -- 10, 9, 8, 7 ... 1

end

while Loop — Repeat While Something is True


local count = 0

while count < 5 do

count = count + 1

print("count:", count)

end

-- Stops when count reaches 5

■■ Infinite Loops!
If your while condition is ALWAYS true, the loop runs forever and crashes Studio!
while true do -- this runs forever! Studio will freeze!
Always make sure your loop has a way to stop.

wait() — Pausing Inside Loops


In Roblox, you can use wait() to pause code for a set number of seconds. Very useful in loops:

-- Give player 1 coin every second

local coins = 0

while true do

wait(1) -- pause for 1 second

coins = coins + 1

print("Coins:", coins)
end

■ while true do with wait()


while true do with a wait() inside is very common in Roblox games!
It creates a loop that runs forever but pauses between each cycle.
Use it for: coin generators, health regeneration, timers, day/night cycles!

■ Quiz Time!

1. What are the two types of loops covered here?


Answer: for loops and while loops

2. What does for i = 1, 10 do mean?


Answer: Loop 10 times, with i going from 1 to 10

3. What do do and end do in a loop?


Answer: They wrap the code that gets repeated

4. What happens if a while condition is always true?


Answer: Infinite loop — Studio freezes!

5. What does wait(2) do?


Answer: Pauses the code for 2 seconds

■ Vocabulary
Loop — A block of code that repeats itself
for loop — Repeats a set number of times — for i = start, end do
while loop — Repeats as long as a condition is true — while condition do
Counter variable — The variable (usually i) that tracks loop iterations
Iteration — One single run through of a loop
wait() — Pauses code execution for a given number of seconds
Infinite loop — A loop that never stops — usually a bug caused by an always-true condition
Chapter 15

Events
Reacting to things that happen in the game

Everything in Roblox is event-driven. When a player touches a part, that's an event. When a player
joins, that's an event. When a player types in chat, that's an event. You can run code in response
to any of these!

How Events Work


[Link]:Connect(function()

-- code that runs when the event fires

end)

The :Connect() part attaches your code to the event. Whenever that event fires, your code runs
automatically.

Touched Event — When Something Touches a Part


local part = [Link]

[Link]:Connect(function(hit)

print("Something touched the part!")

print("It was:", [Link])

end)

-- hit is whatever touched the part

-- [Link] is its name

Kill Brick Example


local killBrick = [Link]

[Link]:Connect(function(hit)

local character = [Link]

local humanoid = character:FindFirstChild("Humanoid")

if humanoid then

[Link] = 0 -- kill the player!

end

end)

■ Why FindFirstChild?
Not everything that touches your part will be a player!
It could be another part, a tool, or anything else.
FindFirstChild('Humanoid') checks IF the thing has a Humanoid.
If it does, it's a player character. If not, we ignore it.

PlayerAdded Event — When a Player Joins


[Link]:Connect(function(player)

print("Welcome to the game,", [Link])

end)

-- [Link] is their actual Roblox username!

Chatted Event — Like Your Reference Images Show


From your book examples — you can listen to what players type in chat:

[Link]:Connect(function(player)

[Link]:Connect(function(message)

if message == "newpart" then

[Link]("Part", [Link])

elseif message == "kill" then


local character = [Link]

local humanoid = [Link]

[Link] = 0

end

end)

end)

■ Quiz Time!

1. What does :Connect() do?


Answer: Attaches a function to an event so it runs when the event fires

2. What is the hit parameter in the Touched event?


Answer: The object that touched the part

3. Why do we use FindFirstChild('Humanoid')?


Answer: To check if what touched the part is actually a player

4. What event fires when a player joins the game?


Answer: [Link]

5. What is [Link]?
Answer: The actual Roblox username of the player

■ Vocabulary
Event — Something that happens in the game — touching, joining, chatting
:Connect() — Attaches a function to an event
Callback function — The function inside :Connect() that runs when the event fires
hit — The parameter in Touched events — the object that touched the part
PlayerAdded — Event that fires when a player joins the game
FindFirstChild() — Looks for a child with a given name — returns nil if not found
Chapter 16

The Humanoid
Controlling player health

Every player character in Roblox has a Humanoid inside it. The Humanoid is what makes them a
living character — it controls their health, their walk speed, their jump power, and more.

The Player Character Hierarchy


-- Player character structure:

-- player

-- Character

-- HumanoidRootPart (the main body part)

-- Head

-- Humanoid (controls health & movement)

-- ...other body parts

Getting the Humanoid


-- From a Touched event:

[Link]:Connect(function(hit)

local character = [Link]

local humanoid = character:FindFirstChild("Humanoid")

if humanoid then

-- do something to the humanoid

end

end)
Humanoid Properties
-- Health (default max is 100)

[Link] = 50 -- set health to 50

[Link] = 0 -- kill the player

[Link] = 200 -- increase max health

-- Movement

[Link] = 32 -- default is 16, double speed!

[Link] = 100 -- default is 50

-- Check if alive

print([Link]) -- prints current health

Taking Damage
-- TakeDamage is the proper way to deal damage

-- It respects ForceFields!

humanoid:TakeDamage(25) -- deal 25 damage

-- Direct health change ignores ForceFields

[Link] = [Link] - 25

Full Damage Brick Example


local damageBrick = [Link]

[Link]:Connect(function(hit)

local character = [Link]

local humanoid = character:FindFirstChild("Humanoid")

if humanoid then

humanoid:TakeDamage(10) -- deal 10 damage on touch

end
end)

■ Quiz Time!

1. What is the Humanoid?


Answer: The object inside a player character that controls health and movement

2. How do you get the Humanoid from a Touched event?


Answer: character:FindFirstChild('Humanoid') where character = [Link]

3. What does [Link] = 0 do?


Answer: Kills the player

4. What is the difference between TakeDamage and setting health directly?


Answer: TakeDamage respects ForceFields. Direct health setting ignores them.

5. What is the default WalkSpeed?


Answer: 16

■ Vocabulary
Humanoid — The object inside a player character — controls health, speed, jump
Health — The current health of the humanoid — 0 means dead
MaxHealth — The maximum health a humanoid can have — default 100
WalkSpeed — How fast the character moves — default 16
TakeDamage() — The proper method to deal damage — respects ForceFields
Character — The physical body of a player in the game world
Chapter 17

Leaderboards
Tracking player stats like coins and kills

A leaderboard shows player stats in the top-right corner of the screen — coins, kills, points,
whatever you want to track. Setting one up is easier than you think!

How Leaderboards Work


Roblox has a built-in system for leaderboards. You create a leaderstats folder inside each player,
then add IntValue or NumberValue objects inside it. Roblox automatically shows these on the
leaderboard!

Basic Leaderboard Setup


[Link]:Connect(function(player)

-- Create the leaderstats folder

local leaderstats = [Link]("Folder")

[Link] = "leaderstats" -- must be exactly this name!

[Link] = player

-- Add a Coins stat

local coins = [Link]("IntValue")

[Link] = "Coins"

[Link] = 0

[Link] = leaderstats

-- Add a Kills stat

local kills = [Link]("IntValue")

[Link] = "Kills"
[Link] = 0

[Link] = leaderstats

end)

■ leaderstats MUST be exactly that spelling!


The folder MUST be named leaderstats — all lowercase, no spaces.
Roblox looks for this exact name to display on the leaderboard.
If you spell it wrong (like LeaderStats), it won't show up!

Giving a Player Coins


-- Find the player's coins stat and add to it

local function giveCoins(player, amount)

local leaderstats = player:FindFirstChild("leaderstats")

if leaderstats then

local coins = leaderstats:FindFirstChild("Coins")

if coins then

[Link] = [Link] + amount

end

end

end

-- Use it like this:

giveCoins(player, 10) -- give player 10 coins


■ Quiz Time!

1. What must the leaderstats folder be named?


Answer: Exactly 'leaderstats' — all lowercase

2. What type of value do you use to store whole numbers like coins?
Answer: IntValue

3. Where does the leaderstats folder go?


Answer: Inside the player object

4. How do you add 5 to a player's coins?


Answer: [Link] = [Link] + 5

■ Vocabulary
leaderstats — A specially named folder that Roblox uses to show stats on the leaderboard
IntValue — An instance that stores a whole number — used for coins, kills, etc.
NumberValue — Like IntValue but can store decimals
StringValue — An instance that stores text
.Value — The actual number stored in an IntValue or NumberValue
Chapter 18

Comments
Writing notes in your code

Comments are notes you write in your code. Lua completely ignores them — they don't affect how
your game runs at all. They're just for YOU (and other developers) to understand what the code
does.

Single Line Comments


-- This is a comment. Lua ignores this line.

local coins = 50 -- you can also put comments on the same line as code

local health = 100 -- player starts with full health

Multi-Line Comments
--[[

This is a multi-line comment.

You can write as many lines as you want.

Great for explaining big sections of code.

]]

local coins = 50

Why Write Comments?


• Your future self will forget what code does — comments remind you
• If someone else reads your code, they can understand it
• You can 'comment out' broken code to temporarily disable it
• Good comments make you look like a professional developer
-- ===================================

-- COIN SYSTEM

-- Gives players coins over time

-- ===================================

local COINS_PER_SECOND = 5 -- change this to adjust coin rate

[Link]:Connect(function(player)

-- Set up leaderboard

local leaderstats = [Link]("Folder")

[Link] = "leaderstats"

[Link] = player

local coins = [Link]("IntValue")

[Link] = "Coins"

[Link] = 0

[Link] = leaderstats

-- Give coins every second

while true do

wait(1)

[Link] = [Link] + COINS_PER_SECOND

end

end)

■ Vocabulary
Comment — A note in code that Lua ignores — starts with --
Single-line comment — A comment that starts with -- and goes to the end of the line
Multi-line comment — A comment wrapped in --[[ and ]] — can span many lines
Comment out — Putting -- in front of code to disable it temporarily
Chapter 19

Advanced Tips & Tricks


Clean code habits and common mistakes

1. Use Constants for Magic Numbers


Instead of writing random numbers everywhere, give them names:

-- BAD: what does 16 mean?

[Link] = 16

-- GOOD: now it is obvious

local DEFAULT_WALK_SPEED = 16

local SPRINT_SPEED = 32

[Link] = DEFAULT_WALK_SPEED

■ UPPERCASE for Constants


By convention, constant values (things that never change) are written in UPPERCASE.
This tells other developers: this value should not be changed during the game!

2. Avoid Repeating Code


-- BAD: same code repeated

print("Player: Alex")

print("Level: 5")

print("Player: Suri")

print("Level: 3")

-- GOOD: use a function

local function showPlayer(name, level)


print("Player:", name)

print("Level:", level)

end

showPlayer("Alex", 5)

showPlayer("Suri", 3)

3. Check Before Using


-- BAD: crashes if Humanoid doesnt exist

local humanoid = [Link]

[Link] = 0

-- GOOD: check first

local humanoid = character:FindFirstChild("Humanoid")

if humanoid then

[Link] = 0

end

4. Common Errors and How to Fix Them


Error Message What it Means Fix

attempt to index nil value Variable is nil (empty) Check spelling, use FindFirstChild

Missing end keyword


Expected 'end' (to close...) Count your end statements

unexpected symbol near '=' Wrong use of = Check if you meant ==

Math on a string or nil


attempt to perform arithmetic Remove quotes from the number

'(' expected near ')' Syntax error in function Check brackets and commas

5. Debugging Checklist
• Check the Output window — the error message tells you the line number!
• Add print() statements to see what values your variables have
• Check spelling — Lua is case-sensitive
• Make sure every if, function, for, while has a matching end
• Check that all strings have opening AND closing quotes
• Check that you're using == not = for comparisons
Chapter 20

Full Game Project


Putting it all together!

Let's build a simple game using EVERYTHING we've learned. The game will have:

• A leaderboard tracking Coins and Kills


• Coin pickups that give coins when touched
• A kill brick that kills players
• A speed boost brick that increases walk speed
• A welcome message when players join

Step 1 — Set Up the Leaderboard (ServerScriptService)


-- Script 1: LeaderboardSetup

[Link]:Connect(function(player)

local leaderstats = [Link]("Folder")

[Link] = "leaderstats"

[Link] = player

local coins = [Link]("IntValue")

[Link] = "Coins"

[Link] = 0

[Link] = leaderstats

local kills = [Link]("IntValue")

[Link] = "Kills"

[Link] = 0

[Link] = leaderstats
print("Welcome to the game,", [Link] .. "!")

end)

Step 2 — Coin Pickup


-- Script 2: CoinPickup

-- Attach to a part named "CoinPart" in Workspace

local coinPart = [Link]

local COIN_VALUE = 10

[Link]:Connect(function(hit)

local character = [Link]

local player = [Link]:GetPlayerFromCharacter(character)

if player then

local coins = [Link]:FindFirstChild("Coins")

if coins then

[Link] = [Link] + COIN_VALUE

print([Link], "collected a coin! Total:", [Link])

end

end

end)

Step 3 — Kill Brick


-- Script 3: KillBrick

-- Attach to a part named "KillBrick" in Workspace

local killBrick = [Link]

[Link]:Connect(function(hit)

local character = [Link]


local humanoid = character:FindFirstChild("Humanoid")

if humanoid then

[Link] = 0

end

end)

Step 4 — Speed Boost Brick


-- Script 4: SpeedBoost

local speedBrick = [Link]

local BOOST_SPEED = 50

local NORMAL_SPEED = 16

[Link]:Connect(function(hit)

local character = [Link]

local humanoid = character:FindFirstChild("Humanoid")

if humanoid then

[Link] = BOOST_SPEED

wait(5) -- boost lasts 5 seconds

[Link] = NORMAL_SPEED

end

end)

■ How to Set Up the Game


1. Create parts in Workspace named: CoinPart, KillBrick, SpeedBrick
2. Color them differently so players know what each does
3. Create a separate Script in ServerScriptService for each section above
4. Hit Play and test everything!
5. Experiment — change COIN_VALUE, BOOST_SPEED, etc. to tweak the game!
Chapter

Quick Reference Sheet


Everything in one place

Variables & Data Types


local name = "Alex" -- String (text)

local health = 100 -- Number

local isAlive = true -- Boolean

local coins = 50

coins = coins + 10 -- Update variable

print()
print("Hello!") -- print text

print(100) -- print number

print("coins:", coins) -- print text + variable

print("a" .. "b") -- concatenation: prints ab

Functions & Parameters


local function greet(name)

print("Hello,", name)

return "done"

end

greet("Alex") -- call it

local result = greet("Alex") -- capture return value

If Statements
if health == 100 then

print("Full health")

elseif health > 50 then

print("OK")

else

print("Low health")

end

-- Operators: == ~= > < >= <=

-- Logical: and or not

Loops
for i = 1, 10 do -- for loop

print(i)

end

while health > 0 do -- while loop

health = health - 1

end

wait(1) -- pause 1 second

Instances & Properties


local part = [Link]

[Link] = [Link]("Bright red")

[Link] = [Link](10, 5, 10)

[Link] = [Link](0, 5, 0)

[Link] = true

[Link] = 0.5

local p = [Link]("Part", workspace)


Events
[Link]:Connect(function(hit)

local char = [Link]

local hum = char:FindFirstChild("Humanoid")

if hum then [Link] = 0 end

end)

[Link]:Connect(function(player)

print("Welcome", [Link])

end)

Leaderboard
[Link]:Connect(function(player)

local ls = [Link]("Folder")

[Link] = "leaderstats" -- exact spelling!

[Link] = player

local coins = [Link]("IntValue")

[Link] = "Coins"

[Link] = 0

[Link] = ls

end)

Humanoid
[Link] = 0 -- kill

humanoid:TakeDamage(25) -- deal damage (respects ForceField)

[Link] = 32 -- speed (default 16)

[Link] = 100 -- jump (default 50)

[Link] = 200 -- max health (default 100)


You now have everything you need to start making real Roblox games! Keep
practicing, keep experimenting, and most importantly — have fun! ■

You might also like