Created
October 22, 2014 15:46
-
-
Save johnmyleswhite/bb184e2fb202b262ef35 to your computer and use it in GitHub Desktop.
Pausable Loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# TODO: Need different behavior for the REPL | |
function set_stdin_mode!(raw::Bool) | |
res = ccall( | |
:jl_tty_set_mode, | |
Int32, | |
(Ptr{Void}, Int32), | |
STDIN.handle, | |
int32(raw) | |
) | |
return res != -1 | |
end | |
function has_input() | |
start_reading(STDIN) | |
Base.process_events(false) | |
stop_reading(STDIN) | |
return nb_available(STDIN) > 0 | |
end | |
get_input() = readavailable(STDIN) | |
# Mutate state over body of a early-terminated loop | |
x = 0 | |
set_stdin_mode!(true) | |
for i in 1:100 | |
# Original body of loop | |
println(i) | |
x -= 1 | |
sleep(0.1) | |
# Pause logic | |
abort_signal = false | |
if has_input() && get_input() == "p" | |
@printf("Press 'c' to continue.\n") | |
@printf("Press 'a' to abort.\n") | |
while true | |
if has_input() | |
input = get_input() | |
if input == "c" | |
break | |
elseif input == "a" | |
abort_signal = true | |
break | |
end | |
end | |
end | |
end | |
if abort_signal | |
break | |
end | |
end | |
set_stdin_mode!(false) | |
println(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment