Continuations

Theory and application

Or try the wikipedia article

Serializeable continuations (applied to our needs), allow code to be 'paused' indefinitely, with the execution state stored on disk, waiting for the user to respond, and continue the game.

It is very hard to write code in a 'callback' style, where each and every user interaction causes another level of nesting to occur. It also can be confusing, since local variables reset, etc.

Continuations solve this problem elegantly, but storing the state to disk, then resuming it later.

Obviously, continuations are subject to the same limitations as normal code - if the code changes while the user is in the middle of something, they will get either messed up, or bounced to the nearest 'checkpoint'. Alternatively, they could run the old version of their module until they move on to the next module.

Thus, modules should 'switch' to each other instead of calling each other, whenever possible.
In a 'switch', the original module disappears from the call stack, and can be upgraded to the latest version. 'Calling', returns control to the original module.

With granular security settings, calling functions with a different clearance represents a security risk. Thus, switching may even be required, not just reccomended.

Additional links

Implementation

While continuations are implemented in many languages (exceptions are kind of a continuation subset), serializeable continuations are very rare.

  • Rhino, a javascript JIT compiler/interpreter for Java, has serializeable continuations.
  • Pluto for Lia, clams to be able to persist Lua threads to disk.
  • JavaFlow Real continuations for Java. If every single class implements Serializeable, you can serialize them also :D.
  • Rife for java A big library with a little bit of continuations. No mention of serialization.
  • JWacs a javascript->javascript transformer for eliminating the callback pattern. Very pre-alpha, seems abandoned. No mention of serialization.
  • NarrativeJS A No mention of serialization.nother javascript-javascript transformer for eliminating callbacks. Now abandoned.

CPS

Continuation-passing style, allows for a subset of continuation behavior, but in itself offers no serialization.

Most javascript-based implementations of continuations translate the source code into a continuation-passing style.

While real continuations mean CPS isn't needed for user interaction, CPS has the advantage of clearing the call stack frequently, which is good for hot-swapping code.
Thus, we should use CPS for moving between modules, but continuations for simplifying in-module logic. Using CPS inside modules would add a ton of complexity to the source code, or make debugging difficult if we use a transformer.

A few articles on CPS: