Differences
This shows you the differences between two versions of the page.
Next revision | Previous revisionNext revisionBoth sides next revision | ||
tutorials:advanced:events [2015/05/11 17:31] – created gkazhoya | tutorials:advanced:events [2015/05/11 19:23] – gkazhoya | ||
---|---|---|---|
Line 4: | Line 4: | ||
CRAM has an event protocol that makes the above-mentioned very simple. | CRAM has an event protocol that makes the above-mentioned very simple. | ||
- | The event callback mechanism is based on the notion of hooks of the [[doc/ | + | Code-wise, the event callback mechanism is based on the notion of hooks of the [[doc/ |
- | The protocol itself is defined in the ``cram_plan_knowledge`` package. That is also the package where new types of events and their handlers should be defined. That's why we will work in that package. | + | The protocol itself is defined in the '' |
- | First, load the plan knowledge system and switch to the corresponding Lisp package: | + | In the nutshell, the protocol is pretty trivial: there is a generic function called '' |
+ | |||
+ | So, let's first load the plan knowledge system and switch to its corresponding Lisp package: | ||
<code lisp> | <code lisp> | ||
CL-USER> (asdf: | CL-USER> (asdf: | ||
- | CL-USER> (in-package : | + | CL-USER> (in-package :cram-plan-knowledge) |
</ | </ | ||
Line 48: | Line 50: | ||
</ | </ | ||
- | To trigger the event we simply call the '' | + | To trigger the event we simply call the '' |
<code lisp> | <code lisp> | ||
PLAN-KNOWLEDGE> | PLAN-KNOWLEDGE> | ||
OMG! I just saw a black cat! | OMG! I just saw a black cat! | ||
+ | (NIL) | ||
</ | </ | ||
+ | |||
+ | Now, imagine that we would like to have multiple handlers for the same event. | ||
+ | E.g., in addition to screaming excitedly each time we see a cat, we would also like to count the number of cats seen so far: | ||
+ | |||
+ | <code lisp> | ||
+ | PLAN-KNOWLEDGE> | ||
+ | (defmethod on-event cat-counter ((event cat-appeared-event)) | ||
+ | (incf saw-cats) | ||
+ | (format t " | ||
+ | saw-cats)) | ||
+ | #< | ||
+ | |||
+ | PLAN-KNOWLEDGE> | ||
+ | number of cats seen so far: 1 | ||
+ | OMG! I just saw a black cat! | ||
+ | (1 NIL) | ||
+ | |||
+ | PLAN-KNOWLEDGE> | ||
+ | number of cats seen so far: 2 | ||
+ | OMG! I just saw a black cat! | ||
+ | (2 NIL) | ||
+ | </ | ||
+ | |||
+ | Let's break this down. | ||
+ | |||
+ | * We define a lexical variable '' | ||
+ | * Then we overload our '' |