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

using parallel.waitForAny to run a program until it's finished or key input

Started by remiX, 10 February 2013 - 06:01 AM
remiX #1
Posted 10 February 2013 - 07:01 AM
So I'm trying to using parallel.waitForAny( shell.run('program'), FunctionToReturnWhenAKeyIsPressed ) but it isn't working…

Example:
Main Program:
function test()
	while true do
		_, k = os.pullEvent("key")
		if k == keys.up then return end
	end
end

parallel.waitForAny(shell.run('a'), test )

Program 'a':
i = 1
while true do
	term.setBackgroundColour( 2^(math.random(1, 15)) )
	term.clear()
	i = i + 1
	sleep(1)
	if i == 10 then break end
end

Clicking up does nothing, and when i is 10, it does stop with this error:
parallel:4: bad argument, function expected, got boolean

the shell.run('a') returns false when it returns but why isn't clicking the up arrow working?
tesla1889 #2
Posted 10 February 2013 - 07:03 AM
it only works when the program yields

put a sleep(0.01) in the while loop

oh, and make

parallel.waitForAny(shell.run("a"),test)
this

parallel.waitForAny(function() shell.run("a") end,test)
remiX #3
Posted 10 February 2013 - 07:09 AM
it only works when the program yields

put a sleep(0.01) in the while loop

oh, and make

parallel.waitForAny(shell.run('a'), test )
this

parallel.waitForAny(function() shell.run('a') end, test )

It pulls an event so it doesn't need a sleep(0.01)

BUT Doing this helped ._,
parallel.waitForAny(function() shell.run('a') end, test ) 

Why does that fix it o_O

Thanks xD
tesla1889 #4
Posted 10 February 2013 - 07:11 AM
oh yeah lol. i must be a little off this evening

long day
Orwell #5
Posted 10 February 2013 - 07:20 AM
BUT Doing this helped ._,
parallel.waitForAny(function() shell.run('a') end, test ) 

Why does that fix it o_O
parallel.waitForAny takes function references as arguments. 'test' is a function reference, but shell.run('a') is a function call. So it will actually run the program 'a' and then pass the output from shell.run (which is a boolean) to the waitForAny. "function() … end" creates a reference to a function and therefor can be used. That's also why you can do:

local func = function() print(42) end
You define a function and assign the reference to that function to the variable func.
remiX #6
Posted 10 February 2013 - 08:16 AM
Oh yeah of course you can't call functions inside parallel. Completely forgot about that… Haven't used parallel for a while now and it slipped my mind ,_,

Thanks for jogging my memory :P/>