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

How do i reference a value in a for loop for a local function after using :Connect?

I am making a script for a tycoon for when you step on a button. The problem is, I don't know how to put "button" as a parameter so i can reference it in the local function. Heres the code:


local function buy(part)

	--code

end


for _, button in pairs(CollectionService:GetTagged("BuyButtons")) do

	button.Touched:Connect(buy)

end

Any help?

2 answers

✓ Accepted answer
for _, button in pairs(CollectionService:GetTagged("BuyButtons")) do
	button.Touched:Connect(function()
		button.Transparency = 1
	end)
end

Put the function directly on the Connection. Now you can know who is the part. That's make the same effect on your script.

3 comments

1

button.Touched:Connect(function() buy(button) end)

0

You can't send extra parameters with connect, only the parameters given by the function which is why we have to do this

0

are you also able to make "button" as a global variable?

Also if you want you can use a higher-order function (google if u don't know what that is) to do it for you.

local function buy(part)
	return function()
		-- Do something with part
	end
end

button.Touched:Connect(buy(button))

Pls don't tho.

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