Jump to content

Simple sleep() function


glowdemon1

Recommended Posts

Hi, my suggestion is to implement a simple sleep(time) function, this can be used to delay something in your functions, for instance :

outputChatBox("I have waited 0 seconds") 
sleep(10000) -- Sleep in ms. 
outputChatBox("I have waited 10 seconds") 

I dislike the fact that I have to add timers and such which will eventualy make your code a mess.

Link to comment
function callFunctionWithSleeps(calledFunction, ...) 
    local co = coroutine.create(calledFunction) --we create a thread 
    coroutine.resume(co, ...) --and start its execution 
end 
  
function sleep(time) 
    local co = coroutine.running() 
    local function resumeThisCoroutine() --since setTimer copies the argument values and coroutines cannot be copied, co cannot be passed as an argument, so we use a nested function with co as an upvalue instead 
        coroutine.resume(co) 
    end 
    setTimer(resumeThisCoroutine, time, 1) --we set a timer to resume the current thread later 
    coroutine.yield() --we pause the execution, it will be continued when the timer calls the resume function 
end 
  
-----------example----------- 
  
function pauseExample(a, b, c) 
    outputChatBox("Started the execution. a value: "..tostring(a)) 
    sleep(5000) 
    outputChatBox("Waited 5 seconds. b value: "..tostring(b)) 
    sleep(5000) 
    outputChatBox("Waited 10 seconds, finishing the execution. c value: "..tostring(c)) 
end 
  
callFunctionWithSleeps(pauseExample, 1, 2, 3) 

Not tested, but should work. Keep in mind, however, that this exact implementation won't display errors within the called function, because coroutine.resume returns the error as a string instead of propagating it to the caller.

Edited by Guest
  • Like 3
Link to comment
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...