title: How to save state and return to a deep C function?
body: <h2>Background</h2>
  
  <p>I am porting an existing C program to work as an online game using Emscripten.</p>
  
  <p>The problem is that Emscripten wants the program to be organised around a single function that is called 60 times a second.  This is okay for the main game loop, except that there are quite a few places where the code displays a set of options and then waits for a key to be pressed to select the option.  This is expressed as a function deep in a calling hierarchy using getch() to wait for a keypress. I find it hard to see how to fit this into the required Emscripten style of a function that runs and then completes.</p>
  
  <h2>Question</h2>
  
  <p>When the code has called a function, which has called a function, which has called a function, is there an easy way of saving the entire state of the callstack so that I can return to the same place at a later time?</p>
  
  <h2>What I've tried</h2>
  
  <ol>
  <li><p>The approach I am currently using is to set a global state variable to indicate my current location and to write all the things on the stack that seem important into static variables.  I then return from all the functions.  To reenter I use the global variable to decide which function to call and which variables to reload from saved data.  However, this involves writing a lot of extra code and is very error-prone.</p></li>
  <li><p>I wondered about using a thread for the game logic and just sending messages from the GUI thread, but the current <a href="http://flohofwoe.blogspot.co.uk/2013/01/multithreading-in-emscripten-with-html5.html">thread API</a> inside Emscripten seems to require me to try and copy all of the game data into a message so this feels like a lot more work for little benefit.</p></li>
  <li><p>Emscripten supports setjmp/longjmp but as far as I understand, this only does half the job.  I think I can use a longjmp to simply return from a deep function back to the upper level, but I don't see anyway that I can use it to later go back to where I was.</p></li>
  </ol>
  
  <p>Any better ideas on how I can do this?</p>