Coroutine feedback needed

Hello, I’ve been using lua for a few years now but I’ve never really dove into coroutines that much and mostly avoided them since with roblox’s task library I never really needed another way to thread my code.
However I’ve tried implementing it recently and the script works but I don’t know if its efficient or if I’m even using it correctly. I’ve placed it in my script for more efficiency.

For example I have a module that has an .enableGui and .disableGui function that both turn visibility on and off. But also I have a loop going that gives this certain gui some animation and this loop is in a coroutine that pauses whenever the gui goes invisible and resumes once its visible. I’m guessing this is more efficient as the only other option would be to place some sort of repeat task.wait() until which I think is quite inefficient or just run the function again which is a bit annoying to handle.

Anyone with good knowledge of coroutines please give some insight. I’ll paste a simple version of my script below

local module = {}

function module.enableGui()
  gui.Visible = true
  coroutine.resume(updateThread)
end

function module.disableGui()
  gui.Visible = false
end

updateThread = coroutine.create(function()
  while task.wait() do
     if gui.Visible then
       -- do animation
     else
       coroutine.yield()
     end
  end
end)

return module

The module should work correctly, although personally for a case like this (playing an animation while a Gui is visible) I’d use GetPropertyChangedSignal to detect when the Visible property changes, and run the animation if it’s true instead of using coroutines, since functions connected to events run in a new thread anyway when the event is fired

BTW one tiny edit you can make to the module is by doing this:

local module = {}

function module.enableGui()
  gui.Visible = true
  coroutine.resume(updateThread)
end

function module.disableGui()
  gui.Visible = false
end

updateThread = coroutine.create(function()
  while true do
     if gui.Visible then
       -- do animation
       task.wait()
     else
       coroutine.yield()
     end
  end
end)

return module

which would allow you to use the delta returned by task.wait for the Gui’s animation, and is also slightly more optimised now since it will switch between yielding using task.wait or coroutine.yield instead of firing both when Visible is false

1 Like