This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
GlassOS's profile picture

Multi-Talking?

Started by GlassOS, 27 June 2014 - 12:47 PM
GlassOS #1
Posted 27 June 2014 - 02:47 PM
Hey Ive been messing around with loa for about 2 years (never got deep though) and I was wondering if it was possible to run lets say two programs at once so one does


while true do
  os.pullEvent(0 = os.pullEventRaw()
  print("Press Any Key To Continue")
  os.pullEvent("key")
end
and the other something completely different these are just examples!
theoriginalbit #2
Posted 27 June 2014 - 02:49 PM
Yes it is definitely possible. it is an advanced topic in Lua, so just know that when you go in. there's a good tutorial on coroutines here. I feel I should point out to you to be aware that programs (as well as computers) in ComputerCraft/Lua never run concurrently. one has focus, and the next will not run until the current one has yielded.
GlassOS #3
Posted 27 June 2014 - 04:01 PM
Yes it is definitely possible. it is an advanced topic in Lua, so just know that when you go in. there's a good tutorial on coroutines here. I feel I should point out to you to be aware that programs (as well as computers) in ComputerCraft/Lua never run concurrently. one has focus, and the next will not run until the current one has yielded.
Hey Thanks alot
0099 #4
Posted 27 June 2014 - 09:45 PM
You can, of course, use coroutines, but in CC, coroutines are used by CraftOS itself. It means, you can use "parallel API" to do such things. There's only 2 functions in this API. parallel.waitForAny(…) runs all its arguments (functions), but stops them all when one of them finishes. parallel.waitForAll(…) runs its arguments until they all finish, and only then your main program continues (the main program is the program that called parallel.waitForAll).

But I also strongly recommend you to study coroutines, I find them useful, not for multitasking, but to do some things more simple. Typical example: you're running a bunch of loops, like:

for x=1,10 do
for y=1,10 do
  while f(x, y) do
   for z=1,10 do
	-- do something
   end
  end
end
end
And if something happens inside, you want to quickly jump out of all loops. You can make an if-break structure in each loop, or you can do this:

cf = function()
-- all that loops
  coroutine.yield(x, y, z)
-- a bunch of ends
end
c = coroutine.create(cf)
repeat
status, x, y, z = coroutine.resume(c)
if status == false then error() end
-- do something
until <your condition>
Edited on 27 June 2014 - 08:18 PM