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?
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)