Need to start a function after returning it

I want to start the same function (called routine) with just different numbers in value “newTime” after closing/returning the same function that was already running before. I tried looking it up here on DevForum and tried asking other people I know but I haven’t found anything. Does anybody have any solutions?

Here is the code (it’s in server script which is in Workspace):

-- Services
local WorkSpace = game:GetService("Workspace")
local Players = game:GetService("Players")
-- Values
local lastTime = 0
local newTime = 0

local cd = false
local cTime = 5

Players.PlayerAdded:Connect(function(player)
	local PlayerGUI = player.PlayerGui

	local UI = PlayerGUI:WaitForChild("Times")
	local textButton = UI.TextButton

	textButton.MouseButton1Click:Connect(function()
		while wait() do
			lastTime = os.time() -- USES UTC TIME!!
		end
	end)
end)

for i, part in pairs(WorkSpace:GetChildren()) do
	wait(0.01)
	if part:IsA("Part") and string.match(part.Name, "Detector") then
		part.Touched:Connect(function(hit)
			if cd == false then
				cd = true
				if hit.Parent:FindFirstChild("Humanoid") then
					local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
					-- Date Folder
					local DateFolder = player.DateFolder

					local Year1 = DateFolder.Year
					local Month1 = DateFolder.Month
					local Day1 = DateFolder.Day

					local Hour1 = part.NextStopHour
					local Min1 = part.NextStopMin
					local Sec1 = part.NextStopSec

					function routine()
						while wait() do
							newTime = os.time({
								year=Year1.Value, month=Month1.Value, day=Day1.Value,
								hour=(Hour1.Value - 2), min=Min1.Value, sec=Sec1.Value}) -- USES UTC TIME!!

							local DelayTime = newTime - lastTime
						player.CurrentRoute.Delay.Value = DelayTime
					end
				end
			end
		end
			wait(cTime)
	cd = false

	wait(1)
	part:Destroy()
    end)
  end
end

Thanks for any helpful responses. :slight_smile:

I would normally assign it to a variable which you can then call:

local myfunc = function()
    ...
end

myfunc()

However I think you are able to just do this

function routine()
    ...
end

routine()

Use local function() instead of function() because i dont know if there is any difference

Thanks so much! This worked. :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.