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

Trying to use a loop to connect to a function?

What I am trying to do is have a script that can detect an unlimited^ number of switches inside of a model and connect them to a function when clicked, I have the following script, but it returns the error of Attempt to connect failed: Passed value is not a function

^ Not exactly unlimited but quite high

repeat wait() until workspace.PowerSubstation
local radian = 0.0174533
local degree = 60
local totalr  = degree * radian
if totalr <= 1.0470 or totalr >= 1.0474 then
	warn'Something went wrong!'
end

local function switch(switch)
	if not switch.Type.Value then
		switch.Enabled.Transparency = 0
		switch.Transparency = 1
		switch.Type.Value = not switch.Type.Value
		script["Enabled  Switches"].Value = script["Enabled  Switches"].Value + 1
	elseif switch.Type.Value then
		switch.Enabled.Transparency = 1
		switch.Transparency = 0
		switch.Type.Value = not switch.Type.Value
	    script["Enabled  Switches"].Value = script["Enabled  Switches"].Value - 1
	end
	print(script["Enabled  Switches"].Value)
end

for i,v in pairs(script.Parent.Switches:GetChildren()) do
	v.ClickDetector.MouseClick:connect(switch(v))
end

Any help would be appreciated, thank you!


TheHospitalDev

2 comments

0

You know about the math.rad(degrees) function, right? You don't need your own conversion.

0

Line 15 can just be "else" by itself because bool values only have 2 values.

1 answer

✓ Accepted answer

Your problem is on the connection line. What happens is when you write :connect(switch(v)) is that you are telling the computer connect the event 'MouseClick' to the value returned from 'switch(v)'.

To fix this, we can wrap you switch function in an anonymous function call:

for _, object in ipairs(script.Parent.Switches:GetChildren()) do
	object.ClickDetector.MouseClick:connect(function(playerWhoClicked)
		switch(object)
	end)
end

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