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

How to do a while loop for a function?

Didn't really know how to word the title :P

Anyway, now I can explain what I mean. So, I'm really to make a loop that's stating "if the mouse's button is pressed down, then do this." I'm not sure if there are simpler ways Roblox has made, but these are the ways I've been trying to get around it.

power = script.Parent.Parent:FindFirstChild("Power")
check = false
script.Parent.MouseButton1Down:connect(function()
	check = true
end)

script.Parent.MouseButton1Up:connect(function()
	check = false
end)

while check == true do
	power.Value = power.Value - 0.5
	wait(0.25)
end

But really, it won't even enter the while loop. Any ways on fixing this, or a different way of doing it?

1 answer

This can be solved with a function, example:

power = script.Parent.Parent:FindFirstChild("Power")	--Is this in workspace?
check = false

function RunLoop()
	while (check) do
		if not (check) then
			break
		else
			power.Value = power.Value - 1
			wait(0.5)	--wait(1) takes up one second, so I switched your numbers... :P
		end
	end
end

script.Parent.MouseButton1Down:connect(function()
	check = true
	spawn(RunLoop())	--The spawn() runs the function in a separate loop, to reduce lag.
end)

script.Parent.MouseButton1Up:connect(function()
	check = false
end)

Hope this helps, if not, then maybe the next person will be right... :P Regards, Xetrax

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