Lua Roblox Scripting Basics (1)
Lua Roblox Scripting Basics (1)
1. Lua Basics
Variables
lua
If-Else Statements
lua
local health = 50
if health > 0 then
print("Player is alive!")
else
print("Player is dead!")
end
Loops
lua
for i = 1, 5 do
print("Iteration:", i)
end
Functions
lua
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/6
end
greetPlayer("Alex")
2. Roblox-Specific Scripting
lua
Handling Events
lua
Modifying Properties
lua
lua
button.MouseButton1Click:Connect(function()
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/6
print("Button clicked!")
end)
lua
Spawning Parts
lua
5. Game Logic
Player Interaction
lua
game.Players.PlayerAdded:Connect(function(player)
print(player.Name .. " joined the game!")
end)
Leaderstats Example
lua
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/6
local score = Instance.new("IntValue")
score.Name = "Score"
score.Value = 0
score.Parent = leaderstats
end)
lua
script.Parent.ClickDetector.MouseClick:Connect(function(player)
if not cooldown then
cooldown = true
print(player.Name .. " clicked!")
wait(5) -- Cooldown period
cooldown = false
end
end)
6. Advanced Concepts
Remote Events
lua
event.OnServerEvent:Connect(function(player, message)
print(player.Name .. " says: " .. message)
end)
lua
Module Scripts
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/6
Module Script (in ReplicatedStorage):
lua
local module = {}
function module.sayHello(name)
return "Hello, " .. name
end
return module
lua
DataStore
lua
game.Players.PlayerAdded:Connect(function(player)
local data = dataStore:GetAsync(player.UserId) or 0
print(player.Name .. "'s data:", data)
end)
lua
print("Script started!")
local part = game.Workspace:FindFirstChild("NonExistentPart")
if part then
print("Part found:", part.Name)
else
print("Part not found!")
end
Optimized Loops
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/6
Improve performance by reducing redundant operations.
lua
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/6