Handlers versus functions

The documentation isn’t very clear on the differences between handlers and functions. What are the differences? What are the pros/cons of using either? Are they equivalent but simply force programmers to use a different syntax depending on which was used?

“Handler” is a generic term used in SenseTalk (and other xTalk languages) for a script or subroutine. In other languages, subroutines are often called functions, methods, procedures, or subprograms.

In SenseTalk, a handler can be called as a “command” (the first word in a statement) or as a “function” (as part of an expression). When a handler is called as a function, it is expected to return a value, which becomes the value of the function within the calling expression. When a handler is called as a command, it is usually expected to perform some action but usually not to return a value.

A “to” handler can be called from either a command or a function context. A script (or the “initial handler” of a script that has multiple handlers) is also considered to be a “to” handler, so a script can be called either as a command or as a function. An “on” handler can only be called as a command, and a “function” handler can only be called as a function.

We generally recommend writing “to” handlers, which makes things simpler. Then you can call any handler or script using either the command or function syntax. Some people prefer to use “on” or “function” though, to indicate the intended use of a handler – whether it is mainly intended to perform actions, or to supply a value to the caller.

I hope that helps make the distinction clearer. Fundamentally there is no real difference in what the different types of handlers can do. Any of the three types of handler can perform any sort of actions, and may or may not return a value (if not, the return value is implicitly empty). The only difference is in the type of message (command, function, or either) that the handler will respond to.

Hey Doug–

One quick point of clarification. If a handler does not explicitly return something, “the result” is empty, correct?

That’s right. Anytime a handler runs to completion without explicitly returning something, SenseTalk will treat it the same as though it had ended with “return empty”.

A detail I omitted from my explanation above is this fact: If a value is returned by a handler which was called as a command, that value can be accessed by the “result()” (or “the result”) function on the next line following the call.