Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Created October 22, 2014 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmyleswhite/bb184e2fb202b262ef35 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/bb184e2fb202b262ef35 to your computer and use it in GitHub Desktop.
Pausable Loops
# 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