On this page
- Script, LocalScript or ModuleScript: where your code runs
- Your first script
- Luau basics: variables, if statements and loops
- Functions, tables and ModuleScripts
- Events, Connect and services
- Mini project: a coin that gives points
- Debugging with the Output window
- Common beginner errors and how to fix them
- Questions
Roblox scripting means writing code in Luau, Roblox's version of the Lua language, to make your game react to players. You add a script in Roblox Studio, and it runs when the game starts or when something happens, like a player touching a part. This tutorial teaches the basics in order, with short examples you can paste in and run.
Script, LocalScript or ModuleScript: where your code runs
Every Roblox game runs in two places: the server, Roblox's computer that runs the one true copy of the game, and each player's device, called a client. Where your code runs decides what it can do.
| Type | Runs on | Where to put it | Use it for |
|---|---|---|---|
| Script | The server | ServerScriptService, or inside a part in Workspace | Game rules, money, damage, saving, spawning |
| LocalScript | One player's device | StarterPlayerScripts, StarterCharacterScripts, StarterGui, or inside a Tool | UI, camera, input, effects only that player sees |
| ModuleScript | Wherever it's required | ReplicatedStorage (shared) or ServerScriptService (server only) | Code and settings you reuse in many scripts |
Location matters: a LocalScript in ServerScriptService never runs, and by default neither does a Script in StarterPlayerScripts. If code seems ignored, check where it is.
The rule that keeps your game safe: the server decides, the client asks. Players can change anything on their own device, so a LocalScript must never be what adds coins or deals damage. It asks the server through a RemoteEvent, and the server checks the request first.
Your first script
In Explorer, hover over ServerScriptService, click the + button and choose Script. Replace the starter line with this:
-- Script in ServerScriptService: your first script
print("Hello from the server!")Press Play (F5) and your message appears in the Output window. If it's hidden, open it from Studio's list of windows (the View tab in the classic layout). Now add a LocalScript to StarterPlayer > StarterPlayerScripts:
-- LocalScript in StarterPlayerScripts: runs on each player's device
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print("Hello from " .. player.Name .. "'s device")Play again and both messages appear. Players.LocalPlayer is the player whose device runs the code, so it only exists on the client. In a server Script it's nil.
Luau basics: variables, if statements and loops
Variables and types
A variable is a name that holds a value. Create one with local:
-- Script in ServerScriptService: variables and types
local coins = 10 -- a number
local playerName = "Ava" -- a string (text)
local isAlive = true -- a boolean: true or false
local target = nil -- nil: no value at all
coins = coins + 5
coins += 5 -- the same thing, shorter
print(playerName .. " has " .. coins .. " coins") -- Ava has 20 coins
print(typeof(coins), typeof(isAlive), typeof(target)) -- number boolean nil
local walkSpeed: number = 16 -- an optional type annotation
print(walkSpeed)Anything after -- is a comment, .. joins text, and typeof tells you a value's type. The optional : number tells Luau's type checker what the variable should hold, so the editor can flag mistakes. Names are case sensitive: coins and Coins are different variables.
If statements
-- Script in ServerScriptService: making decisions
local health = 35
if health <= 0 then
print("Knocked out")
elseif health < 50 then
print("Low health")
else
print("Healthy")
endLuau runs the first block whose condition is true, so this prints "Low health". Compare with ==, ~= (not equal), <, >, <= and >=, and combine conditions with and, or and not. Only false and nil count as false, so 0 and empty text count as true.
Loops
-- Script in ServerScriptService: two kinds of loop
for seconds = 5, 1, -1 do
print(seconds)
task.wait(1)
end
print("Go!")
while true do
print("Still running")
task.wait(10)
endA numeric for loop counts from the first number to the second, in steps of the optional third, so 5, 1, -1 counts down. task.wait(1) pauses the script, not the game, for one second. A while true do loop repeats forever, and break leaves any loop early.
Functions, tables and ModuleScripts
Functions
A function is a named block of code you can run whenever you need it. Values go in as parameters and come back out with return.
-- Script in ServerScriptService: a function with parameters and a return value
local function addCoins(current: number, amount: number): number
return current + amount
end
local total = addCoins(10, 5)
print(total) -- 15Write a function whenever you catch yourself copying the same lines, and declare it with local function above the code that calls it.
Arrays
A table holds many values in one variable. A table used as a list is called an array, and its first item is at index 1, not 0.
-- Script in ServerScriptService: arrays
local fruits = {"Apple", "Banana", "Cherry"}
table.insert(fruits, "Mango") -- add to the end
print(fruits[1]) -- Apple
print(#fruits) -- 4
for index, fruit in ipairs(fruits) do
print(index, fruit)
end#fruits is the length, and ipairs walks the array in order.
Dictionaries
A dictionary stores values under names, called keys.
-- Script in ServerScriptService: dictionaries
local prices = {
Sword = 100,
Shield = 75,
}
prices.Bow = 120 -- add a new key
prices["Shield"] = 80 -- change a value
print(prices.Sword) -- 100
for item, price in pairs(prices) do
print(item .. " costs " .. price)
endUse a dot (prices.Sword) or brackets (prices["Shield"]) for keys, and pairs to loop, in no fixed order. A missing key such as prices.Axe gives nil, which leads to the most common beginner error, covered at the end.
ModuleScripts
A ModuleScript doesn't run by itself. It returns a value, usually a table of settings or functions, and other scripts load it with require:
-- ModuleScript named GameSettings in ReplicatedStorage
local GameSettings = {}
GameSettings.CoinValue = 1
GameSettings.RespawnTime = 5
return GameSettings-- Script in ServerScriptService: load the shared settings
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local GameSettings = require(ReplicatedStorage:WaitForChild("GameSettings"))
print("A coin is worth", GameSettings.CoinValue)Because the module is in ReplicatedStorage, LocalScripts can require it too, so the server and your UI share the same numbers.
Events, Connect and services
Services
Roblox groups its features into services. Get each one with game:GetService at the top of your script:
| Service | What it's for |
|---|---|
| Players | Who is in the game, joining and leaving |
| ReplicatedStorage | Things the server and every client can see, like RemoteEvents |
| ServerStorage | Server-only storage that players can't see |
| TweenService | Smooth movement, fades and color changes |
| UserInputService | Keyboard, mouse and touch input (LocalScripts) |
Use a colon before GetService, not a dot: a colon calls a method on an object.
Events
An event is something that happens: a player joins, a part is touched, a value changes. You :Connect a function to it, and Roblox runs that function every time the event fires.
-- Script in ServerScriptService: run code for every player who joins
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.Name .. " joined the game")
end
Players.PlayerAdded:Connect(onPlayerAdded)
-- Also run it for anyone who joined before this script connected
for _, player in ipairs(Players:GetPlayers()) do
onPlayerAdded(player)
endPlayerAdded passes the new player to your function, and the loop covers anyone who joined before the script connected, which can happen in Studio playtests. Parts have events too: Touched fires when another part touches yours, as the next project shows.
Mini project: a coin that gives points
Now combine it all: a coin that gives a point when touched, then disappears and comes back.
Step 1: give each player a Coins stat
-- Script in ServerScriptService: a leaderstats folder with Coins for each player
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Value = 0
coins.Parent = leaderstats
end
Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in ipairs(Players:GetPlayers()) do
onPlayerAdded(player)
endA folder named exactly leaderstats inside a player is a Roblox convention: its values show on the player list in the top right corner. The leaderboard guide builds on this with more stats and a global top 10.
Step 2: make the coin
Insert a small gold part named Coin, tick Anchored, untick CanCollide so players pass through it, and add a Script inside it:
-- Script inside the Coin part in Workspace: give 1 coin, hide, then respawn
local Players = game:GetService("Players")
local coin = script.Parent
local COIN_VALUE = 1
local RESPAWN_TIME = 5
local collected = false -- the debounce
coin.Touched:Connect(function(otherPart)
if collected then
return
end
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if not player then
return
end
local leaderstats = player:FindFirstChild("leaderstats")
local coins = leaderstats and leaderstats:FindFirstChild("Coins")
if not coins then
return
end
collected = true
coins.Value += COIN_VALUE
coin.Transparency = 1
coin.CanTouch = false
task.wait(RESPAWN_TIME)
coin.Transparency = 0
coin.CanTouch = true
collected = false
end)How it works:
Touchedpasses in the part that touched the coin, usually a foot or a hand.GetPlayerFromCharacterturns its parent, the character, into a player (ornilif it isn't one).collectedis the debounce.Touchedfires for every body part that brushes the coin, so the first touch sets the flag and the rest return early until the respawn.- The
FindFirstChildchecks skip anything without a Coins value instead of erroring. - The coins are added on the server, so the total is real and everyone sees it.
Press Play and walk into the coin to watch your Coins go up. For dozens of coins, use one script that finds them by a CollectionService tag. You can also ask Revix to build systems like this in your place: it writes the scripts, playtests them and fixes what the Output reports, and you can read every line to learn from it.
Debugging with the Output window
When something doesn't work, look at the Output first:
- Errors are red and show the script, the line and the problem, like
Workspace.Coin.Script:20: attempt to index nil with 'Value'. Click one to jump to that line. - Warnings are orange. The script keeps going, but something is probably wrong.
- Messages come from your own
printcalls.
No error, but the wrong result? Use print debugging: add a print at each step your code should reach and see which ones show up. In the coin script, put print("touched by", otherPart:GetFullName()) first inside the function and print("player:", player) after the player check. If only the first prints, the toucher isn't a character. If both print but Coins don't change, check the leaderstats script.
Common beginner errors and how to fix them
| What you see | What it means | How to fix it |
|---|---|---|
attempt to index nil with 'Touched' | You used a dot on a value that is nil | Check the name and path in Explorer, and check for nil first |
Infinite yield possible on 'ReplicatedStorage:WaitForChild("CoinEvent")' | WaitForChild has waited 5 seconds for something that isn't there | Fix the name, or put the object where that side can see it |
| Your coin falls through the floor or rolls away on Play | It isn't anchored, which looks like a script bug but isn't | Tick Anchored on everything that should stay still |
Expected ':' not '.' calling member function GetService | You called a method with a dot | Use a colon: game:GetService("Players") |
Attempt to index nil is the error you'll see most. Indexing means using a dot or brackets on a value, like part.Touched. If part is nil (a wrong name, an object that hasn't loaded yet, or Players.LocalPlayer in a server Script), there's nothing to index. Find the value before the dot and work out why it's nil.
Infinite yield possible is a warning, but the script is stuck on that line. Besides typos, the usual cause is a side that can't see the object: clients can't see ServerStorage or ServerScriptService, and the server never sees what a LocalScript creates.
Next, practice with small systems like a door that opens with a ProximityPrompt or a round timer, then turn them into a full game with how to make a Roblox game.
Questions
Is Roblox scripting Lua or Luau?
Luau. It grew out of Lua 5.1, and Roblox added type checking, better performance and extras like compound assignment (+=). Most Lua tutorials still apply, but Luau is what runs in Roblox.
How long does it take to learn Roblox scripting?
With short daily practice, most beginners can write simple scripts like kill bricks and coin pickups within a week or two. Full systems such as shops, saving and combat take a few months. Small projects teach faster than reading alone.
Should I use a Script or a LocalScript?
Use a Script for anything that must be fair and shared: money, damage, saving and spawning. Use a LocalScript for things only one player sees or controls, such as UI, the camera and input. When the two need to talk, use a RemoteEvent and check the request on the server.
Why is my Roblox script not running?
Check where it is first. By default, Scripts run only in Workspace and ServerScriptService, and LocalScripts only in places tied to a player, like StarterPlayerScripts, StarterGui or the character. Then make sure it is enabled and read the Output window for errors.
Do I need to know another programming language first?
No. Luau is a good first language: the syntax is small and you see the result in your game right away. Basic math helps for positions and movement, but you can pick that up as you go.









