📚 Scripting Basics for Roblox

Welcome to the complete beginner's guide to Lua scripting in Roblox! By the end of this tutorial, you'll understand the fundamentals and be able to create your first interactive scripts.

📦 Variables and Data Types

Variables store information that your script can use later. In Lua, you don't need to specify the type – it's automatically detected.

Numbers

local score = 100
local speed = 25.5
local negative = -10

Strings (Text)

local name = "Player1"
local message = 'Hello!'
local color = [[Red]]

Booleans

local isAlive = true
local hasKey = false
local isAdmin = true
💡 Real Example: Player Stats
-- Player information
local playerName = "Robloxian"
local playerLevel = 5
local experience = 1250
local isVip = false

print(playerName .. " is level " .. playerLevel)
-- Output: Robloxian is level 5

⚙️ Functions

Functions are reusable blocks of code. They can take parameters and return values.

-- Basic function
function greetPlayer(name)
print("Welcome to the game, " .. name .. "!")
end

-- Call the function
greetPlayer("Alex") -- Output: Welcome to the game, Alex!

-- Function with return value
function calculateDamage(damage, armor)
local finalDamage = damage - armor
if finalDamage < 0 then
return 0
end
return finalDamage
end

local received = calculateDamage(50, 20)
print("You took " .. received .. " damage") -- Output: You took 30 damage
💎 Pro Tip: Always use local for variables inside functions to avoid conflicts with other scripts!

🎯 Events

Events are what make Roblox games interactive. They trigger code when something happens.

-- Touched event (when something touches a part)
local part = script.Parent

part.Touched:Connect(function(hit)
-- hit is the object that touched the part
if hit.Parent:FindFirstChild("Humanoid") then
print("A player touched the part!")
part.BrickColor = BrickColor.new("Bright red")
end
end)

-- ClickDetector event (when player clicks)
local clickDetector = Instance.new("ClickDetector")
clickDetector.Parent = part

clickDetector.MouseClick:Connect(function(player)
print(player.Name .. " clicked the part!")
-- Give reward
player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 10
end)

🔀 If Statements

Make decisions in your code based on conditions.

local playerLevel = 10
local requiredLevel = 5
local hasPass = true

-- Basic if
if playerLevel >= requiredLevel then
print("You can enter the zone!")
end

-- If-else
if playerLevel >= 10 then
print("You have access to advanced weapons")
else
print("Keep playing to unlock more!")
end

-- Multiple conditions
if playerLevel >= 10 and hasPass then
print("Welcome to the VIP area!")
elseif playerLevel >= 10 then
print("Get the game pass for VIP access!")
else
print("Reach level 10 first!")
end

🔄 Loops

Repeat code multiple times.

While Loop

local count = 0
while count < 5 do
print("Count: " .. count)
count = count + 1
wait(1) -- Wait 1 second
end

For Loop

for i = 1, 10 do
print("Number: " .. i)
end

-- Step by 2
for i = 1, 10, 2 do
print("Odd: " .. i)
end
🎮 Spawn enemies every 5 seconds
while true do
-- Create enemy
local enemy = game.ServerStorage.Enemy:Clone()
enemy.Parent = workspace.Enemies
enemy.HumanoidRootPart.Position = Vector3.new(0, 10, 0)

print("Enemy spawned!")
wait(5) -- Wait 5 seconds
end

📋 Tables

Tables store multiple values. They're like lists or dictionaries.

-- Array-style table (list)
local weapons = {"Sword", "Gun", "Bow"}
print(weapons[1]) -- Output: Sword (Lua starts at 1, not 0!)

-- Dictionary-style table
local playerInfo = {
name = "John",
level = 10,
class = "Warrior",
inventory = {"Potion", "Key"}
}

print(playerInfo.name) -- Output: John
print(playerInfo.level) -- Output: 10

-- Loop through a table
for i, weapon in ipairs(weapons) do
print("Weapon " .. i .. ": " .. weapon)
end

for key, value in pairs(playerInfo) do
print(key .. ": " .. tostring(value))
end

🏗️ Instances

Everything in Roblox is an Instance. Here's how to work with them.

-- Finding objects
local part = workspace:FindFirstChild("Part")
local players = game:GetService("Players")

-- Creating new objects
local newPart = Instance.new("Part")
newPart.Name = "MyPart"
newPart.Size = Vector3.new(4, 1, 2)
newPart.BrickColor = BrickColor.new("Bright blue")
newPart.Position = Vector3.new(10, 5, 10)
newPart.Parent = workspace

-- Changing properties
part.BrickColor = BrickColor.new("Red")
part.Transparency = 0.5
part.Anchored = true

-- Destroying objects
-- part:Destroy()
📝 Note: Always set Parent last for better performance!

🎮 Complete Example: Coin Collection System

-- Put this script in a part named "Coin"

local coin = script.Parent
local collectionSound = Instance.new("Sound")
collectionSound.SoundId = "rbxassetid://9120387021" -- Replace with your sound
collectionSound.Parent = coin

-- Make coin spin
local spinSpeed = 50

-- Collection counter
local collectedCount = 0
local maxCollects = 10

-- Function to respawn coin
function respawnCoin()
coin.CanCollide = false
coin.Transparency = 1
collectionSound:Play()

wait(3) -- Wait 3 seconds

coin.CanCollide = true
coin.Transparency = 0
collectedCount = 0
end

-- When touched
coin.Touched:Connect(function(hit)
-- Check if it's a player
local humanoid = hit.Parent:FindFirstChild("Humanoid")
if humanoid and collectedCount < maxCollects then
collectedCount = collectedCount + 1

-- Find player's leaderstats
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
local coins = player:FindFirstChild("leaderstats"):FindFirstChild("Coins")
if coins then
coins.Value = coins.Value + 5
print(player.Name .. " got 5 coins! Total: " .. coins.Value)
end
end

-- Visual effect
local effect = Instance.new("Explosion")
effect.Position = coin.Position
effect.BlastRadius = 2
effect.BlastPressure = 0
effect.Visible = true
effect.Parent = workspace

if collectedCount >= maxCollects then
respawnCoin()
end
end
end)

-- Spin animation
while true do
if coin.Transparency == 0 then
coin.CFrame = coin.CFrame * CFrame.Angles(0, math.rad(spinSpeed), 0)
end
wait(0.1)
end

✍️ Practice Tasks

Task 1: Door System

Create a door that opens when a player with a game pass touches it.

-- Hint structure:
local gamePassId = 12345678

-- Check if player owns pass
-- If yes, open door (CFrame animation)
-- If no, show message "You need the VIP pass!"

Task 2: Timer System

Create a countdown timer that displays on a part's surface.

-- Hint:
local timeLeft = 60
local surfaceGui = Instance.new("SurfaceGui")
local textLabel = Instance.new("TextLabel")

-- Update every second until timeLeft = 0

Task 3: Random Loot

Create a chest that gives random rewards when touched.

-- Hint:
local rewards = {"Coins", "Health", "Weapon", "Key"}
local randomIndex = math.random(1, #rewards)
-- Give random reward

⚠️ Common Mistakes to Avoid

❌ Forgetting "local"
Always use local for variables unless you need them globally.
❌ Not using wait() in loops
while true do without wait() will crash your game!
❌ Assuming array index starts at 0
Lua arrays start at 1, not 0!

📚 Additional Resources