Restart function

Straight to the point, how can I restart a function? The only ideas I’m having of doing it is coroutine, but I really don’t no how. Thanks for any help.

An example code:

local function foo()
	task.wait(1)
	print("foo")
end

foo()

-- Restart function after it ended.
1 Like
local function foo()
	task.wait(1)
	print("foo")
end

foo()
foo()

That’s not it. If that was the case, I could just copy-paste it. But I want it to restart repeatedly and that it could be disconnected any time. For example, using coroutine or connections.

local condition = true
while condition do
    foo()
end

Now when you change the condition to false, the function will stop repeating. One of many examples of use is that you can wrap that loop into a coroutine and then change the condtion outside of the coroutine.

2 Likes

I haven’t tried it this way. I’ll let you know after trying.

local function foobar()
	print("Hello world!")
	if math.random(1, 10) == 1 then --breaking condition
		coroutine.yield(true)
	end
end

while true do
	local routine = coroutine.create(foobar)
	local success, result = coroutine.resume(routine)
	coroutine.close(routine)
	if result then print("End.") break end
	task.wait(1)
end

This creates routines out of the ‘foobar’ function until a particular condition in the ‘foobar’ function is reached.

local function foobar()
	print("Hello world!")
	if condition then
		foobar() --Function recurses if a condition is met otherwise it stops entirely.
	end
end
1 Like

Thank you, that’s the efficient version I was looking for. I appreciate everybody’s help.