i made a mystery block in roblox studio so when you click it something the script picks a number from 1-50 and makes something random happen for each number. I completed my first thing but when i was ready to make number 2 the script underlined something like it didnt know what it was.
local debounce = true script.Parent.ClickDetector.MouseClick:connect(function() if debounce then local selection = math.random(1, 50) debounce = false if selection == 1 then game.Lighting.Ambient = 154, 38, 255 end elseif selection == 2 then -- the selection part was underlined even though it was explained on line 6 end end)
This is due to how local variables interact with scope. Scope acts as a private container for local variables. All local variables created in a scope, are only accessible inside that scope.
A scope is created between any block of code that requires an end
statement (appropriately, to "end" the scope that was created). However, in an if statement, new scopes are also created in between else
or elseif
statements. For example:
if true then -- Scope 1 print("True") else -- Scope 2 print("False") end
Using this logic, we can see that on line 5 of your code, you created a local variable called selection
in the first scope of the if statement. You then try to access the same variable in scope 2 of the if statement, which doesn't exist. This is where the underline is coming from.
To make the variable accessible throughout the entire scope of the function, you simply just want to declare the local variable outside of the if statement, so that everything inside the if statement can access it. Example:
script.Parent.MouseClick:Connect(function() local selection = math.random(50) if ... then -- code end end)
Now everything under the declaration of that variable, will be able to access it as long as they belong to the parent scope.
You also have another problem on line 8, where you try and assign a tuple of numbers instead of a Color3
value. You're actually only assigning ambient to 154, due to how multiple assignment works in Lua. For example:
local a, b, c = 1, 2, 3 -- > a = 1, b = 2, c = 3 local a, b = 1, 2, 3 -- > a = 1, b = 2, nothing = 3 local a = 1, 2, 3 -- > a = 1, nothing = 2, nothing = 3
As you can see, assignment is completely dependent on order.
What you want is a Color3 value to group these RGB components. Here's a quick correction: game.Lighting.Ambient = Color3.fromRGB(154, 38, 255)
. Hope this helped, let me know if you have any questions.