Variables - types, scoping, argument passing – Crunch CRiSP File Editor 6 User Manual

Page 16

Advertising
background image

Page 16

int(pg.
21).

32-bit signed integer.

float(pg.
21).

64-bit floating point value.

string(p
g. 21).

Variable length string.

list(pg.
22).

Arbitrary collection of objects, similar to an array. Lists may contain nested lists, and
can be used like a structure or array.

declare(
pg. 25).

Used to define a polymorphic variable - one that can contain a value of any type.

As well as these primitive data types, CRiSP also supports complex data types(pg. 38). used to refer to
particular instances of objects within the editor.

{button See Also, ALink(crunch,,,)}

Variables - types, scoping, argument passing

CRiSP supports a minimal set of data types necessary to allow sophisticated editing macros to be written.
Crunch requires that all variables to be used be declared before they are used. This is similar to the C
language, and is a useful feature since it avoids bugs being introduced due to spelling errors. The compiler
will complain about references to variables which have not been declared.

Although crunch may be classed as a fairly strongly typed language, it has mechanisms for processing
arbitrary variable types. For example, a macro could be written to return the minimum value of the
arguments passed:

int
min(int a, int b)
{
return a < b ? a : b;
}

This is fine, but doesn't allow the user to write a generic macro which can handle arbitrary variable types.
For example, if two strings were passed, maybe the shortest length string should be returned. This can be
handled by crunch with variables which are called polymorphic. The term polymorphic means that a variable
can have an arbitrary type and value. The type is dependent on its context. Originally, polymorphic variables
were added to facilitate the processing of lists, which are sequences of values of arbitrary type. To write a
more generic min() function, one could write:

declare
min(declare a, declare b)
{
if (typeof(a) != typeof(b)) {
error("Incompatible types.");
return -1;
}
switch (typeof(a)) {
case "integer":
case "float":
return a < b ? a : b;
case "string":
return strlen(a) < strlen(b) ? a : b;
case "list":
return length_of_list(a) < length_of_list(b) ?
a : b;
default:
error("Unknown type");
return -1;
}
}

Because the type of a polymorphic variable may change, CRiSP supports functions for determining the type
of the variable and macros can ensure that they don't attempt to perform an invalid operation.

Advertising