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

Run a program on background using coroutine

Started by Meni, 03 May 2013 - 05:59 PM
Meni #1
Posted 03 May 2013 - 07:59 PM
Hello, im having trouble to run a program on the background. Here is my program:


rednet.open("bottom")
modem=peripheral.wrap("bottom")
mag=peripheral.wrap("mag card reader_2")
pass="ilovecows4ever"
function open()
local modem = peripheral.wrap('bottom')
modem.transmit(1,1,'open')
end
function read() e,w=os.pullEvent("mag_swipe"); return w end
while true do  w=read() or false; if w==pass then open() end
end
BUT i want to do this using coroutine so i can stop it when i want.
Espen #2
Posted 04 May 2013 - 04:02 AM
You don't need a coroutine if you just want to be able to stop the program.
I've removed some redundancy and added a stop key to it ("q"):
local modem = peripheral.wrap("bottom")
local mag   = peripheral.wrap("mag card reader_2")
local pass  = "ilovecows4ever"

function open()
  modem.transmit(1, 1, 'open')
end

while true do
  local e, w = os.pullEvent();

  if e == "char" and w == "q" then break end
  if e == "mag_swipe" and w == pass then
    open()
  end
end
Meni #3
Posted 04 May 2013 - 12:25 PM
You don't need a coroutine if you just want to be able to stop the program.
I've removed some redundancy and added a stop key to it ("q"):
local modem = peripheral.wrap("bottom")
local mag   = peripheral.wrap("mag card reader_2")
local pass  = "ilovecows4ever"

function open()
  modem.transmit(1, 1, 'open')
end

while true do
  local e, w = os.pullEvent();

  if e == "char" and w == "q" then break end
  if e == "mag_swipe" and w == pass then
	open()
  end
end
But it stop the shell until break, i`d like to run the program in multitasking. So in another program i have:

function MagSwipe() shell.run("mag_program") end
mag=coroutine.create(MagSwipe)
coroutine.resume(mag)
-- More code.....
Espen #4
Posted 05 May 2013 - 05:25 PM
Ok, if you want to run it parallel to the shell, then you'll have to start the program together with the shell.
In order to do that you can make use of [topic='5651']NeverCast's Top Level Coroutine Override code[/topic] which will terminate the parent shell and let you start all kinds of programs in parallel (like your magcard program + the shell).

So just take the code (but remove the break-condition for when q is pressed) and save it as a file.
Then modify [topic='5651']NeverCast's injection program[/topic] by adding the path of the mag program from the previous step to it (look right at the top for "loadPool").
Whenever you now run the injection program it will terminate the shell and start it right up again in parallel with the mag program (which will be running in the background).