How to implement multiple infinite loops?

  1. What do you want to achieve?
    I have a bunch of droppers and each dropper has an infinite loop inside it that produces goods every two seconds. I want to make those things happen.

  2. What is the issue?
    But when I trigger a Dropper infinite loop, the code outside the loop will be invalidated. The first Dropper works fine, but the others don’t.

dropper1:Product()-- have loop
dropper2:Product() -- don't work

The inside of the function looks something like

while true do
         print("gooods")
         wait(2)
  1. What solutions have you tried so far?
    I know the problem is not getting out of the first loop, but I don’t have a solution. Please help me. Thank you very much.

You should use coroutines, you can too use spawn() function (you can find description of this function in Roblox Globals) but coroutines are more solid and efficient

5 Likes

spawn() is for simple loops, coroutine is mostly necessary if you’re trying to pause / stop something

1 Like

example

spawn(function()
       while wait() do
             print("yes")
       end
end)

spawn(function()
       while wait() do
             print("yes2")
       end
end)
1 Like

use task.spawn over the global spawn function. Task Library - Now Available!

2 Likes

Yes, task library too have that function but coroutines are still more universal

1 Like

two infinite loops = two scripts . simple right?

1 Like

He means multiple loops inside 1 script

1 Like

I think I have an idea of what you want, you’d probably want to something like this:

local lastDrops = {}

while true do
	for _, dropper in ipairs(...) do
		local now = os.clock()

		local last_drop = lastDrops[dropper]
		if last_drop then
			if now - last_drop < dropper_cooldown then continue end -- if it hasn't reached then cooldown skip over it
			-- keep in mind that the dropper cooldown is in seconds so plan accordingly
		end

		drop(dropper)
		lastDrops[dropper] = now
	end
	task.wait()
end
1 Like