Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Running a function every certain amount of seconds?

Asked by 7 years ago
Edited 7 years ago

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
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. TheeDeathCaster 2368 — 7y

1 answer

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

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
Ad

Answer this question