Why It can't run in the order

Posted by Tianxz on Sat 09 Jul 2011 02:33 PM — 4 posts, 21,859 views.

#0
function a()
DoAfter(1,"e")
end

function b()
DoAfter(0.1,"hp")
a()
DoAfter(0.1,"l")
end
The result is
hp then l then e

But I just want to it can run in the order
first:hp
after 1s then: e
then:l

Of course, If I change the DoAfter(0.1,"l") to DoAfter(2,"l"), the result is same I want. If I don't know how long it need to run for function a, how can I correct it? Thank you.


#1
If some Doafter is nested in function a, it will be more complex. I think the important thing is how can let the code run in the order.
USA #2
DoAfter() sets a timer with the delay you specify, and immediately continues with the script. That means that in this script, "hi" is shown first:
DoAfter(0.1, "lol")
DoAfter(0.2, "rofl")
print("hi")

And then as time passes, MUSHclient runs the timers as they're fired, so "lol" would come after 0.1 seconds, and 0.1 seconds after that (i.e. 0.2 seconds from being created) "rofl" would show up.

I'd suggest doing this:
function a(delay)
  DoAfter(delay, "e")
end

function b()
  DoAfter(0.1, "hp")
  a(1.1)
  DoAter(1.2, "l")
end


You could also try using the "wait.lua" module, which uses coroutines to give you a pause mechanism closer to what you expect.

require "wait"

function a()
  Send("e")
end

wait.make(function()
  wait.time(0.1)
  Send("hp")
  wait.time(1)
  a()
  wait.time(0.1)
  Send("l")
end)


Template:post=4956
Please see the forum thread: http://gammon.com.au/forum/?id=4956.
Australia Forum Administrator #3
Twisol is quite right, using the wait module is a much better way of doing it. In fact, you don't even need the second wait.time (0.1) because things will be executed in sequence.

http://www.gammon.com.au/forum/?id=4956

and:

http://www.gammon.com.au/forum/?id=4957