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

[lua] run in backround

Started by Beefy547, 11 July 2012 - 06:45 PM
Beefy547 #1
Posted 11 July 2012 - 08:45 PM
I am new to lua and I want to make a script that makes a looping script toggle in the background.

what I want to run in the background-

while true do
redstone.setOutput("back",true )
sleep(120)
redstone.setOutput("back",false )
sleep(30)
end
xuma202 #2
Posted 11 July 2012 - 08:54 PM
Pack it into a function and take a look at coroutine/parallel on the lua help pages/CC wik.
Grim Reaper #3
Posted 11 July 2012 - 10:42 PM
Well, xuma202, that was an awfully simplistic and almost frustrated answer. Here's my go at it:

If you haven't read the wiki, I would definitely suggest it. (Focus on parallels! :)/>/>)

Here is some sample code that would make yours run in the background with the shell (Craft OS):


pulseTick = 0
function redstonePulse()
   if pulseTick == 150 then pulseTick =0; end
   if pulseTick == 0 then
	   redstone.setOutput("back",true )
  -- sleep(120) Try leaving this out so the whole program doesn't pause'
   end
  
   if pulseTick == 120 then
	  redstone.setOutput("back",false )
   -- sleep(30)
   end
end
function runShell()
   shell.run("rom/programs/shell")
end
while true do
  parallel.waitForAny(redstonePulse(), runShell())
  pulseTick = pulseTick+1
end

Now, this code is isn't tested but I believe that it should work.

Hope I helped! B)/>/>
xuma202 #4
Posted 11 July 2012 - 11:07 PM
Sorry I has in a hurry when I posted my 1st answer.

But your're code is not caring of the time and I don't know if the line

pulseTick = pulseTick+1
will ever be called before the program is closed.

I'd suggest this:


function redstonePulse()
on = false
while true do
if on then
redstone.setOutput("back",true
os.startTimer(120)
else
redstone.setOutput("back",false )
os.startTimer(30)
end

os.pullEvent("timer")
on = not on
end


end

function runShell()
shell.run("rom/programs/shell")
end
while true do
parallel.waitForAny(redstonePulse(), runShell())
end


This code is untested
MysticT #5
Posted 11 July 2012 - 11:30 PM
And why don't you leave the function like he had it and just add the parallel code?
Like this:

local function redstonePulse()
  while true do
    redstone.setOutput("back",true )
    sleep(120)
    redstone.setOutput("back",false )
    sleep(30)
  end
end

parallel.waitForAny(redstonePulse, function() shell.run("shell") end)
That should work.
xuma202 #6
Posted 11 July 2012 - 11:53 PM
Hmm. That was to obvious :)/>/>