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

Using a Variable that was defined in a function?

Hi, I'm having trouble since I would like to use a variable that I have defined inside a function that I called. Here is an example from my code:

function button()
	local startbutton = Instance.new("ImageButton")
	startbutton.Parent = gui
	startbutton.Name = "StartButton"
	startbutton.Size = UDim2.new(0, 100, 0, 28)
	startbutton.Position = UDim2.new(0, 5, 0, 570)
end

	startbutton.Mousebutton1Click:connect(newfunction)

Now, I can't use the variable startbutton outside of the function, which makes sense since the function is where I defined it. Is there a way to be able to use this variable again? Or are there any workarounds? On a side note, I've already tried using WaitForChild to wait for the new Image Button to appear, and it doesn't seem to be working as it stops the script and nothing happens.

1 comment

0

The "Local" could be the problem make it a regular variable: startbutton instead of local startbutton

1 answer

✓ Accepted answer
local startbutton

function button()
	startbutton = Instance.new("ImageButton")
	startbutton.Parent = gui
	startbutton.Name = "StartButton"
	startbutton.Size = UDim2.new(0, 100, 0, 28)
 	startbutton.Position = UDim2.new(0, 5, 0, 570)
end
button()
startbutton.Mousebutton1Click:connect(newfunction)

now the value of the variable startbutton is assigned witht he function but can be used outside it

1 comment

0

Thanks! This is what I was looking for!

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