#Coroutine won't work

32 messages · Page 1 of 1 (latest)

opal phoenix
#

s

glossy atlas
#

If you're just going to immediately resume a coroutine and don't need to pause it for any reason you might as well just use task.spawn

#

Your coroutine is working tho

#

Your while loop's condition is false

#

So it doesn't even begin looping

opal phoenix
glossy atlas
#
local condition = false
while condition do
    print("This will never run")
end
condition = true -- this doesn't start the loop again
#

The program has already passed that point in execution

opal phoenix
stray surgeBOT
#

studio** You are now Level 4! **studio

opal phoenix
#

Under LLight Script

glossy atlas
#

Yeah inside an event (right?) which happens at a future point in time. After the while loop ends.

glossy atlas
glossy atlas
#

An event may fire immediately, or 10 seconds from now, or never.

opal phoenix
glossy atlas
#

Yes and no. While that may solve it temporarily, as soon as your condition becomes false again the loop stops and can't be restarted

#

The easiest solution is to just have an infinite loop, that only executes code when your condition is true.

#
while true do
  if condition then continue end
  print("This will only print when condition is true")
end
#

Although this isn't that performant

#

Limiting the rate of polling (checking) you're doing can make it more performant. But it also reduces the accuracy.

#
while task.wait(0.1) do -- Now we're only checking every 0.1 seconds
  if condition then continue end
  print("CONDITION = TRUE")
end
#

The most optimal solution would just be to break your while loop out into its own function where you can spawn a new loop whenever your condition is true.

opal phoenix
#

this is what I came up with and it works

glossy atlas
#

For example:

local condition = false

local function Operation()
  while condition do
      -- Do some operation while condition is true
  end
end

local function SetCondition(state: boolean?)
  state = if state == nil then (not condition) else state -- Lets you pass in a state or just exclude it to toggle
  if (state == condition) then return end -- condition already equals state
  
  condition = state
  if not condition then return end -- Exit early if our condition is false

  task.spawn(Operation) -- Spawn our operation if state is true
end

Part.Touched:Connect(function ()
  print("Part was touched")
  SetCondition() -- Toggling state of condition
end)
glossy atlas
#

That should be fine

opal phoenix
glossy atlas
#

There are some situations were polling is necessary, but a good rule of thumb is to keep everything event orientated.

glossy atlas