Log In  


Cart #parallel-0 | 2025-09-23 | Code ▽ | Embed ▽ | No License


I've been playing Computercraft and decided to create a simplified version of its Parallel API for Pico-8. This code introduces two functions: waitforany and waitforall, which lets you run multiple functions in parallel using coroutines.

Actually, the entered functions don't all run at the same time; functions will run in sequence and switch between themselves whenever they yield(). The above cart shows an example usage of both functions.

waitforany()

Takes functions as parameters, and runs each one in parallel.
Returns the index of the first function that finishes.

usage:
waitforany(func1, func2, ...)

code:

function waitforany(...)
 colist = {...}
 for i=1,#colist do
  colist[i] = cocreate(colist[i])
 end

 while true do
  for i=1,#colist do
   assert(coresume(colist[i]))
   if costatus(colist[i])=="dead" then
    return i
   end
  end
 end
end

waitforall()

Takes functions as parameters, and runs each one in parallel.
Returns when all functions have finished running.

usage:
waitforall(func1, func2, ...)

code:

function waitforall(...)
 colist = {...}
 for i=1,#colist do
  colist[i] = cocreate(colist[i])
 end

 local i=0
 while true do
  if (#colist == 0) return
  i+=1
  if (i>#colist) i=1

  assert(coresume(colist[i]))
  if costatus(colist[i])=="dead" then
   deli(colist,i)
   i-=1
  end
 end
end

WARNING

Be sure to pass in the names of functions you want to run in parallel, and not the result of the functions.
waitforany(func1, func2) ✅ right
waitforany(func1(), func2()) ❌ wrong




[Please log in to post a comment]