While a function pointer points to a function defined in a program, a codeblock is compiled code that can be stored in a variable or property. Codeblocks do not require a separate program; they actually contain code. Codeblocks are another distinct data type that can be stored in variables or properties and passed as parameters, just like function pointers.

Codeblocks are called with the same call operator that functions use, and may receive parameters.

There are two types of codeblocks:

  1. Expression codeblocks

Expression codeblocks return the value of a single expression. Statement codeblocks act like functions; they contain one or more statements, and may return a value.

In terms of syntax, both kinds of codeblocks are enclosed in curly braces ({ }) and

Cannot span multiple lines.

Must start with either two pipe characters (||) or a semicolon (;)

If ; it must be a statement codeblock with no parameters

If || it may be either an expression or statement codeblock

The || are used for parameters to the codeblock, which are placed between the two pipe characters. They may also have nothing in-between, meaning no parameters for either an expression or statement codeblock.

Parameters inside the ||, if any, are separated by commas.

For an expression codeblock, the || must be followed by one and only one expression, with no ; These are valid expression codeblocks:

 {|| false}

 {|| date( )}

 {|x| x * x}

Otherwise, it is a statement codeblock. A statement codeblock may begin with || (again, with or without parameters in-between).

Each statement in a statement codeblock must be preceded by a ; symbol. These are valid statement codeblocks (the first two are functionally the same):

 {; clear}

 {||; clear}

 {|x|; ? x}

 {|x|; clear; ? x}

You may use a RETURN inside a statement codeblock, just like with any other function. (A RETURN is implied with an expression codeblock.) For example,

 {|n|; for i=2 to sqrt(n); if n % i == 0; return false; endif; endfor; return true}

Because codeblocks don’t rely on functions in programs, you can create them in the Command window. For example,

square = {|x| x * x} // Expression codeblock

? square( 4 ) // Displays 16

// A statement codeblock that returns true if a number is prime

p = {|n|; for i=2 to sqrt(n); if n % i == 0; return false; endif; endfor; return true}

? p( 23 ) // Displays true

? p( 25 ) // Displays false

As mentioned previously, curly braces are also used for literal dates and literal arrays. Compare the following:

{10} // A literal array containing one element with the value 10

{10/5} // A literal array containing one element with the value 2

{10/5/97} // A literal date

{||10/5} // An expression codeblock that returns 2