Dataset Viewer
Auto-converted to Parquet Duplicate
instruction
stringlengths
47
104
output
stringlengths
73
2.13k
category
stringlengths
5
33
What are the basic Lua syntax fundamentals including variables, loops, conditionals, and functions?
--create variable-- word = "hello" or local word = "hello" --if else-- if true then print("1") elseif false then print("2") else print("3") end --while loop-- while true do print("THIS IS WORKING YAY") end --for loop-- for i = 1, 5 do print("IM PRINTING MANY TIMES") end --print-- print("REAL PRINT") --wait...
Lua things
How do I work with Roblox objects like parts, players, and instances using Luau?
--change brick color-- game.Workspace.Mypart.BrickColor = BrickColor.new("Black") --change color through RGB-- game.Workspace.Mypart.Color = Color3.fromRGB(255, 255, 255) --change brick transparency-- game.Workspace.Mypart.Transparency = 1 --get player name-- game.Players.LocalPlayer.Name --check if thing exists-- ...
Roblox things
How do I handle UI events like hovering, clicking, and create moving platforms in Roblox?
--Hovering-- script.Parent.MouseEnter:Connect(function() print("Mouse is hovering above") end) --leaving-- script.Parent.MouseLeave:Connect(function() print("Mouse is no longer hovering") end) --clicking-- script.Parent.MouseButton1Click:Connect(function() print("Button clicked") end) game.StarterGui:SetCoreGuiEn...
UI STUFF
How do I save and load player data using DataStoreService in Roblox?
--Get DataStore service local DataStoreService = game:GetService("DataStoreService") local dataStore = DataStoreService:GetDataStore("MyDataStore") --Save data local success, err = pcall(function() dataStore:SetAsync(player.UserId, player.leaderstats.Cash.Value) end) --Load data local success, data = pcall(function(...
DATA STORES (Saving Data)
How do I use RemoteFunctions to call the server from a client and get a return value in Roblox?
--Create RemoteFunction local remoteFunction = Instance.new("RemoteFunction") remoteFunction.Name = "MyRemoteFunction" remoteFunction.Parent = game.ReplicatedStorage --Client calls server and waits for response local result = game.ReplicatedStorage.MyRemoteFunction:InvokeServer("request") --Server handles the call ga...
REMOTE FUNCTIONS
How do I listen to player joining, leaving, and character spawning events in Roblox?
--Player joining Players.PlayerAdded:Connect(function(player) print(player.Name .. " joined!") end) --Player leaving Players.PlayerRemoving:Connect(function(player) print(player.Name .. " left!") end) --Character spawning player.CharacterAdded:Connect(function(character) print(player.Name .. " spawned!") end) --G...
PLAYER EVENTS
How do I access and modify a player's Humanoid properties like health, speed, and jump power?
--Get Humanoid local humanoid = character:WaitForChild("Humanoid") --Change health humanoid.Health = 100 --Change walk speed humanoid.WalkSpeed = 16 -- Default is 16 --Change jump power humanoid.JumpPower = 50 -- Default is 50 --Kill player humanoid.Health = 0 --OR humanoid:TakeDamage(25) -- Deals 25 damage --C...
HUMANOID & CHARACTER
How do I detect when a player or object touches a part in Roblox, including with debounce?
--Basic touch event part.Touched:Connect(function(hit) print("Something touched: " .. hit.Name) end) --Touch with player detection part.Touched:Connect(function(hit) local character = hit.Parent local humanoid = character:FindFirstChild("Humanoid") if humanoid then print("Player touched: " .. character.Name) ...
TOUCH EVENTS
How do I create and configure parts with physics properties in Roblox?
--Create a part local newPart = Instance.new("Part") newPart.Size = Vector3.new(4, 4, 4) newPart.Position = Vector3.new(0, 10, 0) newPart.Anchored = true newPart.Parent = workspace --Part properties part.Anchored = true/false part.CanCollide = true/false part.Transparency = 0 -- 0 = visible, 1 = invisible part.Materi...
PARTS & PHYSICS
How do I use CFrame to move, rotate, and position parts in Roblox?
--Move part part.CFrame = CFrame.new(0, 10, 0) --Rotate part part.CFrame = CFrame.new(0, 10, 0) * CFrame.Angles(0, math.rad(45), 0) --Look at a position part.CFrame = CFrame.new(part.Position, targetPosition) --Move relative to current position part.CFrame = part.CFrame * CFrame.new(0, 0, -5) -- Move forward 5 stud...
CFRAME (Position & Rotation)
How do I create, move, and get the position of a Model in Roblox?
--Create model local model = Instance.new("Model") model.Name = "MyModel" model.Parent = workspace --Set PrimaryPart (required for movement) model.PrimaryPart = partInsideModel --Move model model:PivotTo(CFrame.new(0, 10, 0)) --Get model position local pos = model:GetPivot().Position
MODELS
How do I use TweenService to smoothly animate parts in Roblox?
local TweenService = game:GetService("TweenService") --Create tween local tweenInfo = TweenInfo.new( 2, -- Duration (seconds) Enum.EasingStyle.Linear, -- Easing style Enum.EasingDirection.Out, -- Easing direction 0, -- Repeat count (-1 = infinite) false, -- Reverses? 0 -- Delay time ) local goals = { Pos...
TWEENING (Smooth Animations)
How do I create, play, and configure sounds in Roblox?
--Create sound local sound = Instance.new("Sound") sound.SoundId = "rbxassetid://1234567890" -- Replace with actual ID sound.Volume = 1 sound.Parent = workspace --Play sound sound:Play() --Stop sound sound:Stop() --Sound properties sound.Looped = true/false sound.PlaybackSpeed = 1.0 sound.TimePosition = 0 -- Start...
SOUNDS
How do I use ParticleEmitter to create particle effects in Roblox?
--Create particle emitter local particles = Instance.new("ParticleEmitter") particles.Parent = part --Particle properties particles.Rate = 10 -- Particles per second particles.Lifetime = NumberRange.new(1, 2) particles.Speed = NumberRange.new(5, 10) particles.Color = ColorSequence.new(Color3.new(1, 0, 0)) particles.S...
PARTICLES & EFFECTS
How do I cast a ray and detect what it hits in Roblox?
local rayParams = RaycastParams.new() rayParams.FilterDescendantsInstances = {workspace} rayParams.FilterType = Enum.RaycastFilterType.Exclude --Cast ray local origin = Vector3.new(0, 10, 0) local direction = Vector3.new(0, -20, 0) local result = workspace:Raycast(origin, direction, rayParams) if result then print("...
RAYCASTING
How do I create teams and assign players to them in Roblox?
local Teams = game:GetService("Teams") --Create team local team = Instance.new("Team") team.Name = "Red Team" team.TeamColor = BrickColor.new("Bright red") team.AutoAssignable = true team.Parent = Teams --Set player team player.Team = team player.Neutral = false --Get players on team local teamPlayers = team:GetPlay...
TEAMS
How do I create tools, give them to players, and handle equip/unequip events in Roblox?
--Create tool local tool = Instance.new("Tool") tool.Name = "Sword" tool.Parent = player.Backpack --Tool equipped tool.Equipped:Connect(function() print("Tool equipped!") end) --Tool unequipped tool.Unequipped:Connect(function() print("Tool unequipped!") end) --Give tool to player local tool = game.ReplicatedStora...
TOOLS
How do I use BindableEvents to communicate between server-side scripts in Roblox?
--Create bindable event local bindable = Instance.new("BindableEvent") bindable.Name = "MyEvent" bindable.Parent = game.ReplicatedStorage --Fire event bindable:Fire("data", 123) --Connect to event bindable.Event:Connect(function(data, number) print("Event fired with: " .. data) end)
BINDABLE EVENTS
How do I create and use a ModuleScript in Roblox?
--ModuleScript code local Module = {} Module.variable = "Hello" function Module.myFunction() print("Function called!") end return Module --Require module in another script local myModule = require(game.ReplicatedStorage.MyModule) myModule.myFunction() print(myModule.variable)
MODULE SCRIPTS
What math functions are available in Luau for Roblox scripting?
--Random numbers local random = Random.new() local num = random:NextInteger(1, 100) local dec = random:NextNumber(0, 1) --Math operations math.abs(-5) -- Returns 5 math.floor(5.7) -- Returns 5 math.ceil(5.2) -- Returns 6 math.sqrt(16) -- Returns 4 math.pow(2, 3) -- Returns 8 math.min(5, 10) -- Returns 5 math.max...
MATH FUNCTIONS
What string manipulation functions are available in Luau?
--String length local length = #"Hello" -- Returns 5 --Find substring local found = string.find("Hello World", "World") -- Returns 7 --Get substring local sub = string.sub("Hello", 1, 3) -- Returns "Hel" --Replace local new = string.gsub("Hello", "l", "x") -- Returns "Hexxo" --Split local parts = string.split("...
STRING FUNCTIONS
What are the common table functions in Luau for managing arrays and dictionaries?
--Create table local myTable = {"apple", "banana", "orange"} --Add to table table.insert(myTable, "grape") --Remove from table table.remove(myTable, 1) -- Remove first item --Find in table local index = table.find(myTable, "banana") -- Returns index or nil --Sort table table.sort(myTable) -- Alphabetical --Get ...
TABLE FUNCTIONS
How do I iterate over a dictionary table in Luau?
for key, value in pairs(dict) do print(key .. ": " .. tostring(value)) end
DICTIONARY ITERATION
How do I iterate over an array table in Luau using ipairs?
for index, value in ipairs(myTable) do print(index .. ": " .. value) end
ARRAY ITERATION
How do I use time functions and waits in Roblox Luau scripts?
--Wait task.wait(1) -- Wait 1 second --Get time local time = os.time() -- Unix timestamp local date = os.date() -- Current date string --Tick (precise time) local startTime = tick() -- do stuff local elapsed = tick() - startTime
TIME & WAIT
How do I search for and retrieve parts or objects in the Workspace in Roblox?
--Get all parts local parts = workspace:GetDescendants() --Find by name local part = workspace:FindFirstChild("MyPart") --Find by class local part = workspace:FindFirstChildWhichIsA("Part") --Get children local children = workspace:GetChildren() --Get bounding box local cframe, size = model:GetBoundingBox()
WORKSPACE FUNCTIONS
What are the main Roblox game services and how do I access them?
game:GetService("Players") game:GetService("Workspace") game:GetService("ReplicatedStorage") game:GetService("ServerScriptService") game:GetService("Lighting") game:GetService("SoundService") game:GetService("Teams") game:GetService("DataStoreService") game:GetService("TweenService") game:GetService("RunService") game:...
GAME SERVICES
How do I control lighting settings like time of day, fog, and brightness in Roblox?
local Lighting = game:GetService("Lighting") --Time of day Lighting.ClockTime = 12 -- Noon (0-24) --Ambient Lighting.Ambient = Color3.new(0.5, 0.5, 0.5) --Brightness Lighting.Brightness = 2 --Fog Lighting.FogEnd = 100 Lighting.FogColor = Color3.new(0.8, 0.8, 0.8)
LIGHTING
How do I run code every frame using RunService in Roblox?
local RunService = game:GetService("RunService") --Runs every frame (client) RunService.RenderStepped:Connect(function(deltaTime) print("Frame time: " .. deltaTime) end) --Runs every frame (server) RunService.Heartbeat:Connect(function(deltaTime) print("Frame time: " .. deltaTime) end)
RUN SERVICE (Every Frame)
How do I create a proximity prompt that players can interact with in Roblox?
--Create proximity prompt local prompt = Instance.new("ProximityPrompt") prompt.ObjectText = "Press to interact" prompt.ActionText = "Open" prompt.KeyboardKeyCode = Enum.KeyCode.E prompt.Parent = part --Triggered event prompt.Triggered:Connect(function(player) print(player.Name .. " interacted!") end)
PROXIMITY PROMPT
How do I detect mouse clicks on a part using ClickDetector in Roblox?
--Create click detector local clickDetector = Instance.new("ClickDetector") clickDetector.MaxActivationDistance = 10 clickDetector.Parent = part --Mouse click clickDetector.MouseClick:Connect(function(player) print(player.Name .. " clicked!") end) --Right click clickDetector.RightMouseClick:Connect(function(player) ...
CLICK DETECTOR
How do I run a function asynchronously in the background in Roblox?
--Spawn function (runs async) task.spawn(function() while true do print("Running in background") task.wait(1) end end)
SPAWN FUNCTION
How do I delay the execution of a function by a set number of seconds in Roblox?
--Run after delay task.delay(3, function() print("3 seconds later!") end)
DELAY FUNCTION
How do I handle errors safely using pcall in Luau?
--Safe function call local success, result = pcall(function() return riskyFunction() end) if success then print("Success: " .. result) else warn("Error: " .. result) end
PCALL (Error Handling)
How do I check the type of a variable in Luau, including Roblox-specific types?
--Check type type(variable) -- Returns type string typeof(variable) -- Returns Roblox type --Type checking examples type(5) == "number" type("hello") == "string" type(true) == "boolean" type({}) == "table" type(nil) == "nil" typeof(part) == "Instance" typeof(Vector3.new()) == "Vector3" typeof(CFrame.new()) == "CFra...
TYPE CHECKING
How do I set and get custom attributes on Instances in Roblox?
local part = Instance.new("Part") part:SetAttribute("Health", 100) part:SetAttribute("Speed", 16) --Get attribute local health = part:GetAttribute("Health") --Get all attributes local attrs = part:GetAttributes()
INSTANCE ATTRIBUTES
How do I tag objects and retrieve them using CollectionService in Roblox?
local CollectionService = game:GetService("CollectionService") --Add tag CollectionService:AddTag(part, "Interactable") --Get tagged objects local objects = CollectionService:GetTagged("Interactable") --Tag added event CollectionService:GetInstanceAddedSignal("Interactable"):Connect(function(instance) print("New ob...
COLLECTION SERVICE (Tag System)
How do I create a ScreenGui with frames, labels, and buttons in Roblox?
--Create ScreenGui local screenGui = Instance.new("ScreenGui") screenGui.Parent = player.PlayerGui --Create Frame local frame = Instance.new("Frame") frame.Size = UDim2.new(0, 200, 0, 100) frame.Position = UDim2.new(0.5, -100, 0.5, -50) frame.BackgroundColor3 = Color3.new(0.2, 0.2, 0.2) frame.Parent = screenGui --Cre...
GUI CREATION
What are the common properties for configuring GUI elements like UDim2, text, and frames in Roblox?
--UDim2 (size/position) UDim2.new(0, 100, 0, 50) -- 100 pixels wide, 50 pixels tall UDim2.new(0.5, 0, 0.5, 0) -- Center of screen UDim2.new(1, -20, 1, -20) -- Full screen with 10 pixel margin --Text properties label.Text = "Hello" label.TextColor3 = Color3.new(1, 1, 1) label.TextSize = 24 label.Font = Enum.Font.Got...
GUI PROPERTIES
How do I add rounded corners and a border stroke to UI elements in Roblox?
--Rounded corners local corner = Instance.new("UICorner") corner.CornerRadius = UDim.new(0, 10) corner.Parent = frame --Border stroke local stroke = Instance.new("UIStroke") stroke.Color = Color3.new(1, 1, 1) stroke.Thickness = 2 stroke.Parent = frame
UI CORNER & STROKE
How do I add padding and list/grid layouts to a UI Frame in Roblox?
--Padding local padding = Instance.new("UIPadding") padding.PaddingTop = UDim.new(0, 10) padding.PaddingLeft = UDim.new(0, 10) padding.Parent = frame --List layout (vertical) local listLayout = Instance.new("UIListLayout") listLayout.Padding = UDim.new(0, 5) listLayout.Parent = frame --Grid layout local gridLayout = ...
UI PADDING & LIST
How do I create a scrollable frame in Roblox GUI?
local scrollFrame = Instance.new("ScrollingFrame") scrollFrame.Size = UDim2.new(0, 200, 0, 300) scrollFrame.CanvasSize = UDim2.new(0, 0, 0, 500) -- Scrollable area scrollFrame.Parent = screenGui
SCROLLING FRAME
How do I display an image inside a Roblox GUI using ImageLabel?
local imageLabel = Instance.new("ImageLabel") imageLabel.Image = "rbxassetid://1234567890" imageLabel.Size = UDim2.new(0, 100, 0, 100) imageLabel.Parent = screenGui
IMAGE LABEL
How do I create a text input field and read player input in Roblox GUI?
local textBox = Instance.new("TextBox") textBox.Size = UDim2.new(0, 200, 0, 30) textBox.PlaceholderText = "Type here..." textBox.Parent = screenGui --Get text when submitted textBox.FocusLost:Connect(function(enterPressed) if enterPressed then print("Submitted: " .. textBox.Text) end end)
TEXTBOX (Input)
How do I load and play animations on a character in Roblox?
--Load animation on character local animation = Instance.new("Animation") animation.AnimationId = "rbxassetid://1234567890" local animator = humanoid:WaitForChild("Animator") local track = animator:LoadAnimation(animation) --Play animation track:Play() --Stop animation track:Stop() --Animation properties track.Loop...
ANIMATIONS
How do I create and configure a SpawnLocation for players in Roblox?
--Create spawn location local spawn = Instance.new("SpawnLocation") spawn.Position = Vector3.new(0, 1, 0) spawn.Anchored = true spawn.Parent = workspace --Set as neutral spawn spawn.Neutral = true --Set team spawn spawn.TeamColor = BrickColor.new("Bright red")
SPAWN LOCATION
How do I build a basic round system with a timer and intermission in Roblox?
local roundDuration = 60 -- seconds local intermission = 15 -- seconds local inRound = false local function startRound() inRound = true print("Round started!") task.wait(roundDuration) inRound = false print("Round ended!") task.wait(intermission) startRound() end
ROUND SYSTEM
How do I create an explosion effect at a position in Roblox?
local explosion = Instance.new("Explosion") explosion.Position = Vector3.new(0, 10, 0) explosion.BlastPressure = 100000 explosion.BlastRadius = 10 explosion.DestroyJointRadiusPercent = 0.5 explosion.Parent = workspace
EXPLOSION
How do I add a highlight glow effect to a part in Roblox?
local highlight = Instance.new("Highlight") highlight.FillColor = Color3.new(1, 0, 0) highlight.OutlineColor = Color3.new(1, 1, 1) highlight.FillTransparency = 0.5 highlight.Parent = part
HIGHLIGHT EFFECT
How do I add a bloom post-processing effect to the Roblox Lighting?
local bloom = Instance.new("BloomEffect") bloom.Intensity = 0.5 bloom.Size = 24 bloom.Threshold = 0.9 bloom.Parent = game.Lighting
BLOOM EFFECT
How do I add a blur effect to the screen in Roblox?
local blur = Instance.new("BlurEffect") blur.Size = 10 blur.Parent = game.Lighting
BLUR EFFECT
How do I use ColorCorrectionEffect to adjust the game's color in Roblox?
local colorCorrection = Instance.new("ColorCorrectionEffect") colorCorrection.Saturation = 0.2 colorCorrection.Contrast = 0.1 colorCorrection.Brightness = 0.05 colorCorrection.Parent = game.Lighting
COLOR CORRECTION
How do I create an atmosphere with haze and fog in Roblox Lighting?
local atmosphere = Instance.new("Atmosphere") atmosphere.Density = 0.3 atmosphere.Color = Color3.new(0.8, 0.8, 0.8) atmosphere.Haze = 2 atmosphere.Parent = game.Lighting
ATMOSPHERE
How do I control the camera's position, type, and field of view using a LocalScript in Roblox?
local camera = workspace.CurrentCamera camera.CameraType = Enum.CameraType.Scriptable camera.CFrame = CFrame.new(0, 50, 50) camera.FieldOfView = 70
CAMERA MANIPULATION (LocalScript)
How do I lerp (linearly interpolate) between two numbers, colors, or vectors in Luau?
local function lerp(a, b, t) return a + (b - a) * t end local function lerpColor(color1, color2, t) return Color3.new( lerp(color1.R, color2.R, t), lerp(color1.G, color2.G, t), lerp(color1.B, color2.B, t) ) end local function lerpVector3(v1, v2, t) return Vector3.new( lerp(v1.X, v2.X, t), lerp(v1.Y, v2....
LERP (LINEAR INTERPOLATION)
How do I build a simple inventory system to add, remove, and check items per player in Roblox?
local inventory = {} local function addItem(player, itemName) if not inventory[player] then inventory[player] = {} end table.insert(inventory[player], itemName) end local function removeItem(player, itemName) local inv = inventory[player] if not inv then return false end for i, item in ipairs(inv) do if item =...
INVENTORY SYSTEM
How do I make an NPC follow a player using MoveTo in Roblox?
local function followPlayer(npc, targetPlayer) local hrp = npc:FindFirstChild("HumanoidRootPart") local targetChar = targetPlayer.Character if not hrp or not targetChar then return end local targetHrp = targetChar:FindFirstChild("HumanoidRootPart") if targetHrp then npc.Humanoid:MoveTo(targetHrp.Position) end e...
FOLLOW PLAYER AI
How do I create a patrolling NPC that moves between waypoints in Roblox?
local waypoints = {Vector3.new(0, 0, 0), Vector3.new(50, 0, 0), Vector3.new(50, 0, 50)} local currentWaypoint = 1 local function patrol(npc) while true do npc.Humanoid:MoveTo(waypoints[currentWaypoint]) npc.Humanoid.MoveToFinished:Wait() currentWaypoint = currentWaypoint % #waypoints + 1 end end
PATROL AI
How do I build a basic shop system where players can buy items using in-game currency in Roblox?
local shopItems = { { name = "Sword", price = 100 }, { name = "Shield", price = 50 }, { name = "Potion", price = 25 } } local function buyItem(player, itemName) for _, item in ipairs(shopItems) do if item.name == itemName then local cash = player.leaderstats.Cash if cash.Value < item.price then return ...
SHOP SYSTEM
How do I create a checkpoint system that tracks and respawns players at their last checkpoint in Roblox?
local checkpoints = {checkpoint1, checkpoint2, checkpoint3} local playerCheckpoints = {} local function setupCheckpoint(checkpoint, index) checkpoint.Touched:Connect(function(hit) local player = Players:GetPlayerFromCharacter(hit.Parent) if player then playerCheckpoints[player] = index end end) end
CHECKPOINT SYSTEM
How do I make collectible coins that give players cash when touched in Roblox?
local coins = workspace.Coins for _, coin in ipairs(coins:GetChildren()) do coin.Touched:Connect(function(hit) local character = hit.Parent local humanoid = character:FindFirstChild("Humanoid") local player = Players:GetPlayerFromCharacter(character) if humanoid and player then player.leaderstats.Cash.Valu...
COIN COLLECT SYSTEM
How do I create a door that opens and closes by rotating its CFrame in Roblox?
local door = workspace.Door local isOpen = false local function toggleDoor() if isOpen then door.CFrame = door.CFrame * CFrame.Angles(0, math.rad(-90), 0) else door.CFrame = door.CFrame * CFrame.Angles(0, math.rad(90), 0) end isOpen = not isOpen end ----DEBRIS SERVICE (Auto-Cleanup)---- local Debris = game:G...
DOOR SYSTEM
How do I make a part float up and down using a sine wave in Roblox?
local function float(part, height, speed) local startY = part.Position.Y task.spawn(function() while part.Parent do part.Position = Vector3.new(part.Position.X, startY + math.sin(tick() * speed) * height, part.Position.Z) task.wait() end end) end
PART FLOAT
How do I make a part orbit around a center point in Roblox?
local function orbit(part, center, radius, speed) task.spawn(function() while part.Parent do local angle = tick() * speed local x = center.X + math.cos(angle) * radius local z = center.Z + math.sin(angle) * radius part.Position = Vector3.new(x, part.Position.Y, z) task.wait() end end) end
PART ORBIT
How do I check the distance between two parts and do something when they are close enough in Roblox?
local distance = (part1.Position - part2.Position).Magnitude if distance < 10 then print("Close enough!") end
DISTANCE CHECK
How do I create a countdown timer that prints each second in Roblox?
local function countdown(seconds) for i = seconds, 1, -1 do print(i) task.wait(1) end print("Time is up!") end
COUNTDOWN TIMER
How do I use IntValue, StringValue, and BoolValue objects and detect when their value changes in Roblox?
local intValue = Instance.new("IntValue") intValue.Value = 100 local stringValue = Instance.new("StringValue") stringValue.Value = "Hello" local boolValue = Instance.new("BoolValue") boolValue.Value = true intValue.Changed:Connect(function(newValue) print("Value changed to: " .. newValue) end)
VALUE OBJECTS
How do I implement pathfinding service in Roblox Luau?
local PathfindingService = game:GetService("PathfindingService") local Players = game:GetService("Players") local npc = workspace.NPC local humanoid = npc:WaitForChild("Humanoid") local hrp = npc:WaitForChild("HumanoidRootPart") local path = PathfindingService:CreatePath({ AgentHeight = 5, AgentRadius = 2, ...
AI & NPC
How do I implement pathfinding with obstacle recompute in Roblox Luau?
local PathfindingService = game:GetService("PathfindingService") local npc = workspace.NPC local humanoid = npc.Humanoid local hrp = npc.HumanoidRootPart local path = PathfindingService:CreatePath({ AgentCanJump = true }) local waypoints = {} local currentWaypointIndex = 1 local reachedConnection local function foll...
AI & NPC
How do I implement oop with metatables in Roblox Luau?
-- Define a class local Enemy = {} Enemy.__index = Enemy function Enemy.new(name, health, damage) local self = setmetatable({}, Enemy) self.Name = name self.Health = health self.Damage = damage return self end function Enemy:TakeDamage(amount) self.Health -= amount print(self.Name .. " too...
OOP & Metatables
How do I implement oop inheritance in Roblox Luau?
local Animal = {} Animal.__index = Animal function Animal.new(name, sound) return setmetatable({ Name = name, Sound = sound }, Animal) end function Animal:Speak() print(self.Name .. " says " .. self.Sound) end -- Subclass local Dog = setmetatable({}, { __index = Animal }) Dog.__index = Dog function Dog.new(...
OOP & Metatables
How do I implement singleton pattern in Roblox Luau?
-- Singleton module (only one instance exists) local GameManager = {} GameManager.__index = GameManager local instance = nil function GameManager.getInstance() if not instance then instance = setmetatable({ round = 0, isRunning = false, scores = {} }, GameManage...
OOP & Metatables
How do I implement coroutines basics in Roblox Luau?
-- Create a coroutine local co = coroutine.create(function(a, b) print("Start:", a, b) coroutine.yield("first yield") print("Resumed!") coroutine.yield("second yield") print("Done!") return "finished" end) -- Run it step by step local ok, val = coroutine.resume(co, 10, 20) print(val) -- "first...
Coroutines
How do I implement producer-consumer with coroutines in Roblox Luau?
-- Producer generates values, consumer processes them local function producer() local items = {"sword", "shield", "potion", "bow"} for _, item in ipairs(items) do print("Producing: " .. item) coroutine.yield(item) end end local function consumer(prod) while true do local ok, ite...
Coroutines
How do I implement network ownership in Roblox Luau?
-- Server script -- By default server owns all unanchored parts -- Giving ownership to a player reduces lag for that player local part = workspace.MovingPart local Players = game:GetService("Players") -- Give ownership to specific player local function giveOwnership(player) part:SetNetworkOwner(player) print(...
Networking
How do I implement streaming enabled handling in Roblox Luau?
-- LocalScript: safely wait for parts to exist with streaming enabled local function waitForPart(parent, name, timeout) timeout = timeout or 10 local part = parent:FindFirstChild(name) if part then return part end local startTime = tick() while not part and (tick() - startTime) < timeout do ...
Networking
How do I implement tween ui elements in Roblox Luau?
local TweenService = game:GetService("TweenService") local frame = script.Parent -- Frame inside ScreenGui local button = frame.OpenButton local tweenInfo = TweenInfo.new(0.4, Enum.EasingStyle.Quart, Enum.EasingDirection.Out) local openTween = TweenService:Create(frame, tweenInfo, { Position = UDim2.new(0.5, -1...
UI & GUI
How do I implement tween button hover effect in Roblox Luau?
local TweenService = game:GetService("TweenService") local button = script.Parent local normalSize = UDim2.new(0, 200, 0, 50) local hoverSize = UDim2.new(0, 210, 0, 55) local growTween = TweenService:Create(button, TweenInfo.new(0.15), { Size = hoverSize }) local shrinkTween = TweenService:Create(button, TweenInfo....
UI & GUI
How do I implement notification ui system in Roblox Luau?
-- LocalScript local TweenService = game:GetService("TweenService") local Players = game:GetService("Players") local player = Players.LocalPlayer local gui = player.PlayerGui local function showNotification(message, color) color = color or Color3.fromRGB(40, 40, 40) local screenGui = Instance.new("ScreenGui")...
UI & GUI
How do I implement character appearance & body color in Roblox Luau?
local Players = game:GetService("Players") local function customizeCharacter(character) -- Change body colors local bodyColors = character:FindFirstChild("Body Colors") if bodyColors then bodyColors.HeadColor3 = Color3.fromRGB(255, 200, 150) bodyColors.TorsoColor3 = Color3.fromRGB(0, 1...
Character
How do I implement give accessory to character in Roblox Luau?
local function giveHat(character, assetId) local accessory = game:GetService("InsertService"):LoadAsset(assetId) local hat = accessory:FindFirstChildOfClass("Accessory") if hat then hat.Parent = character end accessory:Destroy() end -- Or create accessory manually local function createAcces...
Character
How do I implement resize character in Roblox Luau?
local function resizeCharacter(character, scale) local humanoid = character:FindFirstChild("Humanoid") if not humanoid then return end -- Use HumanoidDescription for proper scaling local desc = humanoid:GetAppliedDescription() desc.HeightScale = scale desc.WidthScale = scale desc.Depth...
Character
How do I implement basic server-side anti-cheat in Roblox Luau?
-- Server Script: never trust the client local Players = game:GetService("Players") local RunService = game:GetService("RunService") local MAX_SPEED = 30 -- studs/sec threshold local lastPositions = {} Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(character) local hr...
Anti-Cheat
How do I implement validate remoteevent inputs server-side in Roblox Luau?
-- NEVER trust data sent from client -- Always validate on server local ReplicatedStorage = game:GetService("ReplicatedStorage") local buyEvent = ReplicatedStorage:WaitForChild("BuyItem") local VALID_ITEMS = { sword = { price = 100, maxBuy = 1 }, potion = { price = 25, maxBuy = 10 } } buyEvent.OnServerEven...
Anti-Cheat
How do I implement datastore with retry logic in Roblox Luau?
local DataStoreService = game:GetService("DataStoreService") local Players = game:GetService("Players") local dataStore = DataStoreService:GetDataStore("PlayerData_v2") local MAX_RETRIES = 3 local RETRY_DELAY = 2 local function safeGet(key) for attempt = 1, MAX_RETRIES do local success, result = pcall(fun...
DataStore
How do I implement nested datastore save structure in Roblox Luau?
-- Save complex nested data (inventory, stats, settings) local DataStoreService = game:GetService("DataStoreService") local store = DataStoreService:GetDataStore("PlayerData_v3") local DEFAULT_DATA = { stats = { cash = 0, gems = 0, level = 1, xp = 0, }, inventory = ...
DataStore
How do I implement datastore with updateasync (safe concurrent saves) in Roblox Luau?
local DataStoreService = game:GetService("DataStoreService") local store = DataStoreService:GetDataStore("SafeData") -- UpdateAsync is safer than SetAsync for concurrent updates local function addCurrency(userId, amount) local success, newValue = pcall(function() return store:UpdateAsync("uid_" .. userId, ...
DataStore
How do I implement custom signal class in Roblox Luau?
-- A clean Signal implementation (no BindableEvents needed) local Signal = {} Signal.__index = Signal function Signal.new() return setmetatable({ _listeners = {} }, Signal) end function Signal:Connect(callback) local connection = { callback = callback, connected = true } table.insert(self._listeners, conn...
Patterns & Signals
How do I implement viewportframe (3d preview in ui) in Roblox Luau?
-- LocalScript local Players = game:GetService("Players") local player = Players.LocalPlayer local gui = player.PlayerGui local screenGui = Instance.new("ScreenGui") screenGui.Parent = gui -- Create viewport frame local viewport = Instance.new("ViewportFrame") viewport.Size = UDim2.new(0, 200, 0, 200) viewport.Positi...
UI & GUI
How do I implement surfaceappearance (pbr textures) in Roblox Luau?
-- SurfaceAppearance enables PBR (physically based rendering) textures local part = workspace.MyPart local sa = Instance.new("SurfaceAppearance") -- Color / albedo map sa.ColorMap = "rbxassetid://111111111" -- Normal map (surface detail / bumps) sa.NormalMap = "rbxassetid://222222222" -- Roughness map (0 = mirror, ...
Visual Effects
How do I implement simple queue matchmaking system in Roblox Luau?
local Players = game:GetService("Players") local TeleportService = game:GetService("TeleportService") local GAME_PLACE_ID = 1234567890 local MIN_PLAYERS = 2 local MAX_PLAYERS = 10 local queue = {} local function tryStartMatch() if #queue < MIN_PLAYERS then return end local batch = {} for i = 1, math.min...
Game Systems
How do I implement party system in Roblox Luau?
local Players = game:GetService("Players") local parties = {} -- { [leaderId] = { leader, members = {} } } local function createParty(leader) parties[leader.UserId] = { leader = leader, members = { leader } } print(leader.Name .. " created a party") end local function inviteToParty(leader...
Game Systems
How do I implement contextactionservice (mobile + keyboard) in Roblox Luau?
-- Works on keyboard AND mobile (creates on-screen button) local ContextActionService = game:GetService("ContextActionService") local function onAction(actionName, inputState, inputObject) if inputState == Enum.UserInputState.Begin then if actionName == "Sprint" then print("Sprint started") ...
Input
How do I implement mobile touch input detection in Roblox Luau?
local UserInputService = game:GetService("UserInputService") local Players = game:GetService("Players") local player = Players.LocalPlayer -- Detect if on mobile local isMobile = UserInputService.TouchEnabled and not UserInputService.KeyboardEnabled -- Touch began UserInputService.TouchStarted:Connect(function(touch,...
Input
How do I implement billboardgui (floating ui above parts) in Roblox Luau?
-- BillboardGui floats above a part in 3D world space local part = workspace.NPC local billboard = Instance.new("BillboardGui") billboard.Size = UDim2.new(0, 100, 0, 40) billboard.StudsOffset = Vector3.new(0, 3, 0) -- float 3 studs above part billboard.AlwaysOnTop = false billboard.Adornee = part billboard.Parent = p...
UI & GUI
How do I implement surfacegui (ui painted on part surface) in Roblox Luau?
-- SurfaceGui renders UI directly on a part's surface local part = workspace.Screen local surfaceGui = Instance.new("SurfaceGui") surfaceGui.Face = Enum.NormalId.Front surfaceGui.PixelsPerStud = 50 surfaceGui.AlwaysOnTop = false surfaceGui.Parent = part local background = Instance.new("Frame") background.Size = UDim2...
UI & GUI
How do I implement spring module for smooth camera in Roblox Luau?
-- Spring utility for smooth damped motion local Spring = {} Spring.__index = Spring function Spring.new(initial) return setmetatable({ position = initial, velocity = initial * 0, target = initial, damping = 10, speed = 20 }, Spring) end function Spring:update(dt)...
Camera & Effects
How do I implement head bobbing camera effect in Roblox Luau?
-- LocalScript: head bobbing while walking local RunService = game:GetService("RunService") local Players = game:GetService("Players") local player = Players.LocalPlayer local camera = workspace.CurrentCamera local bobSpeed = 10 local bobAmount = 0.15 local bobTimer = 0 RunService.RenderStepped:Connect(function(dt)...
Camera & Effects
How do I implement save player settings with datastore in Roblox Luau?
local DataStoreService = game:GetService("DataStoreService") local Players = game:GetService("Players") local settingsStore = DataStoreService:GetDataStore("PlayerSettings") local DEFAULT_SETTINGS = { musicVolume = 0.5, sfxVolume = 1.0, showHints = true, quality = "High" } local playerSettings...
DataStore
How do I implement hitbox combat system in Roblox Luau?
-- Server Script local Players = game:GetService("Players") local function getHumanoid(part) local char = part.Parent return char:FindFirstChild("Humanoid"), char end local function createHitbox(attacker, size, offset, damage, duration) local hrp = attacker.Character and attacker.Character:FindFirstChild(...
Combat
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
6