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

Clock script help?

local go=false;
script.Parent.IsRunning.Changed:connect(function()
	go=script.Parent.IsRunning.Value;
	if go then
		while go do
			wait(1);
			script.Parent.Value=script.Parent.Value-1;
			if script.Parent.IsRunning.Value == false then
				go=false
			end
			if script.Parent.Value<=0 then go=false; end
end end end
)

So for some reason, when the value goes false this script doesn't stop. It changes to true for about 15 seconds, then it goes false for about .5 seconds then goes true again, and this is when it runs twice. So rather than only one second subtracting each second, two does, and then three, and so forth for each time the false and then true value is re-set.

2 comments

0

Excuse the bad indentation and other syntax errors, thanks.

0

You should break the loop using 'break' when the value is false. So, if IsRunning is false then break the while loop.

1 answer

✓ Accepted answer

They way this is currently set up is, to be blunt, quite messy.

I don't usually like while true loops, but in this case I think it is the best (easiest) thing to do. So in every iteration of the loop we want to check if the clock should be running. If it should be then subtract the elapsed time, if not then we should wait until it should run again.

local time = script.Parent.Value

while wait(1) do
	if script.Parent.IsRunning.Value then
		time = time - 1
	else
		script.Parent.IsRunning.Changed:wait()
	end
end

This will work, however there could be a maximum of a 2 second delay between when it is started and stopped (has to wait a whole second, instead of picking up where it left off). To shorten this delay, we can use a smaller wait time. We can use the fact that wait returns the time that the function yielded to subtract it from the current time:

local time = script.Parent.Value

while true do
	local elapsed, _ = wait()
	if script.Parent.IsRunning.Value then
		time = time - elapsed
	else
		script.Parent.IsRunning.Changed:wait()
	end
end

NOTE: The latter example assumes you are using NumberValue and not a IntValue, as an IntValue will simple truncate the number to the ones place (resulting in incorrect values for time).

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