🚀 Ultimate Roblox Lua Cheatsheet

Complete reference for Roblox scripting mastery

🎯 Lua Essentials

Variables & Types

local str = "Hello"
local num = 42
local bool = true
local arr = {1, 2, 3}
local dict = {x = 10, y = 20}

Functions

local function add(a, b)
    return a + b
end

-- Variable args
local function sum(...)
    local total = 0
    for i, v in pairs({...}) do
        total = total + v
    end
    return total
end

Control Flow & Loops

-- Conditionals
if condition then
    -- code
elseif other then
    -- code
else
    -- fallback
end

-- Ternary-like
local result = condition and "yes" or "no"

-- Loops
for i = 1, 10 do print(i) end
for k, v in pairs(table) do print(k, v) end
for i, v in ipairs(array) do print(i, v) end
while condition do -- code end

🛠️ Core Services

-- Essential services
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Lighting = game:GetService("Lighting")
local SoundService = game:GetService("SoundService")
local Debris = game:GetService("Debris")
local HttpService = game:GetService("HttpService")
local DataStoreService = game:GetService("DataStoreService")
local PathfindingService = game:GetService("PathfindingService")
local CollectionService = game:GetService("CollectionService")
local ContextActionService = game:GetService("ContextActionService")
local MarketplaceService = game:GetService("MarketplaceService")
local StarterGui = game:GetService("StarterGui")

👥 Players & Characters

Player Basics

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local rootPart = character:WaitForChild("HumanoidRootPart")

Player Events

Players.PlayerAdded:Connect(function(plr)
    print(plr.Name .. " joined")
end)

player.CharacterAdded:Connect(function(char)
    local hum = char:WaitForChild("Humanoid")
    hum.Died:Connect(function()
        print("Player died")
    end)
end)

Humanoid Properties

humanoid.WalkSpeed = 50         -- Speed (default 16)
humanoid.JumpPower = 100        -- Jump height (default 50)
humanoid.MaxHealth = 200        -- Max health
humanoid.Health = 100           -- Current health
humanoid.PlatformStand = true    -- Disable movement
humanoid.Sit = true              -- Make player sit
humanoid:LoadAnimation(anim)      -- Play animation

🧱 Parts & Objects

Creating Parts

local part = Instance.new("Part")
part.Size = Vector3.new(4, 1, 2)
part.Position = Vector3.new(0, 10, 0)
part.BrickColor = BrickColor.new("Bright red")
part.Material = Enum.Material.Neon
part.Anchored = true
part.Parent = workspace

Finding Objects

-- Find methods
local part = workspace:FindFirstChild("PartName")
local part2 = workspace:WaitForChild("PartName")
local model = workspace:FindFirstChildOfClass("Model")

-- Get collections
local children = workspace:GetChildren()
local descendants = workspace:GetDescendants()

Part Properties

part.Transparency = 0.5           -- 0 = opaque, 1 = invisible
part.CanCollide = false            -- Collision detection
part.Shape = Enum.PartType.Ball     -- Ball, Block, Cylinder
part.TopSurface = Enum.SurfaceType.Smooth
part.Name = "MyPart"              -- Object name
part:Destroy()                   -- Delete object

⚡ Events & Input

Touch Events

part.Touched:Connect(function(hit)
    local hum = hit.Parent:FindFirstChild("Humanoid")
    if hum then
        print("Player touched!")
    end
end)

part.TouchEnded:Connect(function(hit)
    print("Touch ended")
end)

User Input

UserInputService.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.E then
        print("E pressed")
    end
end)

-- Mouse events
local mouse = player:GetMouse()
mouse.Button1Down:Connect(function()
    print("Left click")
end)

RunService Events

-- Game loop events
RunService.Stepped:Connect(function(time, dt)
    -- Runs after physics (server & client)
end)

📡 Remote Events & Functions

Remote Events

-- Create in ReplicatedStorage
local remoteEvent = Instance.new("RemoteEvent")
remoteEvent.Name = "PlayerAction"
remoteEvent.Parent = ReplicatedStorage

-- Client → Server
remoteEvent:FireServer("jump", 10)

-- Server → Client
remoteEvent:FireClient(player, "data")
remoteEvent:FireAllClients("explosion")

Remote Functions

-- Create RemoteFunction
local remoteFunc = Instance.new("RemoteFunction")
remoteFunc.Name = "GetData"
remoteFunc.Parent = ReplicatedStorage

-- Server function
remoteFunc.OnServerInvoke = function(plr, type)
    return playerData[plr][type]
end

-- Client invoke
local coins = remoteFunc:InvokeServer("coins")
⚠️ Security: Always validate data on the server! Never trust client input.

🔢 Math & Vectors

Vector3 Operations

local v1 = Vector3.new(1, 2, 3)
local v2 = Vector3.new(4, 5, 6)

local sum = v1 + v2
local scaled = v1 * 2
local mag = v1.Magnitude
local unit = v1.Unit
local dot = v1:Dot(v2)
local cross = v1:Cross(v2)

CFrame Magic

local cf = CFrame.new(0, 10, 0)
local lookAt = CFrame.lookAt(pos, target)

-- Rotation
local rotated = cf * CFrame.Angles(0, math.rad(90), 0)

-- Direction vectors
local forward = cf.LookVector
local right = cf.RightVector
local up = cf.UpVector

Useful Math Functions

-- Random & interpolation
local rand = math.random(1, 100)
local function lerp(a, b, t) return a + (b - a) * t end
local function clamp(val, min, max) return math.max(min, math.min(max, val)) end
local function distance(p1, p2) return (p1 - p2).Magnitude end

-- Raycasting
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {character}
local result = workspace:Raycast(origin, direction, params)

🎬 Tweening & Animation

-- Basic tween
local tweenInfo = TweenInfo.new(2, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
local tween = TweenService:Create(part, tweenInfo, {Position = Vector3.new(0, 20, 0)})
tween:Play()

-- Tween events
tween.Completed:Connect(function() print("Done!") end)

-- Common easing styles: Quad, Cubic, Quart, Quint, Sine, Back, Bounce, Elastic
-- Directions: In, Out, InOut

🖥️ GUI Creation

Basic GUI Elements

-- ScreenGui
local gui = Instance.new("ScreenGui")
gui.Parent = player.PlayerGui

-- Frame
local frame = Instance.new("Frame")
frame.Size = UDim2.new(0.5, 0, 0.5, 0)
frame.Position = UDim2.new(0.25, 0, 0.25, 0)
frame.BackgroundColor3 = Color3.fromRGB(100, 100, 100)
frame.Parent = gui

Text & Buttons

-- TextLabel
local label = Instance.new("TextLabel")
label.Text = "Hello World"
label.TextScaled = true
label.Parent = frame

-- TextButton
local button = Instance.new("TextButton")
button.Text = "Click Me"
button.MouseButton1Click:Connect(function()
    print("Clicked!")
end)

GUI Properties & Effects

-- UDim2 positioning: UDim2.new(scaleX, offsetX, scaleY, offsetY)
frame.AnchorPoint = Vector2.new(0.5, 0.5)  -- Center anchor
frame.BorderSizePixel = 0                -- Remove border
frame.BackgroundTransparency = 0.5      -- Semi-transparent

-- Corner rounding
local corner = Instance.new("UICorner")
corner.CornerRadius = UDim.new(0, 10)
corner.Parent = frame

-- Gradient
local gradient = Instance.new("UIGradient")
gradient.Color = ColorSequence.new(Color3.fromRGB(255, 0, 0), Color3.fromRGB(0, 0, 255))
gradient.Parent = frame

💾 DataStores

local dataStore = DataStoreService:GetDataStore("PlayerData")

-- Save data
local function saveData(player, data)
    local success, err = pcall(function()
        dataStore:SetAsync(player.UserId, data)
    end)
    if not success then warn("Save failed:", err) end
end

-- Load data
local function loadData(player)
    local success, data = pcall(function()
        return dataStore:GetAsync(player.UserId)
    end)
    return success and data or {coins = 0, level = 1}
end

-- Ordered DataStore (leaderboards)
local leaderboard = DataStoreService:GetOrderedDataStore("Leaderboard")
leaderboard:SetAsync(player.UserId, score)
local pages = leaderboard:GetSortedAsync(false, 10)

⚛️ Physics & Forces

BodyVelocity & Forces

-- BodyVelocity (deprecated, use AssemblyLinearVelocity)
part.AssemblyLinearVelocity = Vector3.new(0, 50, 0)
part.AssemblyAngularVelocity = Vector3.new(0, 10, 0)

-- VectorForce
local force = Instance.new("VectorForce")
force.Force = Vector3.new(0, 1000, 0)
force.Parent = part

Joints & Constraints

-- WeldConstraint
local weld = Instance.new("WeldConstraint")
weld.Part0 = part1
weld.Part1 = part2
weld.Parent = part1

-- HingeConstraint
local hinge = Instance.new("HingeConstraint")
hinge.ActuatorType = Enum.ActuatorType.Motor
hinge.MotorMaxTorque = 1000

🔊 Audio & Sounds

-- Create sound
local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://123456789"
sound.Volume = 0.5
sound.Pitch = 1
sound.Looped = false
sound.Parent = workspace

-- Play/stop sounds
sound:Play()
sound:Stop()
sound:Pause()
sound:Resume()

-- Sound events
sound.Ended:Connect(function() print("Sound finished") end)

-- Sound effects
local reverb = Instance.new("ReverbSoundEffect")
reverb.Parent = sound

🚀 Advanced Techniques

Module Scripts

-- MyModule.lua
local MyModule = {}

function MyModule.sayHello(name)
    return "Hello, " .. name
end

local function private()
    return "Hidden"
end

return MyModule

-- Usage
local mod = require(script.MyModule)

Object-Oriented Programming

local Player = {}
Player.__index = Player

function Player.new(name, health)
    local self = setmetatable({}, Player)
    self.name = name
    self.health = health or 100
    return self
end

function Player:takeDamage(amt)
    self.health = math.max(0, self.health - amt)
end

Coroutines & Async

-- Spawn new thread
spawn(function()
    while true do
        print("Background task")
        wait(5)
    end
end)

-- Coroutines
local co = coroutine.create(function()
    for i = 1, 5 do
        print("Step:", i)
        coroutine.yield()
    end
end)
coroutine.resume(co)

HttpService & JSON

-- Enable HTTP requests in game settings!
local data = {player = "John", score = 100}
local json = HttpService:JSONEncode(data)
local decoded = HttpService:JSONDecode(json)

-- HTTP Request
local response = HttpService:GetAsync("https://api.example.com/data")
HttpService:PostAsync("https://api.example.com/save", json, Enum.HttpContentType.ApplicationJson)

🔍 Debugging & Testing

Debug Functions

-- Print variants
print("Normal message")
warn("Warning message")
error("Error message")

-- Assertions
assert(condition, "Error if false")

-- Type checking
print(type(variable))
print(typeof(instance))

Error Handling

-- Protected calls
local success, result = pcall(function()
    return riskyOperation()
end)

if success then
    print("Result:", result)
else
    warn("Error:", result)
end

-- Try-catch pattern
local function tryOperation()
    local ok, err = pcall(dangerousFunc)
    return ok and err or nil
end

Performance Profiling

-- Time measurement
local start = tick()
-- Your code here
local elapsed = tick() - start
print("Took:", elapsed, "seconds")

-- Memory usage
print("Memory:", collectgarbage("count"), "KB")
collectgarbage("collect") -- Force garbage collection

⚡ Performance Optimization

💡 Performance Tips: • Use local variables • Cache function calls • Avoid creating objects in loops • Use RunService for game loops • Disconnect unused connections • Batch operations with wait()

Efficient Loops

-- Cache length
local items = workspace:GetChildren()
local count = #items
for i = 1, count do
    local item = items[i]
    -- process item
end

-- Reverse loop for removal
for i = #items, 1, -1 do
    if shouldRemove(items[i]) then
        table.remove(items, i)
    end
end

Object Pooling

local pool = {}
local active = {}

local function getObject()
    local obj = table.remove(pool)
    if not obj then
        obj = createNewObject()
    end
    active[obj] = true
    return obj
end

local function returnObject(obj)
    active[obj] = nil
    table.insert(pool, obj)
end

Memory Management

-- Weak references (auto-cleanup)
local cache = setmetatable({}, {__mode = "v"}) -- Values are weak

-- Connection cleanup
local connections = {}
local function cleanup()
    for i, conn in pairs(connections) do
        conn:Disconnect()
    end
    connections = {}
end

-- Debounce function
local function debounce(func, delay)
    local lastCall = 0
    return function(...)
        local now = tick()
        if now - lastCall >= delay then
            lastCall = now
            return func(...)
        end
    end
end
🎯 Quick Reference Cheat Codes:
game.Players.LocalPlayerworkspace:GetChildren()Instance.new("Part")Vector3.new(x,y,z)CFrame.new(x,y,z)wait(seconds)spawn(function)game:GetService("ServiceName")
🚀 Pro Tips: Always use local variables for better performance • Use :WaitForChild() for reliability • Implement proper error handling with pcall() • Clean up connections when done • Use CollectionService for tagging systems • Cache frequently used services and objects
RunService.Heartbeat:Connect(function(dt) -- every frame end)
RunService.RenderStepped:Connect(function(dt) -- before render end)