title: R: Let users use the console while inside a function, record their inputs and react
body: <p>Is it possible to write a function in R which will hold its execution, giving the users control over the console (while in interactive mode of course), meanwhile recording their inputs, and continuing execution either:</p>
  
  <ul>
  <li>after a certain input has been made</li>
  <li>or after a certain output has been made</li>
  <li>or a certain duration of time has passed</li>
  </ul>
  
  <p>Example: ask the user a question (without using <code>readline()</code> for the answer)</p>
  
  <pre><code>question &lt;- function() {
    message("How much is 2 + 2?")
    #let users take control of the console
    #continue to next statement only if they input "2+2", or "4" or a minute has passed
    #meanwhile record their last input similar to ".Last.Value", e.g.:
    startTime &lt;- Sys.time()
    timeout &lt;- FALSE
    lastInput &lt;- lastInput()
    while (eval(parse(text = lastInput)) != 4 &amp; !timeout) {
      if (difftime(Sys.time(), startTime, units = "mins") &gt; 1) {
        timeout &lt;- TRUE
      }
      lastInput &lt;- lastInput()
    }
    if (timeout) {
      stop("Sorry, timeout.")
    } else {
      message("Correct! Let's continue with this function:")
    }
  }
  </code></pre>
  
  <p>Where <code>lastInput()</code> is a function which "listens" to user input when it changes.</p>
  
  <p>Obviously the above structure is tentative and won't give me what I want, some way to "listen" or "observe" and only react when the user inputs something to the console.</p>
  
  <p>The final user experience should be:</p>
  
  <pre><code>&gt; question()
  How much is 2+2?
  &gt; #I'm the user, I can do whatever
  &gt; head(mtcars)
  &gt; plot(1:10)
  &gt; 3
  &gt; 2 + 2
  [1] 4
  Correct! Let's continue with this function:
  </code></pre>
  
  <p>Am I too optimistic or is there some R magic for this?</p>