Skip to content

coroutine

Anthony Headley edited this page Mar 21, 2024 · 2 revisions

coroutine

Coroutines in Lua are detailed on the Lua Documentation page.

In MA3 your plugins are already running within the environment of a coroutine and thus you do not need to .create() or .resume() them. However, you can utilize them as a way to allow long-running plugins to continue to run while allowing the console to also have control by using the .yield() method.

In general, you want your plugin to do its job as quickly as possible, so something like the below code is quite bad:

The Bad

-- **PLEASE DO NOT DO THIS!**
local function main()
  local wakeup = os.clock() + 3 -- wakeup holds the time of 3 seconds in the future

  while os.clock() < wakeup do end -- loop until the current time (os.clock()) is greater than wakeup
  Echo("More than three seconds have passed.")
end

While the above code has the desired effect of delaying for 3 seconds, nothing else on the console can be done until three seconds have expired.

The Good

Instead, we can use coroutine.yield(float:seconds) to give control back to the system for a given amount of time in seconds and then return control to us.

In this case, this code is much better:

local function main()
  local wakeup = 3.0; -- wakeup holds the time in (float) seconds to relinquish control the system.
  coroutine.yield(wakeup);
  Echo("more than three seconds have passed.")
end

In this example, we print a line every 1.5 seconds 3 times.

local function main()
  local count = 0;
  for count = 1, 1, 3 do
    Echo("Iteration " .. count);
    coroutine.yield(1.5); -- wait 1.5 seconds
  end
end

Wait until the show is ready

As of Version 2, you can how yield until the show is in an active state or some number of seconds: coroutine.yield({activeShowstatus=1.0})

a yield will likely not return to your code exactly at the time you requested, but some fraction longer.

Clone this wiki locally