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

How do you connect to a function with an argument?

Sorry if this is something really easy to learn, but I just don't get it. I'm trying to connect to my function while passing along the argument for num1.

wait()
player = game.Players.LocalPlayer
MainGUI = script.Parent.ScreenGui
Scroll = MainGUI.ScrollingFrame
RStorage = game:GetService("ReplicatedStorage")
ClassFolder = RStorage.ClassFolder

-- Button List
Class1 = Scroll.Class1
Class1Event = ClassFolder.Class1Event


function mainEvent(num1)
	if num1 == 1 then
		Class1Event:FireServer()
	end
end

Class1.MouseButton1Down:connect(mainEvent(1))

It gives me the error: "Attempt to connect failed: Passed value is not a function" and afterwards "attempt to call a nil value"

The error is line 19

3 comments

0

Why would you want an argument which will be the same forever? Just use variables!

0

I'm pretty new at scripting, how would you do this?

0

Re-read my answer btw

2 answers

✓ Accepted answer

You cannot pass a value through the connection. You have to call the function with a parameter sent in through the parenthesis to send the value.

MainGUI = script.Parent.ScreenGui
Scroll = MainGUI.ScrollingFrame
Class1 = Scroll.Class1

function mainEvent(num)
	if num1 == 1 then 
		Class1Event:FireServer()
	end
end

function passparameter()
	mainEvent(1)
end

Class1.MouseButton1Down:Connect(passparameter)

Also :connect() is deprecated, ROBLOX is case-sensitive so it has to be :Connect()

3 comments

0

I forgot the :FireServer() doesn't require a parameter, only :FireClient() does. Sorry for my mistake.

0

it's ok lol, I didn't use the passparameter

0

Sociallycole, it does not matter on connect's capitalization. roblox simply ignores this.

As @User#18043 mentioned, you can't directly pass arguments, but you can still do this:

Class1.MouseButton1Down:Connect(function() mainEvent(1) end)

If you're going to make multiple connections to MouseButton1Down on multiple, different Classes and want to utilize the same mainEvent function, this would be a solution as you can supply different arguments, such as in the case of GUI TextButtons:

local buttons = YouGui

buttons.FirstButton.MouseButton1Down:Connect(function() mainEvent(1) end)
buttons.SecondButton.MouseButton1Down:Connect(function() mainEvent(2) end)


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