os.sleep

From ComputerCraft Wiki
Revision as of 13:12, 29 July 2013 by Daniel-Dane (Talk | contribs)

Jump to: navigation, search


Grid Redstone.png  Function os.sleep
Pauses the computer for a number of seconds. Fractions of a second are supported, but only down to a game tick, or 1/20 of a second (0.05s). Times are rounded up to the next tick, so os.sleep(1.01) and os.sleep(1.05) both wait for 1.05 seconds. You can also use sleep( timeout ).
Syntax os.sleep(timeout)
Returns nil
Part of ComputerCraft
API OS

Examples

Grid paper.png  Example
Pause for 3 seconds.
Code
os.sleep( 3 )


Concerns when using events

The implementation of the sleep function is as follows:

function sleep( _nTime )
    local timer = os.startTimer( _nTime )
	repeat
		local sEvent, param = os.pullEvent( "timer" )
	until param == timer
end

If you are using events and the sleep function at the same time, you may notice events received during the sleep never firing. The sleep function continually loops, emptying the event queue, until the timer event fires. If you still want to sleep, you should create your own sleep function which takes care of the events while sleeping. One such function would be:

-- Replacement for sleep(s), which passes on events instead of dropping them
function wait(s)
    local timer = os.startTimer(s)
    while true do
        local event = {os.pullEvent()}
        if (event[1] == "timer" and event[2] == timer) then
            break
        else
            processMeessages(event)
        end
    end
end