Next: , Previous: , Up: Scripting   [Contents][Index]


2.4.2 Scripts

Now that we can schedule tasks, let’s take things to the next level. It sure would be great if we could make procedures that described a series of actions that happened over time, especially if we could do so without contorting our code into a nest of callback procedures. This is where scripts come in. With scripts we can write code in a linear way, in a manner that appears to be synchronous, but with the ability to suspend periodically in order to let other scripts have a turn and prevent blocking the game loop. Building on top of the scheduling that agendas provide, here is a script that models a child trying to get their mother’s attention:

(script
  (while #t
    (display "mom!")
    (newline)
    (sleep 60))) ; where 60 = 1 second of real time

This code runs in an endless loop, but the sleep procedure suspends the script and schedules it to be run later by the agenda. So, after each iteration of the loop, control is returned back to the game loop and the program is not stuck spinning in a loop that will never exit. Pretty neat, eh?

Scripts can suspend to any capable handler, not just the agenda. The yield procedure will suspend the current script and pass its “continuation” to a handler procedure. This handler procedure could do anything. Perhaps the handler stashes the continuation somewhere where it will be resumed when the user presses a specific key on the keyboard, or maybe it will be resumed when the player picks up an item off of the dungeon floor; the sky is the limit.

Sometimes it is necessary to abruptly terminate a script after it has been started. For example, when an enemy is defeated their AI routine needs to be shut down. When a script is spawned, a handle to that script is returned that can be used to cancel it when desired.

(define script (script (while #t (display "hey\n") (sleep 60))))
;; sometime later
(cancel-script script)
Procedure: spawn-script thunk

Apply thunk as a script and return a handle to it.

Syntax: script body

Evaluate body as a script and return a handle to it.

Procedure: script? obj

Return #t if obj is a script handle.

Procedure: script-cancelled? obj

Return #t if obj has been cancelled.

Procedure: script-running? obj

Return #t if obj has not yet terminated or been cancelled.

Procedure: script-complete? obj

Return #t if obj has terminated.

Procedure: cancel-script co

Prevent further execution of the script co.

Procedure: yield handler

Suspend the current script and pass its continuation to the procedure handler.

Procedure: sleep duration

Wait duration before resuming the current script.

Procedure: channel-get channel

Wait for a message from channel.

Syntax: forever body

Evaluate body in an endless loop.


Next: , Previous: , Up: Scripting   [Contents][Index]