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

Running a function every certain amount of seconds?

I wanted to make this function run every 5 hours. It basically just clears parts in the workspace. I tried setting the wait to a lower number and it didn't work. Also, I'm pretty sure this isn't an efficient way to write this script. Could anyone help me out here?

function CleanParts()
	local w = workspace:GetChildren()
	for i,v in pairs(w) do
		if v:IsA("BasePart") then
			_G.SendMessage("All building materials are being cleaned.")
			v:Destroy()
		end
	end
end

while wait(18000) do
	CleanParts()
end

1 comment

0

You would multiple the amount of seconds in an hour by the amount of hours you wish for it to run for. (HoursInSecond x 5) However, I can't confirm if this'll work, although I do know that to get the amount of seconds in an hour, you multiple 60 seconds by 60 minutes, so that would probably be the case.

1 answer

✓ Accepted answer

####Recursion

Recursion is a term for calling a function inside of itself. If you want to iterate through every descendant and "clean" it then you must recurse-iterate through the workspace.

Here is what recurstion looks like:

function a(b)
	if b < 10 then
		return a(b+1)
	else
		return b 
	end
	wait();
end

local val = 1;
val = a(val);

print(val);

Function a recursed upon the given input, value b until b was equal to 10.

Here's how you can apply this to your code.

###Code

local sm = _G.SendMessage

function CleanParts(m)
	for _,v in pairs(m:GetChildren()) do
		if v:IsA("BasePart") then
			sm("All building materials are being cleaned.")
			v:Destroy()
		else
			if #v:GetChildren() > 0 then
				CleanParts(v)
			end
		end
	end
end

local t = 60*60*5

while wait(t) do
    CleanParts(workspace)
end

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