Roblox Luau Scripting
Script a Roblox experience in Luau: services, Instances, events, the
server/client split, and secure cross-boundary communication. Targets the current
Roblox engine and Studio.
When to use
- Use when writing Roblox scripts: getting services, creating/parenting instances,
connecting events, deciding server vs client, or wiring
RemoteEvent/
RemoteFunction communication.
- Use when the project has
Script/LocalScript/ModuleScript objects, .rbxl(x)
places, or a Rojo *.project.json, and code calls game:GetService(...).
When not to use: persisting data across sessions → roblox-datastores.
Remote protocol architecture, exploit hardening, rate limits, high-frequency replication, and
multi-client abuse testing → roblox-networking. Generic Lua questions unrelated to the Roblox
API. Engine-agnostic input/save architecture → input-systems / save-systems.
Core workflow
- Get services with
game:GetService("Name"). Common ones: Players,
Workspace, ReplicatedStorage (shared client+server), ServerScriptService
(server-only code), ServerStorage, RunService, UserInputService (client).
- Know where code runs. A
Script runs on the server; a LocalScript
runs on a client (in StarterPlayerScripts, StarterGui, or the player's
character). A Script whose RunContext is Client also runs on clients, from
ReplicatedStorage; check RunContext before deciding where a Script runs. A
ModuleScript is shared code you require.
- Create instances deliberately.
local p = Instance.new("Part"), set its
properties, then set p.Parent last (parenting triggers replication).
- React with events.
:Connect to signals like Players.PlayerAdded,
part.Touched, or RunService.Heartbeat. Disconnect when done to avoid leaks.
- Cross the client/server boundary with Remotes — and never trust the client.
Clients request via
RemoteEvent:FireServer(...); the server validates and
applies. The server is authoritative for all game state.
- Test in Studio with Test / Test Here / Server & Clients; use the
Output window and the Client/Server toggle to confirm where code ran.
- Run static checks before Studio when the project already has the tools. Put
std = "roblox" in the root selene.toml, then run selene ..
For a Rojo project, write the sourcemap once with
rojo sourcemap default.project.json --output sourcemap.json, then run
luau-lsp analyze --sourcemap=sourcemap.json src, passing the Roblox type definitions
with --definitions (luau-lsp analyze --help lists the flags). Studio Script Sync
projects may not have a sourcemap.
Patterns
1. Server Script: react to players joining (leaderstats)
-- ServerScriptService/Leaderboard.server.luau (a Script = runs on the server)
local Players = game:GetService("Players")
local function onPlayerAdded(player: Player)
local stats = Instance.new("Folder")
stats.Name = "leaderstats" -- this name makes it show on the leaderboard
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Value = 0
coins.Parent = stats
stats.Parent = player -- parent LAST
end
Players.PlayerAdded:Connect(onPlayerAdded)
2. Create and configure an instance
local Workspace = game:GetService("Workspace")
local part = Instance.new("Part")
part.Size = Vector3.new(4, 1, 4)
part.Position = Vector3.new(0, 10, 0)
part.Anchored = true -- won't fall under gravity
part.BrickColor = BrickColor.new("Bright blue")
part.Parent = Workspace -- set Parent last so it replicates once, fully
3. Connect an event (and disconnect to avoid leaks)
local debounce = false
local connection
connection = part.Touched:Connect(function(hit: BasePart)
local character = hit.Parent
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if not humanoid or debounce then return end
debounce = true
humanoid.Health -= 10
task.wait(1) -- task.wait, NOT the deprecated wait()
debounce = false
end)
-- Later, when the part is removed or the round ends:
-- connection:Disconnect()
4. Client → server with a RemoteEvent (validate on the server!)
-- ReplicatedStorage: create a RemoteEvent named "BuyItem" (in Studio or via code).
-- CLIENT (LocalScript): request a purchase. The client can lie — this is only a request.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local buyItem = ReplicatedStorage:WaitForChild("BuyItem") -- wait: may not have replicated yet
buyButton.MouseButton1Click:Connect(function()
buyItem:FireServer("sword") -- send the item id only; never the price/result
end)
-- SERVER (Script): the ONLY place the transaction is decided.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local buyItem = ReplicatedStorage:WaitForChild("BuyItem")
local PRICES = { sword = 100, shield = 75 }
buyItem.OnServerEvent:Connect(function(player: Player, itemId)
-- TRUST NOTHING from the client. Validate types and values.
if type(itemId) ~= "string" then return end
local price = PRICES[itemId]
if not price then return end -- unknown item
local coins = player.leaderstats.Coins
if coins.Value < price then return end -- can't afford
coins.Value -= price -- server applies the change
grantItem(player, itemId)
end)
5. A per-frame loop with RunService
local RunService = game:GetService("RunService")
-- Heartbeat fires every frame AFTER physics; dt is seconds since the last step.
RunService.Heartbeat:Connect(function(dt)
spinner.CFrame *= CFrame.Angles(0, math.rad(90) * dt, 0) -- 90deg/sec, frame-independent
end)
6. Shared code in a ModuleScript
-- ReplicatedStorage/GameConfig (a ModuleScript) — usable by server and client.
local GameConfig = {}
GameConfig.MaxHealth = 100
function GameConfig.damageFor(weapon: string): number
return ({ sword = 25, bow = 15 })[weapon] or 0
end
return GameConfig
local GameConfig = require(game:GetService("ReplicatedStorage"):WaitForChild("GameConfig"))
print(GameConfig.MaxHealth)
Pitfalls
- Trusting the client is an exploit → clients can send any arguments to a
RemoteEvent/RemoteFunction. Validate every argument's type and range on the
server and keep the server authoritative over health, currency, and inventory.
LocalScript doesn't run where you put it → LocalScripts run in
StarterPlayerScripts, StarterCharacterScripts, StarterGui, or tools — not in
Workspace or ServerScriptService. Server Scripts belong in
ServerScriptService/Workspace. A Script with RunContext = Client placed in a
Starter* container runs twice (original and copy); keep those in ReplicatedStorage.
- Deprecated globals → use
task.wait/task.spawn/task.delay, not the old
wait()/spawn()/delay() (worse scheduling and throttling).
- Parenting first, then setting properties → set properties first and
Parent
last so the instance replicates once in its final state.
nil on the client right after join → objects stream/replicate over time; use
parent:WaitForChild("Name") instead of indexing directly on the client.
- Connections never disconnected → long-lived
:Connect handlers leak and can
fire on destroyed objects; store the connection and :Disconnect() (or use
Instance:GetAttributeChangedSignal/:Once where appropriate).
- Using a RemoteFunction where a RemoteEvent fits →
RemoteFunction blocks
waiting for a return and a malicious/slow client can stall the server; prefer
one-way RemoteEvents unless you genuinely need a reply.
- Assuming the old type checker -> Luau's New Type Solver reached general release
(out of Studio Beta) in Nov 2025.
nocheck/non-strict places get it automatically;
strict-mode places opt in with the UseNewLuauTypeSolver workspace property, and
LuauTypeCheckMode sets a place's default checking mode. It runs only at edit time
(no runtime cost), so triage type warnings against the solver the place actually has
enabled, not older behavior.
References
- For the full client/server model (replication,
RemoteFunction vs RemoteEvent,
:WaitForChild timing, BindableEvent for same-context messaging, attributes,
CollectionService tags, and :Once/connection cleanup), read
references/client-server.md.
Related skills
roblox-datastores — persist player data across sessions (server-only).
roblox-networking — production remote contracts, server validation, rate limits, replication,
streaming, prediction, and multi-client testing.
save-systems — engine-agnostic persistence concepts.
game-ai / input-systems — portable AI and input patterns to implement in Luau.
1---2name: roblox-luau3description: >4 Script a Roblox experience in Luau: get services, create and parent Instances,5 connect events, run server Scripts vs client LocalScripts, and communicate across6 the client/server boundary with RemoteEvents/RemoteFunctions (server-authoritative).7 Use when building or debugging Roblox Studio scripts — when the user mentions8 Roblox, Luau, services, RemoteEvent, Instance.new, PlayerAdded, or client vs9 server. For saving player data use roblox-datastores.10metadata:11 source: https://skillmd.com/skills/junmystery/roblox-luau12---1314# Roblox Luau Scripting1516Script a Roblox experience in **Luau**: services, `Instance`s, events, the17server/client split, and secure cross-boundary communication. Targets the current18Roblox engine and Studio.1920## When to use2122- Use when writing Roblox scripts: getting services, creating/parenting instances,23 connecting events, deciding server vs client, or wiring `RemoteEvent`/24 `RemoteFunction` communication.25- Use when the project has `Script`/`LocalScript`/`ModuleScript` objects, `.rbxl(x)`26 places, or a Rojo `*.project.json`, and code calls `game:GetService(...)`.2728**When *not* to use:** persisting data across sessions → `roblox-datastores`.29Remote protocol architecture, exploit hardening, rate limits, high-frequency replication, and30multi-client abuse testing → `roblox-networking`. Generic Lua questions unrelated to the Roblox31API. Engine-agnostic input/save architecture → `input-systems` / `save-systems`.3233## Core workflow34351. **Get services with `game:GetService("Name")`.** Common ones: `Players`,36 `Workspace`, `ReplicatedStorage` (shared client+server), `ServerScriptService`37 (server-only code), `ServerStorage`, `RunService`, `UserInputService` (client).382. **Know where code runs.** A `Script` runs on the **server**; a `LocalScript`39 runs on a **client** (in `StarterPlayerScripts`, `StarterGui`, or the player's40 character). A `Script` whose `RunContext` is `Client` also runs on clients, from41 `ReplicatedStorage`; check `RunContext` before deciding where a `Script` runs. A42 `ModuleScript` is shared code you `require`.433. **Create instances deliberately.** `local p = Instance.new("Part")`, set its44 properties, then set `p.Parent` **last** (parenting triggers replication).454. **React with events.** `:Connect` to signals like `Players.PlayerAdded`,46 `part.Touched`, or `RunService.Heartbeat`. Disconnect when done to avoid leaks.475. **Cross the client/server boundary with Remotes — and never trust the client.**48 Clients request via `RemoteEvent:FireServer(...)`; the server validates and49 applies. The server is authoritative for all game state.506. **Test in Studio** with **Test** / **Test Here** / **Server & Clients**; use the51 Output window and the Client/Server toggle to confirm where code ran.527. **Run static checks before Studio when the project already has the tools.** Put53 `std = "roblox"` in the root `selene.toml`, then run `selene .`.54 For a Rojo project, write the sourcemap once with55 `rojo sourcemap default.project.json --output sourcemap.json`, then run56 `luau-lsp analyze --sourcemap=sourcemap.json src`, passing the Roblox type definitions57 with `--definitions` (`luau-lsp analyze --help` lists the flags). Studio Script Sync58 projects may not have a sourcemap.5960## Patterns6162### 1. Server Script: react to players joining (leaderstats)6364```lua65-- ServerScriptService/Leaderboard.server.luau (a Script = runs on the server)66local Players = game:GetService("Players")6768local function onPlayerAdded(player: Player)69 local stats = Instance.new("Folder")70 stats.Name = "leaderstats" -- this name makes it show on the leaderboard7172 local coins = Instance.new("IntValue")73 coins.Name = "Coins"74 coins.Value = 075 coins.Parent = stats7677 stats.Parent = player -- parent LAST78end7980Players.PlayerAdded:Connect(onPlayerAdded)81```8283### 2. Create and configure an instance8485```lua86local Workspace = game:GetService("Workspace")8788local part = Instance.new("Part")89part.Size = Vector3.new(4, 1, 4)90part.Position = Vector3.new(0, 10, 0)91part.Anchored = true -- won't fall under gravity92part.BrickColor = BrickColor.new("Bright blue")93part.Parent = Workspace -- set Parent last so it replicates once, fully94```9596### 3. Connect an event (and disconnect to avoid leaks)9798```lua99local debounce = false100local connection101connection = part.Touched:Connect(function(hit: BasePart)102 local character = hit.Parent103 local humanoid = character and character:FindFirstChildOfClass("Humanoid")104 if not humanoid or debounce then return end105 debounce = true106 humanoid.Health -= 10107 task.wait(1) -- task.wait, NOT the deprecated wait()108 debounce = false109end)110111-- Later, when the part is removed or the round ends:112-- connection:Disconnect()113```114115### 4. Client → server with a RemoteEvent (validate on the server!)116117```lua118-- ReplicatedStorage: create a RemoteEvent named "BuyItem" (in Studio or via code).119-- CLIENT (LocalScript): request a purchase. The client can lie — this is only a request.120local ReplicatedStorage = game:GetService("ReplicatedStorage")121local buyItem = ReplicatedStorage:WaitForChild("BuyItem") -- wait: may not have replicated yet122buyButton.MouseButton1Click:Connect(function()123 buyItem:FireServer("sword") -- send the item id only; never the price/result124end)125```126127```lua128-- SERVER (Script): the ONLY place the transaction is decided.129local ReplicatedStorage = game:GetService("ReplicatedStorage")130local buyItem = ReplicatedStorage:WaitForChild("BuyItem")131local PRICES = { sword = 100, shield = 75 }132133buyItem.OnServerEvent:Connect(function(player: Player, itemId)134 -- TRUST NOTHING from the client. Validate types and values.135 if type(itemId) ~= "string" then return end136 local price = PRICES[itemId]137 if not price then return end -- unknown item138 local coins = player.leaderstats.Coins139 if coins.Value < price then return end -- can't afford140 coins.Value -= price -- server applies the change141 grantItem(player, itemId)142end)143```144145### 5. A per-frame loop with RunService146147```lua148local RunService = game:GetService("RunService")149-- Heartbeat fires every frame AFTER physics; dt is seconds since the last step.150RunService.Heartbeat:Connect(function(dt)151 spinner.CFrame *= CFrame.Angles(0, math.rad(90) * dt, 0) -- 90deg/sec, frame-independent152end)153```154155### 6. Shared code in a ModuleScript156157```lua158-- ReplicatedStorage/GameConfig (a ModuleScript) — usable by server and client.159local GameConfig = {}160GameConfig.MaxHealth = 100161function GameConfig.damageFor(weapon: string): number162 return ({ sword = 25, bow = 15 })[weapon] or 0163end164return GameConfig165```166167```lua168local GameConfig = require(game:GetService("ReplicatedStorage"):WaitForChild("GameConfig"))169print(GameConfig.MaxHealth)170```171172## Pitfalls173174- **Trusting the client is an exploit** → clients can send any arguments to a175 `RemoteEvent`/`RemoteFunction`. Validate every argument's type and range on the176 server and keep the server authoritative over health, currency, and inventory.177- **`LocalScript` doesn't run where you put it** → LocalScripts run in178 `StarterPlayerScripts`, `StarterCharacterScripts`, `StarterGui`, or tools — not in179 `Workspace` or `ServerScriptService`. Server `Script`s belong in180 `ServerScriptService`/`Workspace`. A `Script` with `RunContext = Client` placed in a181 `Starter*` container runs twice (original and copy); keep those in `ReplicatedStorage`.182- **Deprecated globals** → use `task.wait`/`task.spawn`/`task.delay`, not the old183 `wait()`/`spawn()`/`delay()` (worse scheduling and throttling).184- **Parenting first, then setting properties** → set properties first and `Parent`185 last so the instance replicates once in its final state.186- **`nil` on the client right after join** → objects stream/replicate over time; use187 `parent:WaitForChild("Name")` instead of indexing directly on the client.188- **Connections never disconnected** → long-lived `:Connect` handlers leak and can189 fire on destroyed objects; store the connection and `:Disconnect()` (or use190 `Instance:GetAttributeChangedSignal`/`:Once` where appropriate).191- **Using a RemoteFunction where a RemoteEvent fits** → `RemoteFunction` blocks192 waiting for a return and a malicious/slow client can stall the server; prefer193 one-way `RemoteEvent`s unless you genuinely need a reply.194- **Assuming the old type checker** -> Luau's New Type Solver reached general release195 (out of Studio Beta) in Nov 2025. `nocheck`/non-strict places get it automatically;196 strict-mode places opt in with the `UseNewLuauTypeSolver` workspace property, and197 `LuauTypeCheckMode` sets a place's default checking mode. It runs only at edit time198 (no runtime cost), so triage type warnings against the solver the place actually has199 enabled, not older behavior.200201## References202203- For the full client/server model (replication, `RemoteFunction` vs `RemoteEvent`,204 `:WaitForChild` timing, `BindableEvent` for same-context messaging, attributes,205 `CollectionService` tags, and `:Once`/connection cleanup), read206 `references/client-server.md`.207208## Related skills209210- `roblox-datastores` — persist player data across sessions (server-only).211- `roblox-networking` — production remote contracts, server validation, rate limits, replication,212 streaming, prediction, and multi-client testing.213- `save-systems` — engine-agnostic persistence concepts.214- `game-ai` / `input-systems` — portable AI and input patterns to implement in Luau.