Start building

Roblox scripting for beginners: learn Luau step by step

Learn the handful of Luau ideas every Roblox script is built from, then put them together in a coin pickup that really works.

A rainbow pet fusion machine in Roblox Studio above the Fusion script Revix wrote, with the message Added Fusion.rainbow.
On this page
  1. Script, LocalScript or ModuleScript: where your code runs
  2. Your first script
  3. Luau basics: variables, if statements and loops
  4. Functions, tables and ModuleScripts
  5. Events, Connect and services
  6. Mini project: a coin that gives points
  7. Debugging with the Output window
  8. Common beginner errors and how to fix them
  9. 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.

TypeRuns onWhere to put itUse it for
ScriptThe serverServerScriptService, or inside a part in WorkspaceGame rules, money, damage, saving, spawning
LocalScriptOne player's deviceStarterPlayerScripts, StarterCharacterScripts, StarterGui, or inside a ToolUI, camera, input, effects only that player sees
ModuleScriptWherever it's requiredReplicatedStorage (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:

ScriptServerScriptService
-- 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:

LocalScriptStarterPlayerScripts
-- 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:

ScriptServerScriptService
-- 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

ScriptServerScriptService
-- 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")
end

Luau 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

ScriptServerScriptService
-- 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)
end

A 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.

ScriptServerScriptService
-- 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) -- 15

Write 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.

ScriptServerScriptService
-- 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.

ScriptServerScriptService
-- 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)
end

Use 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:

ModuleScriptReplicatedStorage
-- ModuleScript named GameSettings in ReplicatedStorage
local GameSettings = {}

GameSettings.CoinValue = 1
GameSettings.RespawnTime = 5

return GameSettings
ScriptServerScriptService
-- 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:

ServiceWhat it's for
PlayersWho is in the game, joining and leaving
ReplicatedStorageThings the server and every client can see, like RemoteEvents
ServerStorageServer-only storage that players can't see
TweenServiceSmooth movement, fades and color changes
UserInputServiceKeyboard, 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.

ScriptServerScriptService
-- 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)
end

PlayerAdded 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

ScriptServerScriptService
-- 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)
end

A 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:

ScriptCoin
-- 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:

  • Touched passes in the part that touched the coin, usually a foot or a hand. GetPlayerFromCharacter turns its parent, the character, into a player (or nil if it isn't one).
  • collected is the debounce. Touched fires for every body part that brushes the coin, so the first touch sets the flag and the rest return early until the respawn.
  • The FindFirstChild checks 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 print calls.

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 seeWhat it meansHow to fix it
attempt to index nil with 'Touched'You used a dot on a value that is nilCheck 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 thereFix the name, or put the object where that side can see it
Your coin falls through the floor or rolls away on PlayIt isn't anchored, which looks like a script bug but isn'tTick Anchored on everything that should stay still
Expected ':' not '.' calling member function GetServiceYou called a method with a dotUse 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.

Your game is
one sentence away.

Start building free

Free to start. No card needed.