Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Moving an event out of a function makes it not work?

function Response()
	Rpns = Instance.new("TextButton", scrl)
		Rpns.Position = UDim2.new(0, 40,0.78, 0)
		Rpns.Size = UDim2.new(0.75, 0,0, 10)
		Rpns.BackgroundTransparency = 1
		Rpns.Font = 1
		Rpns.FontSize = 4
		Rpns.TextColor3 = Color3.new(255, 0, 0)
		Rpns.AutoButtonColor = false
		Rpns.Text = ("> Bla bla bloo")
end
-- When this block is here it doesn't work
Rpns.MouseButton1Click:connect(function()
	Txt.Text = ("Bla bla bla.")
end)

I have a strange problem where if I move a block of code outside of another function, it doesn't work. In the figure above, if those last three lines of code are there, it doesn't work and gives me the output: attempt to index global 'Rpns' (a nil value).

Yet if I move those last three lines inside of the top function, it works! (see figure below)

function Response()
	Rpns = Instance.new("TextButton", scrl)
		Rpns.Position = UDim2.new(0, 40,0.78, 0)
		Rpns.Size = UDim2.new(0.75, 0,0, 10)
		Rpns.BackgroundTransparency = 1
		Rpns.Font = 1
		Rpns.FontSize = 4
		Rpns.TextColor3 = Color3.new(255, 0, 0)
		Rpns.AutoButtonColor = false
		Rpns.Text = ("> Bla bla bloo")
-- When it is here it does work.
Rpns.MouseButton1Click:connect(function()
	Txt.Text = ("Bla bla bla.")
end)
end

So why is this? Rpns isn't defined as local or anything. Does it have something to do with it being a Textbutton?

1 answer

✓ Accepted answer

Nothing has called Response(), so there's no such thing as Rpns.

If you do

Response()
Rpns.MouseButton1Click:connect(function()
    Txt.Text = ("Bla bla bla.")
end)

It will work. BUT you shouldn't.


It is bad to do this. Global variables are bad. This is true in any language and is almost universally accepted. They are bad because they are confusing in cases precisely like this one!

You can't tell where / when values are coming from.

Instead, make Response return the value you need.

This makes it much easier to think about (and avoids problems like you're having)

function Response()
	local Rpns = Instance.new("TextButton", scrl)
	Rpns.Position = UDim2.new(0, 40,0.78, 0)
	Rpns.Size = UDim2.new(0.75, 0,0, 10)
	Rpns.BackgroundTransparency = 1
	Rpns.Font = 1
	Rpns.FontSize = 4
	Rpns.TextColor3 = Color3.new(255, 0, 0)
	Rpns.AutoButtonColor = false
	Rpns.Text = ("> Bla bla bloo")
	return Rpns;
end

local button = Response()

button.MouseButton1Click:connect(function()
	Txt.Text = ("Bla bla bla.")
end)

1 comment

0

Ah, okay. So the global variable somehow messed it up.

This discussion is preserved as it was. New answers, comments, and votes are closed.