Writing with Ink – Runtime Loop

I’ve written an old knock-knock joke into an Ink script to show a basic runtime loop. The logic here is simple: tell a joke three times, but the third time with a different ending.

I define the loop start with an index: joke.

The loop gate has two settings: closed diverts the runtime to the start of the loop, open (or unlocked) allows the runtime to proceed. My start state is closed. On the third try it will open.

CONST punchline = 3 

- (joke) Knock knock! 
+ Who is there? 
- {joke<punchline: 
   Banana. 
   + Banana Who? 
      -> joke 
   - else: 
   Orange. 
   * Orange Who? 
      Orange you glad I didn't say banana? 
}

My conditional test doesn’t use variables, although the loop gate looks as if joke and punchline are variables. Ink is counting how many times the index joke has been seen and comparing it against a constant value called punchline. When joke is less than punchline the loop is closed.

joke<punchline

Things to know:

  • A constant looks like a variable in Ink script, but it isn’t dynamic. At runtime it is replaced with the value it represents. Constants are for scripting convenience.
  • The index cannot be addressed from outside this knot, but leaving and coming back to the knot will preserve the seen count.