[ prev | next | top ]

## 13. Expressions, Variables, and Assignment

A number is a valid expression, of course (all numbers are stored internally as floating-point). Decimal-point notation is acceptable; in GNU gpic, scientific notation in C’s ‘e’ format (like `5e-2`) is accepted.

Anywhere a number is expected, the language also accepts a variable. Variables may be the built-in style variable described in the last section, or new variables created by assignment.

DWB pic supports only the ordinary assignment via =, which defines the variable (on the left side of the equal sign) in the current block if it is not already defined there, and then changes the value (on the right side) in the current block. The variable is not visible outside of the block. This is similar to the C programming language where a variable within a block shadows a variable with the same name outside of the block.

GNU gpic supports an alternate form of assignment using :=. The variable must already be defined, and the value is assigned to that variable without creating a variable local to the current block. For example, this

    x=5
    y=5
    [
      x:=3
      y=3
    ]
    print x " " y

prints 3 5.

You can use the height, width, radius, and x and y coordinates of any object or corner in expressions. If A is an object label or name, all the following are valid:

    A.x                  # x coordinate of the center of A
    A.ne.y               # y coordinate of the northeast corner of A
    A.wid                # the width of A
    A.ht                 # and its height
    2nd last circle.rad  # the radius of the 2nd last circle

Note the second expression, showing how to extract a corner coordinate.

Basic arithmetic resembling those of C operators are available; +, *, -, /, and %. So is ^ for exponentiation. Grouping is permitted in the usual way using parentheses. GNU gpic allows logical operators to appear in expressions; ! (logical negation, not factorial), &&, ||, ==, !=, >=, <=, <, >.

Various built-in functions are supported: sin(x), cos(x), log(x), exp(x), sqrt(x), max(x,y), atan2(x,y), min(x,y), int(x), rand(), and srand(). Both exp and log are base 10; int does integer truncation; rand() returns a random number in [0-1), and srand() sets the seed for a new sequence of pseudo-random numbers to be returned by rand() (srand() is a GNU extension).

GNU gpic also documents a one-argument form or rand, rand(x), which returns a random number between 1 and x, but this is deprecated and may be removed in a future version.

The function sprintf() behaves like a C sprintf(3) function that only takes %, %e, %f, and %g format strings.

[ prev | next | top ]