Alphabetical List of All Turing Elements

  • abs - absolute value function
  • addr - address of a variable
  • addressint - type
  • all - all members of a set
  • and - operator
  • anyclass - the ancestor of all classes
  • arctan - arctangent function (radians)
  • arctand - arctangent function (degrees)
  • array - type
  • assert - statement
  • assignability - of expression to variable
  • assignment - statement
  • begin - statement
  • bind - declaration
  • bits - extraction
  • body - declaration
  • boolean - true-false type
  • break - debugger pause statement
  • buttonchoose - switch mouse modes
  • buttonmoved - has a mouse event occurred
  • buttonwait - get a mouse event procedure
  • case - selection statement
  • catenation (+) - joining together strings
  • ceil - real-to-integer function
  • char(n) - type
  • char - type
  • cheat - type cheating
  • checked - compiler directive
  • chr - integer-to-character function
  • class - declaration
  • clock - millisecs used procedure
  • close - file statement
  • cls - clear screen graphics procedure
  • collection - declaration
  • color - text color graphics procedure
  • colorback - background color procedure
  • colour - text color graphics procedure
  • colourback - background color procedure
  • comment - remark statement
  • comparisonOperator
  • Concurrency
  • Concurrency.empty
  • Concurrency.getpriority
  • Concurrency.setpriority
  • Concurrency.simutime
  • condition - declaration
  • Config
  • Config.Display
  • Config.Lang
  • Config.Machine
  • const - constant declaration
  • constantReference - use of a constant
  • cos - cosine function (radians)
  • cosd - cosine function (degrees)
  • date - procedure
  • declaration - create a variable
  • deferred - subprogram declaration
  • delay - procedure
  • Dir
  • Dir.Change
  • Dir.Close
  • Dir.Create
  • Dir.Current
  • Dir.Delete
  • Dir.Get
  • Dir.GetLong
  • Dir.Open
  • div - integer truncating division operator
  • Draw
  • Draw.Arc
  • Draw.Box
  • Draw.Cls
  • Draw.Dot
  • Draw.Fill
  • Draw.FillArc
  • Draw.FillBox
  • Draw.FillMapleLeaf
  • Draw.FillOval
  • Draw.FillPolygon
  • Draw.FillStar
  • Draw.Line
  • Draw.MapleLeaf
  • Draw.Oval
  • Draw.Polygon
  • Draw.Star
  • Draw.Text
  • drawarc - graphics procedure
  • drawbox - graphics procedure
  • drawdot - graphics procedure
  • drawfill - graphics procedure
  • drawfillarc - graphics procedure
  • drawfillbox - graphics procedure
  • drawfillmapleleaf - graphics procedure
  • drawfilloval - graphics procedure
  • drawfillpolygon - graphics procedure
  • drawfillstar - graphics procedure
  • drawline - graphics procedure
  • drawmapleleaf - graphics procedure
  • drawoval - graphics procedure
  • drawpic - graphics procedure
  • drawpolygon - graphics procedure
  • drawstar - graphics procedure
  • empty - condition function
  • enum - enumerated type
  • enumeratedValue - enumerated value
  • eof - end-of-file function
  • equivalence - of types
  • erealstr - real-to-string function
  • Error
  • Error.Last
  • Error.LastMsg
  • Error.LastStr
  • Error.Msg
  • Error.Str
  • Error.Trip
  • ErrorNum
  • Exceptions
  • exit - statement
  • exp - exponentiation function
  • explicitCharConstant - character literal
  • explicitConstant - literal
  • explicitIntegerConstant - integer literal
  • explicitRealConstant - real literal
  • explicitStringConstant - string literal
  • explicitTrueFalseConstant - boolean literal
  • expn - expression
  • export - list
  • external - declaration
  • false - boolean value (not true)
  • fetcharg - fetch argument function
  • File
  • File.Copy
  • File.Delete
  • File.DiskFree
  • File.Exists
  • File.Rename
  • File.Status
  • flexible - array initialization
  • floor - real-to-integer function
  • Font
  • Font.Draw
  • Font.Free
  • Font.GetName
  • Font.GetSize
  • Font.GetStyle
  • Font.Name
  • Font.New
  • Font.Sizes
  • Font.StartName
  • Font.StartSize
  • Font.Width
  • for - statement
  • fork - statement
  • forward - subprogram declaration
  • frealstr - real-to-string function
  • free - statement
  • function - declaration
  • functionCall
  • get - file statement
  • getch - get character procedure
  • getchar - get character function
  • getenv - get environment function
  • getpid - get process id function
  • getpriority - function
  • GUI
  • GUI.AddLine
  • GUI.AddText
  • GUI.Alert
  • GUI.Alert2
  • GUI.Alert3
  • GUI.AlertFull
  • GUI.Choose
  • GUI.ChooseFull
  • GUI.ClearText
  • GUI.CloseWindow
  • GUI.CreateButton
  • GUI.CreateButtonFull
  • GUI.CreateCanvas
  • GUI.CreateCanvasFull
  • GUI.CreateCheckBox
  • GUI.CreateCheckBoxFull
  • GUI.CreateFrame
  • GUI.CreateHorizontalScrollBar
  • GUI.CreateHorizontalScrollBarFull
  • GUI.CreateHorizontalSlider
  • GUI.CreateLabel
  • GUI.CreateLabelFull
  • GUI.CreateLabelledFrame
  • GUI.CreateLine
  • GUI.CreateMenu
  • GUI.CreateMenuItem
  • GUI.CreateMenuItemFull
  • GUI.CreatePicture
  • GUI.CreatePictureButton
  • GUI.CreatePictureButtonFull
  • GUI.CreatePictureRadioButton
  • GUI.CreatePictureRadioButtonFull
  • GUI.CreateRadioButton
  • GUI.CreateRadioButtonFull
  • GUI.CreateTextBox
  • GUI.CreateTextBoxFull
  • GUI.CreateTextField
  • GUI.CreateTextFieldFull
  • GUI.CreateVerticalScrollBar
  • GUI.CreateVerticalScrollBarFull
  • GUI.CreateVerticalSlider
  • GUI.Disable
  • GUI.Dispose
  • GUI.Draw...
  • GUI.Enable
  • GUI.FontDraw
  • GUI.GetCheckBox
  • GUI.GetEventTime
  • GUI.GetEventWidgetID
  • GUI.GetEventWindow
  • GUI.GetHeight
  • GUI.GetMenuBarHeight
  • GUI.GetScrollBarWidth
  • GUI.GetSliderValue
  • GUI.GetText
  • GUI.GetVersion
  • GUI.GetWidth
  • GUI.GetX
  • GUI.GetY
  • GUI.Hide
  • GUI.HideMenuBar
  • GUI.OpenFile
  • GUI.OpenFileFull
  • GUI.Pic...
  • GUI.ProcessEvent
  • GUI.Quit
  • GUI.Refresh
  • GUI.SaveFile
  • GUI.SaveFileFull
  • GUI.SelectRadio
  • GUI.SetActive
  • GUI.SetBackgroundColor
  • GUI.SetBackgroundColour
  • GUI.SetCheckBox
  • GUI.SetDefault
  • GUI.SetDisplayWhenCreated
  • GUI.SetKeyEventHandler
  • GUI.SetLabel
  • GUI.SetMouseEventHandler
  • GUI.SetNullEventHandler
  • GUI.SetPosition
  • GUI.SetPositionAndSize
  • GUI.SetScrollAmount
  • GUI.SetSelection
  • GUI.SetSize
  • GUI.SetSliderMinMax
  • GUI.SetSliderReverse
  • GUI.SetSliderSize
  • GUI.SetSliderValue
  • GUI.SetText
  • GUI.SetXOR
  • GUI.Show
  • GUI.ShowMenuBar
  • handler - exception handler
  • hasch - has character function
  • id - (identifier) name of an item in a program
  • #if - used for conditional compilation
  • if - statement
  • implement by - clause
  • implement - clause
  • import - list
  • in - member of a set
  • include - source files
  • index - find pattern in string function
  • indexType
  • indirection - operator (@)
  • infix - operator
  • inherit - inheritance clause
  • init - array initialization
  • Input
  • Input.getch
  • Input.getchar
  • Input.hasch
  • Input.KeyDown - get keyboard state
  • Input.Pause - pause for keystroke
  • int - integer type
  • intn - n-byte integer type
  • intreal - integer-to-real function
  • intstr - integer-to-string function
  • invariant - assertion
  • Joystick
  • Joystick.GetInfo
  • Keyboard
  • length - of a string function
  • Limits
  • ln - natural logarithm function
  • locate - procedure
  • locatexy - graphics procedure
  • loop - statement
  • lower - bound
  • Math
  • max - maximum function
  • maxcol - maximum column function
  • maxcolor - graphics function
  • maxcolour - graphics function
  • maxint - maximum integer function
  • maxnat - maximum natural number function
  • maxrow - maximum row function
  • maxx - graphics function
  • maxy - graphics function
  • min - minimum function
  • minint - minimum integer function
  • minnat - minimum natural number function
  • mod - modulo operator
  • module - declaration
  • monitor - declaration
  • Mouse
  • Mouse.ButtonChoose
  • Mouse.ButtonMoved
  • Mouse.ButtonWait
  • Mouse.Where
  • mousewhere
  • Music
  • Music.Play
  • Music.PlayFile
  • Music.PlayFileStop
  • Music.Sound
  • Music.SoundOff
  • named - type
  • nargs - number of arguments
  • nat - natural number type
  • natn - n-byte natural number type
  • natreal - natural number to real function
  • natstr - natural-number-to-string function
  • Net
  • Net.BytesAvailable
  • Net.CharAvailable
  • Net.CloseConnection
  • Net.HostAddressFromName
  • Net.HostNameFromAddress
  • Net.LineAvailable
  • Net.LocalAddress
  • Net.LocalName
  • Net.OpenConnection
  • Net.OpenURLConnection
  • Net.TokenAvailable
  • Net.WaitForConnection
  • new - statement
  • nil - pointer to a collection
  • not - true/false (boolean) operator
  • objectclass - of a pointer
  • opaque - type
  • open - file statement
  • or - operator
  • ord - character-to-integer function
  • parallelget - parallel port function
  • parallelput - parallel port procedure
  • paramDeclaration - parameter declaration
  • pause - statement
  • PC
  • PC.ParallelGet
  • PC.ParallelPut
  • pervasive - declaration modifier
  • Pic
  • Pic.Blend
  • Pic.Blur
  • Pic.Draw
  • Pic.DrawFrames
  • Pic.DrawFramesBack
  • Pic.DrawSpecial
  • Pic.DrawSpecialBack
  • Pic.FileNew
  • Pic.FileNewFrames
  • Pic.Flip
  • Pic.Frames
  • Pic.Free
  • Pic.Height
  • Pic.Mirror
  • Pic.New
  • Pic.Rotate
  • Pic.Save
  • Pic.Scale
  • Pic.ScreenLoad
  • Pic.ScreenSave
  • Pic.SetTransparentColor
  • Pic.SetTransparentColour
  • Pic.Width
  • play - procedure
  • playdone - function
  • pointer - type
  • post - assertion
  • pre - assertion
  • precedence - of operators
  • pred - predecessor function
  • prefix - operator
  • procedure - declaration
  • procedureCall - statement
  • process - declaration
  • program - a (main) program
  • put - statement
  • quit - fail statement
  • Rand
  • Rand.Int
  • Rand.Next
  • Rand.Real
  • Rand.Reset
  • Rand.Seed
  • Rand.Set
  • rand - random real number procedure
  • randint - random integer procedure
  • randnext - procedure
  • randomize - procedure
  • randseed - procedure
  • read - file statement
  • real - the real number type
  • realn - n-byte real number type
  • realstr - real-to-string function
  • record - type
  • register - use machine register
  • rem - remainder operator
  • repeat - make copies of string:function
  • result - statement
  • return - statement
  • RGB
  • RGB.AddColor
  • RGB.AddColour
  • RGB.GetColor
  • RGB.GetColour
  • RGB.maxcolor
  • RGB.maxcolour
  • RGB.SetColor
  • RGB.SetColour
  • round - real-to-integer function
  • scalar - type
  • seek - (file) statement
  • self - pointer to current object
  • separator - between tokens in a program
  • set - type
  • setConstructor
  • setpriority - procedure
  • setscreen - graphics procedure
  • shl - shift left operator
  • shr - shift right operator
  • sign - function
  • signal - wake up a process statement
  • simutime - simulated time function
  • sin - sine function (radians)
  • sind - sine function (degrees)
  • sizeof - size of a type
  • sizepic - graphics function
  • skip - used in get statement
  • skip - used in put statement
  • sound - statement
  • Sprite
  • Sprite.Animate
  • Sprite.ChangePic
  • Sprite.Free
  • Sprite.Hide
  • Sprite.New
  • Sprite.SetFrameRate
  • Sprite.SetHeight
  • Sprite.SetPosition
  • Sprite.Show
  • sqrt - square root function
  • standardType
  • statement
  • statementsAndDeclarations
  • Str
  • Stream
  • Stream.eof
  • Stream.Flush
  • Stream.FlushAll
  • string - type
  • string - comparison
  • strint - string-to-integer:function
  • strintok - string-to-integer:function
  • strnat - string to natural number function
  • strnatok - string to natural number function
  • strreal - string-to-real function
  • strrealok - string-to-real function
  • subprogramHeader
  • subprogramType
  • subrangeType
  • substring - of another string
  • succ - successor function
  • Sys
  • Sys.Exec
  • Sys.FetchArg
  • Sys.GetComputerName
  • Sys.GetEnv
  • Sys.GetPid
  • Sys.GetUserName
  • Sys.Nargs
  • sysclock - millisecs used procedure
  • system - statement
  • tag - statement
  • takepic - graphics procedure
  • tell - file statement
  • Text
  • Text.Cls
  • Text.Color
  • Text.ColorBack
  • Text.Colour
  • Text.ColourBack
  • Text.Locate
  • Text.LocateXY
  • Text.maxcol
  • Text.maxrow
  • Text.WhatCol
  • Text.WhatColor
  • Text.WhatColorBack
  • Text.WhatColour
  • Text.WhatColourBack
  • Text.WhatRow
  • Time
  • Time.Date
  • Time.DateSec
  • Time.Delay
  • Time.Elapsed
  • Time.ElapsedCPU
  • Time.PartsSec
  • Time.Sec
  • Time.SecDate
  • Time.SecParts
  • time - time of day as a string procedure
  • token - in input
  • true - boolean value (not false)
  • type - declaration
  • TypeConv
  • typeSpec - type specification
  • unchecked - compiler directive
  • union - type
  • unit - file containing module, monitor, or class
  • unqualified - export
  • upper - bound
  • var - declaration
  • variableReference - use of a variable
  • View
  • View.ClipAdd
  • View.ClipOff
  • View.ClipSet
  • View.maxcolor
  • View.maxcolour
  • View.maxx
  • View.maxy
  • View.Set
  • View.Update - flicker-free animation
  • View.WhatDotColor
  • View.WhatDotColour
  • wait - block a process statement
  • wallclock - seconds since 1/1/1970 procedure
  • whatcol - cursor position function
  • whatcolor - text color graphics function
  • whatcolorback - color of background function
  • whatcolour - text color graphics function
  • whatcolourback - color of background function
  • whatdotcolor - graphics function
  • whatdotcolour - graphics function
  • whatrow - cursor position function
  • Window
  • Window.Close
  • Window.GetActive
  • Window.GetPosition
  • Window.GetSelect
  • Window.Hide
  • Window.Open
  • Window.Select
  • Window.Set
  • Window.SetActive
  • Window.SetPosition
  • Window.Show
  • Window.Update
  • write - file statement
  • xor - exclusive "or" operator


abs

abs absolute value function

Syntax abs (expn)

Description The abs function is used to find the absolute value of a number (the expn). For example, abs (-23) is 23.

Example This program outputs 9.83.

        var x : real := -9.83
        put abs (x) % Outputs 9.83
Execute

Details The abs function accepts numbers that are either int's or real's. The type of the result is the same type as the accepted number. The abs function is often used to see if one number x is within a given distance d of another number y; for example:

if abs (x - y) <= d then …

See also predefined unit Math.


addr

addr address of a variable

Syntax addr (reference)

Description The addr attribute is used to find the integer address of a variable or non scalar constant. This is implementation-dependent. This address may be used in an indirection operation @.

Example Set a to be the address of x.

        var x : real
        var a : addressint := addr (x)
Details The value of the address produced by addr is of type addressint, an integer type whose range is that of the underlying memory addresses.

The concept of an address is implementation-dependent. For example, an optimizing compiler could determine that a variable does not require space because the program could be computed without the variable with no change in output. However, in most implementations, types have a predictable size and variables of that type occupy that number of bytes in memory.

See also the indirection operator @, cheat, explicitIntegerConstant (how to write hexadecimal constants), and pointer type (in particular unchecked pointer type). See also sizeof, which returns the size of a variable.


addressint

addressint type

Syntax addressint

Description The addressint (address integer) type is an integer type whose range of value is the same as that of the underlying computer. This range is, by its nature, implementation-dependent. On 32-bit architectures, it is commonly the same range as nat4 (4-byte natural number).

Example Record r contains three fields, one of which has type char(28). Variable a is an integer whose range of values is the same as the addresses of the underlying computer. This assigns B to the seventh character of a record of type r which is assumed to be located at absolute address a.

        type r :
            record
                i : int
                c28 : char (28)
                c11 : char (11)
            end record
        var a : addressint      % An integer
        …                   % a is assigned an integer value
        r @ (a) . c28 (7) := 'B'        % Use indirection operator @
Details Although addressint is called an integer type, it is commonly equivalent to a natural type such as nat4 (for 32-bit machines).

Be careful not to confuse addressint with pointer types. In low level languages such as assembler and C, addresses and pointers are the same. In Turing, however, a pointer is a high level concept that is more abstract than a machine address. A Turing pointer is a reference to an object, and the representation of this reference depends upon the implementation. In current Turing implementations, pointers (which are by default checked) are represented as a time stamp (a unique number) together with an address. The time stamp is used to make sure that the pointer actually locates an object. There are also unchecked pointers. An unchecked pointer's internal representation is a machine address. You can use type cheats (a dangerous feature) to translate between addressint and unchecked pointers. This is meaningful in current implementations.

See also the indirection operator @, cheat, explicitIntegerConstant (how to write hexadecimal constants), and pointer type (in particular unchecked pointer type). See also addr, which returns the address of a variable.


all

all all members of a set

Syntax setTypeName (all)

Description Given a set type named S, the set of all of the possible elements of S is written S (all).

Example

        type smallSet : set of 0 .. 2
        var x : smallSet := smallSet (all)
                        % Set x contains elements 0, 1 and 2
See also set type for details about sets.


and

and operator

Syntax A and B

Description The and (boolean) operator yields a result of true if, and only if, both operands are true. The and operator is a short circuit operator. For example, if A is false in A and B then B is not evaluated.

Example

        var success : boolean := false
        var continuing := true      % The type is boolean
        …
        continuing := continuing and success
Details The continuing variable is set to true if, and only if, both continuing and success are true. Since Turing uses short circuit operators, once continuing is false, success will not be looked at.

The and operator can also be applied to natural numbers. The result is the natural number that is the bit-wise and of the operands. See nat (natural number).

Example This masks out the everything but the lower two bytes of number.

        var number : nat := 16#ABCD
        var mask : nat := 16#FF
        put number and mask     % Outputs 205 (CD16)
See also boolean (which discusses true/false values), explicitTrueFalseConstant (which discusses the values true and false), precedence and expn (expression).


anyclass

anyclass the ancestor of all classes

Syntax anyclass

Description There is a predefined class called anyclass, which is the root of the expansion tree. All classes that do not have inherit lists are considered to be expansions of anyclass. The main purpose of anyclass is to allow pointers that can locate objects of any class.

Example Here is the declaration of a pointer p that can locate an object of any class.

        var p : pointer to anyclass     % Short form: var p : ^ anyclass
        var q : pointer to stack        % Short form: var q : ^ stack
        new q               % Create a stack object
        p := q              % Legal because p's class
                            % is an ancestor of q's class
Assuming stack is a class, this creates a stack object and places its location in q and p. The compiler will not allow a call to stack's exported subprograms using p directly, as in:

        p -> push (14)      % ILLEGAL!  anyclass has no operations
An assignment from p to q is legal, as in:

        q := p  % Checks that p locates a stack object (or descendant)
This implies a run time check to make sure that p locates an object that is a stack (or a descendant of a stack).

Here is a way to call a subprogram exported from stack using p:

        stack (p) . push (14)   % Checks that p locates a stack object
This checks to see that p locates a stack object (or a descendant) before calling the stack operation push.

Details It is legal to create objects of the class called anyclass, but this is not of much use, because there is nothing you can do with these objects (they have no operations). It is legal to assign these objects to other objects of the same class (anyclass), although this accomplishes nothing.

See also objectclass, which takes a class pointer and produces the class of the object located by the pointer. This is used for testing to determine the class of the object located by a pointer.

See also class. See also export list, import list, inherit list, implement list and implement by list.


arccos

arccos arccosine function (radians)

Syntax arccos (r : real) : real

Description The arccos function is used to find the arc cosine of a value. The result is given in radians. For example, arccos (0.5) is p / 3.

Example This program prints out the arccosine of -1 through 1 in radians.

        for i : -4 .. 4
            const arg := i / 4
            put "Arc cosine of ", arg, " is ",
                arccos (arg), " radians"
        end for
Execute

See also the arcsin and arctan functions for calculating arcsine and arctangent.

the arccosd function which finds the arc cosine of a value with the result given in degrees. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


arccosd

arccosd arccosine function (degrees)

Syntax arccosd (r : real) : real

Description The arccosd function is used to find the arc cosine of an angle given in degrees. For example, arccosd (0.5) is 60.

Example This program prints out the arccosine of values from -1 to 1 in degrees.

        for i : -4 .. 4
            const arg := i / 4
            put "Arc cosine of ", arg, " is ",
                arccosd (arg), " degrees"
        end for
Execute

See also the arcsind and arctand functions for calculating arcsine and arctangent

the arccos function which finds the arc cosine of a value with the result given in radians. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


arcsin

arcsin arcsine function (radians)

Syntax arcsin (r : real) : real

Description The arcsin function is used to find the arc sine of a value. The result is given in radians. For example, arcsin (0.5) is p / 6.

Example This program prints out the arcsine of -1 through 1 in radians.

        for i : -4 .. 4
            const arg := i / 4
            put "Arc sine of ", arg, " is ",
                arcsin (arg), " radians"
        end for
Execute

See also the arccos and arctan functions for calculating arccosine and arctangent.

the arcsind function which finds the arc sine of a value with the result given in degrees. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


arcsind

arcsind arcsine function (degrees)

Syntax arcsind (r : real) : real

Description The arcsind function is used to find the arc sine of an angle given in degrees. For example, arcsind (0.5) is 30.

Example This program prints out the arcsine of values from -1 to 1 in degrees.

        for i : -4 .. 4
            const arg := i / 4
            put "Arc sine of ", arg, " is ",
                arcsind (arg), " degrees"
        end for
Execute

See also the arccosd and arctand functions for calculating arccosine and arctangent

the arcsin function which finds the arc sine of a value with the result given in radians. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


arctan

arctan arctangent function (radians)

Syntax arctan (r : real) : real

Description The arctan function is used to find the arc tangent of a value. The result is given in radians. For example, arctan (1) is p / 4.

Example This program prints out the arctangent of 0 through 3 in radians.

        for i : 0 .. 12
            const arg := i / 4
            put "Arc tangent of ", arg, " is ",
                arctan (arg), " radians"
        end for
Execute

See also the arcsin and arccos functions for calculating arcsine and arccosine

the arctand function which finds the arc tangent of a value with the result given in degrees. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


arctand

arctand arctangent function (degrees)

Syntax arctand (r : real) : real

Description The arctand function is used to find the arc tangent of an angle given in degrees. For example, arctand (0) is 0.

Example This program prints out the arctangent of values from 0 to 3 in degrees.

        for i : 0 .. 12
            const arg := i / 4
            put "Arc tangent of ", arg, " is ",
                arctand (arg), " degrees"
        end for
Execute

See also the arcsind and arccosd functions for calculating arcsine and arccosine

the arctan function which finds the arc tangent of a value with the result given in radians. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


array

array type

Syntax array indexType { , indexType } of typeSpec

Description An array consists of a number of elements. The typeSpec gives the type of these elements. There is one element for each item in the (combinations of) range(s) of the indexType(s). In the following example, the array called marks consists of 100 elements, each of which is an integer.

Example

        var marks : array 1 .. 100 of int
        …
        var sum : int := 0
        for i : 1 .. 100        % Add up the elements of marks
            sum := sum + marks (i)
        end for
Execute

Details In the above example, marks(i) is the i-th element of the marks array. We call i the index or subscript of marks. In Turing, a subscript is surrounded by parentheses, not by square brackets as is the case in the Pascal or C-like languages.

Example The prices array shows how an array can have more than one dimension. This array has one dimension for the year (1988, 1989 or 1990) and another for the month (1 .. 12). There are 36 elements of the array, one for each month of each year.

        var price : array 1988 .. 1990, 1 .. 12 of int
        …
        var sum : int := 0
        for year : 1988 .. 1990     % For each year
            for month : 1 .. 12     % For each month
                sum := sum + price (year, month)
            end for
        end for
Execute

Details Each indexType must contain at least one item. The range 1 .. 0, for example, would not be allowed. Each index type must be a subrange of the integers, characters (the char type), or of an enumerated type, an (entire) enumerated type, the char type, the boolean type, or a named type which is one of these.

Arrays can also be declared in the form

        var a : array 1 .. * of typeSpec := init (…)
The upper bound of a will be computed from the count of the initializing values. Both var and const arrays can be declared this way. An array variable/constant declared with "*" as an upper bound must have an initializing list. Only one dimensional arrays may be declared in this form.

Arrays can be assigned as a whole (to arrays of an equivalent type), but they cannot be compared.

An array can be initialized in its declaration using init. For details, see var and const declarations.

Example In this example, the size of the array is not known until run time.

        var howMany : int
        get howMany
        var height : array 1 .. howMany of real
            …read in all the elements of this array…
        function total (a : array 1 .. * of real) : real
            var sum : real := 0
            for i : 1 .. upper (a)
                sum := sum + a (i)
            end for
            result sum
        end total

        put "Sum of the heights is ", total (height)
Execute

Details The ends of the range of a subscript are called the bounds of the array. If these values are not known until run time, the array is said to be dynamic. In the above example, height is a dynamic array. Dynamic arrays can be declared as variables, as in the case for height. However, dynamic arrays cannot appear inside other types such as records, and cannot be named types. Dynamic arrays cannot be assigned and cannot be initialized using init.

In the above example, upper(a) returns the size of a. See also upper and lower.

In the declaration of an array parameter, the upper bound can be given as an asterisk (*), as is done in the above example. This means that the upper bound is taken from that of the corresponding actual parameter (from height in this example).

You can have arrays of other types, for example arrays of record. If R is an array of records, then R(i).f is the way to access the f field of the i-th element of array R.

Details Arrays can also be made resizeable. This is done using the flexible keyword. The declaration syntax is:

        var name : flexible array indexType { , indexType } of typeSpec
The indices may have compile-time or run-time upper bounds (the lower bound must be compile-time). The upper bounds can be changed by using:

        new name , newUpper1 {,newUpper2}
The existing array entries will retain their values, except that any index made smaller will have the corresponding array entries lost. Any index made larger will have the new array entries uninitialized (if applicable).

Additionally, the upper bound (both in the declaration and the new statement) can be made one less than the lower bound. This effectively makes an array that contains 0 elements. It can later be increased in size with another new.

In the current implementation (2002), with a multi-dimensional array with a non-zero number of total elements, it is a run-time error to change any but the first dimension (unless one of the new upper bounds is one less than the corresponding lower bound, giving 0 elements in the array) as the algorithm to rearrange the element memory locations has not yet been implemented.

Currently, only variables can be declared in this form. There is no flexible array parameter type, although a flexible array can be passed to an array parameter with “*” as the upper bound.

Example In this example, the array is resized to fit the number of elements in the file.

        function getLines (fileName : string) : int
            var f, numLines : int
            var line : string
            open : f, fileName, get
            numLines := 0
            loop
                exit when eof (f)
                get : f, line : *
                numLines += 1
            end loop
            close : f
            result numLines
        end getLines

        procedure readFile (var lines : array 1 .. * of string, fileName : string)
            var f : int
            var line : string
            open : f, fileName, get
            for i : 1 .. upper (lines)
                get : f, lines (i) : *
            end for
            close : f
        end readFile

        var lines : flexible array 1 .. 0 of string
        new lines, getLines ("text.dat")
        readFile (lines, "text.dat")
        for i : 1 .. upper (lines)
            put lines (i)
        end for
Execute

See also init to initialize arrays, flexible to declare resizable arrays and indexType to specify the index of an array.


assert

assert statement

Syntax assert trueFalseExpn

Description An assert statement is used to make sure that a certain requirement is met. This requirement is given by the trueFalseExpn. The trueFalseExpn is evaluated. If it is true, all is well and execution continues. If it is false, execution is terminated with an appropriate message.

Example Make sure that n is positive.

        assert n > 0
Example This program assumes that the textFile exists and can be opened, in other words, that the open will set the fileNumber to a positive stream number. If this is not true, the programmer wants the program halted immediately.

        var fileNumber : int
        open : fileNumber, "textFile", read
        assert fileNumber > 0
Details In some Turing systems, checking can be turned off. If checking is turned off, assert statements may be ignored and as a result never cause termination.


assignability

assignability of expression to variable

Description A value, such as 24, is assignable to a variable, such as i, if certain rules are followed. These rules, given in detail below, are called the assignability rules. They must be followed in assignment statements as well as when passing values to non-var parameters.

Example

        var i : int
        i := 24         % 24 is assignable to i

        var width : 0 .. 319
        width := 3 * i      % 3 * i is assignable to width

        var a : array 1 .. 25 of string
        a (i) := "Ralph"        % "Ralph" is assignable to a(i)

        var name : string (20)
        name := a (i)       % a(i) is assignable to name

        …
        var b : array 1 .. 25 of string
        b := a          % Array a is assignable to b

        type personType :
            record
                age : int
                name : string (20)
            end record
        var r, s : personType
        …
        s := r          % Record r is assignable to s
Details The expression on the right of := must be assignable to the variable on the left. An expression passed to a non-var parameter must be assignable to the corresponding parameter.

An expression is defined to be assignable to a variable if the two root types are equivalent or if an integer value is being assigned to a real variable (in which case the integer value is automatically converted to real). Two types are considered to be equivalent if they are essentially the same type (see equivalence for the detailed definition of this term).

In most cases a root type is simply the type itself. The exceptions are subranges and strings. The root type of a subrange, such as 0 .. 319, is the type of its bounds (int type in this example). The root type of a string, such as the type string(9), is the most general string type, namely string.

When a subrange variable, such as width, is used as an expression, for example on the right side of an assignment statement, its type is considered to be the root type (integer in this case) rather than the subrange. When an expression is assigned to a subrange variable such as width, the value (3*i in this example) must lie in the subrange. Analogously, any string variable used in an expression is considered to be of the most general type of string. When a string value is assigned to a string variable, its length must not exceed the variable's maximum length.

Turing's assignability rule applies to characters and strings in this way. A char value can be assigned (or passed to an non var parameter) with automatic conversion to a char(1) variable and vice versa. String values of length 1 can be assigned to char variables. Character, that is char, values can be assigned to string variables, yielding a string of length 1. String values of length n are assignable with automatic conversion to char(n) variables. Values of type char(n) can be assigned with automatic conversion to string variables.

Turing's assignability rule applies to pointers to classes in this way. A pointer that locates an object created as class E, can be assigned to a pointer to class B only if B is an ancestor of (or the same as) E. For example, a pointer to an object that is a stackWithDepth can be assigned to a pointer to stack, where stackWithDepth is a child of stack, but not vice versa. The pointer nil can be assigned to any pointer variable, but the value nil(C) can only be assigned to a pointer to an ancestor of C.

Objects of classes can be assigned to each other only if both were created as the same class.


assignment

assignment statement

Syntax An assignmentStatement is:

variableReference := expn

Description An assignment statement calculates the value of the expression (expn) and assigns that value to the variable (variableReference).

Example

        var i : int
        i := 24         % Variable i becomes 24
        var a : array 1 .. 25 of string
        a (i) := "Ralph"        % The i-th element of a becomes "Ralph"
        …
        var b : array 1 .. 25 of string
        b := a          % Array b becomes (is assigned) array a
Details The expression on the right of := must be assignable to the variable on the left. For example, in the above, any integer value, such as 24, is assignable to i, but a real value such as 3.14 would not be not assignable to i. Entire arrays, records and unions can be assigned. For example, in the above, array a is assigned to array b. See assignability for the exact rules of allowed assignments.

You cannot assign a new value to a constant (const).

There are short forms that allow you to write assignment statements more compactly. For example,

i := i + 1

can be shortened to

i += 1

In Turing, there are short forms for combining +, = and * with assignment. For example, i *= 2 doubles i.

There are also short forms to allow any binary operator to be combined with assignment. For example, i shl= 2 shifts i by 2 to the left.


begin

begin statement

Syntax A beginStatement is:

begin
statementsAndDeclarations
end

Description A begin statement limits the scope of declarations made within it to the confines of the begin/end block. In Turing, begin is rarely used, because declarations can appear wherever statements can appear, and because every structured statement such as if ends with an explicit end.

Example

        begin
            var bigArray : array 1 .. 2000 of real
            … bigArray will exist only inside this begin statement…
        end
Details In Pascal programs, begin statements are quite common because they are required for grouping two or more statements, for example, to group the statements that follow then. This is not necessary in Turing as where ever you can write a single statement, you can also write several statements.


bind

bind declaration

Syntax A bindDeclaration is:

bind [var] id to variableReference
{ , [var] id to variableReference }

Description The bind declaration creates a new name (or names) for a variable reference (or references). You are allowed to change the named item only if you specify var. You can also bind to named non scalar constants.

While variableReference is bound it does not disappear in the scope.

Example Rename the n-th element of array A so it is called item and then change this element to 15.

        bind var item to A (n)
        item := 15
Details The scope of the identifier (item above) begins with the bind declaration and lasts to the end of the surrounding program or statement (or to the end of the surrounding part of a case or if statement). During this scope, a change to a subscript (n above) that occurs in the variable reference does not change the element to which the identifier refers.

You are not allowed to use bind at the outermost level of the main program (except nested inside statements such as if) or at the outermost level in a module.

You can also optionally use the register keyword to request that the bind be done using a machine register. The syntax for bindDeclaration is actually:

bind [var] [register] id to variableReference
{ , [var] [register] id to variableReference }

In the current (2002) implementation, programs are run interpretively using pseudo-code and the register keyword is ignored.


bits

bits extraction

Syntax bits (expn, subrange)

Description The bits operator is used to extract a sequence of bits from a natural (non-negative) number expression. The bits are numbered from right to left as 0, 1, 2 …

Example Set bits 2 and 1 (third and second from the right) in the variable d to be 01. We first set b to be the bit string 1100.

        type T12 : 1 .. 2           % Use to specify bit range
        var d : nat2 := 2#1100      % Two byte natural number
        % At this point bits(d, T12) = 2#10
        bits (d, T12) := 2#01
        % At this point d = 2#1010
Example Set bit 7 in variable n to be 1. As a result, n will equal 2#10000000.

        var n : nat1 := 0       % A one byte variable set to zero
        bits (n, 7) := 1        % n now contains the pattern 10000000
Details The form of subrange must be one of:

(a) | typeSpec | % Subrange type
(b) | compileTimeIntegerExpression

In form (a) the subrange type specifies a range from L to M (for least and most significant). This is a little confusing because the subrange is written L .. M with L on the left and M on the right, but in a number, the least significant bit is on the right and the most significant is on the left. The subrange type can be either the name of a type, for example T12, or an explicit subrange, for example 3 .. 7. The values in the explicit subrange must be compile time values.

Form (b) represents the range n .. n where n is the non-negative value of the expression. In other words, both L and M equal n. The expression can be any non-negative integer value or natural number value.

If the expression expn is a variable reference, the bits operation can be assigned to, but cannot be passed to, a var parameter. For example, in the above, bits (d, T12) has the value 2#01 assigned to it. For this assignment to be allowed, the expression expn must be a natural number type (nat, nat1, nat2 or nat4).

See also explicitIntegerConstant (for description of constants such as 16#FFFF) and the following functions that convert one type to another in a machine-independent manner: ord, chr, intstr, strint, natstr, and strnat. See also shr and shl (shift right and left).


body

body declaration

Syntax A bodyDeclaration is one of:

(a) | body procedure procedureId
 |  | statementsAndDeclarations
 | end procedureId
(b) | body function functionId
 |  | statementsAndDeclarations
 | end functionId
(c) | body procedure id [(paramDeclaration
 |  |  |  | {, paramDeclaration })]
 |  | statementsAndDeclarations
 | end id
(d) | body function id [ ( [paramDeclaration {,
 |  |  | paramDeclaration } ]) ] : typeSpec
 |  | statementsAndDeclarations
 | end id

Description A body declaration is used to resolve either a forward subprogram or a deferred subprogram.

You declare a procedure or function forward when you want to define its header but not its body. This is the case when one procedure or function calls another, which in turn calls the first. This situation is called mutual recursion. The use of forward is necessary in this case because every item must be declared before it can be used. The forward declaration must be followed by a body declaration for the same procedure or function. For details, see forward declarations.

When a procedure or function in a class is declared to be deferred (or simply exported from the class), it can be resolved or overridden afterward by giving its body further down in that class or in descendant classes. The overriding procedure must use the keyword body. See class or "implement by" for examples.

Details You can specify the parameter and return values of the subprogram in the body declaration. However, the names and types of the parameters and return values must match the initial declaration exactly, or a warning results and the parameter list and return values from the body declaration are ignored.

Example The example given here is part of a complete Turing program that includes an explanation of forward declarations.

        var token : string
        forward procedure expn (var eValue : real)
            import forward term, var token
        … other declarations appear here …
        body procedure expn
            var nextValue : real
            term (eValue)               % Evaluate t
            loop                        % Evaluate { + t}
                exit when token not= "+"
                get token
                term (nextValue)
                eValue := eValue + nextValue
            end loop
        end expn
Execute

Details The syntax of a bodyDeclaration presented above has been simplified by omitting the optional result identifier, import list, pre and post condition and init clause. See procedure and function declarations for descriptions of these omissions.

The "function" or "procedure" token in the declaration is now optional. In other words the following code fragment is legal

        forward procedure p
        …
        body  p
        …
        end p
See also class, forward and implement by


boolean

boolean true-false type

Syntax boolean

Description The boolean type is used for values that are either true or false. These true-false values can be combined by various operators such as or and and.

Example

        var success : boolean := false
        var continuing := true      % The type is boolean
        …
        success := mark >= 60
        continuing := success and continuing
        if continuing then …
Details This type is named after the British mathematician, George Boole, who formulated laws of logic.

The operators for true and false are and, or, xor, =>, and not. For two true/false values A and B, these operators are defined as follows:

A and B is true when both are true
A or B is true when either or both are true
A xor B is true when either but not both are true
A => B (A implies B) is true when both are true or when A is false
not A is true when A is false

The and operator has higher precedence than or, so A or B and C means A or (B and C).

The operators or, and and => are short circuit operators. For example, if A is true in A or B, B is not evaluated.

Details The boolean type can be used as an index to an array.

Example Declaration of an array with boolean index.

        var a : array boolean of int
        a (false) := 10
        a (true) := 20
Details The put and get semantics allow put's and get's of boolean values. true values will be output as "true" and false values will be output as "false". The only legal input values are "true" and "false", which are case sensitive.

See also explicitTrueFalseConstant (which discusses the values true and false), precedence and expn (expression).


break

break debugger pause statement

Syntax break

Description On systems with a debugger, the environment "pauses" when execution reaches the break statement. While "pausing" is environment specific, in general, the program stops execution until the user presses the "Resume" or "Continue" button. While paused, the program variables can be inspected, stack traces done, etc.

Example

        for i : 1 .. 100
            put i
            break
        end for


buttonchoose

buttonchoose switch mouse modes

Syntax buttonchoose (choice : string)

Description The buttonchoose procedure is used to change the mode of the mouse. In Turing, the mouse can either be in "single-button mode" or in "multi-button mode". In "single-button mode" the mouse is treated as a one button mouse. A button is considered pressed when any button is pressed and released only when all buttons have been released.

In Turing, the mouse starts in "single-button mode".

The parameter choice can be one of "singlebutton", "onebutton" (which switch the mouse into "single-button mode") or "multibutton" (which switches the mouse into "multi-button mode").

Example A program that displays the status of the mouse at the top left corner of the screen.

        buttonchoose ("multibutton")
        var x, y, button, left, middle, right : int
        mousewhere (x, y, button)
        left := button mod 10           % left = 0 or 1
        middle := (button - left) mod 100   % middle = 0 or 10
        right := button - middle - left     % right = 0 or 100
        if left = 1 then
            put "left button down"
        end if
        if middle = 10 then
            put "middle button down"
        end if
        if right = 100 then
            put "right button down"
        end if
Execute

See also buttonmoved and buttonwait to get mouse events saved in a queue. See also mousewhere to get the current status of mouse button(s).

See also predefined unit Mouse.


buttonmoved

buttonmoved has a mouse event occurred

Syntax buttonmoved (motion : string) : boolean

Description The buttonmoved function indicates whether there is a mouse event of the appropriate type on the mouse queue. Events are either "up", "down", "updown" or "downup" events (although the "downup" and "updown" are the same event).

The parameter motion must be one of "up", "down", "updown" or "downup". If an event of the type requested is in the queue, buttonmoved returns true. If the event is not in the queue, then buttonmoved returns false.

In "single-button mode" (where the mouse is treated like a one-button mouse), a "down" event occurs whenever all the buttons are up and a button is pressed. An "up" event takes place when the last button is released so that no buttons remain pressed.

In "multi-button mode", a "down" event occurs whenever any button is pressed, and an "up" event occurs whenever any button is released.

Example This program draws random circles on the screen until the user clicks the mouse button, whereupon is starts drawing random boxes. Clicking the mouse button switches between the two.

        var circles: boolean := true
        loop
            var x, y, radius, clr: int
            if buttonmoved ("down") then
                var buttonnumber, buttonupdown : int
                buttonwait ("down", x, y, buttonnumber, buttonupdown)
                circles := not circles
            end if
            randint (x, 0, maxx)
            randint (y, 0, maxy)
            randint (radius, 0, 100)
            randint (clr, 0, maxcolor)
            if circles then
                drawfilloval (x, y, radius, radius, clr)
            else
                drawfillbox (x, y, x + radius, y + radius, clr)
            end if
        end loop
Execute

Example This is an example demonstrating how to check for both character and mouse input at the same time.

        var ch : string (1)
        var x, y, btnnum, btnupdown : int
        loop
            if hasch then
                getch (ch)
                locate (1, 1)
                put "The character entered is a: ", ch
            end if
            if buttonmoved ("down") then
                buttonwait ("down", x, y, btnnum, btnupdown)
                locate (1, 1)
                put "The button was clicked at position: ", x, ", ",y
            end if
        end loop
Execute

Details buttonmoved can be thought of as the mouse equivalent of hasch in that they both check for something in a queue and both return immediately.

See also buttonwait to get mouse events saved in the queue. See also buttonchoose to switch between "single-button mode" and "multi-button mode".

See also predefined unit Mouse.


buttonwait

buttonwait get a mouse event procedure

Syntax buttonwait (motion : string,
var x, y, buttonnumber, buttonupdown : int)

Description The buttonwait procedure gets information about a mouse event and removes it from the queue.

The parameter motion must be one of "up", "down", "updown" or "downup". If an event of the type requested is in the queue, buttonwait returns instantly. If there isn't such an event, buttonwait waits until there is one and then returns (much like getch handles keystrokes).

In "single-button mode" (where the mouse is treated like a one-button mouse), a "down" event occurs whenever all the buttons are up and a button is pressed. An "up" event takes place when the last button is released so that no buttons remain pressed.

In "multi-button mode", a "down" event occurs whenever any button is pressed, and an "up" event occurs whenever any button is released.

The parameters x and y are set to the position of the mouse cursor when the button was pressed. The parameter buttonnumber is set to 1 when in "single-button mode". In "multi-button mode", it is set to 1 if the left button was pressed, 2 if the middle button was pressed, and 3 if the right button was pressed. The parameter buttonupdown is set to 1, if a button was pressed and 0 if a button was released.

Example This program draws lines. It starts a line where the user presses down and continues to update the line while the mouse button is held down. When the button is released, the line is permanently draw and the user can draw another line.

        var x, y, buttonnumber, buttonupdown, buttons : int
        var nx, ny : int
        loop
            buttonwait ("down", x, y, buttonnumber, buttonupdown)
            nx := x
            ny := y
            loop
                drawline (x, y, nx, ny, 0)  % Erase previous line
                exit when buttonmoved ("up")
                mousewhere (nx, ny, buttons)
                drawline (x, y, nx, ny, 1)  % Draw line to position
            end loop
            buttonwait ("up", nx, ny, buttonnumber, buttonupdown)
            drawline (x, y, nx, ny, 2)  % Draw line to final position
        end loop
Execute

Example In the previous example, when the mouse moves, the line is erased by drawing it in white. This erases anything that the line was drawn on top of, including previous lines. A more complete example involving the clicking and dragging of filled rectangles using the mouse is available. In this example, the background is fully restored when the rectangle is moved by using "xor".
Example This is an example demonstrating how to check for both character and mouse input at the same time.

        var ch : string (1)
        var x, y, btnnum, btnupdown : int
        loop
            if hasch then
                getch (ch)
                locate (1, 1)
                put "The character entered is a: ", ch
            end if
            if buttonmoved ("down") then
                buttonwait ("down", x, y, btnnum, btnupdown)
                locate (1, 1)
                put "The button was clicked at position: ", x, ", ",y
            end if
        end loop
Execute

Details buttonwait can be thought of as the mouse equivalent of getch in that they both read something in a queue and both wait until they get the thing they're looking for.

See also buttonwait to see if an appropriate event is in the queue. See also buttonchoose to switch between "single-button mode" and "multi-button mode".

See also predefined unit Mouse.


case

case selection statement

Syntax A caseStatement is:

case expn of
 | { label compileTimeExpn {, compileTimeExpn } :
 |  | statementsAndDeclarations }
 | [ label :
 |  | statementsAndDeclarations ]
end case

Description A case statement is used to choose among a set of statements (and declarations). One set is chosen and executed and then execution continues just beyond end case.

The expression (expn) following the keyword case is evaluated and used to select one of the alternatives (sets of declarations and statements) for execution. The selected alternative is the one having a label value equaling the case expression. If none are equal and there is a final label with no expression, that alternative is selected.

Example Output a message based on value of mark.

        case mark of
            label 9, 10 :   put "Excellent"
            label 7, 8 :        put "Good"
            label 6 :       put "Fair"
            label :     put "Poor"
        end case
Execute

Example Output a message based on value of name.

        case name of
            label "horse", "cow" :  put "Farm animal"
            label "tiger", "lion" : put "Jungle animal"
            label "cat", "dog" :    put "Pet"
            label :         put "Unknown animal"
        end case
Execute

Details The case expression is required to match one of the labels. If it does not, there must be a final label with no expression. Label expressions must have values known at compile time. All label values must be distinct. The case expression and the label values must have the same equivalent type, which must be an integer, char, boolean, an enum type or strings.

Note that there is no way to express a range of values (for example from 5 to 10) in a label. Each individual value must be expressed in the label.


catenation (+)

catenation (+) joining together strings

Syntax A catenation is:

stringExpn + stringExpn

Description Two strings (stringExpns), char or char(n) values can be joined together (catenated) using the + operator.

Example

        var lastName, wholeName : string
        lastName := "Austere"
        wholeName := "Nancy" + "  " + lastName
                % The three strings Nancy, a blank and Austere
                % catenated together to make the string
                % "Nancy  Austere". This string becomes the
                % value of wholeName
Details The length of a string catenation is limited to 255 characters.

Catenation is sometimes called concatenation.

Catenation can also be applied to char and char(n) values. See char and char(n). If either operand, s or t in s + t, is a string or a dynamic char(n) (length not known at compile time), the result type is string. Otherwise (when both s and t are char or non-dynamic char(n)) the result type is char(n).

The result of catenation is considered to be a compile time value if both operands are compile time values.

If both operands have the type char or char(n) neither of which is a dynamic char(n), the result is of type char(n), which is also of a non dynamic type. This allows the creation of very long char(n) values that can effectively span line boundaries using catenation to join lines. If either operand is a dynamic type or a string type, the catenation produces a string, whose length is limited to 255 characters.

See also substrings (for separating a strings into parts), repeat (for making repeated catenations), string type, length, and index (to determine where one string is located inside another).

See also string, char, char(n), explicitStringConstant, explicitCharConstant, substring and length.


ceil

ceil real-to-integer function

Syntax | ceil (r : real) : int
Description | Returns the smallest integer greater than or equal to r.
Details | The ceil (ceiling) function is used to convert a real number to an integer. The result is the smallest integer that is greater than or equal to r. In other words, the ceil function rounds up to the nearest integer. For example, ceil (3) is 3, ceil (2.25) is 3 and ceil (-8.43) is -8.
See also | See also the floor and round functions.


char(n)

char(n) type

Syntax char (numberOfCharacters)

Description Each variable whose type is a char(n) contains exactly n characters.

Example Canadian postal codes contain six characters, for example, M4V 1Y9. This is represented in a char(6) variable:

        var postalCode : char (6) := 'M4V1Y9'
Details Explicit constants for the char(n) type use single quotes as in 'M4V1Y9', as opposed to explicit string constants which use double quotes, as in "Nancy". A single character single quoted character, such as 'A', is considered to have the type char instead of char(n), but since these two types can be assigned to each other and compared to each other, this fact has little consequence.

The type char(n) is generally more difficult to use than the string type, which is favored for most simple programs. The type char(n) has the advantage that it is efficient in terms of both space and time. In particular, it is represented as n bytes in the computer's memory. By contrast, the string type must use extra space (a trailing zero byte in current implementations) to represent the current length and allocates space for the maximum value it can hold.

The form of numberOfCharacters is one of:

(a) expn | % Integer value
(b) * | % Only in subprogram parameters

The first form determines n. If the expression is a run time value, the type is considered to be dynamic char(n). The value of n must be at least 1. The second form is used only for subprogram parameters and uses the length of the actual parameter. This too, is considered to be a dynamic char(n) type. Dynamic char(n) types can only be passed to char(*) parameters. Dynamic char(n) types have the same restrictions as dynamic arrays. This implies they cannot be assigned as a whole and cannot appear in record and union types.

An implementation may impose a limit, recommended to be at least 32767, on the length n.

Values of the char(n) type can be assigned and they can be compared for both equality and for ordering, but only if they have the same length and they are not dynamic (i.e. the length must be known at compile time).

Values of the char(n) type can be read and written by get and put statements.

The char(n) type is a nonscalar, which implies that its parameters are always passed by reference (by means of an implicit pointer).

As is true for the char type, all 256 possible values of an 8-bit byte are allowed for each character in char(n) type. There is no pattern left to be used for the "initialized value", so there is no uninitialized checking for char(n).

In general, you can freely intermix the values of the types char, char(n) and string. This means that catenation (+), comparisons, length and substrings can be applied to any of these types. See catenation and substring. If two non dynamic char(n) values (or char values) are catenated, the result is a char(n)value. If either are dynamic, it is a string value. This implies that very long char(n) values can be created by catenating them together, for example to initialize a char(n) variable.

A char value can be assigned (or passed to an non var parameter) with automatic conversion to a char(1) variable and vice versa. String values of length 1 can be assigned to char variables. Character (char) values can be assigned to string variables, yielding a string of length 1. String values of length n are assignable with automatic conversion to char(n) variables. Values of type char(n) can be assigned with automatic conversion to string variables.

When comparing two char(n) values, as in s > t, if both are non-dynamic and of the same length, they are compared without converting to strings. If either are dynamic, they are converted to strings and then compared.

See also the char type which is much like char(1). See also the string type.


char

char type

Syntax char

Description Each variable whose type is a char contains a single character, such as the letter A, the digit 3 or the special character &.

Example Count characters until a period is found. Character c is read using a get statement and is compared to the explicit character constant '.'.

        var c : char
        var counter := 0
        loop
            exit when eof
            get c           % Read a single character
            exit when c = '.'   % Single quotes for char constant
            counter := counter + 1
        end loop
        put counter, " characters before the period"
Execute

Example Count capital letters. This example illustrates the use of the char type as the subscript type for the frequency array, the use of character variable c as a subscript, and the use of d as a for counter that ranges across the letters A to Z.

        var frequency : array 'A' .. 'Z' of nat
        for d : 'A' .. 'Z'
            frequency (d) := 0
        end for
        loop                % Tabulate use of capital letters
            exit when eof
            var c : char
            get c           % Read one character
            if c >= 'A' and c <= 'Z' then
                frequency (c) := frequency (c) + 1
            end if
        end loop
        for d : 'A' .. 'Z'      % Print frequency of capital letters
            put d, " ", frequency (d)
        end for
Execute

Details The type string (or char(n)) is used instead of char when more than one character needs to be stored, such as the string of characters Henry. Unless the program needs to be quite efficient, it is usually easier to use the string type. See also the char(n) type, which always stores exactly n characters.

The char type differs from the string(1) type in the following way: char always represents exactly one character, while string(1) can represent either the null string or a string containing one character. The char type is similar to the char(1) type in that both contain at most one character.

The char type is an index type and can be used, for example, as subscripts, for ranges and case labels. For example, this declaration

var charCounts : array char of int

creates an array whose subscripts are characters.

The char type is a scalar type, which implies that its parameters are passed by value, instead of by reference (which is the case for char(n) and string).

Values of the char type can be assigned and they can be compared for both equality and ordering. Explicit char constants are written as a character surrounded by single quotes, for example, 'A'. For details, including how to write control characters, see explicitCharConstant.

Characters can be read and written by get and put statements.

There are 256 char values, corresponding to the distinct patterns in an 8-bit byte. This allows the patterns eos (internal value 0) and uninitchar (internal value 128) to be char values (these patterns are not allowed in the string type; see the string type). All 256 patterns are used, so there is no pattern left to be the "uninitialized value". Uninitialized checking is not done for the char type.

The ord and chr functions convert between the char values and their corresponding numeric representation in a byte. See ord and chr.

In general, you can freely intermix the values of the types char, char(n) and string. This means that catenation (+), comparisons, length and substrings can be applied to any of these types. See char(n) for details about conversions between char, char(n) and string.

See also string and char(n) for related types. See ord and chr functions for conversion from and to ASCII values. See explicitCharConstant for information on special characters like caret (^) and backslash (\).


cheat

cheat type cheating

Dangerous

Syntax A typeCheat is one of:

(a) | cheat (targetType, expn [ : sizeSpec ] )
(b) | # expn
(c) | id : cheat typeSpec

Description A type cheat interprets the representation (bits) of one type as another type. Type cheats are dirty (machine-dependent) and sometimes dangerous (arbitrary corruption) and should be used only by programmers who know the underlying computer representation of values.

Form (b) is a short form type cheat in which the target type is a natural number.

Form (c) is used as a parameter in a subprogram declaration. It causes whatever is passed in to the parameter to be interpreted as typeSpec.

Example The character 'B' is assigned to variable i, whose type is considered to be char (although it is really int1).

        var i : int1        % One byte integer
        cheat (char, i) := 'B'
This assignment is equivalent (on byte oriented computers) to either of the following:

        i := cheat (int1, 'B')
        i := ord ('B')
Details The form of targetType must be one of:

(a) | [ id . ] typeId
(b) | int, int1, int2 or int4
(c) | nat, nat1, nat2 or nat4
(d) | boolean
(e) | char [ (numberOfCharacters ) ]
(f) | string [ (maximumLength ) ]
(g) | addressint

In form (a) the beginning identifier id must be the name of a module, monitor or class that exports the typeId. Each of numberOfCharacters and maximumLength must be compile time integer expressions.

If the expn in a type cheat is a variable reference and the sizeSpec is omitted, the type cheat is considered to be a variable whose type is targetType. This allows, for example, the type cheat to be assigned to, as in:

cheat (char, i) := 'B'

If the expn is a value that is not a variable reference, or if sizeSpec is present, the type cheat is an expression value whose type is targetType.

The sizeSpec is a compile time integer expression giving the size of the expn's value. It can be specified only for integer or natural number values (where it must be 1, 2 or 4) or real values (where it must be 4 or 8).

A type cheat is carried out in two steps. The first step converts the value if necessary to the size given by sizeSpec. The second step, which involves no generated code, interprets the value as the target type.

The prefix operator # is a short form for a class of type cheats. It interprets its argument as a natural number. In general, # expn is the same as cheat (nat n, expn) where n is determined as follows. If the expn is a variable or expression of size 1, 2 or 4, n is the size of the item, otherwise n is 4.

Example Set the second character of d so it has the numeric representation 24. In general, if c is a character, then #c = ord(c). Note that #c can have a number value assigned to it, but ord(c) cannot.

        var d : char (3)
        #d (2) := 24        % Same as d(2) := chr(24)
Example The notation 16#FFFF means FFFF in base 16, which is 32767 in base 10 and is 16 1's in a row in base 2. This same pattern is the two's complement representation of the value -1 in a 2-byte integer.

        var i : int2
        #i := 16#FFFF       % Equivalent to i := -1
Example The following example prints out a string located at addressint myAddr.

        procedure PrintString (str : cheat string)
            put str
        end PrintString

        var myAddr : addressint
        ...             % Assigned a value to myAddr
        PrintString (myAddr)    % myAddr will be treated as a string
Details An implementation may prohibit certain type cheats. Memory alignment requirements may render some type cheats unfeasible. It is dangerous to consider a value to have a targetType larger than the value's type. An implementation may prohibit certain type cheats on register scalar items.

See also explicitIntegerConstant (for description of constants such as 16#FFFF) and the following functions that convert one type to another in a machine-independent manner: ord, chr, intstr, strint, natstr, and strnat.


checked

checked compiler directive

Description Unchecked means that certain run time tests, which take place by default, can be eliminated, usually to make the program more efficient at the risk of unreliability. The keyword checked, used as a statement, requests that the disabling of checking, previously requested by the keyword unchecked, be re-enabled. See unchecked for details and an example.


chr

chr integer-to-character function

Syntax chr (i : int) : char

Description The chr function is used to convert an integer to a character. The character is the i-th character of the ASCII sequence of characters (except on the IBM mainframe, which uses the EBCDIC sequence.) For example, chr (65) is "A".

The ord function is the inverse of chr, so for any character c,:

chr(ord (c)) = c.

Execute

Details There are two sets of characters representing values 128-255: the ANSI values (the default values for Windows), and the MS-DOS OEM character set, which contains various line drawing characters. To use the MS-DOS character set, you must use the setscreen ("msdos") command.

Example Another example is available that displays the entire characters set, both the regular ANSI character set and the MS_DOS OEM character set.
See also ord, intstr and strint functions.


class

class declaration

Pointer p is used to locate individual objects of the class. The new statement creates one of these objects. The statement

        p -> push ("Harvey")
is a short form for:

        stackClass (p) . push ("Harvey")
This inserts the string Harvey into the stack object located by p.

Syntax A classDeclaration is:

[ monitor ]
class id
 | [ inherit inheritItem ]
 | [ implement implementItem ]
 | [ implement by implementByItem ]
 | [ import [ var ] importItem {, [ var ] importItem } ]
 | [ export [ howExport ] id {, [ howExport ] id } ]
 | statementsAndDeclarations
end id

Description A class declaration defines a template for a package of variables, constants, types, subprograms, etc. The name of the class (id) is given in two places, just after class and just after end. Items declared inside the class can be accessed outside of the class only if they are exported. Items from outside the class that are to be used in the class, need to be imported (unless they are predefined or pervasive). Instances (objects) of a class are created using the new statement. Each object is essentially a module located by a pointer.

Example This class is a template for creating objects, each of which is a stack of strings. (See the module description for the corresponding module that implements a single stack of strings.)

        class stackClass    % Template for creating individual stacks
            export push, pop

            var top : int := 0
            var contents : array 1 .. 100 of string

            procedure push (s : string)
                top := top + 1
                contents (top) := s
            end push

            procedure pop (var s : string)
                s := contents (top)
                top := top - 1
            end pop
        end stackClass

        var p: pointer to stackClass    % Short form: var p: ^stackClass
        new stackClass, p           % Short form: new p
        p -> push ("Harvey")
        var name : string
        p -> pop (name)         % This sets name to be Harvey
Execute

Details The new statement is used to create objects of a class. Many instances of a class can exist at a given time, each located by a pointer. The free statement is used to destroy objects that are no longer of use. Turing does not support garbage collection (automatic recovery of space belonging to inaccessible objects).

See modules for a discussion of importing, exporting and related concepts. When an object is created by new, its initialization code is executed. In this example, the object's top variable is set to 0. As is true in modules, an exported subprogram of an object's class cannot be called until the object is completely initialized.

You are not allowed to create variables of a class, as in:

        var s : stack       % Not legal!
If the monitor keyword is present (just before class), the objects are monitors. This means that only one process at a time can be active in the object. See monitor and process.

Inherit lists are used to specify inheritance. See inherit list. Implement and implement-by lists provide a special kind of expansion which supports the separation of an interface from its implementation. See implement list and implement-by list. A class cannot contain both an inherit and an implement list.

Class declarations can be nested inside modules and monitors but cannot be nested inside other classes or inside procedures or functions. A class must not contain a bind as one of its (outermost) declarations. A return statement cannot be used as one of the (outermost) statements in a class.

A class cannot export variables (or run time constants) as unqualified (because each object has a distinct set of variables).

The syntax of a classDeclaration presented above has been simplified by leaving out pre, invariant and post clauses. The full syntax which supports pre, invariant and post is the same as that for modules. The initialization of classes is the same as that for modules. See module.

Example We will give an example in which a subprogram in one class overrides the corresponding subprogram in a class that is being inherited. The example is based on a program that implements a file system inside an operating system. All files have open, close, read and write operations. Some files, called Device files, also have an operation called ioCtl (input/output control). The kind of file determines the implementation method. Here is the expansion (inheritance) hierarchy among the classes of files.

The class called File gives the interface to all possible kinds of files. The TextFile class implements files that are text (ASCII characters). The Device class gives the interface to all files that have the ioCtl operation in addition to open, close, read and write. The Tape and Disk classes implement files that are actually physical tapes or disks. Here is the declaration of the File class:

        class File
            export open, close, read, write
            deferred procedure open (… parameters for open …)
            deferred procedure close (… parameters for close …)
            deferred procedure read (… parameters for read …)
            deferred procedure write (… parameters for write …)
        end File
The TextFile class implements the File interface by giving variables declarations and procedure bodies for ASCII files:

        class TextFile
            inherit File
            var internalTextFileData :
                … internal data for text files …

            body procedure open
                … body for open for text files …
            end open

            … bodies for close, read and write procedures for text files…
        end TextFile
Objects to represent individual text files are created using the new statement:

        var textFilePtr : ^ TextFile
                        % Pointer will locate a text file object
        new textFilePtr     % Create a text file object

        textFilePtr -> read (… actual parameters …)  % Read text file
The Device class adds the ioCtl procedure to the File interface.

        class Device
            inherit File
            export ioCtl
            deferred procedure ioCtl (… parameters for ioCtl …)
        end Device
The Disk class provides data and procedures to implement a file that is actually a disk (the Tape class is analogous):

        class Disk
            inherit Device
            var internalDiskFileData : … internal data for disk files

            body procedure open
                … body for open …
            end open

            … bodies for close, read, write and ioCtl procedures for disk …
        end Disk
A pointer that can locate any kind of File object is declared this way:

        var filePtr : ^ File
This may locate, for example, a TextFile:

        filePtr := textFilePtr
This assignment is allowed because filePtr's corresponding class (File) is an ancestor of textFilePtr's corresponding class (TextFile). It is guaranteed that the object now located by filePtr supports a version of all the operations of a File (open, close, read and write).

When we call a procedure in the object located by filePtr, the actual procedure called will depend upon the object:

        filePtr -> read (… actual parameters …)
For example, if filePtr currently locates a Disk file, this will call the read procedure from the Disk class. This is an example of dynamic binding in which the version of read to be used is selected at run time and this choice is based on the object located by filePtr. This is called polymorphism, because File objects can have more than one form.

Example As another example, consider class C, which contains headers and bodies for functions f and g. C exports functions f and g. There is also a class D, which inherits from C. Class D contains a body that overrides the body for g. D also contains a header and body for function h. D exports function h.

Pointer p has been declared to locate an object of class C, but at runtime p locates an object of class D. When p is used to call f, by means of p->f, the body of f, which appears in C, is invoked. When p is used to call g, by means of p->g, g's overriding body in D is invoked. Any attempt to use p to call h is illegal because p can only be used to call functions that are exported from C.

        class C
            export f, g

            procedure f
                put "C's f"
            end f

            procedure g
                put "C's g"
            end g
        end C

        class D
            inherit C           % Inherit f and g

            body procedure g    % Overrides g in C
                put "*** D's g ***"
            end g

            procedure h
                put "*** D's h ***"
            end h
        end D

        var p : pointer to C    % p can point to any descendant of C
        new D, p        % p locates an object of class D
        p -> f          % Outputs "C's f"
        p -> g          % Outputs "*** D's g ***"
        p -> h          % Causes error "'h' is not in export list of 'C'"
Execute

See also module, monitor and unit. See also import list, export list, implement list, implement by list, and inherit list. See also deferred subprogram. See also anyclass and objectclass.


clock

clock millisecs used procedure

Syntax clock (var c : int)

Description The clock statement is used to determine the amount of time since a program (process) started running. Variable c is assigned the number of milliseconds since the program started running.

Example This program tells you how much time it has used.

        var timeRunning : int
        clock (timeRunning)
        put "This program has run ", timeRunning, " milliseconds"
Execute

Details On Apple Macintoshes, the hardware resolution of duration is in units of 17 milliseconds (1/60-th of a second).

See also delay, time, sysclock, wallclock and date statements.

See also predefined unit Time.


close

close file statement

Syntax A closeStatement is:

close : fileNumber

Description In Turing, files are read and written using a fileNumber. In most cases, this number is given a value using the open statement, which translates a file name, such as "Master", to a file number, such as 5. When the program is finished using the file, it disconnects from the file using the close statement.

Example This program illustrates how to open, read and then close a file.

        var fileName : string := "Master"   % Name of file
        var fileNo : int                % Number of file
        var inputVariable : string (100)
        open : fileNo, fileName, read
        …
        read : fileNo, inputVariable
        …
        close : fileNo
Details In a Turing implementation, there will generally be a limit on the number of currently open files. This limit will typically be around 20. To avoid exceeding this limit, a program that uses many files one after another should close files that are no longer in use.

If a program does not close a file, the file will be automatically closed when the program finishes.

There is an older and still acceptable version of close that has this syntax:

        close (fileNumber : int)
See also the open, get, put, read, write, seek and tell statements.


cls

cls clear screen graphics procedure

Syntax | cls
Description | The cls (clear screen) procedure is used to blank the output window. The cursor is set to the top left (to row 1, column 1).
Details | The entire output window is set to the current text background color (as set by colorback or Text.ColorBack). The output window must be in "graphics" mode. See setscreen for details.
See also | See also predefined unit Text.


collection

collection declaration

Syntax A collectionDeclaration is one of:

(a) | var id { , id } : collection of typeSpec
(b) | var id { , id } : collection of forward typeId

Description A collection declaration creates a new collection (or collections). A collection can be thought of as an array whose elements are dynamically created (by new) and deleted (by free). Elements of a collection are referred to by the collection's name subscripted by a pointer. See also new, free and pointer.

Example Create a collection that will represent a binary tree.

        var tree : collection of
            record
                name : string (10)
                left, right : pointer to tree
            end record

        var root : pointer to tree
        new tree, root
        tree (root) . name := "Adam"
Details The statement "new C,p" creates a new element in collection C and sets p to point at i. If there is no more memory space for the element, though, p is set to nil (C), which is the null pointer for collection C. The statement "free C,p" deletes the element of C pointed to by p and sets p to nil (C). In each case, p is passed as a var parameter and must be a variable of the pointer type of C.

The keyword forward (form b above) is used to specify that the typeId of the collection elements will be given later in the collection's scope. The later declaration must appear at the same level (in the same list of declarations and statements) as the original declaration. This allows cyclic collections, for example, when a collection contains pointers to another collection, which in turn contains pointers to the first collection. In this case, the typeId is the name of the type that has not yet been declared; typeId cannot be used until its declaration appears. A collection whose element type is forward can be used only to declare pointers to it until the type's declaration is given.

Suppose pointer q is equal to pointer p and the element they point to is deleted by "free C,p". We say q is a dangling pointer because it seems to locate an element, but the element no longer exists. A dangling pointer is considered to be an uninitialized value. It cannot be assigned, compared, used as a collection subscript, or passed to free.

Collections cannot be assigned, compared, passed as parameters, bound to, or named by a const declaration. Collections must not be declared in procedures, functions, records or unions.

The same short forms for classes can be also used for collections. These include omission of the collection name in new, free and nil together with the ^ and -> notations. Pointers to types (see pointer) can also be used, which are often more convenient to use than collections.

The syntax of a collectionDeclaration presented above has been simplified by leaving out unchecked collections. With this feature, a collectionDeclaration is one of:

(a) var id { , id } : [ unchecked ] collection of typeSpec
(b) var id { , id } : [ unchecked ] collection of forward typeId

When unchecked is specified, the checking to verify that pointers actually locate elements is removed. This checking is done using a "time stamp" attached to each element and pointer, and making sure that these match with each other. When unchecked is specified, the execution is dangerous, but faster and smaller, and the pointers become simply machine addresses (as in C).


color

color text color graphics procedure

Syntax color (Color : int)

Description The color procedure is used to change the currently active color. This is the color of characters that are to be put on the screen. The alternate spelling is colour.

Example This program prints out the message "Bravo" three times, each in a different color.

        setscreen ("graphics")
        for i : 1 .. 3
            color (i)
            put "Bravo"
        end for
Execute

Example This program prints out a message. The color of each letter is different from the preceding letter. For letter number i the color number is i mod maxcolor + 1. This cycles repeatedly through all the available colors.

        setscreen ("graphics")
        const message := "Happy New Year!!"
        for i : 1 .. length (message)
            color (i  mod maxcolor + 1)
            put message (i) ..
        end for
Execute

Details See maxcolor for the number of colors available in the various "graphics" modes. The background color that text appears upon can be set using the colorback procedure.

The screen must be in a "graphics" mode to use the color procedure. See setscreen for details.

See also colorback, whatcolor and maxcolor.

See also predefined unit Text.


colorback

colorback background color procedure

Syntax colorback (Color : int)

Description The colorback procedure is used to change the color upon which text appears. The alternate spelling is colourback.

Example When the message "Greetings" is output, the background surrounding each letter will be inred.

        setscreen ("graphics")
        colorback (red)
        put "Greetings" ..
Execute

Details When a newline is output, such as when the put statement does not contain a .. at the end, the rest of the line is cleared from cursor to the right edge of the output window in the text background color.

Example This program will result in the word "Hello" being displayed in red on a green background followed by the word "Again" displayed in red on a yellow background. The yellow background stretches across the window.

        setscreen ("graphics")
        color (red)
        colorback (green)
        put "Hello " .. % The ".." at the end of line stops the newline
        colorback (yellow)
        put "Again" % The rest of the line is cleared in yellow
Execute

Example This program displays the letter 'X' in 16 different colors on 16 different backgrounds. Note that the letter is not visible when the text color and the bacground color are the same

        setscreen ("graphics")
        for row : 0 .. 15
            colorback (row)
            for column : 0 .. 15
                color (column)
                locate (row, column)
                put "X" ..
            end for
        end for
Execute

Details See maxcolor for the number of background colors available . The color in which text appears can be set using the color procedure.

The screen must be in a "graphics" mode to use the color procedure. See setscreen for details.

See also color and whatcolorback.

See also predefined unit Text.


comment

comment remark statement

Description A comment is a remark to the reader of the program, which the computer ignores. The most common form of comment in Turing starts with a percent sign (%) and continues to the end of the current line; this is called an end-of-line comment. There is also the bracketed comment, which begins with the /* and ends with */ and which can continue across line boundaries.

Example

        % This is an end-of-line comment
        var x : real        % Here is another end-of-line comment
        const s := "Hello"
        /* Here is a bracketed comment that
            lasts for two lines */
        const pi := 3.14159
Details In the BASIC language, comments are called remarks and start with the keyword REM. In Pascal, comments are bracketed by (* and *).


comparisonOperator

Syntax A comparisonOperator is one of:

(a) | < | % Less than
(b) | > | % Greater than
(c) | = | % Equal
(d) | <= | % Less than or equal; subset
(e) | >= | % Greater than or equal; superset
(f) | not= | % Not equal

Description A comparison operator is placed between two values to determine their equality or ordering. For example, 7 > 2 is true and so is "Adam" < "Cathy". The comparison operators can be applied to numbers as well as to enumerated types. They can also be applied to strings to determine the ordering between strings (see the string type for details). Arrays, records, unions and collections cannot be compared. Boolean values (true and false) can be compared only for equality (= and not=); the same is true of pointer values. Set values can be compared using <= and >=, which are the subset and superset operators. The not= operator can be written as ~=.

Comparisons among classes is also supported (see class). If C and D are classes, C <= D means D is a descendant of (inherits from) C. See class.

See also See also infix operators and precedence of operators. See also the int, real, string, set, boolean and enum types. See also string comparison.


Concurrency

Description This unit contains the predefined procedures that deal with concurrency. It contains one predefined function, although conceptually it contains three other subprograms.

All routines in the Concurrency module are exported unqualified. (This means you can call the entry points directly.)

Entry Points
empty* | Returns true if no processes are waiting on the condition queue.
getpriority* | Returns the priority of the current process.
setpriority* | Sets the priority of the current process.
simutime | Returns the number of simulated time units that have passed.

* Part of the language, conceptually part of the Concurrency unit.


Concurrency.empty

Concurrency.empty Part of Concurrency module

Syntax | empty (variableReference) : boolean
Description | The empty function is used in a concurrent program. It returns true if the variableReference, which must be a condition variable, has no processes waiting for it. Processes join the queue of a condition variable by executing the wait statement, and are awakened by the signal statement.
Status | Part of the language and only conceptually part of the Concurrency unit. This means that you can only call the function by calling empty, not by calling Concurrency.empty.
See also | condition, wait, signal, fork and monitor.


Concurrency.getpriority

Concurrency.getpriority Part of Concurrency module

Syntax | getpriority : nat
Description | The getpriority function returns the priority of an executing process in a concurrent program. A smaller value means a faster speed.
Status | Part of the language and only conceptually part of the Concurrency unit. This means that you can only call the function by calling getpriority, not by calling Concurrency.getpriority.
See also | setpriority, fork and monitor.


Concurrency.setpriority

Concurrency.setpriority Part of Concurrency module

Syntax | setpriority (p : nat)
Description | The setpriority procedure is used to set the priority of a process in a concurrent program. This priority cannot be counted on to guarantee critical access to shared variables. A smaller value of p means increased speed. The argument to setpriority may be limited to the range 0 to 2**15 - 1.
Status | Part of the language and only conceptually part of the Concurrency unit. This means that you can only call the function by calling setpriority, not by calling Concurrency.setpriority.
See also | getpriority, fork and monitor.


Concurrency.simutime

Concurrency.simutime Part of Concurrency module

Syntax simutime : int

Description The simutime function returns the number of simulated time units that have passed since program execution began.

Details Simulated time only passes when all process are either paused or waiting. This simulates the fact that CPU time is effectively infinitely faster than "pause" time.

Example This prints out the simulated time passing between two processes. This will print out 3, 5, 6, 9, 10, 12, 15, 15, 18, 20, 21, ...

        process p (t : int)
            loop
                pause t
                put simutime
            end loop
        end p

        fork p (3)
        fork p (5)
Execute

Status Exported unqualified.

This means that you can call the function by calling simutime or by calling Concurrency.simutime.


condition

condition declaration

Syntax A conditionDeclaration is:

var id { , id } : [ array indexType {, indexType } of ]
[ conditionOption ] condition

Description A condition is essentially a queue of sleeping processes. It is used in a concurrent program to allow processes to block themselves (by the wait statement) and later to be awakened (by the signal statement). A condition variable, which can occur only inside a monitor (a special kind of module that handles concurrency) or monitor class, is used by the wait and signal statements for putting processes to sleep and later waking them up.

Example The processes use this monitor to gain exclusive access to a resource. A process wanting to use the resource calls the request entry point and is blocked until the resource is free. When the process is finished with the resource, it calls the release entry point. This monitor is essentially a binary semaphore in which the semaphore's P operation is the request and the V is the release.

        monitor resource
            export request, release

            var available : boolean := true
            var nowAvailable : condition

            procedure request
                if not available then
                    wait nowAvailable   % Go to sleep
                end if
                assert available
                available := false      % Allocate resource
            end request

            procedure release
                assert not available    % Resource is allocated
                available := true       % Free the resource
                signal nowAvailable % Wake up one process
                                % If any are sleeping
            end release

        end resource
        process worker
            loop
                …
                resource.request        % Block until available
                … use resource …
                resource.release
            end loop
        end worker

        fork worker             % Activate one worker
        fork worker             % Activate another worker
Execute

Details A conditionOption is one of:

(a) | priority
(b) | deferred
(c) | timeout

The priority option requires that the corresponding wait statements include priorities. Options (b) and (c) declare deferred conditions. A signal to a deferred condition causes the signaled process to become ready to enter the monitor when the monitor becomes inactive. The signaling process continues running in the monitor. A signal to an immediate (non deferred) condition causes the signaled process to begin running in the monitor immediately. The signaling process waits to re-enter the monitor when the monitor becomes inactive. All conditions in a device monitor must be deferred (or timeout).

A timeout option means the signaling is deferred and that an extra parameter to the wait statement must give a timeout interval. If a process waits longer than its interval, it is automatically signaled. Beware that the empty function can be non-repeatable when applied to timeout conditions. For example, empty(c) may not be equal to empty(c) in a single expression. In the current (1999) version of Turing, the time for time outs is measured in simulation time rather than real time. See the pause statement.

Conditions cannot be named as types, cannot be contained in records, unions or collections and cannot be declared in statements (such as begin or loop) or in subprograms. They can only be declared in monitors and monitor classes.

There is no guaranteed order of progress among awakened deferred processes, processes signaling immediate conditions, and processes attempting to enter an active monitor.

Note that conditionOption must precede the keyword condition.

See also wait and signal. See also monitor and fork. See also empty. See also pause.


Config

Description This unit contains the predefined subprograms that deal with getting configuration information about the machine and environment on which the program is being run. It exists in order to allow users to obtain information about the system that may only be available at run time.

All routines in the Config module are exported qualified (and thus must be prefaced with "Config.").

Entry Points
Display | Returns information about the display currently attached.
Lang | Returns information about the language environment that the program is currently running within.
Machine | Returns information about the hardware on which the program is running.


Config.Display

Config.Display Part of Config module

Syntax Config.Display (displayCode : int) : int

Description Config.Display returns information about the display (or displays) attached to the computer. The parameter displayCode determines what sort of information is passed back. displayCode has a number of possible values, all summarized by a set of predefined constants.

At the time of this writing, the following constants were defined:

cdScreenHeight | return the height of the screen in pixels.
cdScreenWidth | return the width of the screen in pixels.
cdMaxNumColors | return the maximum number of colors supported by the display.
cdMaxNumColours | return the maximum number of colors supported by the display.

Execute

Example This program prints the screen width and height.

        const width : int := Config.Display (cdScreenWidth)
        const height: int := Config.Display (cdScreenHeight)
        put "The screen width is ", width, "  the screen height is ", height
Details On the Macintosh, it's possible to have multiple displays attached to a single computer. To get information about the extra displays, you can call Config.Display with any of the first four constants above plus one, two, three, etc. This will return the height, width or maximum number of colors for the second, third and beyond displays.

Example This program prints the screen width and height of the second display on a Macintosh.

        const width : int := Config.Display (cdScreenWidth + 1)
        const height: int := Config.Display (cdScreenHeight + 1)
        put "The second display size is ", width, "  x ", height
Status Exported qualified.

This means that you can only call the function by calling Config.Display, not by calling Display.


Config.Lang

Config.Lang Part of Config module

Syntax Config.Lang (langCode : int) : int

Description Config.Lang returns information about the language and the limitations of the implementation that the program is currently running. The parameter langCode determines what sort of information is passed back. langCode has a number of possible values, all summarized by a set of predefined constants.

At the time of this writing, the following constants were defined:

clRelease | return the current release number of the environment (e.g. 4.02 = 400).
clLanguageVersion | return the current version number of the language (e.g. 1.81 = 181).
clMaxNumStreams | return the maximum number of I/O streams (used by the open and close statements) that can be opened at once.
clMaxNumDirStreams | return the maximum number of directory streams that can be opened at once.
clMaxNumRunTimeArgs | return the maximum number of run-time arguments.

Example This program prints the current environment version.

        const version : int := Config.Lang (clLanguageVersion)
        put "The language version number is ", version
Status Exported qualified.

This means that you can only call the function by calling Config.Lang, not by calling Lang.


Config.Machine

Config.Machine Part of Config module

Syntax Config.Machine (machineCode : int) : int

Description Config.Machine returns information about the machine that the program is currently running on. The parameter machineCode determines what sort of information is passed back. machineCode has a number of possible values, all summarized by a set of predefined constants.

At the time of this writing, the following constants were defined:

cmProcessor | return an encoding of the processor number.
cmFPU | return 1 if there is an FPU installed, 0 if not.
cmOS | return the current version number of the operating system (e.g. 6.07 = 607).

Example This program prints whether the machine has an FPU or not.

        if Config.Machine (cmFPU) = 1 then
            put "The machine has an FPU installed"
        else
            put "The machine does not have an FPU installed"
        end if
Status Exported qualified.

This means that you can only call the function by calling Config.Machine, not by calling Machine.


const

const constant declaration

Syntax A constantDeclaration is:

const id [ : typeSpec ] := initializingValue

Description A const declaration creates a name id for a value.

Example

        const c := 3
        const s := "Hello"      % The type of s is string
        const x := sin (y) ** 2
        const a : array 1..3 of int := init (1, 2, 3)
        const b : array 1..3 of int := a
        const c : array 1..2, 1..2 of int := init (1, 2, 3, 4)
                % So c(1,1)=1, c(1,2)=2, c(2,1)=3, c(2,2)=4
Details The initializing value can be an arbitrary value or else a list of items separated by commas inside init (…). The syntax of initializingValue is:

a. | expn
b. | init (initializingValue, initializingValue)

Each init (…) corresponds to an array, record or union value that is being initialized. These must be nested for initialization of nested types. In the Pascal language, constants must have values known at compile time; Turing has no such restriction.

When the typeSpec is omitted, the variable's type is taken to be the (root) type of the initializing expression, for example, int or string. The typeSpec cannot be omitted for dynamic arrays or when the initializing value is of the form init (…). The values inside init (…) must be known at compile time.

The keyword pervasive can be inserted just after const. When this is done, the constant is visible inside all subconstructs of the constant's scope. Without pervasive, the constant is not visible inside modules, monitors or classes unless explicitly imported. Pervasive constants need not be imported. You can abbreviate pervasive as an asterisk (*).

You can also optionally use the register keyword to request that the constant be placed in a machine register. The syntax for constantDeclaration is actually:

        const [pervasive] [register] id [ : typeSpec ] := initializingValue
In the current (2002) implementation, programs are run interpretively using pseudo-code, which has no machine registers, and the register keyword is ignored. See also register for restrictions on the use of register constants.


constantReference

constantReference use of a constant

Syntax A constantReference is:

constantId { componentSelector }

Description In a Turing program, a constant is declared and given a name (constantId) and then used. Each use is called a constant reference.

If the constant is an array, record or union, its parts (components) can be selected using subscripts and field names (using componentSelectors). The form of a componentSelector is one of:

(a) | (expn {, expn} )
(b) | . fieldId

Form (a) is used for subscripting (indexing) arrays. The number of array subscripts must be the same as in the array's declaration. Form (b) is used for selecting a field of a record or union. Component selectors are used in the same manner as variable references. See variableReference for details. See also const declaration and explicitConstant.

Example

        var radius : real
        const pi := 3.14159     % Constant declaration
        …
        put "Area is: ", pi * radius **2
                            % pi is a constant reference.


cos

cos cosine function (radians)

Syntax cos (r : real) : real

Description The cos function is used to find the cosine of an angle given in radians. For example, cos (0) is 1.

Example This program prints out the cosine of p/6, 2p/6, 3p/6, up to 12p/6 radians.

        const pi := 3.14159
        for i : 1 .. 12
            const angle := i * pi / 6
            put "Cos of ", angle, " is ", cos (angle)
        end for
Execute

See also the sin and tan functions for calculating sine and tangent.

the cosd function which finds the cosine of an angle given in degrees. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


cosd

cosd cosine function (degrees)

Syntax cosd (r : real) : real

Description The cosd function is used to find the cosine of an angle given in degrees. For example, cosd (0) is 1.

Example This program prints out the cosine of 30, 60, 90, up to 360 degrees.

        for i : 1 .. 12
            const angle := i * 30
            put "Cos of ", angle, " is ", cosd (angle)
        end for
Execute

See also the sind and tand functions for calculating sine and tangent.

the cos function which finds the cosine of an angle given in radians. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


date

date procedure

Syntax date (var d : string)

Description The date statement is used to determine the current date. Variable d is assigned a string in the format "dd mmm yy", where mmm is the first 3 characters of the month, e.g., "Apr". For example, if the date is Christmas 2002, d will be set to "25 Dec 02".

Example This program greets you and tells you the date.

        var today : string
        date (today)
        put "Greetings!!  The date today is ", today
Execute

Details Be warned that Turing gets the date from the operating system. If the date is is not correctly set in the operating system, then the date procedure will give incorrect results.

See also delay, clock, sysclock, wallclock and time statements.

See also predefined unit Time.


declaration

declaration create a variable

Syntax A declaration is one of:

(a) | variableDeclaration
(b) | constantDeclaration
(c) | typeDeclaration
(d) | bindDeclaration
(e) | procedureDeclaration
(f) | functionDeclaration
(g) | moduleDeclaration
(h) | classDeclaration
(i) | processDeclaration
(j) | monitorDeclaration
(k) | conditionDeclaration

Description A declaration creates a new name (or names) for a variable, constant, type, procedure, function, module, class, process, monitor, or condition. These names are called identifiers, where id is the abbreviation for identifier.

Example

        var width : int         % Variable declaration
        const pi := 3.14159     % Constant declaration
        type range : 0 .. 150       % Type declaration

        procedure greet         % Procedure declaration
            put "Hello  world"
        end greet
Details Ordinarily, each new name must be distinct from names that are already visible; that is, redeclaration is not allowed. There are certain exceptions to this rule, for example, names of parameters and fields of records can be the same as existing visible variables. Variables declared inside a subprogram (a procedure and function) are allowed to be the same as variables global to (outside of) the subprogram.

The effect of a declaration (its scope) lasts to the end of the construct in which the declaration occurs; this will be the end of the program, the end of the surrounding procedure, function or module, the end of a loop, for, case or begin statement, or the end of the then, elsif, or else clause of an if statement, or the end of the case statement alternative.

A name must be declared before it can be used; this is called the DBU (Declaration Before Use) rule. The exceptions to this rule use the keyword forward, as in import lists and in collection declarations.

A declaration can appear any place a statement can appear. This differs from the Pascal language, in which declarations are allowed only at the beginning of the program or at the beginning of a procedure or function. Each declaration can optionally be followed by a semicolon (;).

There are certain restrictions on the placement of declarations. Procedures and functions cannot be declared inside other procedures and functions nor inside statements (for example, not inside an if statement). A bind declaration cannot appear at the outer level of either the main program or a module. A condition declaration can appear only inside a monitor. Processes cannot be declared inside procedures, functions, monitors or classes. Classes cannot be declared inside classes. However, modules and monitors can be declared inside classes and vice versa. Monitors can be declared inside modules, not vice versa.


deferred

deferred subprogram declaration

Syntax A deferredDeclaration is:

deferred subprogramHeader

Description A procedure or function is declared to be deferred when you want to be able to override the subprogram in an expansion. The procedure or function must be in a module, monitor or class.

Example The display procedure is deferred in this class of stacks to allow various ways of graphically displaying the stack on the screen:

        class stack
            export push, pop
            … local declarations …
            … declarations of the push and pop procedures …
            deferred procedure display (howbig : int)
        end stack
An expansion to the stack class can give a body for display, as in:

        class stackWithSimpleDisplay
            body procedure display      % (howbig : int)
                   … graphically display the stack on the screen …
            end display
        end stackWithSimpleDisplay
The following creates a stack that can be displayed and displays it:

        var p : ^stackWithSimpleDisplay
        new p
        …
        p -> display (25)       % Display the stack on the screen
Details A deferred procedure is resolved by giving its body. This can be done in the scope (module, monitor or class) containing the deferred declaration (following the deferred declaration) or in any expansion of that scope. Only one resolution per scope is allowed. Unresolved subprograms can be called, but they immediately abort.

All exported subprograms are implicitly deferred and can be overridden in expansions.

During initialization of a module, monitor or object of a class, deferred subprograms (including exported subprograms) cannot be called. This restriction prevents accessing an object before it is fully initialized.

A deferred declaration must not appear in the main program.

See also module, monitor and class. See also export list, import list, inherit list, implement list and implement by list.


delay

delay procedure

Syntax delay (duration : int)

Description The delay statement is used to cause the program to pause for a given time. The time duration is in milliseconds.

Example This program prints the integers 1 to 10 with a second delay between each.

        for i : 1 .. 10
            put i
            delay (1000)    % Pause for 1 second
        end for
Execute

Details On Apple Macintoshes, the hardware resolution of duration is in units of 17 milliseconds (1/60th of a second). For example, delay(500) will delay the program by about half a second, but may be off by as much as 17 milliseconds.

See also sound, clock, sysclock, wallclock, time and date statements.

See also predefined unit Time.


Dir

Description This unit contains the predefined subprograms that deal with directories. You can use these subprograms to list the contents of directories, create directories, change directories and return the current directory.

All routines in the Dir module are exported qualified (and thus must be prefaced with "Dir.").

Entry Points
Open | Opens a directory stream in order to get a listing of the directory contents.
Get | Gets the next file name in the directory listing.
GetLong | Gets the next file name and other information in the directory listing.
Close | Closes the directory stream.
Create | Creates a new directory.
Delete | Deletes a directory (must be empty).
Change | Changes the current execution directory.
Current | Returns the current execution directory.
Exists | Returns whether a directory exists.

Details Path names in Turing can be expressed using either forward slashes or backslashes. For example, Dir.Change ("d:\\turing files\\assignment 3") or Dir.Change ("d:/turing files/assignment 3") are both legal. Note that backslashes must be doubled in string literals. The "." directory represent the current directory (as in Dir.Open (".")), and the ".." directory represents the parent directory. For example, if the current execution directory is "d:/turing files/assignment 3", then Dir.Change ("..") changes the current execution directory to "d:/turing files".
See also File unit for more explanation of the different ways of specifying a path name of a file or directory under the different operating systems.


Dir.Change

Dir.Change Part of Dir module

Syntax Dir.Change (directoryPathName : string)

Description Dir.Change changes the execution directory to that specified by the parameter directoryPathName. This is the equivalent of doing a cd in UNIX.

Under Microsoft Windows, specifying a drive in the directoryPathName parameter causes the drive to become the default drive (unlike the DOS cd command).

Details If the Dir.Change call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program changes to the directory called /usr/west and then lists the current directory.

        Dir.Change ("/usr/west")
        if Error.Last = eNoError  then
            put "Directory changed"
        else
            put "Did not change the directory."
            put "Error: ", Error.LastMsg
        end if
        put "The current execution directory is ", Dir.Current
Example An example demonstrating the use of several of the Dir subprograms is available. In this example, a directory is created, a file is written to the directory, an attempt is made to delete the directory, the file is deleted, and then the directory is deleted.

This example demonstrates the use of Dir.Change, Dir.Current, Dir.Create, and Dir.Delete.

Status Exported qualified.

This means that you can only call the function by calling Dir.Change, not by calling Change.


Dir.Close

Dir.Close Part of Dir module

Syntax Dir.Close (streamNumber : int)

Description Dir.Close is part of a series of four subprograms that help users get directory listings. Dir.Close is used to close a directory stream number opened by Dir.Open. After the directory stream number is closed, it can not be used with Dir.Get or Dir.GetLong.

Details If the Dir.Close call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program prints a listing of all the files in the directory datafiles.

        var streamNumber : int
        var fileName : string
        streamNumber := Dir.Open ("datafiles")
        assert streamNumber > 0
        loop
            fileName := Dir.Get (streamNumber)
            exit when fileName = ""
            put fileName
        end loop
        Dir.Close (streamNumber)
Execute

Status Exported qualified.

This means that you can only call the function by calling Dir.Close, not by calling Close.


Dir.Create

Dir.Create Part of Dir module

Syntax Dir.Create (directoryPathName : string)

Description Dir.Create is used to create the directory specified by the parameter directoryPathName. This is the equivalent of doing a mkdir in DOS or UNIX. On the Macintosh, it creates a folder.

Details If the Dir.Create call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program creates the directory called information.

        Dir.Create ("information")
        if Error.Last = eNoError  then
            put "Directory created"
        else
            put "Did not create the directory."
            put "Error: ", Error.LastMsg
        end if
Example An example demonstrating the use of several of the Dir subprograms is available. In this example, a directory is created, a file is written to the directory, an attempt is made to delete the directory, the file is deleted, and then the directory is deleted.

This example demonstrates the use of Dir.Change, Dir.Current, Dir.Create, and Dir.Delete.

Status Exported qualified.

This means that you can only call the function by calling Dir.Create, not by calling Create.


Dir.Current

Dir.Current Part of Dir module

Syntax Dir.Current : string

Description Dir.Current returns the full path name of the current execution directory. This is the equivalent of doing a pwd in UNIX.

Details If the Dir.Current call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program changes to the directory called /usr/west and then lists the current directory.

        Dir.Change ("/usr/west")
        if Error.Last = eNoError  then
            put "Directory changed"
        else
            put "Did not change the directory."
            put "Error: ", Error.LastMsg
        end if
        put "The current execution directory is ", Dir.Current
Example An example demonstrating the use of several of the Dir subprograms is available. In this example, a directory is created, a file is written to the directory, an attempt is made to delete the directory, the file is deleted, and then the directory is deleted.

This example demonstrates the use of Dir.Change, Dir.Current, Dir.Create, and Dir.Delete.

Status Exported qualified.

This means that you can only call the function by calling Dir.Current, not by calling Current.


Dir.Delete

Dir.Delete Part of Dir module

Syntax Dir.Delete (directoryPathName : string)

Description Dir.Delete is used to delete the directory specified by the parameter directoryPathName. This is the equivalent of doing a rmdir in DOS or UNIX. On the Macintosh, it removes a folder.

Dir.Delete will fail if it attempts delete a directory that has files in it.

Details If the Dir.Delete call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program deletes the directory called information.

        Dir.Delete ("information")
        if Error.Last = eNoError then
            put "Directory delete"
        else
            put "Did not delete the directory."
            put "Error: ", Error.LastMsg
        end if
Example An example demonstrating the use of several of the Dir subprograms is available. In this example, a directory is created, a file is written to the directory, an attempt is made to delete the directory, the file is deleted, and then the directory is deleted.

This example demonstrates the use of Dir.Change, Dir.Current, Dir.Create, and Dir.Delete.

Status Exported qualified.

This means that you can only call the function by calling Dir.Delete, not by calling Delete.


Dir.Exists

Dir.Exists Part of Dir module

Syntax Dir.Exists (directoryPathName : string) : boolean

Description Dir.Exists returns true if a directory by the name of directoryPathName exists. It will return false if directoryPathName is a file.

Details If the Dir.Exists returns false, you can examine Error.Last or Error.LastMsg for more information (i.e. whether the path failed or the directory was simply not found).

Example The following program determines if the directory "d:/usr/west" exists, and outputs an error message if it does not.
        if Dir.Exists ("d:/usr/west") then
            put "Directory exists"
        else
            put "Directory does not exists: ", Error.LastMsg
        end if
Status Exported qualified.

This means that you can only call the function by calling Dir.Exists, not by calling Exists.


Dir.Get

Dir.Get Part of Dir module

Syntax Dir.Get (streamNumber : int) : string

Description Dir.Get is part of a series of four subprograms that help users get directory listings. Dir.Get is used to get the file names in the directory. Each time the function is called, it returns the next file name in the directory. The names are not sorted. When there are no more file names in the directory, Dir.Get returns the empty string.

Details If the Dir.Get call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program prints a listing of all the files in the directory datafiles.

        var streamNumber : int
        var fileName : string
        streamNumber := Dir.Open ("datafiles")
        assert streamNumber > 0
        loop
            fileName := Dir.Get (streamNumber)
            exit when fileName = ""
            put fileName
        end loop
        Dir.Close (streamNumber)
Execute

Status Exported qualified.

This means that you can only call the function by calling Dir.Get, not by calling Get.


Dir.GetLong

Dir.GetLong Part of Dir module

Syntax Dir.GetLong (streamNumber : int, var entryName : string,
var size, attribute, fileTime : int)

Description Dir.GetLong is part of a series of four subprograms that help users get directory listings. Dir.GetLong is used to get the names and assorted information of the files in the directory. Each time the function is called, it returns the name and information of the next file in the directory. The names are not sorted. When there are no more file names in the directory, Dir.GetLong returns the empty string in the entryName parameter.

The size parameter is the size of the file in bytes. The attribute parameter has its individual bits set as follows (the individual bits can be extracted using the bits operator):

Bit 0 attrDir set to 1 if entry is a directory.

Bit 1 attrRead set to 1 if the program can read the file.

Bit 2 attrWrite set to 1 if the program can write the file.

Bit 3 attrExecute set to 1 if the program can execute the file.

Bit 4 attrHidden set to 1 if the entry if a hidden file (PC, Mac).

Bit 5 attrSystem set to 1 if the entry is a system file (PC only).

Bit 6 attrVolume set to 1 if the entry is a volume name (PC only).

Bit 7 attrArchive set to 1 if the entry has archive bit set (PC only).

The attr... constants are defined in the Dir unit. They correspond to the values of attribute if a specified bit is set. For example, attrSystem is the value of the attribute parameter if bit 5 is set to 1. You can and or or these constants to get combinations of specific file attributes.

The fileTime is the time of last modification of the file. It is returned as the number of seconds since 00:00:00 GMT 1/1/1970. To convert this to a string, use Time.SecDate

Details If the Dir.GetLong call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program prints a listing of all the files in the directory datafiles.

        var streamNumber : int
        var fileName : string
        var size, attribute, fileTime : int
        streamNumber := Dir.Open ("datafiles")
        assert streamNumber > 0
        loop
            Dir.GetLong (streamNumber, fileName, size, attribute, fileTime)
            exit when fileName = ""
            put fileName, "  ", Time.SecDate (fileTime)
        end loop
        Dir.Close (streamNumber)
Example This program prints a listing of the attributes of all the files in the current directory.

        var streamNumber : int
        var fileName : string
        var size, attribute, fileTime : int
        streamNumber := Dir.Open (Dir.Current)
        assert streamNumber > 0
        loop
            Dir.GetLong (streamNumber, fileName, size, attribute, fileTime)
            exit when fileName = ""
            put fileName, "  "..
            if (attribute and attrDir) not= 0 then
                put "Directory  "..
            end if
            if (attribute and attrRead) not= 0 then
                put "Readable  "..
            end if
            if (attribute and attrWrite) not= 0 then
                put "Writeable  "..
            end if
            if (attribute and attrExecute) not= 0 then
                put "Executable  "..
            end if
            put ""
        end loop
        Dir.Close (streamNumber)
Execute

Status Exported qualified.

This means that you can only call the function by calling Dir.GetLong, not by calling GetLong.


Dir.Open

Dir.Open Part of Dir module

Syntax Dir.Open (directoryPathName : string) : int

Description Dir.Open is part of a series of four subprograms that help users get directory listings. Dir.Open returns a directory stream number if the directory could be opened. This stream number can be used to get file names and information using the Dir.Get and Dir.GetLong subprograms. After getting the listing, the user should call Dir.Close.

Details If the Dir.Open call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program prints a listing of all the files in the current directory.

        var streamNumber : int
        var fileName : string
        streamNumber := Dir.Open (Dir.Current)
        assert streamNumber > 0
        loop
            fileName := Dir.Get (streamNumber)
            exit when fileName = ""
            put fileName
        end loop
        Dir.Close (streamNumber)
Execute

Status Exported qualified.

This means that you can only call the function by calling Dir.Open, not by calling Open.


div

div integer truncating division operator

Syntax div

Description The div operator divides one number by another and produces the integer result, truncated in the direction of zero. For example, 7 div 2 produces 3 and -7 div 2 produces -3.

Example In this example, eggCount is the total number of eggs. The first put statement determines how many dozen eggs there are. The second put statement determines how many extra eggs there are beyond the last dozen.

        var eggCount : int
        get eggCount
        put "You have ", eggCount div 12, " dozen eggs"
        put "You have ", eggCount mod 12, " left over"
Execute

See also infix operators, precedence of operators and the mod operator.


Draw

Description This unit contains the predefined subprograms that deal with drawing pixel graphics to the screen.

All routines in the Draw unit are exported qualified (and thus must be prefaced with "Draw.").

Entry Points
Cls | Clears the screen to color 0.
Dot | Draws a dot.
Line | Draws a line.
DashedLine | Draws a dashed or dotted line.
ThickLine | Draws a thick line.
Box | Draws a box.
FillBox | Draws a filled box.
Oval | Draws an oval.
FillOval | Draws a filled oval.
Arc | Draws an arc.
FillArc | Draws a filled arc or a wedge.
Polygon | Draws a polygon.
FillPolygon | Draws a filled polygon.
MapleLeaf | Draws a maple leaf.
FillMapleLeaf | Draws a filled maple leaf.
Star | Draws a star.
FillStar | Draws a filled star.
Fill | Does a flood fill.
Text | Draws text as graphics


Draw.Arc

Draw.Arc Part of Draw module

Syntax Draw.Arc (x, y, xRadius, yRadius : int,
initialAngle, finalAngle, Color : int)

Description The Draw.Arc procedure is used to draw an arc whose center is at (x, y). This is just like Draw.Oval, except that you must also give two angles, initialAngle and finalAngle, which determine where to start and stop drawing. Zero degrees is "three o'clock", 90 degrees is "twelve o'clock", etc. The horizontal and vertical distances from the center to the arc are given by xRadius and yRadius.

Example This program draws a quarter circle whose center is (midx, midy) the center of the screen, using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen.

        View.Set ("graphics")
        const midx := maxx div 2
        const midy := maxy div 2
        Draw.Arc (midx, midy, midx, midy, 0, 90, 1)
Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur

Status Exported qualified.

This means that you can only call the function by calling Draw.Arc, not by calling Arc.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Box

Draw.Box Part of Draw module

Syntax Draw.Box (x1, y1, x2, y2, Color : int)

Description The Draw.Box procedure is used to draw a box on the screen with bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color.

Example This program draws a large box, reaching to each corner of the screen using color number 12. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen and (maxx, maxy) is the right top.

        View.Set ("graphics")
        Draw.Box (0, 0, maxx, maxy, 12)
Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.Box, not by calling Box.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Cls

Draw.Cls Part of Draw module

Syntax | Draw.Cls
Description | The Draw.Cls (clear screen) procedure is used to blank the output window The cursor is set to the top left (to row 1, column 1).
Details | The Draw.Cls procedure sets all pixels in the output window to color 0. In this way it differs from the cls and Text.Cls procedures which set the screen to the text background color. The screen must be in "graphics" mode. See View.Set for details.
Status | Exported qualified. This means that you can only call the function by calling Draw.Cls, not by calling Cls.
See also | View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.DashedLine

Draw.DashedLine Part of Draw module

Syntax Draw.DashedLine (x1, y1, x2, y2, lineStyle, Color : int)

Description The Draw.DashedLine procedure is used to draw a dotted or dashed line on the screen from (x1, y1) to (x2, y2) using the specified Color.

There are five possible line styles: drawSolid Draws a solid line (same as Draw.Line) drawDash Draws a dashed line drawDot Draws a dotted line drawDashDot Draws a line that alternates dashes and dots drawDashDotDot Draws a line that alternates dash and dot-dot

Example This program draws a large X, reaching to each corner of the screen in two different colors. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen, (maxx, maxy) is the right top, etc.

        View.Set ("graphics")
        % Draw a line in each of the styles.
        Draw.DashedLine (0, 50, maxx, 50, drawSolid, brightred)
        Draw.DashedLine (0, 100, maxx, 100, drawDash, brightred)
        Draw.DashedLine (0, 150, maxx, 150, drawDot, brightred)
        Draw.DashedLine (0, 200, maxx, 200, drawDashDot, brightred)
        Draw.DashedLine (0, 250, maxx, 250, drawDashDotDot, brightred)

Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.DashedLine, not by calling DashedLine.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Dot

Draw.Dot Part of Draw module

Syntax Draw.Dot (x, y, Color : int)

Description The Draw.Dot procedure is used to color the dot (pixel) at location (x, y) using the specified Color.

Example This program randomly draws dots with random colors. The maxx, maxy and maxcolor functions give the maximum x, y and color values.

        View.Set ("graphics")
        var x, y, c : int
        loop
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            c := Rand.Int (0, maxcolor) % Random color
            Draw.Dot (x, y, c)
        end loop

Execute

Details The screen must be in a "graphics" mode. If the screen is not in a "graphics" mode, an error will occur. See View.Set for details.

Status Exported qualified.

This means that you can only call the function by calling Draw.Dot, not by calling Dot.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Fill

Draw.Fill Part of Draw module

Syntax Draw.Fill (x, y : int, fillColor, borderColor : int)

Description The Draw.Fill procedure is used to color in a figure that is on the screen. Starting at (x, y), the figure is filled with fillColor to a surrounding border whose color is borderColor.

Example This program draws an oval with x and y radius of 10 in the center of the screen in bright green. Then the oval is filled with red. The maxx and maxy functions are used to determine the maximum x and y values on the screen.

        View.Set ("graphics")
        const midx := maxx div 2
        const midy := maxy div 2
        Draw.Oval (midx, midy, 10, 10, brightgreen)
        Draw.Fill (midx, midy, red, brightgreen)

Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.Fill, not by calling Fill.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.FillArc

Syntax Draw.FillArc (x, y, xRadius, yRadius : int,
initialAngle, finalAngle, Color : int)

Description The Draw.FillArc procedure is used to draw a filled arc whose center is at (x, y). It then fills in the pie-shaped wedge using the specified Color. To outline a filled arc, use Draw.FillArc with the Color parameter set to the fill color and then Draw.Arc with the Color parameter set to the border color. For initialAngle and finalAngle, which determine the edges of the wedge, zero degrees is "three o'clock" and 90 degrees is "twelve o'clock", etc. The horizontal and vertical distances from the center to the arc are given by xRadius and yRadius.

Example This program draws a filled semicircle (actually, an approximation to a semicircle) whose center is (midx,0) the bottom center of the screen, in bright red. The maxx and maxy functions are used to determine the maximum x and y values on the screen.

        View.Set ("graphics")
        const midx := maxx div 2
        Draw.FillArc (midx, 0, maxy, maxy, 0, 180, brightred)
Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.FillArc, not by calling FillArc.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.FillBox

Syntax Draw.FillBox (x1, y1, x2, y2, Color : int)

Description The Draw.FillBox procedure is used to draw a filled box on the screen with bottom left and top right corners of (x1, y1) to (x2, y2) filled using the specified Color. To get a box outlined in a different color, use Draw.FillBox with the Color parameter set to the fill color and then call Draw.Box with the Color parameter set to the border color.

Example This program will fill the bottom half of the screen with color 1 and then outline it in color 2. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen and (maxx, maxy) is the right top.

        View.Set ("graphics")
        Draw.FillBox (0, 0, maxx, maxy div 2, 1)
        Draw.Box (0, 0, maxx, maxy div 2, 2)
Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.FillBox, not by calling FillBox.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.FillMapleLeaf

Syntax Draw.FillMapleLeaf (x1, y1, x2, y2, Color : int)

Description The Draw.FillMapleLeaf procedure is used to draw a filled maple leaf on the screen bounded by a rectangle with bottom left and top right corners of (x1, y1) to (x2, y2) and filled using the specified Color. To get a maple leaf outlined in a different color, use Draw.FillMapleLeaf with the Color parameter set to the fill color and then call Draw.MapleLeaf with the Color parameter set to the border color. If y1 is greater than y2, then the mapleleaf is drawn upside down.

Example This program will draw two maple leaves beside each other. The first will be outlined in black and filled in brightred. The second maple leaf will be upside down and both filled and outlined in green.

        View.Set ("graphics")
        Draw.FillMapleLeaf (0, 0, 100, 100, brightred)
        Draw.MapleLeaf (0, 0, 100, 100, black)
        Draw.FillMapleLeaf (150, 100, 250, 0, green)
Execute

Details The Draw.FillMapleLeaf procedure is useful for drawing the Canadian flag.

The screen should be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

Status Exported qualified.

This means that you can only call the function by calling Draw.FillMapleLeaf, not by calling FillMapleLeaf.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.FillOval

Syntax Draw.FillOval (x, y, xRadius, yRadius, Color : int)

Description The Draw.FillOval procedure is used to draw a filled oval whose center is at (x, y). The horizontal and vertical distances from the center to the oval are given by xRadius and yRadius. To get an oval outlined in a different color, use Draw.FillOval with the Color parameter set to the fill color and then call Draw.Oval with the Color parameter set to the border color.

Example This program draws a large filled oval that just touches each edge of the screen using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The center of the oval is at (midx, midy), which is the middle of the screen.

        View.Set ("graphics")
        const midx := maxx div 2
        const midy := maxy div 2
        Draw.FillOval (midx, midy, midx, midy, 1)
Execute

Details Ideally, a circle is drawn when xRadius = yRadius.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, am error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.FillOval, not by calling FillOval.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.FillPolygon

Syntax Draw.FillPolygon (x, y : array 1 .. * of int, n : int, Color : int)

Description The Draw.FillPolygon procedure is used to draw a filled polygon with n points. The polygon is described by the points (x(1), y(1)) to (x(2), y(2)) to (x(3), y(3)) and so on to (x(n), y (n)). The polygon will be drawn and filled with Color.

To get an polygon outlined in a different color, use Draw.FillPolygon with the Color parameter set to the fill color and then call Draw.Polygon with the Color parameter set to the border color.

Example This program will create a filled octagon and display it in bright blue and then outline it in cyan.

        View.Set ("graphics")
        var x : array 1..8 of int := init (100, 100, 135, 185,
                                   220, 220, 185, 135)
        var y : array 1..8 of int := init (100, 150, 185, 185,
                                   150, 100, 65, 65)
        Draw.FillPolygon (x, y, 8, brightblue)
        Draw.Polygon (x, y, 8, cyan)
Execute

Details The PC allows a maximum of 256 points. As well, Draw.FillPolygon can fail (due to lack of memory). If failure occurs, it will try to draw an outline of the polygon. If that also fails, it will not draw anything.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.FillPolygon, not by calling FillPolygon.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.FillStar

Draw.FillStar Part of Draw module

Syntax Draw.FillStar (x1, y1, x2, y2, Color : int)

Description The Draw.FillStar procedure is used to draw a filled five pointed star on the screen bounded by a rectangle with bottom left and top right corners of (x1, y1) to (x2, y2) and filled using the specified Color. To get a star outlined in a different color, use Draw.FillStar with the Color parameter set to the fill color and then call Draw.Star with the Color parameter set to the border color. If y1 is greater than y2, then the star is drawn upside down.

Example This program will draw two stars beside each other. The first will be outlined in color 1 and filled in color 2. The second star will be upside down and both filled and outlined in color 3.

        View.Set ("graphics")
        Draw.FillStar (0, 0, 100, 100, brightred)
        Draw.Star (0, 0, 100, 100, green)
        Draw.FillStar (150, 100, 250, 0, brightblue)
Execute

Details The Draw.FillStar procedure is useful for drawing the American flag.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.FillStar, not by calling FillStar.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Line

Draw.Line Part of Draw module

Syntax Draw.Line (x1, y1, x2, y2, Color : int)

Description The Draw.Line procedure is used to draw a line on the screen from (x1, y1) to (x2, y2) using the specified Color.

Example This program draws a large X, reaching to each corner of the screen using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen, (maxx, maxy) is the right top, etc.

        View.Set ("graphics")
        % First draw a line from the left bottom to right top
        Draw.Line (0, 0, maxx, maxy, 1)
        % Now draw a line from the left top to right bottom
        Draw.Line (0, maxy, maxx, 0, 1)
Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.Line, not by calling Line.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.MapleLeaf

Draw.MapleLeaf Part of Draw module

Syntax Draw.MapleLeaf (x1, y1, x2, y2, Color : int)

Description The Draw.MapleLeaf procedure is used to draw a maple leaf on the screen bounded by a rectangle described by the bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color. If y1 is greater than y2, then the maple leaf is drawn upside down.

Example This program will draw two maple leaves beside each other. The first will be in red and the second maple leaf will be upside down and in yellow.

        View.Set ("graphics")
        Draw.MapleLeaf (0, 0, 100, 100, red)
        Draw.MapleLeaf (150, 100, 250, 0, yellow)
Execute

Details The Draw.MapleLeaf procedure is useful for drawing the Canadian flag.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.MapleLeaf, not by calling MapleLeaf.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Oval

Draw.Oval Part of Draw module

Syntax Draw.Oval (x, y, xRadius, yRadius, Color : int)

Description The Draw.Oval procedure is used to draw an oval whose center is at (x, y). The horizontal and vertical distances from the center to the oval are given by xRadius and yRadius.

Example This program draws a large oval that just touches each edge of the screen in magenta. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The center of the oval is at (midx, midy), which is the middle of the screen.

        View.Set ("graphics")
        const midx := maxx div 2
        const midy := maxy div 2
        Draw.Oval (midx, midy, midx, midy, magenta)
Execute

Details Ideally, a circle is drawn when xRadius = yRadius. In fact, the aspect ratio (the ratio of height to width of pixels displayed on the screen) of the IBM PC compatibles is not 1.0, so this does not draw a true circle. In CGA graphics mode this ratio is 5 to 4.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.Oval, not by calling Oval.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Polygon

Draw.Polygon Part of Draw module

Syntax Draw.Polygon (x, y : array 1 .. * of int, n : int, Color : int)

Description The Draw.Polygon procedure is used to draw a polygon with n points. A line is drawn in Color from the point (x(1), y(1)) to (x(2), y(2)) to (x(3), y(3)) and so on. After drawing the line to (x(n), y (n)), a line will be drawn back to (x(1), y(1)), closing the polygon. The Draw.Polygon procedure is equivalent to:

        for i : 1 .. n - 1
            Draw.Line (x (i), y(i), x (i + 1), y (i + 1), Color)
        end for
        Draw.Line (x (n), y (n), x (1), y (1), Color)
Example This program will create an octagon and display it in color 1.

        View.Set ("graphics")
        var x : array 1..8 of int := init (100, 100, 135, 185,
                                   220, 220, 185, 135)
        var y : array 1..8 of int := init (100, 150, 185, 185,
                                   150, 100, 65, 65)
        Draw.Polygon (x, y, 8, brightblue)
Execute

Details The IBM PC limits Draw.Polygon to a maximum of 256 points.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.Polygon, not by calling Polygon.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Star

Draw.Star Part of Draw module

Syntax Draw.Star (x1, y1, x2, y2, Color : int)

Description The Draw.Star procedure is used to draw a star on the screen bounded by a rectangle described by the bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color. If y1 is greater than y2 then the star is drawn upside down.

Example This program will draw two stars beside each other. The first star will be in color 1 and the second star will be upside down and in color 2.

        View.Set ("graphics")
        Draw.Star (0, 0, 100, 100, brightred)
        Draw.Star (150, 100, 250, 0, brightblue)
Execute

Details The Draw.Star procedure is useful for drawing the American flag.

The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.Star, not by calling Star.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


Draw.Text

Draw.Text Part of Draw module

Syntax Draw.Text (txtStr : string, x, y, fontID, Color : int)

Description Draw.Text is used to actually draw text in a specified font. The textStr parameter contains the string to be drawn. The x and y paramters are the location of the lower left hand corner of the text to be displayed. The fontID parameter is the number of the font in which the text is to be drawn. The Color parameter is used to specify the color in which the text is to appear.

Note that the text that appears is completely unrelated to the text that appears using put. Draw.Text is a graphics command and thus does not use or affect the cursor location.

The text drawn by the Draw.Text procedure does not erase the background.

Details If Draw.Text is passed an invalid font ID, a fatal error occurs. If the Draw.Text call fails for other (non-fatal) reasons then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Details Draw.Text is identical to Font.Draw. It is placed here for consistency with other pixel graphics drawing routines.

Example The program draws a phrase in red surrounded by a box in bright blue.

        var font : int
        font := Font.New ("serif:12")
        assert font1 > 0
        var width : int:= Font.Width ("This is in a serif font", font)
        var height, ascent, descent, internalLeading : int
        Font.Sizes (font, height, ascent, descent, internalLeading)
        Draw.Text ("This is in a serif font", 50, 30, font, red)
        Draw.Box (50, 30 + descent, 50 + width, 30 + height, brightblue)
        Font.Free (font)
Execute

Details To use the same font as is used by the put statement, use defFontID for the font number. This font does not have to be created or freed by the user, and allows a program to quickly place text in any location on the screen.
Example The program draws two strings in the default font (defFontID).

        Draw.Text ("Drawing Here", 100, 120, defFontID, brightred)
        Draw.Text ("and Here", 180, 90, defFontID, brightgreen)
Execute

Status Exported qualified.

This means that you can only call the function by calling Draw.Text, not by calling Text.

See Also Font module for more information about selecting the font to be displayed.


Draw.ThickLine

Draw.ThickLine Part of Draw module

Syntax Draw.ThickLine (x1, y1, x2, y2, lineWidth, Color : int)

Description The Draw.ThickLine procedure is used to draw a line on the screen from (x1, y1) to (x2, y2) using the specified Color.

Example This program draws a large X, reaching to each corner of the screen in two different colors. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen, (maxx, maxy) is the right top, etc.

        View.Set ("graphics")
        % First draw a line of 5 pixel width from the left bottom to right top
        Draw.ThickLine (0, 0, maxx, maxy, 5, brightred)
        % Now draw a line of 5 pixel width from the left top to right bottom
        Draw.ThickLine (0, maxy, maxx, 0, 5, brightgreen)
Execute

Details The screen must be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Status Exported qualified.

This means that you can only call the function by calling Draw.ThickLine, not by calling ThickLine.

See also View.Set, maxx, maxy and the various procedures in the Draw unit.


drawarc

drawarc graphics procedure

Syntax drawarc (x, y, xRadius, yRadius : int,
initialAngle, finalAngle, Color : int)

Description The drawarc procedure is used to draw an arc whose center is at (x, y). This is just like drawoval, except that you must also give two angles, initialAngle and finalAngle, which determine where to start and stop drawing. Zero degrees is "three o'clock", 90 degrees is "twelve o'clock", etc. The horizontal and vertical distances from the center to the arc are given by xRadius and yRadius.

Example This program draws a semicircle (actually, an approximation to a semicircle) whose center is (midx,0) the bottom center of the screen, using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen.

        setscreen ("graphics")
        const midx := maxx div 2
        drawarc (midx, 0, maxy, maxy, 0, 180, 1)
Execute

Details The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawbox

drawbox graphics procedure

Syntax drawbox (x1, y1, x2, y2, Color : int)

Description The drawbox procedure is used to draw a box on the screen with bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color.

Example This program draws a large box, reaching to each corner of the screen using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen and (maxx, maxy) is the right top.

        setscreen ("graphics")
        drawbox (0, 0, maxx, maxy, 1)
Execute

Details The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawdot

drawdot graphics procedure

Syntax drawdot (x, y, Color : int)

Description The drawdot procedure is used to color the dot (pixel) at location (x, y) using the specified Color.

Example This program randomly draws dots with random colors. The maxx, maxy and maxcolor functions give the maximum x, y and color values.

        setscreen ("graphics")
        var x, y, c : int
        loop
            randint (x, 0, maxx)        % Random x
            randint (y, 0, maxy)        % Random y
            randint (c, 0, maxcolor)    % Random color
            drawdot (x, y, c)
        end loop
Execute

Details The screen should be in a "graphics" mode. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode. See setscreen for details.

Example This program draws a line of dots that bounce off the “sides” of the screen. It also demonstrates that you can use real coordinates to store position (x, y), as long as you convert the coordinates to int values using round in the drawdot call.

        var x, y : real
        var dx, dy : real
        var clr : int := 1
        x := Rand.Int (1, maxx - 1)
        y := Rand.Int (1, maxy - 1)
        dx := Rand.Real - 0.5
        dy := Rand.Real - 0.5
        loop
            drawdot (round (x), round (y), clr)
            clr := (clr + 1) mod maxcolor
            x := x + dx
            y := y + dy
            if x <= 0 or x >= maxx then
                dx := -dx
            end if
            if y <= 0 or y >= maxy then
                dy := -dy
            end if
        end loop
Execute

See also setscreen, maxx, maxy and the various draw… procedures.


drawfill

drawfill graphics procedure

Syntax drawfill (x, y : int, fillColor, borderColor : int)

Description The drawfill procedure is used to color in a figure that is on the screen. Starting at (x, y), the figure is filled with fillColor to a surrounding border whose color is borderColor.

Example This program draws an oval with x and y radius of 10 in the center of the screen using color 1. Then the oval is filled with color 2. The maxx and maxy functions are used to determine the maximum x and y values on the screen.

        setscreen ("graphics")
        const midx := maxx div 2
        const midy := maxy div 2
        drawoval (midx, midy, 10, 10, 1)
        drawfill (midx, midy, 2, 1)
Execute

Details The meaning of the Color number depends on the current palette; see the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

Warning: In Turing for IBM PC compatibles, drawfill fails to completely fill in some complicated figures that contain "islands" within them surrounded by the borderColor.

See also setscreen, maxx, maxy and the various draw… procedures.


drawfillarc

drawfillarc graphics procedure

Syntax drawfillarc (x, y, xRadius, yRadius : int,
initialAngle, finalAngle, Color : int)

Description The drawfillarc procedure is used to draw a filled arc whose center is at (x, y). It then fills in the pie-shaped wedge using the specified Color. To outline a filled arc, use drawfillarc with the Color parameter set to the fill color and then drawarc with the Color parameter set to the border color. For initialAngle and finalAngle, which determine the edges of the wedge, zero degrees is "three o'clock" and 90 degrees is "twelve o'clock", etc. The horizontal and vertical distances from the center to the arc are given by xRadius and yRadius.

Example This program draws a filled semicircle (actually, an approximation to a semicircle) whose center is (midx,0), the bottom center of the screen, using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen.

        setscreen ("graphics")
        const midx := maxx div 2
        drawfillarc (midx, 0, maxy, maxy, 0, 180, 1)
Execute

Details On the PC, drawfillarc fills the pie-shaped wedge by using a "flood" fill and is thus subject to all the conditions of a flood fill.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawfillbox

drawfillbox graphics procedure

Syntax drawfillbox (x1, y1, x2, y2, Color : int)

Description The drawfillbox procedure is used to draw a filled box on the screen with bottom left and top right corners of (x1, y1) to (x2, y2) filled using the specified Color. To get a box outlined in a different color, use drawfillbox with the Color parameter set to the fill color and then call drawbox with the Color parameter set to the border color.

Example This program will fill the bottom half of the screen with color 1 and then outline it in color 2. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen and (maxx, maxy) is the right top.

        setscreen ("graphics")
        drawfillbox (0, 0, maxx, maxy div 2, 1)
        drawbox (0, 0, maxx, maxy div 2, 2)
Execute

Details The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawfillmapleleaf

drawfillmapleleaf graphics procedure

Syntax drawfillmapleleaf (x1, y1, x2, y2, Color : int)

Description The drawfillmapleleaf procedure is used to draw a filled maple leaf on the screen bounded by a rectangle with bottom left and top right corners of (x1, y1) to (x2, y2) and filled using the specified Color. To get a maple leaf outlined in a different color, use drawfillmapleleaf with the Color parameter set to the fill color and then call drawmapleleaf with the Color parameter set to the border color. If y1 is greater than y2, then the maple leaf is drawn upside down.

Example This program will draw two maple leaves beside each other. The first will be outlined in color 1 and filled in color 2. The second maple leaf will be upside down and both filled and outlined in color 3.

        setscreen ("graphics")
        drawfillmapleleaf (0, 0, 100, 100, 1)
        drawmapleleaf (0, 0, 100, 100, 2)
        drawfillmapleleaf (150, 100, 250, 0, 3)
Execute

Details The drawfillmapleleaf procedure is useful for drawing the Canadian flag.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawfilloval

drawfilloval graphics procedure

Syntax drawfilloval (x, y, xRadius, yRadius, Color : int)

Description The drawfilloval procedure is used to draw a filled oval whose center is at (x, y). The horizontal and vertical distances from the center to the oval are given by xRadius and yRadius. To get an oval outlined in a different color, use drawfilloval with the Color parameter set to the fill color and then call drawoval with the Color parameter set to the border color.

Example This program draws a large filled oval that just touches each edge of the screen using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The center of the oval is at (midx, midy), which is the middle of the screen.

        setscreen ("graphics")
        const midx := maxx div 2
        const midy := maxy div 2
        drawfilloval (midx, midy, midx, midy, 1)
Execute

Details Ideally, a circle is drawn when xRadius = yRadius. In fact, the aspect ratio (the ratio of height to width of pixels displayed on the screen) of the IBM PC compatibles is not 1.0, so this does not draw a true circle. In CGA graphics mode this ratio is 5 to 4.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawfillpolygon

drawfillpolygon graphics procedure

Syntax drawfillpolygon (x, y : array 1 .. * of int, n : int, Color : int)

Description The drawfillpolygon procedure is used to draw a filled polygon with n points. The polygon is described by the points (x(1), y(1)) to (x(2), y(2)) to (x(3), y(3)) and so on to (x(n), y (n)). The polygon will be drawn and filled with Color.

To get an polygon outlined in a different color, use drawfillpolygon with the Color parameter set to the fill color and then call drawpolygon with the Color parameter set to the border color.

Example This program will create a filled octagon and display it in color 1 and then outline it in color 3.

        setscreen ("graphics")
        var x : array 1..8 of int := init (100, 100, 135, 185,
                                   220, 220, 185, 135)
        var y : array 1..8 of int := init (100, 150, 185, 185,
                                   150, 100, 65, 65)
        drawfillpolygon (x, y, 8, 1)
        drawpolygon (x, y, 8, 3)
Execute

Details The PC allows a maximum of 256 points. As well, drawfillpolygon can fail (due to lack of memory). If failure occurs, it will try to draw an outline of the polygon. If that also fails, it will not draw anything.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawfillstar

drawfillstar graphics procedure

Syntax drawfillstar (x1, y1, x2, y2, Color : int)

Description The drawfillstar procedure is used to draw a filled five pointed star on the screen bounded by a rectangle with bottom left and top right corners of (x1, y1) to (x2, y2) and filled using the specified Color. To get a star outlined in a different color, use drawfillstar with the Color parameter set to the fill color and then call drawstar with the Color parameter set to the border color. If y1 is greater than y2, then the star is drawn upside down.

Example This program will draw two stars beside each other. The first will be outlined in color 1 and filled in color 2. The second star will be upside down and both filled and outlined in color 3.

        setscreen ("graphics")
        drawfillstar (0, 0, 100, 100, 1)
        drawstar (0, 0, 100, 100, 2)
        drawfillstar (150, 100, 250, 0, 3)
Execute

Details The drawfillstar procedure is useful for drawing the American flag.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawline

drawline graphics procedure

Syntax drawline (x1, y1, x2, y2, Color : int)

Description The drawline procedure is used to draw a line on the screen from (x1, y1) to (x2, y2) using the specified Color.

Example This program draws a large X, reaching to each corner of the screen using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The point (0,0) is the left bottom of the screen, (maxx, maxy) is the right top, etc.

        setscreen ("graphics")
        % First draw a line from the left bottom to right top
        drawline (0, 0, maxx, maxy, 1)
        % Now draw a line from the left top to right bottom
        drawline (0, maxy, maxx, 0, 1)
Execute

Details The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawmapleleaf

drawmapleleaf graphics procedure

Syntax drawmapleleaf (x1, y1, x2, y2, Color : int)

Description The drawmapleleaf procedure is used to draw a maple leaf on the screen bounded by a rectangle described by the bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color. If y1 is greater than y2, then the maple leaf is drawn upside down.

Example This program will draw two maple leaves beside each other. The first will be in color 1 and the second maple leaf will be upside down and in color 2.

        setscreen ("graphics")
        drawmapleleaf (0, 0, 100, 100, 1)
        drawmapleleaf (150, 100, 250, 0, 2)
Execute

Details The drawmapleleaf procedure is useful for drawing the Canadian flag.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawoval

drawoval graphics procedure

Syntax drawoval (x, y, xRadius, yRadius, Color : int)

Description The drawoval procedure is used to draw an oval whose center is at (x, y). The horizontal and vertical distances from the center to the oval are given by xRadius and yRadius.

Example This program draws a large oval that just touches each edge of the screen using color number 1. The maxx and maxy functions are used to determine the maximum x and y values on the screen. The center of the oval is at (midx, midy), which is the middle of the screen.

            setscreen ("graphics")
            const midx := maxx div 2
            const midy := maxy div 2
            drawoval (midx, midy, midx, midy, 1)
Execute

Details Ideally, a circle is drawn when xRadius = yRadius. In fact, the aspect ratio (the ratio of height to width of pixels displayed on the screen) of the IBM PC compatibles is not 1.0, so this does not draw a true circle. In CGA graphics mode this ratio is 5 to 4.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawpic

drawpic graphics procedure

Syntax drawpic (x, y : int, buffer : array 1 .. * of int, picmode : int)

Description The drawpic procedure is used to copy of a rectangular picture onto the screen. The left bottom of the picture is placed at (x, y). In the common case, the buffer was initialized by calling takepic. The values of picmode are:

0: Copy actual picture on screen.
1: Copy picture by XORing it onto the screen.

XORing a picture onto the screen twice leaves the screen as it was (this is a convenient way to move images for animation). XORing a picture onto a background effectively superimposes the picture onto the background.

Details See takepic for an example of the use of drawpic and for further information about buffers for drawing pictures.

The screen must be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, an error will occur.

Details The drawpic, takepic, and sizepic subprograms have been made obsolete by the subprograms Pic.Draw and Pic.New of the Pic module. Users are strongly suggested to use those routines instead. The Pic module also contains subprograms to load images from files.

See also takepic and sizepic. See also setscreen, maxx, maxy and the various draw… procedures.

See also predefined unit Draw and Pic.


drawpolygon

drawpolygon graphics procedure

Syntax drawpolygon (x, y : array 1 .. * of int, n : int, Color : int)

Description The drawpolygon procedure is used to draw a polygon with n points. A line is drawn in Color from the point (x(1), y(1)) to (x(2), y(2)) to (x(3), y(3)) and so on. After drawing the line to (x(n), y (n)), a line will be drawn back to (x(1), y(1)), closing the polygon. The drawpolygon procedure is equivalent to:

        for i : 1 .. n - 1
            drawline (x (i), y(i), x (i + 1), y (i + 1), Color)
        end for
        drawline (x (n), y (n), x (1), y (1), Color)
Example This program will create an octagon and display it in color 1.

        setscreen ("graphics")
        var x : array 1..8 of int := init (100, 100, 135, 185,
                                   220, 220, 185, 135)
        var y : array 1..8 of int := init (100, 150, 185, 185,
                                   150, 100, 65, 65)
        drawpolygon (x, y, 8, 1)
Execute

Details The IBM PC limits drawpolygon to a maximum of 256 points.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


drawstar

drawstar graphics procedure

Syntax drawstar (x1, y1, x2, y2, Color : int)

Description The drawstar procedure is used to draw a star on the screen bounded by a rectangle described by the bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color. If y1 is greater than y2, then the star is drawn upside down.

Example This program will draw two stars beside each other. The first will be in color 1 and the second star will be upside down and in color 2.

        setscreen ("graphics")
        drawstar (0, 0, 100, 100, 1)
        drawstar (150, 100, 250, 0, 2)
Execute

Details The drawstar procedure is useful for drawing the American flag.

The meaning of the Color number depends on the current palette. See the palette statement.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen, maxx, maxy and the various draw… procedures.


empty

empty condition function

Syntax | empty (variableReference) : boolean
Description | The empty function is used in a concurrent program. It returns true if the variableReference, which must be a condition variable, has no processes waiting for it. Processes join the queue of a condition variable by executing the wait statement, and are awakened by the signal statement.
See also | condition, wait, signal, fork and monitor. See also predefined unit Concurrency.


enum

enum enumerated type

Syntax An enumeratedType is:

enum (id { , id } )

Description The values of an enumerated type are distinct and increasing. They can be thought of as the values 0, 1, 2 and so on, but arithmetic is not allowed with these values.

Example

        type color : enum (red, green, blue)
        var c : color := color . red
        var d : color := succ (c)       % d becomes green
Details Each value of an enumerated type is the name of the type followed by a dot followed by the element's name, for example, color.red. Enumerated values can be compared for equality and for ordering. The succ and pred functions can be used to find the value following or preceding a given enumerated value. The ord function can be used to find the enumeration position of a value, for example, ord (color.red) is 0.

Enumerated types cannot be combined with integers or with other enumerated types.

Details It is illegal to declare an "anonymous" enum. The only legal declaration for an enum is in a type declaration. For example, the following is now illegal:

        var a : array enum (red, green, blue) of int
Given that there is no (easy) way of generating an enum value without it being a named type, this should not impact any but the most bizarre code.

Details The "put" and "get" statement semantics have been expanded to allow put's and get's of enum values. The values printed and input are the element names themselves, case sensitive. For example, for

        type colors : enum (red, green, blue)
        var c : colors := colors . red
        put c       % outputs "red" (without the quotes)


enumeratedValue

enumeratedValue enumerated value

Syntax An enumeratedValue is:

enumeratedTypeId . enumeratedId

Description The values of an enumerated type are written as the type name (enumeratedTypeId) followed by a dot followed by one of the enumerated values of the type (enumeratedId).

Example In this example, color.red is an enumeratedValue.

        type color : enum (red, green, blue)
        var c : color := color . red
        var d : color := succ (c)       % d becomes green
Details The above description has been simplified by ignoring the possibility that the enum type can be exported from a module. If this is the case, each use of one of the enumerated values outside of module M must be preceded by the module name and a dot, as in M.color.red.

See also the enum type and explicitConstant.


eof

eof end-of-file function

Syntax eof (streamNumber : int) : boolean

Description The eof (end of file) function is used to determine if there is any more input. It returns true when there are no more characters to be read. The parameter and its parentheses are omitted when referring to the standard input (usually this is the keyboard); otherwise the parameter specifies the number of a stream. The stream number has been determined (in most cases) by an open statement.

Example This program reads and outputs all the lines in the file called "info".

        var line : string
        var fileNumber : int
        open : fileNumber, "info", get
        loop
            exit when eof (fileNumber)
            get : fileNumber, line : *
            put line
        end loop
Execute

Details See also the description of the get statement, which gives more examples of the use of eof. See also the open and read statements.

When the input is from the keyboard, the user can signal end-of-file by typing control-Z on a PC (or control-D on UNIX). If a program tests for eof on the keyboard, and the user has not typed control-Z (or control-D) and the user has typed no characters beyond those that have been read, the program must wait until the next character is typed. Once this character is typed, the program knows whether it is at the end of the input, and returns the corresponding true or false value for eof.

Example Another example is available that illustrates detecting EOF from the keyboard.


equivalence

equivalence of types

Description Two types are equivalent to each other if they are essentially the same types (the exact rules are given below). When a variable is passed to a var formal parameter, the types of the variable and the formal parameter must be equivalent because they are effectively the same variable. When an expression is assigned to a variable, their types must be equivalent, except for special cases. For example, Turing allows you to assign an integer expression to a real variable (see assignability for details).

Example

        var j : int

        var b : array 1 .. 25 of string

        type personType :
            record
                age : int
                name : string (20)
            end record

        procedure p (var i : int, var a : array 1 .. 25 of string,
                    var r : personType)
        … body of procedure p, which modifies each of i, a and r …
        end p

        var s : personType
        p (j, b, s)     % Procedure call to p
                    % i and j have the equivalent type int
                    % Arrays a and b have equivalent types
                    % Records r and s have equivalent types
Details Two types are defined to be equivalent if they are:

(a) | the same standard type (int, real, boolean or string),
(b) | subranges with equal first and last values,
(c) | arrays with equivalent index types and equivalent component types,
(d) | strings with equal maximum lengths,
(e) | sets with equivalent base types, or
(f) | pointers to the same collection; in addition,
(g) | a declared type identifier is also equivalent to the type it names (and to the type named by that type, if that type is a named type, etc.)
(h) | both char,
(i) | both char(n) with the same length,
(j) | both procedure types, with corresponding equivalent parameter types and corresponding var or non-var of the parameters,
(k) | both function types, with corresponding equivalent parameter types and corresponding var or non-var of the parameters and equivalent result types,
(l) | both pointer types to the same class or equivalent type and both are checked or unchecked.

Each separate instance of a record, union or enumerated type (written out using one of the keywords record, union or enum) creates a distinct type, equivalent to no other type. By contrast, separate instances of arrays, strings, subranges and sets are considered equivalent if their parts are equal and equivalent.

Opaque type T, exported from a module, monitor or class M as opaque, is a special case of equivalence. Outside of M this type is written M.T, and is considered to be distinct from all other types. By contrast, if type U is exported non-opaque, the usual rules of equivalence apply. The parameter or result type of an exported procedure or function or an exported constant is considered to have type M.T outside of M if the item is declared using the type identifier T. Outside of M, the opaque type can be assigned, but not compared.

It is not required that subprogram types have the same names and parameter names to be equivalent. They also do not require the same factoring of parameters across their types, as in i, j: int instead of i: int, j: int.


erealstr

erealstr real-to-string function

Syntax erealstr (r : real,
width, fractionWidth, exponentWidth : int) :string

Description The erealstr function is used to convert a real number to a string; for example, erealstr (2.5e1, 10, 3, 2)="b2.500e+01" where b represents a blank. The string (including exponent) is an approximation to r, padded on the left with blanks as necessary to a length of width.

The width must be a non-negative int value. If the width parameter is not large enough to represent the value of r, it is implicitly increased as needed.

The fractionWidth parameter is the non-negative number of fractional digits to be displayed. The displayed value is rounded to the nearest decimal equivalent with this accuracy. In the case of a tie, the value is rounded to the larger of the two values.

The exponentWidth parameter must be non-negative and give the number of exponent digits to be displayed. If exponentWidth is not large enough to represent the exponent, more space is used as needed. The string returned by erealstr is of the form:

        {blank}[-]digit.{digit}e sign digit {digit}
where sign is a plus or minus sign. The leftmost digit is non-zero, unless all the digits are zeros.

The erealstr function approximates the inverse of strreal, although round-off errors keep these from being exact inverses.

See also frealstr, realstr, strreal, intstr and strint functions.


Error

Description This unit contains the predefined subprograms that deal with errors returned from other predefined subprograms.

All routines in the Error unit are exported qualified (and thus must be prefaced with "Error.").

The constants representing the possible errors returned by this module can be found in the ErrorNum module.

Entry Points
Last | Returns the (integer) error code produced by the last call to a predefined subprogram.
LastMsg | Returns the error string produced by the last call to a predefined subprogram.
LastStr | Returns the string version of the error constant produced by the last call to a predefined subprogram.
Msg | Returns the string that corresponds to a specified error code.
Str | Returns the string version of the error constant that corresponds to a specified error code.
Trip | This causes the specified error code to be set.
TripMsg | This causes the specified error code and error message to be set.
Halt | This causes execution to halt with the specified error message.


Error.Last

Error.Last Part of Error module

Syntax Error.Last : int

Description Error.Last is a function that returns the error code set by the last called predefined subprogram. If there is no error, then it returns eNoError (which is 0). If there is an error, you can use Error.LastMsg to obtain a textual form of the error or Error.LastStr to obtain a string version of the error constant.

The fact that Error.Last is not eNoError does not necessarily mean that the previous predefined function failed or failed completely. Error.Last also returns a number of warning codes. For example, if a user specifies a number larger than maxcolor for the color parameter of the Draw.Line procedure, the line is still drawn, only in color maxcolor. However, Error.Last will return a code that warns the user of the fact.

Example This program creates the directory called information. If the creation fails, it prints out the error number and an error message.

        var f : int
        open : f, "testdata/information.txt", get
        if f <= 0 then
            put "File opened"
        else
            put "Could not open file."
            put "Error Number: ", Error.Last
            put "Error Message: ", Error.LastMsg
            put "Error Constant: ", Error.LastStr
        end if
Execute

Status Exported qualified.

This means that you can only call the function by calling Error.Last, not by calling Last.


Error.LastMsg

Error.LastMsg Part of Error module

Syntax Error.LastMsg : string

Description Error.LastMsg is a function that returns the error message set by the last called predefined subprogram. If there is no error, then it returns the empty string. If there is an error, you can use Error.Last to obtain the error code.

The fact that Error.LastMsg is not "" does not necessarily mean that the previous predefined function failed or failed completely. Error.LastMsg also returns a number of warning messages. For example, if a user specifies a number larger than maxcolor for the color parameter of the Draw.Line procedure, the line is still drawn, only in color maxcolor. However, Error.LastMsg will return a message that indicates that the color was out of range

Example This program creates the directory called information. If the creation fails, it prints out the error number and an error message.

        Dir.Create ("testdata/information")
        if Error.Last = eNoError then
            put "Directory created"
        else
            put "Did not create the directory."
            put "Error Number: ", Error.Last
            put "Error Message: ", Error.LastMsg
        end if
Execute

Status Exported qualified.

This means that you can only call the function by calling Error.LastMsg, not by calling LastMsg.


Error.LastStr

Error.LastStr Part of Error module

Syntax Error.LastStr : string

Description Error.LastStr is a function that returns the string version of the error code set by the last called predefined subprogram (i.e. it would return the string "eDrawClrNumTooLarge" for using a color greater than maxcolor in a Draw command). If there is no error then it returns the empty string. If there is an error, you can use Error.Last to obtain the actual error code.

The fact that Error.LastStr is not "" does not necessarily mean that the previous predefined function failed or failed completely. Error.LastStr also returns a number of error codes for warning messages. For example, if a user specifies a number larger than maxcolor for the color parameter of the Draw.Line procedure, the line is still drawn, only in color maxcolor. However, Error.LastStr will return a string version of the error code that indicates that the color was out of range.

You can take a look at the error constants defined by looking at the unit ErrorNum which contains all defined error codes.

Example This program creates the directory called information. If the creation fails, it prints out the error number and an error message.

        Dir.Create ("testdata/information")
        if Error.Last = eNoError then
            put "Directory created"
        else
            put "Did not create the directory."
            put "Error Number: ", Error.Last
            put "Error Constant: ", Error.LastStr
        end if
Execute

Status Exported qualified.

This means that you can only call the function by calling Error.LastStr, not by calling LastStr.


Error.Msg

Error.Msg Part of Error module

Syntax Error.Msg (errorCode : int): string

Description Error.Msg is a function that returns the error message related to a specified error code. If the error code is eNoError, or if there is no such error code, it returns the empty string. If there is such an error, it returns the textual message associated with that error.

Example This program prints out the error message associated with eFsysFileNotFound (“File not found”).

        put Error.Msg (eFsysFileNotFound)
Status Exported qualified.

This means that you can only call the function by calling Error.Msg, not by calling Msg.


Error.Str

Error.Str Part of Error module

Syntax Error.Str (errorCode : int): string

Description Error.Str is a function that returns the error message related to a specified error code. If the error code is eNoError or if there is no such error code, it returns the empty string. If there is such an error, it returns the textual message associated with that error.

Example This program prints out the string "eFsysFileNotFound".

        put Error.Str (eFsysFileNotFound)
Status Exported qualified.

This means that you can only call the function by calling Error.Str, not by calling Str.


Error.Trip

Error.Trip Part of Error module

Syntax Error.Trip (errorCode : int)

Description Error.Trip is a procedure that sets the error number that is returned by Error.Last and Error.LastMsg. It does not halt the program.

Error codes that do not correspond to recognized errors will cause an abort with the error message "Unknown Error #n" where n is the error passed in.

You can find a list of constants for the legal error codes in the module ErrorNum. Any call to Error.Trip should use a constant found in the ErrorNum module.

Example This program sets an error code. The program outputs 201 for the error number and "File not found" for the message.

        Error.Trip (eFsysFileNotFound)
        put "Error code = ", Error.Last
        put "Error message = ", Error.LastMsg
Execute

Status Exported qualified.

This means that you can only call the function by calling Error.Trip, not by calling Trip.


Error.TripMsg

Error.TripMsg Part of Error module

Syntax Error.TripMsg (errorCode : int, errorMessage : string)

Description Error.TripMsg is a procedure that sets the error number and error message that is returned by Error.Last and Error.LastMsg. It does not halt the program.

You can find a list of constants for the legal error codes in the module ErrorNum. Any call to Error.TripMsg should use a constant found in the ErrorNum module or zero, if the error code is not relevant (i.e. only the error message is relevant).

Example This program sets an error code. The program outputs 201 for the error number and "File *really* not found" for the message.

        Error.TripMsg (eFsysFileNotFound, "File *really* not found")
        put "Error code = ", Error.Last
        put "Error message = ", Error.LastMsg
Execute

Status Exported qualified.

This means that you can only call the function by calling Error.TripMsg, not by calling TripMsg.


ErrorNum

Description This unit contains all the constants representing errors used by the Error module.

All constants in the ErrorNum module are exported unqualified. (This means you can use the constants directly without having to use the qualifier "ErrorNum.".)


Exceptions

Description This unit contains all the constants corresponding to exception numbers in Turing for use in building exception handlers.

All constants in the Exceptions module are exported unqualified. (This means you can use the constants directly without having to use the qualifier "Exceptions.".)


exit

exit statement

Syntax An exitStatement is one of:

(a) | exit when trueFalseExpn
(b) | exit

Description An exit statement is used to stop the execution of a loop or for statement. Form (a) is the most common. Here, the true/false expression is evaluated. If it is true, the loop is terminated and execution jumps down and continues just beyond end loop or end for. If it is false, the loop keeps on repeating. Form (b) always causes the loop to terminate. This form is almost always used inside another conditional statement such as if.

Example Input names until finding Jones.

        var name : string
        loop
            get name
            exit when name = "Jones"
        end loop
Details Exit statements must occur only inside loop or for statements. An exit takes you out of the closest surrounding loop or for. The only other ways to terminate a loop or for is by return (in a procedure or in the main program, in which case the entire procedure or main program is terminated) or by result (in a function, in which case the entire function is terminated and a result value must be supplied).

The form "exit when trueFalseExpn" is equivalent to "if trueFalseExpn then exit end if".


exp

exp exponentiation function

Syntax exp (r : real) : real

Description The exp function is used to find e to the power r, where e is the natural base and r is the parameter to exp. For example, exp (0) returns 1 and exp (1) returns the value of e.

Example This program prints out the exponential values of 1, 2, 3, … up to 100.

        for i : 1 .. 100
            put "Exponential of ", i, " is ", exp (i)
        end for
See also ln (natural logarithm function).

See also predefined unit Math.


explicitCharConstant

explicitCharConstant character literal

Syntax An explicitCharConstant is a sequence of characters surrounded by single quotation marks, for example, 'Renzo'.

Example In the following, the explicit character constants are 'H' and 'Hi'.

        var c : char := 'H'
        var d : char (2) := 'Hi'
Details An explicit character constant must contain at least one character. If it contains exactly one character, as in 'A', its type is char. If it contains two or more characters (n characters), as 'Width', its type is char(n). The difference between the char and char(1) types is rarely of significance, but does make a difference in declarations without an explicit type, for example:

        var c := 'H'        % Type is char
        var d := 'Hi'   % Type is char (2)
        var e := "H"    % Type is string
The backslash \ is used in explicit string and char(n) constants to specify special values, for example, '\T' is the tab character. Similarly, the carat ^ is used to specify ASCII control characters, for example, '^H' is the ASCII backspace. See explicitStringConstants for details.

Explicit character constants cannot cross line boundaries. To represent a constant that is longer than a line, break it into two or more strings on separate lines and use + (catenation) to join the individual strings. See catenation.

An explicit character constant may be limited in length by the implementation. We recommend that this limitation be at least 32767.

Explicit character constants, but not strings, are allowed to contain the character internal values 0 (called eos for end of string) and 128 (called uninitchar, used as the uninitialized string value).


explicitConstant

explicitConstant literal

Syntax An explicitConstant is one of:

(a) | explicitStringConstant | % e.g.: "Hello world"
(b) | explicitIntegerConstant | % e.g.: 25
(c) | explicitRealConstant | % e.g.: 51.8
(d) | explicitTrueFalseConstant % e.g.: true
(e) | explicitCharConstant | % e.g.: 'Hi'

Description An explicitConstant gives its value directly. For example, the value of the explicit constant 25 is twenty-five.

Example In the following, the explicit constants are "Hello world", 3.14159 and 2. Note that pi is a named constant rather than an explicit constant.

        put "Hello world"
        var diameter : real
        const pi := 3.14159
        diameter := pi * r ** 2
        var x := diameter
Details In some programming languages, explicit constants are called literals or literal values, because they literally (explicitly) give their values.

See also explicitStringConstant, explicitIntegerConstant, explicitRealConstant, explicitTrueFalseConstant and explicitCharConstant. See also enumeratedValue.


explicitIntegerConstant

explicitIntegerConstant integer literal

Syntax An explicitIntegerConstant is a sequence of one or more decimal digits (0 to 9) optionally preceded by a plus or minus sign. This is an alternate form that specifies a number base (such as base 2 or base 16).

Example In the following, the explicit integer constants are 0, 115 and 5.

        var count : int := 0
        const height := 115
        …
        count := height - 5
Details In current implementations of Turing, the range of the int (integer) type is from -2147483647 to 2147483647. In other words, the maximum size of integer is 2**31 - 1. This is the range that fits into four bytes, with one pattern left over (the largest negative 4-byte number) to represent the uninitialized value. See maxint.

Values can be written in base 2 or 16 or any other base in the range 2 to 36 (36 because there are 10 digits and 26 letters). This form begins with the base, such as 16, then #, and then the value written in that base, for example, 16#A has the value 10. The letters a, b, c … represent the digit values 10, 11, 12 … Capital letters A, B, C … can be used instead of lower case. Here are some examples.

2#1 |  | = 1 |  | (Base 2)
2#11 |  | = 3 |  | (Base 2)
16#a |  | = 10 |  | (Base 16)
16#FF |  | = 255 |  | (Base 16)
16#FFFF | = 32767 |  | (Base 16)
8#10 |  | = 8 |  | (Base 8)

Here is an example of using these:

        const maxnat1 := 16#FF      % Largest 1-byte natural number
        const maxint2 := 16#7FFF    % Largest 2-byte integer
You should be careful to avoid confusion about patterns such as 16#FFFF. It is tempting to think that this is the value 1, because the bit pattern (2-byte two's complement internal representation) for 1 is the same as the bit pattern for 16#FFFF = 32767. However, the value (as opposed to the internal representation) of 1 and 32767 are different.

See also int, maxint (the largest integer value), nat (positive values only) and int n (n-byte integers). See also intstr and natstr which convert integer and natural number values to corresponding character strings in any base, for example intstr (4, 0, 2) = "100".


explicitRealConstant

explicitRealConstant real literal

Syntax An explicitRealConstant consists of an optional plus or minus sign, a significant digits part, and an exponent part.

Example In the following, the explicit real constants are 0.0 and 2.93e3.

        var temperature : real := 0.0
        const speed := 2.93e3       % Value is 2,930.0
Details The significant digits part (or fractional part) of an explicit real constant consists of a sequence of one or more digits (0 to 9) optionally containing a decimal point (a period). The decimal point is allowed to follow the last digit as in 16. or to precede the first digit, as in .25.

The exponent part consists of the letter e or E followed optionally by a plus or minus sign followed by one or more digits. For example, in -9.837e-3 the exponent part is e-3. The value of -9.837e-3 is -9.837 times 0.001.

If the significant figures part contains a decimal point, then the exponent part is not required.


explicitStringConstant

explicitStringConstant string literal

Syntax An explicitStringConstant is a sequence of characters surrounded by quotation marks.

Example In the following, the explicit string constants are "Hello world", "" and "273 O'Reilly Ave.".

        var name : string := "Hello world"
        name := ""      % Null string, containing zero characters
        var address : string := "273 O'Reilly Ave."
Details Within an explicit string constant (and within an explicit character constant), the back slash \ is used to represent certain other characters as follows:

\" |  | quotation mark character
\n or \N | end of line character
\t or \T | tab character
\f or \F | form feed character
\r or \R | return character
\b or \B | backspace character
\e or \E | escape character
\d or \D | delete character
\\ |  | backslash character

For example, put "One\nTwo" will output One on one line and Two on the next. In an explicit character constant (which is surrounded by single quotes, as in 'John'), the backslash is not required before a double quote ", but it is required before a single quote ', as in these two constants:

'John said "Hello" to you'
'Don\'t cry'.

You can use the caret ^ to specify ASCII control characters, for example:

'^H' ASCII backspace character

The caret specifies that the top three bits of the character are set to zero. For any character c, the following is true:

'^c' = chr (ord ('c') & 2#11111)

However if c is the question mark, as in '^?', the bits are not turned off.

Explicit string constants cannot cross line boundaries. To represent a string that is longer than a line, break it into two or more strings on separate lines and use catenation (+) to join the individual strings.

An explicit string constant can contain at most 255 characters (this is in implementation constraint).

String values are not allowed to contain characters with the code values of 0 or 128; these character values are called eos (end of string) and uninitchar (uninitialized character). These are reserved by the implementation to mark the end of a string value and to see if a string variable has been initialized.


explicitTrueFalseConstant

explicitTrueFalseConstant boolean literal

Syntax An explicitTrueFalseConstant is one of:

(a) | true
(b) | false

Example The following determines if string s contains a period. After the for statement, found will be true if there is a period in s.

        var found : boolean := false
        for i : 1 .. length (s)
            if s = "." then
                found := true
            end if
        end for
Details true/false values are called boolean values. A boolean variable, such as found in the above example, can have a value of either true or false.

See also boolean type.


expn

expn expression

Syntax An expn is one of:

(a) | explicitConstant |  | % e.g.: 25
(b) | variableReference |  | % e.g.: width
(c) | constantReference |  | % e.g.: pi
(d) | expn infixOperator expn | % e.g.: 3 + width
(e) | prefixOperator expn | % e.g.: - width
(f) | (expn) |  |  | % e.g.: (width - 7)
(g) | substring |  |  | % e.g.: s (3 .. 5)
(h) | functionCall |  | % e.g.: sqrt (25)
(i) | setConstructor |  | % e.g.: modes (4, 3)
(j) | enumeratedValue |  | % e.g.: color . red

Description An expression (expn) returns a value; in the general case, this may involve a calculation, such as addition, as in the expression:

            3 + width
Example

        put "Hello world"           % "Hello world" is an expn
        var diameter : real
        const pi := 3.14159         % 3.14159 is an expn
        diameter := pi * r ** 2         % pi * r ** 2 is an expn
        var x := diameter               % diameter is an expn
Details In the simplest case, an expression (expn) is simply an explicit constant such as 25 or "Hello world". A variable by itself is considered to be an expression when its value is used. This is the case above, where the value of diameter is used to initialize x. More generally, an expression contains an operator such as + and carries out an actual calculation. An expression may also be a substring, function call, set constructor or enumerated value. For details, see the descriptions of these items.

The Turing infix operators are: +, -, *, /, div, mod, **, <, >, =, <=, >=, not=, not, and, or, =>, in, not in, shr (shift right), shl (shift left), and xor (exclusive or). For details, see infixOperator. The Turing prefix operators are +, - and not, ^ (pointer following) and # (see cheat). For details see prefix operator.

See also precedence of operators, as well as the int, real, string and boolean types.


export

export list

Syntax An exportList is:

export [ howExport ] id {, [ howExport ] id }

Description An export list is used to specify those items declared in a module, monitor or class that can be used outside of it. Items that are declared inside a module, monitor or class but not exported cannot be accessed outside of it.

Example In this example, the procedures names pop and push are exported from the stack module. These two procedures are called from outside the module on the last and third from last lines of the example. Notice that the word stack and a dot must precede the use of these names. Since top and contents were not exported, they can be accessed only from inside the module.

        module stack
            export push, pop
            var top : int := 0
            var contents : array 1..100 of string
            procedure push … end push
            procedure pop … end pop
        end stack

        stack . push ("Harvey")
        var name : string
        stack . pop (name)      % This sets name to Harvey
Details Procedures, functions, variables, constants and types can be exported. Modules, monitors or classes canot be exported. Parentheses are allowed around the items in an export list, as in:

        export (push, pop)
The following syntax specifies that each exported identifier can optionally be preceded by the keywords var, unqualified, pervasive and opaque. Of these, only opaque is available in Turing proper.

The form of howExport is:

{ exportMethod }

The form of exportMethod is one of:

(a) | var
(b) | unqualified
(c) | pervasive
(d) | opaque

The keyword var means that the exported variable can be changed outside of the exporting module, monitor or class. This keyword applies only to exported variables. For example, if string variable name is exported var from module M, name can be changed from outside of M by M.name := "Surprise!".

The keyword unqualified means that references to the exported item do not need to be prefixed by the name of the exporting item. For example, if module M exports procedure p unqualified, a call to p outside of M can be simply p instead of the usual M.p. A class cannot export variables or dynamic constants unqualified (because each object of the class has its own copies of these). The only things a class can export unqualified are types and compile time constants. The keyword unqualified can be abbreviated to ~. which is pronounced as "not dot".

The keyword pervasive, which is only meaningful if unqualified is also present, specifies that the exported item is to be visible in subsequent scopes, in other words that it is not necessary to import it into internal modules, monitors and classes.

The keyword opaque, which can only precede type names, specifies that outside the module, monitor or class, the type is considered to be distinct from all other types. This means, for example, that if the type is an array, it cannot be subscripted outside of the module. See module declaration for an example that uses opaque types. In most cases, classes are preferable to opaque types.

Exported subprograms are considered to be deferred, meaning that expansions are allowed to override these subprograms. See also deferred subprograms. These can be overridden using the keyword body before the resolving subprogram body.

A class cannot export items from its parent or it parent's ancestors. All exported item must be declared in the current class.

Details You can export all from a module, monitor or a class. This means that every sibmle that is legal to export is exported. You may also qualify the all, as in export opaque unqualified pervasive all where the qualifiers are added to each export item (if it makes sense).

If all is specified as the export item, no other item may be specified. Also, and all export affects only the module, monitor or class that it is given in. Any inheriting or implementing module, monitor or class does not export all unless they also specify it.

See also unit, module, monitor and class. See also import list, inherit clause, implement clause, implement by clause and deferred subprogram.


external

external declaration

Dangerous

Syntax An externalDeclaration is one of:

(a) external [ overrideName ] subprogramHeader
(b) external [ addressSpec ] var id [ : typeSpec ] [ :=expn ]

Description An external declaration is used to access variables or subprograms that are written in other languages or which require special linkage. This feature is implementation-dependent and dangerous and may cause arbitrary data or program corruption. From an interpretive environment such as Turing, this provides linkage to items that are part of the Turing system. For compiled versions of Turing, the linkage would be by means of a standard, operating system-specific linkage editor.

Details In form (a) the optional overrideName must be an explicit string constant, such as "printf". If it is omitted, the external name is the name in the subprogramHeader. See subprogramHeader.

The current implementation does not support form (b). This form is documented here in case a future version supports it. The addressSpec is a compile time expression (its value must fit in the range of the addressint type) or is a compile time string value. If the addressSpec is omitted, the identifier is the name of an external variable. This name represents an implementation-dependent method of locating a variable. At least one of typeSpec or expn must be present.

Declaring variables at absolute addresses is useful for device management in computer architectures with memory mapped device registers. External variables declared to be int or nat will by default be checked for initialization. To avoid this check, declare them to be int4 or nat4.

Example Place variable ttyData at hexadecimal location 9001 and assign it the character A.

        external 16#9001 var ttyData : char
        ttyData := 'A'  % Character A is assigned to hex location 9001
Example Access an external integer variable named ERRFLAG.

        external var ERRFLAG : int
        if ERRFLAG = 0 then …
Example Access an integer variable which is called y in this program but is called x externally.

        external "x" var y : int
Example Declare drawcircle to be a procedure that is externally known as circle.

        external "circle" procedure drawcircle (x, y, r, Color : int)


false

false boolean value (not true)

Syntax false

Description A boolean (true/false) variable can be either true or false (see boolean type).

Example

        var found : boolean := false
        var word : int
        for i : 1 .. 10
            get word
            found := found or word = "gold"
        end for
        if found = true then
            put "Found 'gold' in the ten words"
        end if
Details The line if found=true then can be simplified to if found then with no change to the meaning of the program.


fetcharg

fetcharg fetch argument function

Syntax fetcharg ( i : int ) : string

Description The fetcharg function is used to access the i-th argument that has been passed to a program from the command line. For example, if the program is run from the Turing environment using

:r file1 file2

then fetcharg(2) will return "file2". If a program called prog.x is run under UNIX using this command:

prog.x file1 file2

the value of fetcharg(2) will similarly be "file2".

The nargs function, which gives the number of arguments passed to the program, is usually used together with the fetcharg function. Parameter i passed to fetcharg must be in the range 0 .. nargs.

The 0-th argument is the name of the running program.

Example This program lists its own name and its arguments.

        put "The name of this program is : ", fetcharg ( 0 )
        for i : 1 .. nargs
            put "Argument ", i, " is ", fetcharg ( i )
        end for
Execute

See also nargs


File

Description This unit contains the predefined subprograms that deal with file manipulation on a whole-file basis (as opposed to manipulating the data in the file using open and close, etc.). These routines allow you to rename, copy and delete files, as well as get information about a file and get the free space on disk available for a file.

All routines in the File module are exported qualified (and thus must be prefaced with "File.").

Entry Points
Exists | Returns whether a file exists.
FullPath | Returns the full absolute path name of a file.
Parent | Returns the parent directory of a file or directory.
Status | Gets information about a file such as size, modification date, etc.
Copy | Copies a file to another location.
Rename | Renames a file or directory.
Delete | Deletes a file.
DiskFree | Gets the free space on the disk upon which a file or directory resides.

Details On the PC, a path name of a file or a directory can use either the forward slash or backward slash to separate directory names. The drive must be followed by a colon. Thus the following are legal path names:

        x:\students\west\example.t
        c:/turing/test.t
        /west/binary.t  (uses the default drive).
On the Macintosh, a path name of a file or directory can use the standard Macintosh format of Volume Name:Directory Name:Directory Name:File Name or the Unix format of /Volume Name/Directory Name/Directory Name/File Name. Note that the names can have spaces in them.

        HSA:Applications:Turing Files:example.t
        /HSA/Applications/Turing Files/example.t
On UNIX systems, the path name must correspond to the UNIX standard of using a forward slash between parts of the path.

        /export/home/west/turing/example.t
In general, you can achieve the greatest portability by using the UNIX standard for use in path names, as all Turing systems support it.


File.Copy

File.Copy Part of File module

Syntax File.Copy (srcPathName, destPathName : string)

Description File.Copy copies a file named by the srcPathName parameter to the file named by the destPathName parameter. The copy can be between different disks or file systems.

Details The source file name must be an actual file. This procedure will not copy directories.

If the File.Copy call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Note that you can use either forward or backward slashes to separate components in a path. If you use backward slashes, you must double them in a string literal. (i.e. "d:\\west\\example.t")

Example This program copies the file "d:\west\example.dat" to "new_example.t". in the current directory.

        File.Copy ("d:/west/example.dat", "new_example.t")
        if Error.Last = eNoError then
            put "File copied"
        else
            put "Did not copy the file."
            put "Error: ", Error.LastMsg
        end if

Execute An example program is available that copies a file to the current directory using File.Copy, displays its contents to the run window, and then deletes the file using File.Delete.
Status Exported qualified.

This means that you can only call the function by calling File.Copy, not by calling Copy.


File.Delete

File.Delete Part of File module

Syntax File.Delete (filePathName : string)

Description File.Delete is used to delete the file specified by the parameter filePathName. This is the equivalent of doing a del in DOS or rm in UNIX.

Details If the File.Delete call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program deletes the file called information.

        File.Delete ("information")
        if Error.Last = eNoError then
            put "File delete"
        else
            put "Did not delete the file."
            put "Error: ", Error.LastMsg
        end if
Execute An example program is available that creates a file in the current directory, and then deletes the file using File.Delete.
Status Exported qualified.

This means that you can only call the function by calling File.Delete, not by calling File.


File.DiskFree

File.DiskFree Part of File module

Syntax File.DiskFree (pathName : string) : int

Description File.DiskFree gets the number of bytes for the disk upon which pathName resides. The pathName parameter can specify either a file or a directory. If it is the empty string, then File.DiskFree returns the number of bytes of free disk space on the disk upon which the execution directory resides.

Details If the File.DiskFree call fails, then it returns -1. Also Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

If there is more than 2,147,483,647 bytes free on a disk, the File.DiskFree function returns 2,147,483,647.

Example This program prints out the amount of space on the A: drive on a PC and in the execution directory.

        var bytesFree : int
        bytesFree := File.DiskFree ("A:\\")
        if bytesFree = -1 then
            put "Can't get free space on drive A:."
            put "Error: ", Error.LastMsg
        else
            put "There are ", bytesFree , " bytes free on drive A:"
        end if

        bytesFree := File.DiskFree (".")
        if bytesFree = -1 then
            put "Can't get free space on default directory."
            put "Error: ", Error.LastMsg
        else
            put "There are ", bytesFree , " bytes free on the default dir"
        end if

Execute

Status Exported qualified.

This means that you can only call the function by calling File.DiskFree, not by calling DiskFree.


File.Exists

File.Exists Part of File module

Syntax File.Exists (pathName : string) : boolean

Description File.Exists returns true if a file by the name of pathName exists. It will return false if pathName is a directory.

Details If the File.Exists returns false, you can examine Error.Last or Error.LastMsg for more information (i.e. whether the path failed or the file was simply not found).

Example This program loops until the user types in a path name that either doesn't already exist or is allowed to be overwritten.

        var pathName : string
        var choice : string
        loop
            put "Enter file name to write results to" ..
            get pathName
            if File.Exists (pathName) then
                put "Overwrite ", pathName, "?" ..
                get choice
                exit when choice = "y"
            else
                exit
            end if
        end loop
Execute An example program is available that creates a file in the current directory, tests for its existence using File.Exists and deletes the file using File.Delete.
Status Exported qualified.

This means that you can only call the function by calling File.Exists, not by calling Exists.


File.FullPath

File.FullPath Part of File module

Syntax File.FullPath (pathName) : string) : string

Description File.FullPath returns a string representing the full absolute path name in Turing format (forward slashes) of the path that is passed to the function. The path name passed in does not have to describe an existing file or directory.

Details The full path name will be in Turing format and include the drive name (for example "d:/turing/examples/games/SpaceGame.t")

Example This program obtains a path from the user and then outputs a full path name based on the path.

        var pathName : string
        get pathName
    put "Full path = ", File.FullPath (pathName)

Execute

Details Another example is available that checks whether a file and all of the directories in the path to the file exist. This program illustrates the use of File.FullPath, File.Parent, File.Exists, and Dir.Exists.
Status Exported qualified.

This means that you can only call the function by calling File.FullPath, not by calling FullPath.


File.Parent

File.Parent Part of File module

Syntax File.Parent (pathName : string) : string

Description File.Parent returns a string representing the parent directory in Turing format (forward slashes) of the path passed as a parameter. The path name passed in does not have to describe an existing file or directory.
Attempting to obtain the parent directory of a root directory (for example "c:/") will return the same root directory and will set the value returned by Error.Last to a non-zero value.
Example This program obtains a path from the user and then lists all the parent directories until it reaches the root directory.

        var pathName : string
        put "Enter a path: " ..
        get pathName
        loop
            pathName := File.Parent (pathName)
            exit when Error.Last not= eNoError
            put pathName
        end loop
Execute

Details Another example is available that checks whether a file and all of the directories in the path to the file exist. This program illustrates the use of File.FullPath, File.Parent, File.Exists, and Dir.Exists.
Status Exported qualified.

This means that you can only call the function by calling File.Parent, not by calling Parent.


File.Rename

File.Rename Part of File module

Syntax File.Rename (srcPathName, destName : string)

Description File.Copy renames a file or directory named by the srcPathName parameter to the destName parameter. The destName parameter must be a name only. In other words File.Rename can't move a file between different directories.

Details If the File.Rename call fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program renames the file "/usr/west/example" to "testcase"

        File.Rename ("/usr/west/example", "testcase")
        if Error.Last = eNoError then
            put "File renamed"
        else
            put "Did not rename the file."
            put "Error: ", Error.LastMsg
        end if
Execute An example program is available that creates a file in the current directory, renames it to a different name using File.Rename, checks the existence of both files using File.Exists and then deletes the file using File.Delete.
Status Exported qualified.

This means that you can only call the function by calling File.Rename, not by calling Rename.


File.Status

File.Status Part of File module

Syntax File.Status (pathName : string, var size, attribute, fileTime : int)

Description File.Status is used to get assorted information about a file or directory. When the function is called with a specified pathName, it returns the information about the file in the other parameters.

The size parameter is the size of the file in bytes.

The attribute parameter has its individual bits set as exactly as the attribute parameter in Dir.GetLong subprogram does. See Dir.GetLong for the list of attribute constants.

The fileTime is the time of last modification of the file. It is returned as the number of seconds since 00:00:00 GMT 1/1/1970. To convert this to a string, use Time.SecDate.

Details If the File.Status call fails, size, attribute and fileTime are all set to 1. Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example This program prints information about the NotePad.exe application in Windows found at "c:\windows\notepad.exe". (Note on some systems, this will be "c:\winnt\notepade.exe"

        const pathName : string := "c:/windows/notepad.exe"
        var size, attribute, fileTime : int
        File.Status (pathName, size, attribute, fileTime )
        if Error.Last = eNoError then
            put "      Name: ", File.FullPath (pathName)
            put "   Created: ", Time.SecDate (fileTime)
            put "      Size: ", size, " bytes"
            put "Attributes: " ..
            if (attribute and ootAttrDir) not= 0 then
                put "Directory " ..
            else
                put "" ..
            end if
            if (attribute and ootAttrRead) not= 0 then
                put "Readable " ..
            else
                put "" ..
            end if
            if (attribute and ootAttrWrite) not= 0 then
                put "Writable " ..
            else
                put "" ..
            end if
            if (attribute and ootAttrExecute) not= 0 then
                put "Executable", skip
            else
                put skip
            end if
        else
            put "Unable to get file information"
            put "Error: ", Error.LastMsg, skip
        end if

Execute

Execute Another example program is available that uses File.Status to determine the status of several files and directories.
Status Exported qualified.

This means that you can only call the function by calling File.Status, not by calling Status.


flexible

flexible array initialization

Syntax flexible array indexType { , indexType } of typeSpec

Description The flexible keyword allows an array to be resized using new at a later point in time. The indices may have compile-time or run-time upper bounds (the lower bound must be compile-time). The upper bounds can be changed by using:

        new name , newUpper1 {,newUpper2}
The existing array entries will retain their values, except that any index made smaller will have the corresponding array entries lost. Any index made larger will have the new array entries uninitialized (if applicable).

Additionally, the upper bound (both in the declaration and the new statement) can be made one less than the lower bound. This effectively makes an array that contains 0 elements. It can later be increased in size with another new.

In the current implementation (1999), with a multi-dimensional array with a non-zero number of total elements, it is a run-time error to change any but the first dimension (unless one of the new upper bounds is one less than the corresponding lower bound, giving 0 elements in the array) as the algorithm to rearrange the element memory locations has not yet been implemented.

Currently, only variables can be declared in this form. There is no flexible array parameter type, although a flexible array can be passed to an array parameter with “*” as the upper bound.

Example See array for an example of flexible.

Execute

See also array and new.


floor

floor real-to-integer function

Syntax | floor ( r : real ) : int
Description | Returns the largest integer that is less than or equal to r.
Details | The floor function is used to convert a real number to an integer. The result is the largest integer that is less than or equal to r. In other words, the floor function rounds down to the nearest integer. For example, floor (3) is 3, floor (2.75) is 2 and floor (-8.43) is -9.
See also | ceil and round functions.


Font

Description This unit contains the predefined subprograms that deal with fonts. Using these routines, you can display text in a selected font name, size and style on the screen. Note that output in a particular font is treated as graphics output.

All routines in the Font module are exported qualified (and thus must be prefaced with "Font.").

Details There is a default font. You can draw in and obtain information about the default font by passing fontDefaultID to Font.Draw, Font.Width and Font.Sizes. The default font is the same font as is used by put in the output window.

Entry Points
New | Selects a particular font name, size and style for a new font.
Free | Frees up the font created by using New.
Draw | Draws text in a given font.
Width | Gets the width in pixels of a particular piece of text in a specified font.
Sizes | Gets the height and various leadings of a specified font.
Name | Returns the name of the specified font.
StartName | Prepares to list all available fonts,
GetName | Gets the next font name.
GetStyle | Gets all the available styles for a specified font.
StartSize | Prepares to list all available sizes for a specified font and style.
GetSize | Gets the next font size.


Font.Draw

Font.Draw Part of Font module

Syntax Font.Draw (txtStr : string, x, y, fontID, Color : int)

Description Font.Draw is used to actually draw text in a specified font. The textStr parameter contains the string to be drawn. The x and y parameters are the location of the lower left hand corner of the text to be displayed. The fontID parameter is the number of the font in which the text is to be drawn. The Color parameter is used to specify the color in which the text is to appear.

Note that the text that appears is completely unrelated to the text that appears using put. Font.Draw is a graphics command and thus does not use or affect the cursor location.

The text drawn by the Font.Draw procedure does not erase the background.

Details If Font.Draw is passed an invalid font ID, a fatal error occurs. If the Font.Draw call fails for other (non-fatal) reasons, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program prints out several phrases in a variety of fonts.

        var font1, font2, font3, font4 : int
        font1 := Font.New ("serif:12")
        assert font1 > 0
        font2 := Font.New ("sans serif:18:bold")
        assert font2 > 0
        font3 := Font.New ("mono:9")
        assert font3 > 0
        font4 := Font.New ("Palatino:24:bold,italic")
        assert font4 > 0
        Font.Draw ("This is in a serif font", 50, 30, font1, red)
        Font.Draw ("This is in a sans serif font", 50, 80, font2, brightblue)
        Font.Draw ("This is in a mono font", 50, 130, font3, colorfg)
        Font.Draw ("This is in Palatino (if available)", 50, 180, font4, green)
        Font.Free (font1)
        Font.Free (font2)
        Font.Free (font3)
        Font.Free (font4)

Execute

Details To use the same font as is used by the put statement, use defFontID for the font number. This font does not have to be created or freed by the user, and allows a program to quickly place text in any location on the screen.
Example The program draws two strings in the default font (defFontID).

        Font.Draw ("Drawing Here", 100, 120, defFontID, brightred)
        Font.Draw ("and Here", 180, 90, defFontID, brightgreen)
Execute

Status Exported qualified.

This means that you can only call the function by calling Font.Draw, not by calling Draw.


Font.Free

Font.Free Part of Font module

Syntax Font.Free (fontID : int)

Description Font.Free is used to release a font that is no longer needed. There is a limit to the number of fonts that may be defined at any one time. By having a Font.Free for every Font.New, the number of simultaneously defined fonts is kept to a minimum.

Details If Font.Free is passed an invalid font ID, a fatal error occurs. If the Font.Free call fails for other (non-fatal) reasons, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program prints out several phrases in a variety of fonts.

        var font1, font2, font3, font4 : int
        font1 := Font.New ("serif:12")
        assert font1 > 0
        font2 := Font.New ("sans serif:18:bold")
        assert font2 > 0
        font3 := Font.New ("mono:9")
        assert font3 > 0
        font4 := Font.New ("Palatino:24:Bold,Italic")
        assert font4 > 0
        Font.Draw ("This is in a serif font", 50, 30, font1, red)
        Font.Draw ("This is in a sans serif font", 50, 80, font2, brightblue)
        Font.Draw ("This is in a mono font", 50, 130, font3, colorfg)
        Font.Draw ("This is in Palatino (if available)", 50, 180, font4, green)
        Font.Free (font1)
        Font.Free (font2)
        Font.Free (font3)
        Font.Free (font4)

Execute

Status Exported qualified.

This means that you can only call the function by calling Font.Free, not by calling Free.


Font.GetName

Font.GetName Part of Font module

Syntax Font.GetName : string

Description Font.GetName is used to get the next font available on the system. By using Font.StartName and then calling Font.GetName repeatedly, you can get the names of all the fonts available to the program.

Font.StartName must be called before any calls to Font.GetName. After that, Font.GetName returns the list of the font names, one per call. When there are no more sizes, Font.GetName returns the empty string.

Once the name of a font is known, it's possible to list the available styles (using Font.GetStyle) and the available sizes (using Font.StartSize and Font.GetSize) for that font.

Example The program lists all the fonts available on the system.

        var fontName : string
        Font.StartName
        loop
            fontName := Font.GetName
            exit when fontName = ""
            put fontName
        end loop

Execute

Example Another example is available that displays full information about the fonts including name, styles, and point sizes.
Status Exported qualified.

This means that you can only call the function by calling Font.GetName, not by calling GetName.


Font.GetSize

Font.GetSize Part of Font module

Syntax Font.GetSize : int

Description Font.GetSize is used to get the next size in the list of available font sizes for a particular font name and style.

Font.StartSize must be called before any calls to Font.GetSize. After that, Font.GetSize returns the list of sizes, one per call. When there are no more sizes, Font.GetSize returns 0.

Some fonts are “scalable”. This means that the computer can scale the fonts to fit any given size. (Under Microsoft Windows and the Apple Macintosh, TrueType and PostScript fonts are scalable with the appropriate utilities.) In this case, Font.GetSize returns -1.

Example See Font.StartSize for a program that lists all the fonts, styles and sizes available on the system.

Example An example is available that displays full information about the fonts including name, styles, and point sizes.
Status Exported qualified.

This means that you can only call the function by calling Font.GetSize, not by calling GetSize.


Font.GetStyle

Font.GetStyle Part of Font module

Syntax Font.GetStyle (fontName : string,
var bold, italic, underline : boolean) : string

Description Font.GetStyle is used to get the styles available on the system for a specified font. bold, italic and underline are set to true if bold, italic or underline versions of the font are available. Once the styles available for a font are known, it's possible to get the sizes available for each style by using Font.StartSize and Font.GetSize.

Example The program lists all the fonts and their styles available on the system.

        var fontName : string
        var bold, italic, underline : boolean
        Font.StartName
        loop
            fontName := Font.GetName
            exit when fontName = ""
            Font.GetStyle (fontName, bold, italic, underline)
            put fontName : 30 ..
            if bold then
                put "bold  " ..
            end if
            if italic then
                put "italic  " ..
            end if
            if underline then
                put "underline  " ..
            end if
            put ""
        end loop

Execute

Example An example is available that displays full information about the fonts including name, styles, and point sizes.
Status Exported qualified.

This means that you can only call the function by calling Font.GetStyle, not by calling GetStyle.


Font.Name

Font.Name Part of Font module

Syntax Font.Name (fontID : int) fontName : string

Description Font.Name is used to get the name of a font that is being used. The string that is returned can be used to determine which font is actually being used for the default fonts “serif”, “sans serif” and “mono”.

Example The program prints out the fonts used for “serif”, “sans serif” and “mono”.

        var serifFont, sansSerifFont, monoFont : int
        serifFont := Font.New ("serif:12")
        assert serifFont > 0
        sansSerifFont := Font.New ("sans serif:12")
        assert sansSerifFont > 0
        monoFont := Font.New ("mono:12")
        assert monoFont > 0
        put "serif = ", Font.Name (serifFont)
        put "sans serif = ", Font.Name (sansSerifFont)
        put "mono = ", Font.Name (monoFont)
        Font.Free (serifFont)
        Font.Free (sansSerifFont)
        Font.Free (monoFont)

Execute

Status Exported qualified.

This means that you can only call the function by calling Font.Name, not by calling Name.


Font.New

Font.New Part of Font module

Syntax Font.New (fontSelectStr : string) : int

Description Font.New is used to obtain a font for drawing. The fontSelectStrparameter specifies the name, size and style of the font. Font.New returns a font identifier which is then used by the Font.Draw procedure to draw text in the selected font.

The format for the fontSelectStrparameter is "Family:Size:Style". Each element is separated by a colon. The ":Style" is optional. If left out, the text appears in the standard face for the font.

Family is the name of the font, such as "Times", "Helvetica", etc. The name must match an existing font on the system. Because one does not necessarily know which fonts will be available and names for the same font change between different systems (i.e Times, Times-Roman, etc.), Turing defines three family names that will be mapped as closely as possible to fonts that exist on the system.

"serif" is used for a serifed body font. This will usually be mapped to Times-Roman.
"sans serif" is used for a non-serifed display font. This will usually be mapped to Arial.
"mono" is used for a mono spaced font. This will usually be mapped to Courier.

Size is the point size in which the text should appear. If the number is larger or smaller than can be created on a given system, the system will return the font of the largest or smallest size available and set Error.Last.

Under Turing, the size parameter may also have the form height x width where height and width are the pixel height and width desired. What is returned is the font scaled in order to fit into the width and height requested. The font name must be a scaleable font for this to succeed.

        example fontID := Font.New ("Ariel:18x12:Italic")
Style is the font style in which the text should appear. It can be one of "bold", "italic" or "underline". You can also have "bold,italic" and any other combination.

Details If the Font.New call fails, then it returns 0. Also Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

It is quite possible for Error.Last to be set, even if the call succeeds. Font.New will report success even if unable to successfully match the requested font with the available resources. A font will be set that matches as closely as possible the requested font and Last.Error will be set to indicate that some substitutions were required.

Example The program prints out several phrases in a variety of fonts.

        var font1, font2, font3, font4 : int
        font1 := Font.New ("serif:12")
        font2 := Font.New ("sans serif:18:bold")
        font3 := Font.New ("mono:9")
        font4 := Font.New ("Palatino:24:Bold,Italic")
        assert font1 > 0 and font2 > 0 and font3 > 0 and font4 > 0
        Font.Draw ("This is in a serif font", 50, 30, font1, red)
        Font.Draw ("This is in a sans serif font", 50, 80, font2, brightblue)
        Font.Draw ("This is in a mono font", 50, 130, font3, colorfg)
        Font.Draw ("This is in Palatino (if available)", 50, 180, font4, green)
        Font.Free (font1)
        Font.Free (font2)
        Font.Free (font3)
        Font.Free (font4)
Execute

Status Exported qualified.

This means that you can only call the function by calling Font.New, not by calling New.


Font.Sizes

Font.Sizes Part of Font module

Syntax Font.Sizes (fontID : int, var height, ascent, descent,
internalLeading : int)

Description Font.Sizes is used to get the metrics of a particular font. The various parts of the metric are illustrated below. Note that you can calculate the external leading by subtracting the ascent and descent from the height.

Details If Font.Sizes is passed an invalid font ID, a fatal error occurs. If the Font.Sizes call fails for other (non-fatal) reasons, the metrics for the default font will be returned. As well, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program gets information about 24pt Bold Italic Palatino.

        var fontID, height, ascent, descent, internalLeading,  : int
        var externalLeading: int
        fontID := Font.New ("Palatino:24:bold,italic")
        Font.Sizes (fontID, height, ascent, descent, internalLeading)
        externalLeading := height  ascent  descent
        put "The height of the font is ", height, " pixels"
        put "The ascent of the font is ", ascent, " pixels"
        put "The descent of the font is ", descent, " pixels"
        put "The internal leading of the font is ", internalLeading, " pixels"
        put "The external leading of the font is ", externalLeading, " pixels"
        Font.Free (fontID)

Execute

Status Exported qualified.

This means that you can only call the function by calling Font.Sizes, not by calling Sizes.


Font.StartName

Font.StartName Part of Font module

Syntax Font.StartName

Description Font.StartName is used to start the listing of all the fonts available on the system. This procedure is called before making calls to Font.GetName to get the name of the fonts available. Once the name of a font is known, it's possible to list the available styles (using Font.GetStyle) and the available sizes (using Font.StartSize and Font.GetSize).

Example The program lists all the fonts available on the system.

        var fontName : string
        Font.StartName
        loop
            fontName := Font.GetName
            exit when fontName = ""
            put fontName
        end loop

Execute

Example Another example is available that displays full information about the fonts including name, styles, and point sizes.
Status Exported qualified.

This means that you can only call the function by calling Font.StartName, not by calling StartName.


Font.StartSize

Font.StartSize Part of Font module

Syntax Font.StartSize (fontName, fontStyle : string)

Description Font.StartSize is used to start a listing of all the sizes for a particular font name and style.

The fontName parameter should be an actual font name (as opposed to the default names of “serif”, etc). You can get a list of the font names by using the Font.StartName and Font.GetName subprograms. The fontStyle parameter should be in the same format as would appear in the Font.New procedure.

Example The program lists all the fonts, styles and sizes available on the system.

        var fontName : string
        var bold, italic, underline : boolean
        var size : int
        var styles : array boolean, boolean, boolean of string :=
            init ("", "underline", "italic", "italic, underline", "bold",
                         "bold,underline", "bold,italic", "bold,italic,underline")
        Font.StartName
        loop
            fontName := Font.GetName
            exit when fontName = ""
            Font.GetStyle (fontName, bold, italic, underline)
            for b : false .. bold
                for i : false .. italic
                    for u : false .. underline
                        put fontName : 30, styles (b, i, u) : 22 ..
                        Font.StartSize (fontName, styles (b, i, u) )
                        loop
                            size := Font.GetSize
                            exit when size = 0
                            if size = -1 then put "scalable  " ..
                            else put size, " " ..
                            end if
                        end loop
                        put ""
                    end for
                end for
            end for
        end loop
Execute

Status Exported qualified.

This means that you can only call the function by calling Font.StartSize, not by calling StartSize.


Font.Width

Font.Width Part of Font module

Syntax Font.Width (txtStr : string, fontID : int) : int

Description Font.Width is used to obtain the width in pixels that a specified string will take to draw in a specified font. The textStr parameter is the string. The fontID parameter is the font in which the string would be drawn.

Details If Font.Width is passed an invalid font ID, a fatal error occurs. If the Font.Width call fails for other (non-fatal) reasons, the width for string in the default font will be returned. As well, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program gets information about 24pt Bold Palatino.

        const testString := "Test String"
        var width, fontID : int
        fontID := Font.New ("Palatino:24:Bold")
        width := Font.Width (testString, fontID)
        put "The width of \"" + testString + "\" is ", width, " pixels"
        Font.Draw (testString, 100, 100, fontID, black)
        Draw.Line (100, 50, 100, 150, brightred)
        Draw.Line (100 + width, 50, 100 + width, 150, brightred)
        Font.Free (fontID)

Execute

Status Exported qualified.

This means that you can only call the function by calling Font.Width, not by calling Width.


for

for statement

Syntax A forStatement is:

for [decreasing] [id ] : first .. last [by increment]
statementsAndDeclarations
end for

Description The statements and declarations in a for statement are repeatedly executed. In the first iteration, the identifier is assigned the value of first. With each additional iteration, the identifier increases by 1 (or by increment, if the by clause is present). The loop stops executing when adding 1 (or increment) to the identifier would cause the identifier to exceed last. first and last must be integer values (or else enumerated or char values). If you specify decreasing, then the identifier decreases by 1 (or by increment) each time through.

Increment must be a positive integer value. When the by clause is present, the for loop terminates as soon as the identifier would become greater than last, unless decreasing is present. If decreasing is present, the loop terminates when the identifier would become less than last.

Details The identifier is checked before it is added to (or subtracted from). This means that the loop

        for i : 1 .. maxint
will not cause an overflow.

Example Output 1, 2, 3 to 10.

        for i : 1 .. 10
            put i
        end for
Example Output 1, 3, 5, 7 and 9.

        for i : 1 .. 10 by 2
            put i
        end for
Example Output 10, 9, 8, down to 1.

        for decreasing j : 10 .. 1
            put j
        end for
Example Output 10, 6, and 2.

        for decreasing j : 10 .. 1 by 4
            put j
        end for
Example Output 1.

        for j : 1 .. 10 by 20
            put j
        end for
Example Output nothing.

        for j : 5 .. 2
            put j
        end for
Details The for statement declares the counting identifier (a separate declaration should not be given for i or j). The scope of this identifier is restricted to the for statement.

If first is a value beyond last, there will be no repetitions (and no error message). The counting identifier is always increased (or decreased) by 1 or increment if the by clause is present. Executing an exit statement inside a for statement causes a jump to just beyond end for. You are not allowed to change the counting variable (for example, you are not allowed to write i := 10).

The counting identifier can be omitted. In this case, the statement is just as before, except that the program cannot use the value of the identifier.

If decreasing is not present, first .. last can be replaced by the name of a subrange type, for example by dozen, declared by:

        type dozen : 1..12
Procedures, functions and modules cannot be declared inside a for statement. Just preceding the statements and declarations, you are allowed to write an "invariant clause" of the form:

        invariant trueFalseExpn
This clause is equivalent to: assert trueFalseExpn.


fork

fork statement

Dirty parts

Syntax A forkStatement is:

fork processId [ ( [ expn { , expn } ] ) ]
[ : reference [ , expn [ , reference ] ] ]

Description A fork activates (starts the concurrent execution of) a process declaration. If the process has parameters, a parenthesized list of expressions (expns) must follow the process' name (processId).

Example This program initiates (forks) two concurrent processes, one of which repeatedly outputs Hi and the other Ho. The resulting output is an unpredictable sequence of Hi's and Ho's, as greetings executes twice concurrently, one instance with its word set to Hi and the other with its word set to Ho.

        process greetings ( word : string )
            loop
                put word
            end loop
        end greetings

        fork greetings ( "Hi" )
        fork greetings ( "Ho" )
Details See procedure declaration for details about parameters. The first optional reference in the fork statement must be a boolean variable reference. The fork sets this to true if the process is actually activated. If this fails to occur (probably because stack space could not be allocated), this reference is set to false. If the fork fails but this reference is omitted, an exception occurs. See exception handlers.

The optional expn specifies the number of bytes for the process' stack; this overrides the optionally given stack size in the process declaration. The second optional reference must be a variable reference with the type addressint. See addressint. This variable is set to identify the process activation. This reference has the implementation-dependent meaning of locating the process' internal descriptor.

In this explanation of the fork statement, we have up to this point ignored the possibility of processes exported from modules. If the process is being forked from outside of a module from which it has been exported, the syntax of the fork statement is:

        fork moduleId . procedureId [ ( expn {, expn } ) ] …
In other words, the module's name and a dot must precede the process' name.


forward

forward subprogram declaration

Syntax A forwardDeclaration is:

forward subprogramHeader
[ import importItem {, importItem } ]

Description A procedure or function is declared to be forward when you want to define its header but not its body. This is the case when one procedure or function calls another, which in turn calls the first; this situation is called mutual recursion. The use of forward is necessary in this case, because every item must be declared before it can be used.

Example This example program evaluates an input expression e of the form t { + t } where t is of the form p { * p } and p is of the form (e ) or an explicit real expression. For example, the value of 1.5 + 3.0 * (0.5 + 1.5) halt is 7.5.

        var token : string

        forward procedure expn ( var eValue : real )

        forward procedure term ( var tValue : real )

        forward procedure primary ( var pValue: real )

        body procedure expn
            var nextValue : real
            term ( eValue )         % Evaluate t
            loop                    % Evaluate { + t}
                exit when token not= "+"
                get token
                term ( nextValue )
                eValue := eValue + nextValue
            end loop
        end expn

        body procedure term
            var nextValue : real
            primary (tValue )       % Evaluate p
            loop                    % Evaluate { * p}
                exit when token not= "*"
                get token
                primary ( nextValue )
                tValue := tValue * nextValue
            end loop
        end term
        body procedure primary
            if token = "(" then
                get token
                expn ( pValue )     % Evaluate (e)
                assert token = ")"
            else                    % Evaluate "explicit real"
                pValue := strreal ( token )
            end if
            get token
        end primary

        get token               % Start by reading first token
        var answer : real
        expn ( answer )         % Scan and evaluate input expression
        put "Answer is ", answer
Execute

Details Following a forward procedure or function declaration, the body of the procedure must be given at the same level (in the same sequence of statements and declarations as the forward declaration). This is the only use of the keyword body. See also body.

Any procedure or function that is declared using forward requires an import list. In this list, imported procedures or functions that have not yet appeared must be listed as forward. For example, the import list for expn is import forward term … Before a procedure or function can be called, before its body appears, and before it can be passed as a parameter, its header as well as headers of procedures or functions imported directly or indirectly by it must have appeared.

The keyword forward is also used in collection and type declarations.

See also collection and type declarations.


frealstr

frealstr real-to-string function

Syntax frealstr ( r : real, width, fractionWidth : int ) : string

Description The frealstr function is used to convert a real number to a string. For example, frealstr (2.5e1, 5, 1)="b25.0" where b represents a blank. The string is an approximation to r, padded on the left with blanks as necessary to a length of width.

The number of digits of the fraction to be displayed is given by fractionWidth.

The width must be non-negative. If the width parameter is not large enough to represent the value of r, it is implicitly increased as needed.

The fractionWidthmust be non-negative. The displayed value is rounded to the nearest decimal equivalent with this accuracy. In the case of a tie, the value is rounded to the next larger value. The result string is of the form:

                {blank} [-]{digit}. {digit}
If the leftmost digit is zero, then it is the only digit to the left of the decimal point.

The frealstr function approximates the inverse of strreal, although round-off errors keep these from being exact inverses.

See also the erealstr, realstr, strreal, intstr and strint functions.


free

free statement

Syntax A freeStatement is:

free [ collectionOrClassId, ] pointerVariableReference

Description A free statement destroys (deallocates) an element that has been allocated by a new statement.

Example Using a collection, declare a list of records and allocate one of these records. Then deallocate the record.

        var list : collection of
            record
                contents : string ( 10 )
                next : pointer to list
                            % Short form: next : ^ list
            end record
        var first : pointer to list % Short form: var next : ^ list
        new list, first
                % Allocate an element of list; place its location in first
                % Short form: new first
        …
        free list, first    % Deallocate the element of list located by first
                    % Short form: free first
Details The free statement sets the pointer variable to the nil value. See the new statement for examples of allocating elements of classes and values of types. It the pointer locates a type, the collectionOrClassId in the free statement must be omitted.

An imported class can have one of its objects destroyed (by the free statement) only if the class is imported var.

The collectionOrClassId is optional in the free statement.

See also class and collection declarations, the pointer type, the new statement and the nil value.


function

function declaration

Syntax A functionDeclaration is:

function id [ ( [paramDeclaration {, paramDeclaration } ] ) ]
 |  | : typeSpec
 | statementsAndDeclarations
end id

Description A function declaration creates (but does not run) a new function. The name of the function (id) is given in two places, just after function and just after end.

Example

        function doubleIt ( x : real ) : real
            result 2.0 * x
        end doubleIt

        put doubleIt ( 5.3 )        % This outputs 10.6
Details The set of parameters declared with the function are called formal parameters. For example, in the doubleIt function, x is a formal parameter. A function is called (invoked) by a function call which consists of the function's name followed by the parenthesized list of actual parameters (if any). For example, doubleIt (5.3) is a call having 5.3 as an actual parameter. If there are no parameters and no parentheses, the call does not have parentheses. The keyword function can be abbreviated to fcn. See also functionCall and procedureDeclaration.

Each actual non-var parameter must be assignable to the type of its corresponding formal parameter. See also assignability.

A function must finish by executing a result statement, which produces the function's value. In the above example, the result statement computes and returns the value 2.0 * x.

In principle, a function (1) should not change any variables outside of itself (global variables) or (2) should not have var parameters. In other words, it should have no side effects. The original implementation prevented (1) and (2) and thereby prevented function side effects. Current implementations of Turing do not enforce this restriction.

The upper bounds of arrays and strings that are parameters may be declared to be an asterisk (*), meaning the bound is that of the actual parameter. See paramDeclaration for details about parameters.

Procedures and functions cannot be declared inside other procedures and functions.

The syntax of a functionDeclaration presented above has been simplified by leaving out the optional result identifier, import list, pre condition, init clause, post condition and exception handler. The full syntax is

        function [ pervasive ] id
            [ ( [ paramDeclaration {,paramDeclaration } ] ) ]
                [ resultId ] : typeSpec
            [ pre trueFalseExpn ]
            [ init id := expn {, id := expn } ]
            [ post trueFalseExpn ]
            [ exceptionHandler ]
            statementsAndDeclarations
        end id
The resultId is the name of the result of the function and can be used only in the post condition.

A function must be declared before being called; to allow for mutually recursive procedures and functions, there are forward declarations with later declaration of the procedure or function body. See forward and body declarations for explanations.

You declare parameterless functions using an empty parameter list. When this is done, a call to the function must include an empty parameter list.

See also import list, pre condition, init clause, post condition and exceptionHandler for explanations of these additional features.

See also pervasive.


functionCall

Syntax A functionCall is:

functionId [ ( [ expn { , expn } ] ) ]

Description A function call is an expression that calls (invokes or activates) a function. If the function has parameters, a parenthesized list of expressions (expns) must follow the function's name (functionId).

Example This function takes a string containing a blank and returns the first word in the string (all the characters up to the first blank).

        function firstWord ( str : string ): string
            for i : 1 .. length ( str )
                if str ( i ) = " " then
                    result str ( 1 .. i - 1)
                end if
            end for
        end firstWord

        put "The first word is: ", firstWord ("Henry Hudson")
                        % The output is Henry.
Details The parameter declared in the header of a function, is a formal parameter, for example, str above is a formal parameter. Each expression in the call is an actual parameter, for example, sample above is an actual parameter.

Each actual parameter passed to its non-var formal parameter must be assignable to that parameter (see assignability for details). See also functionDeclaration and procedureDeclaration.

In this explanation of functionCall, we have up to this point ignored the possibility of functions exported from modules. If the function is being called from outside of a module from which it has been exported, the syntax of the functionCall is:

        moduleId . functionId [ ( expn {, expn } ) ]
In other words, the module or monitor name and a dot must precede the function's name. If the function is being called from outside of a class from which it has been exported, the syntax of the functionCall is one of:

        (a) classId ( p ) . functionId [ ( [ expn {, expn } ] ) ]
        (b) p -> functionId [ ( [ expn {, expn } ] ) ]
In these p must be a pointer value that locates an object in the class. Form (b) is a short form for form (a).

See also class.


get

get file statement

Syntax A getStatement is:

get [ : streamNumber , ] getItem { , getItem }

Description The get statement inputs each of the getItems. Ordinarily, the output comes from the keyboard. However, if the streamNumber is present, the input comes from the file specified by the stream number (see the open statement for details). Also, input can be redirected so it is taken from a file rather than the keyboard. Check the documentation on the environment for instructions on doing so.

The syntax of a getItem is one of:

        (a) variableReference
        (b) skip
        (c) variableReference : *
        (d) variableReference : widthExpn
These items are used to support three kinds of input:

(1) token and character oriented input: supported by forms (a) and (b),

(2) line oriented input: supported by form (c), and

(3) character oriented input: supported by form (d).

Examples of these will be given, followed by detailed explanations.

Example Token-oriented input.

        var name, title : string
        var weight : real
        get name        % If input is Alice, it is input into name
        get title       % If input is "A lady", A lady is input
        var weight      % If input is 9.62, it is input into weight
Example Line-oriented input.

        var query : string
        get query : *   % Entire line is input into query
Example Character-oriented input.

        var code : string
        get code : 2        % Next 2 characters are input into code.
Details A token is a sequence of characters surrounded by white space, where white space is defined as the characters: blank, tab, form feed, new line, and carriage return as well as end-of-file. The sequence of characters making up the token are either all non-white space or else the token must be a quoted string (an explicit string constant). When the variableReference in form (a) is a string, integer, real, int n, nat n, or real n. Turing skips white space, reads a token into the variableReference, and then skips white space (stopping at the beginning of the next line).

If the variableReference is a string, the token is assigned to the variable (if the token is quoted, the quotation marks are first removed). See the examples involving name and title above. If the variableReference is an integer or a real, the token is converted to be numeric before being assigned to the variable. See the example involving weight above.

When the input is coming from the keyboard, no input is done until Return is typed. The line that is input may contain more than one token. Any tokens that are not input by one get statement will remain to be input by the next get statement.

Turing has been modified so that token-oriented input now also skips white space following the token, but does not skip beyond the beginning of the next line. This change implies that form (b) is usually not needed, as skip was used to skip white space after the token.

Form (a) supports char and char(n). If the type is char, exactly one character is read, with no skipping of white space before or after. This character may be, for example, a blank or a carriage return. If the type is char(n), exactly n characters are read, with no skipping of white space.

Example Inputting char and char(n) types using form (a). The statement get c:1 is not legal, because length specification is not allowed with character variables.

        var c : char
        var d : char ( 3 )
        get c           % Read one character.
        get d           % Read three characters
Details Form (a) supports enumerated types. If the type is an enumerated type, then the token read in must be one of the elements of the enumerated type.

Example Inputting an enumerated type using form (a). The statement get c:1 is not legal, because length specification is not allowed with enumerated variables.

        type colors : enum (red, blue, green)
        var c : colors
        get c           % Read one of red, green or blue
Details Form (a) supports boolean. If the type is an boolean type, then the token read in must be one of "true" or "false"

Example Inputting a boolean type using form (a). The statement get c:1 is not legal, because length specification is not allowed with boolean variable.

        var tf : boolean
        get tf          % Read one of true or false
Details In form (b) of getItem, skip causes white space in the input to be skipped until non-white space (a token) or the end-of-file is reached. This is used when the program needs to determine if there are more tokens to be input. To determine if there are more tokens to be read, the program should first skip over any possible white space (such as a final new line character) and then test to see if eof (end-of-file) is true. This is illustrated in this example:

Example Using token-oriented input, input and then output all tokens. This example gives what used to be the standard way of reading tokens up to end of file. With the new meaning of form (a) for reading tokens, the get skip line can be omitted. This omission is possible because the line get word now automatically skips white space following the input value, up to the beginning of the next line.

        var word : string
        loop
            get skip        % Skip over any white space
            exit when eof   % Are there more characters?
            get word        % Input next token
            put word        % Output the token
        end loop
In the above and the next example, if the input has been redirected so that it is from a file, eof becomes true exactly when there are no more characters to be read. If the input is coming from the keyboard, you can signal eof by typing control-Z (on a PC) or control-D (on UNIX).

Details In form (c) of getItem, the variableReference is followed by :* which implies line-oriented input. This form causes the entire line (or the remainder of the current line) to be read. In this case the variable must be a string (not an integer or real). The new line character at the end of the line is discarded. It is an error to try to read another line when you are already at the end of the file. The following example shows how to use line-oriented input to read all lines in the input.

Example Using line-oriented input, input and then output all lines.

        var line : string
        loop
            exit when eof   % Are there more characters?
            get line : *    % Read entire line
            put line
        end loop
Details In form (d) of getItem, the variableReference is followed by

        : widthExpn
which specifies character-oriented input. This form causes the specified number (widthExpn) of characters to be input (or all of the remaining characters if not enough are left). If no characters remain, the null string is read and no warning is given. In this form, the new line character is actually input into the variableReference (this differs from line-oriented input which discards new line characters). The following example shows how to use character-oriented input to read each character of the input. Form (d) can be used with string and char(n) variables, but not with char, int or any other type.

Example Using character-oriented input, input and then output all characters.

        var ch : string ( 1 )
        loop
            exit when eof   % Are there more characters?
            get ch : 1      % Read one character
            put ch ..       % Output the character, which
                        % may be a new line character
        end loop
Example Using character-oriented input, input two characters.

        var d : char ( 3 ) := 'abc'
        get d : 2           % Read two character (replace 'ab')
See also read statement, which provides binary file input.


getch

getch get character procedure

Syntax getch ( var ch : string ( 1 ) )

Description The getch procedure is used to input a single character without waiting for the end of a line. The parameter ch is set to the next character in the keyboard buffer (the oldest not-yet-read character).

Example This program contains a procedure called getKey which causes the program to wait until a key is pressed.

        setscreen ("graphics")

        procedure getKey
            var ch : string (1)
            getch (ch)
        end getKey

        for i : 1 .. 1000
            put i : 4, " Pause till a key is pressed"
            getKey
        end for
Details The screen should be in a "screen" or "graphics" mode. See the setscreen procedure for details. If the screen is not in one of these modes, it will automatically be set to "screen" mode.

On IBM PC's some keys, such as the left arrow key, insert key, delete key, and function keys do not produce ordinary character values. These keystrokes are returned by getch as their "scan code" with 128 added to them, unless the scan code already has a value of 128 or greater. This provides a unique value for every key on the keyboard. See Appendix D for these codes.

See also hasch (has character) which is used to see if a character has been typed but not yet read.

See also predefined unit Input.


getchar

getchar get character function

Syntax getchar : char

Description The getchar function is used to input a single character without waiting for the end of a line. The next character in the keyboard buffer (the oldest not-yet-read character) is returned.

Example This program contains a procedure called getKey which causes the program to wait until a key is pressed.

        setscreen ("graphics")

        procedure getKey
            var ch : char
            ch := getchar
        end getKey

        for i : 1 .. 1000
            put i : 4, " Pause till a key is pressed"
            getKey
        end for
Details The screen should be in a "screen" or "graphics" mode. See the setscreen procedure for details. If the screen is not in one of these modes, it will automatically be set to "screen" mode.

On IBM PC's some keys, such as the left arrow key, insert key, delete key, and function keys do not produce ordinary character values. These keystrokes are returned by getchar as their "scan code" with 128 added to it, unless the scan code already has a value of 128 or greater. This provides a unique value for every key on the keyboard. See Appendix D for these codes.

See also hasch (has character) which is used to see if a character has been typed but not yet read.

See also predefined unit Input.


getenv

getenv get environment function

Syntax getenv ( symbol : string ) : string

Description The getenv function is used to access the environment string whose name is symbol. These strings are determined by the shell (command processor) or the program that caused your program to run. See also the nargs and fetcharg functions.

Example On a PC, this retrieves the environment variable USERLEVEL and prints extra instructions if USERLEVEL had been set to NOVICE. USERLEVEL can be set to NOVICE with the command SET USERLEVEL = NOVICE in the autoexec.bat file or in any batch file.

        const userLevel : string
        userLevel := getenv ("USERLEVEL")
            if userLevel = "NOVICE" then
            …           % put a set of instructions
        end if
See also See also predefined unit Sys.


getpid

getpid get process id function

Syntax | getpid : int
Description | The getpid function is used to determine the I.D. (number) that identifies the current operating system task (process). Beware that there are processes, activated by the fork statement, that are independent of the operating systems tasks. Under UNIX, the number is used, for example, for creating a unique name of a file.
See also | nargs, fetcharg and getenv. See also predefined unit Sys.


getpriority

getpriority function

Syntax | getpriority : nat
Description | The getpriority function returns the priority of an executing process in a concurrent program. A smaller value means a faster speed.
See also | setpriority, fork and monitor. See also predefined unit Concurrency.


GUI

Description This unit contains the predefined subprograms for creating and using a GUI (Graphical User Interface). Elements of the GUI include buttons, check boxes, text boxes, scroll bars, menus, etc.

For a general introduction to the the GUI module, see Introduction to Graphical User Interfaces.


GUI.AddLine

GUI.AddLine Part of GUI module

Syntax GUI.AddLine (widgetID : int, text : string)

Description GUI.AddLine adds text and a newline to the current line of the text box specified by widgetID. It is essentially equivalent to put text in the text box. GUI.AddLine scrolls the text box (if necessary) so that the added text is now visible. The widgetID parameter must be the widget id of a text box. The text parameter is the text to be added to the text box.

Example The following creates a text box and puts the numbers from 1 to 25 in it.

        import GUI
        var boxID : int := GUI.CreateTextBox (50, 50, 200, 200)
        for i : 1 .. 25
            GUI.AddLine (boxID, intstr (i))
        end for
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.AddLine, not by calling AddLine.

See also GUI.CreateTextBox.


GUI.AddText

GUI.AddText Part of GUI module

Syntax GUI.AddText (widgetID : int, text : string)

Description GUI.AddText adds text to the current line of the text box specified by widgetID. It does not add a newline after the text. It is essentially equivalent to put text ... in the text box. GUI.AddLine scrolls the text box (if necessary) so that the added text is now visible. The widgetID parameter must be the widget id of a text box. The text parameter is the text to be added to the text box.

Details To force a text box to scroll to the end of the text without adding any extra text, call GUI.AddText with "" (the null string) for the text parameter.

Example The following creates a text box and puts the numbers from 1 to 26 followed by the appropriate letter of the alphabet in it.

        import GUI
        var boxID : int := GUI.CreateTextBox (50, 50, 200, 200)
        for i : 1 .. 26
            GUI.AddText (boxID, intstr (i))
            GUI.AddText (boxID, " ")
            GUI.AddLine (boxID, chr (64 + i))
        end for
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.AddText, not by calling AddText.

See also GUI.CreateTextBox.


GUI.Alert[2,3,Full]

GUI.Alert[2,3,Full] Part of GUI module

Syntax One of four procedures:

GUI.Alert (title, msg : string)
GUI.Alert2 (title, msg1, msg2 : string)
GUI.Alert3 (title, msg1, msg2, msg3 : string)
GUI.AlertFull (title : string,
msg : array 1 .. * of string, button : string)

Description Displays a dialog box with the string specified by msg in it. There is a single button labelled OK which dismisses the dialog and resumes execution. The title parameter specifies the window title under Microsoft Windows. On the Apple Macintosh, there is no title, so do not assume the user will see the title. The dialog box is centered on the screen.

The GUI.Alert2 and GUI.Alert3 procedures allow the user to specify a two or three line message respectively. The GUI.AlertFull procedure allows the user to specify any number of lines of text in the string array specified by msg as well as the text in the dismissal button. Any empty strings at the end of the array are not displayed.

Note: This function is not available in the current version of the GUI Procedure Library (shipping with Turing 4.0 and MacOOT 1.5). It is documented here for use with future shipping version of Turing. It is likely to be implemented in the version of Turing released in September 2002. Check the release notes that are found in the on-line help to find out if this function is now available.

Example The following program asks the user for the name of a file puts up an alert dialog box if it fails.

        import GUI in "%oot/lib/GUI"

        var fileName : string
        var streamNumber : int

        loop
            fileName := GUI.SaveFile ("Save As")
            open : streamNumber, fileName, put
            exit when streamNumber > 0
            GUI.Alert ("Open Failure", "\"" + fileName +
                "\" could not be opened")
        end loop
Example The following program asks the user for the name of a file puts up a more complete alert dialog box if it fails.

        import GUI in "%oot/lib/GUI"

        var fileName : string
        var streamNumber : int
        loop
            fileName := GUI.SaveFile ("Save As")
            open : streamNumber, fileName, put
            exit when streamNumber > 0
            GUI.Alert2 ("Open Failure",
                "\"" + fileName + "\" could not be opened.",
                "Reason: " + Error.LastMsg)
        end loop
Example The following program fragment displays an alert with four lines of text and a button that says "Abort".

        var message : array 1 .. 10 of string
        for i : 1 .. 10
            message (i) := ""
        end for
        …
        message (1) := "The program must now quit"
        message (2) := "becasue of an unrecoverable error."
        message (3) := "A Read Error occurred while reading"
        message (4) := "file \"" + fileName + "\"."
        message (5) := Error.LastMsg
        GUI.AlertFull ("Error", message, "Abort")
Status Exported qualified.

This means that you can only call the function by calling GUI.Alert, not by calling Alert.


GUI.Choose[Full]

GUI.Choose[Full] Part of GUI module

Syntax One of two procedures:

GUI.Choose (title, msg1, msg2, msg3 : string,
 | btn1, btn2, btn3 : string) : int
GUI.ChooseFull (title : string,
 | msg : array 1 .. * of string,
 | btn1, btn2, btn3 : string,
 | defaultBtn : int) : int

Description Displays a dialog box with text and from one to three buttons. The user selects a button to dismiss the dialog. The number of the button pressed is returned by the function. The dialog box is centered on the screen.

The title parameter specifies the title in the window bar of the dialog box. The Apple Macintosh does not have a title bar, so do not assume that the user will see the string in the title parameter. The message is specified by strings in msg1, msg2 and msg3 for GUI.Choose and the string array message for GUI.ChooseFull. In each case, empty strings at the end of the list of strings are ignored. The btn1, btn2, and btn3 parameters specify the text to appear in the buttons. If the text is an empty string (""), the button is not displayed.

The function returns the button number from one to three that was chosen.

The defaultBtn parameter in GUI.ChooseFull specifies which, if any, button should be the default button. The default button is selected if the user presses Enter. If the default button is 0, then no button is highlighted as the default button.

Note: This function is not available in the current version of the GUI Procedure Library (shipping with Turing 4.0 and MacOOT 1.5). It is documented here for use with future shipping version of Turing. It is likely to be implemented in the version of Turing. Check the release notes that are found in the on-line help to find out if this function is now available.

Example The following program asks if the user wants coffee or tea and set wantsCoffee appropriately.

        import GUI in "%oot/lib/GUI"
        var wantsCoffee : boolean
        var choice : int := GUI.Choose ("Beverage Choice",
            "Do you want coffee or tea?", "", "", "Coffee", "Tea", "")
        if choice = 1 then
            wantsCoffee := true
        else
            wantsCoffee := false
        end if
Example The following program asks the user whether they want to save their work, don't save their work or Cancel.

        import GUI in "%oot/lib/GUI"

        % Returns false if cancelling operation
        procedure CheckUnsavedWork : boolean
            var message : array 1 .. 3 of string
            message (1) := "Changes to " + fileName + " have not been "
            message (2) := "saved. Unsaved work will be lost. Do you "
            message (3) := "want to save before quitting."
            var choice : int := GUI.ChooseFull ("Save Before Quit",
                message, "Save", "Don't Save", "Cancel", 1)
            if choice = 1 then
                SaveWork
            elsif choice = 3  then
                return false
            end if
            return true
        end CheckUnsavedWork
Status Exported qualified.

This means that you can only call the function by calling GUI.Choose, not by calling Choose.


GUI.ClearText

GUI.ClearText Part of GUI module

Syntax GUI.ClearText (widgetID : int)

Description Clears all the text in a text box specified by widgetID. The widgetID parameter must be the widget id of a text box.

Example The program lists 25 numbers in a text box. Every time the button is pressed, it clears the text box and prints the next 25 numbers.

        import GUI
        var boxID, buttonID, start : int
        start := 1

        procedure PrintTwentyFive
            GUI.ClearText (boxID)
            for i : start .. start + 24
                GUI.AddLine (boxID, intstr (i))
            end for
            start += 25
        end PrintTwentyFive

        boxID := GUI.CreateTextBox (50, 50, 200, 200)
        buttonID := GUI.CreateButton (50, 5, 0, "Next 25", PrintTwentyFive)
        PrintTwentyFive
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.ClearText, not by calling ClearText.

See also GUI.CreateTextBox.


GUI.CloseWindow

GUI.CloseWindow Part of GUI module

Syntax GUI.CloseWindow (window : int)

Description Closes a window with widgets in it. This procedure automatically disposes of any widgets in the window and makes certain that the GUI Library recognizes that the window no longer exists. This procedure will call Window.Close, so there is no need for the user to do so.

Example The program opens up a window with two buttons. If the button labelled "Close and Open" is pressed, the window is closed and a new window with two buttons is opened in a random location on the screen.

        import GUI

        const screenWidth : int := Config.Display (cdScreenWidth)
        const screenHeight : int := Config.Display (cdScreenHeight)
        const titleBarHeight : int := 32
        const windowEdgeSize : int := 13
        const windowWidth : int := 150
        const windowHeight : int := 100
        var windowID, windowNumber, closeButton, quitButton : int := 0

        procedure CloseAndOpen
            if windowID not= 0 then
                GUI.CloseWindow (windowID)
            end if
            windowNumber += 1
            var xPos : int := Rand.Int (0, screenWidth - windowWidth -
                windowEdgeSize)
            var yPos : int := Rand.Int (0, screenHeight - windowHeight -
                titleBarHeight)
            windowID := Window.Open ("title:Window #" +
                intstr (windowNumber) + ",graphics:" +
                intstr (windowWidth) + ";" + intstr (windowHeight) +
                ",position:" + intstr (xPos) + ";" + intstr (yPos))
            closeButton := GUI.CreateButton (10, 60, 130,
                "Close And Open", CloseAndOpen)
            quitButton := GUI.CreateButton (10, 10, 130, "Quit", GUI.Quit)
        end CloseAndOpen

        CloseAndOpen
        loop
            exit when GUI.ProcessEvent
        end loop
        GUI.CloseWindow (windowID)

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.CloseWindow, not by calling CloseWindow.

See also GUI.ShowWindow and GUI.HideWindow, for showing and hiding windows with widgets in them.


GUI.CreateButton[Full]

GUI.CreateButton[Full] Part of GUI module

Syntax GUI.CreateButton (x, y, width : int, text : string,
actionProc : procedure x ()) : int

GUI.CreateButtonFull (x, y, width : int, text : string,
actionProc : procedure x (), height : int, shortcut : char, default : boolean) : int

Description Creates a button and returns the button's widget ID.

The button widget is used to implement a textual button. When you click on a button, the button's action procedure is called. If a button is given a short cut, then entering the keystroke will cause the action procedure to be called. It will not visibly cause the button to depress.

Two Buttons

The x and y parameters specify the lower-left corner of the button. The width parameter specifies the width of the button. If width is less than the size necessary to display the button, the button is automatically enlarged to fit the text. The text parameter specifies the text to appear in the button. The actionProc parameter is the name of a procedure that is called when the button is pressed.

For GUI.CreateButtonFull, the height parameter specifies the height of the button. If height is less than the size necessary to display the button, the button is automatically enlarged to fit the text. The shortcut parameter is the keystroke to be used as the button's shortcut. The default parameter is a boolean indicating whether the button should be the default button. If there is already a default button, and default is set to true, then this button becomes the new default button.

Example The following program creates two buttons, one which draws a random circle on the screen and one which quits the program.

        import GUI

        procedure DrawRandomCircle
            var r : int := Rand.Int (20, 50)
            var x : int := Rand.Int (r, maxx - r)
            var y : int := Rand.Int (r, maxy - r)
            var c : int := Rand.Int (0, maxcolor)
            Draw.FillOval (x, y, r, r, c)
            % In case we drew over the buttons, redraw them.
            GUI.Refresh
        end DrawRandomCircle

        View.Set ("graphics:300;200,nobuttonbar ")
        var draw : int := GUI.CreateButtonFull (50, 10, 0, "Draw Circle",
            DrawRandomCircle, 0, '^D', true)
        var quitBtn : int := GUI.CreateButton (200, 10, 0, "Quit", GUI.Quit)
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details When GUI.CreateButton or GUI.CreateButtonFull is called, the newly created button will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

If a button's width or height is set to zero (or not specified at all), then the button is shaped to fit the text.

A button can be the default button for a window. The default button is drawn with a thicker border around it. If the user presses ENTER in a window with a default button, the default button's action procedure is called.

When a button is not enabled, the text in the button is grayed out and the button no longer responds to any mouse clicks or keystrokes until the button is enabled again.

Details The following GUI subprograms can be called with a button as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.SetLabel, GUI.SetDefault

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateButton, not by calling CreateButton.

See also GUI.SetLabel for changing the button's text, GUI.SetDefault for setting the default button in a window and GUI.SetColor for setting the button's color.


GUI.CreateCanvas[Full]

GUI.CreateCanvas[Full] Part of GUI module

Syntax GUI.CreateCanvas (x, y, width, height : int) : int

GUI.CreateCanvasFull (x, y, width, height : int,
border : int,
mouseDown : procedure x (mx, my : int),
mouseDrag : procedure x (mx, my : int),
mouseUp : procedure x (mx, my : int)) : int

Description Creates a canvas and returns the canvas' widget ID.

A canvas is a drawing surface for use by the program. It differs from just using the window surface to draw on in that (0, 0) represents the lower-left corner of the canvas and all drawing is clipped to the canvas. (This means that if you accidently attempt to draw outside of the canvas, it will not actually draw beyond the border of the canvas.)

Canvases have procedures that emulate all the procedures in the Draw module as well as a procedure to emulate Font.Draw, Pic.Draw, Pic.New, Pic.ScreenLoad and Pic.ScreenSave.

You can get mouse feedback from a canvas. Using the CreateCanvasFull method, you can specify three routines that are called when the mouse button is depressed while pointing in a canvas. One routine will be called when the user presses the mouse button down in a canvas. Another routine will be called while the user drags the mouse with the mouse button down. This routine is repeatedly called whenever the mouse changes position while the mouse button is down. The last routine is called when the mouse button is released. All three routines take an x and y parameter, which is the location of the mouse with respect to the canvas (i.e. (0, 0) is the lower-left corner of the canvas).

Output of Canvases.dem

The x and y parameters specify the lower-left corner of the canvas. The width and height parameters specify the width and height of the canvas.

For GUI.CreateCanvasFull, the border parameter specifies the type of border that surrounds the canvas and is one of 0, GUI.LINE, GUI.INDENT or GUI.EXDENT. A border of 0 is the default and is the same as GUI.LINE. GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the canvas appear indented or recessed. GUI.EXDENT makes the canvas appear to stand out from the window.

The mouseDown parameter is a procedure called when the user presses the mouse button in the canvas. The mouseDrag parameter is a procedure called when the user drags the mouse while the mouse button is still pressed. The mouseUp parameter is a procedure called when the user releases the mouse button. The parameters to all three are the x and y location of the mouse where the button was pressed (dragged/released). The coordinates are given with respect to the canvas (i.e. (0, 0) is the lower-left corner of the canvas).

Example The following program draws 10 random stars in the canvas.

        import GUI
        var canvas : int := GUI.CreateCanvas (10, 10, maxx - 20, maxy - 20)
        for i : 1 .. 10
            var x : int := Rand.Int (0, maxx - 20)
            var y : int := Rand.Int (0, maxy - 20)
            var c : int := Rand.Int (0, maxcolor)
            GUI.DrawFillOval (canvas, x, y, 20, 20, c)
        end for

Execute

Details When GUI.CreateCanvas or GUI.CreateCanvasFull is called, the newly created canvas will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

The border of the canvas is just outside the drawing surface, so GUI.GetWidth and GUI.GetHeight will return slight larger values than width and height.

When the canvas is disabled, clicking the mouse in the canvas does not call any of the mouseDown, mouseDrag, or mouseUp procedures. The appearance of the canvas does not change.

Details The following GUI subprograms can be called with a button as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.Draw…, GUI.FontDraw, GUI.Pic…, GUI.SetXOR

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateCanvas, not by calling CreateCanvas.

See also GUI.Draw…, GUI.FontDraw, GUI.Pic…, and GUI.SetXOR for drawing on a canvas.


GUI.CreateCheckBox[Full]

GUI.CreateCheckBox[Full] Part of GUI module

Syntax GUI.CreateCheckBox (x, y : int, text : string,
actionProc : procedure x (filled : boolean)) : int

GUI.CreateCheckBoxFull (x, y : int, text : string,
actionProc : procedure x (filled : boolean), alignment : int, shortcut : char) : int

Description Creates a check box (with accompanying text) and returns the check box's widget ID.

The check box widget is used to implement a check box that can be set or unset. When you click on a check box, the status of the check box flips from set to unset and back again and the check box's action procedure is called with the new status as a parameter. If a check box is given a short cut, then entering the keystroke will cause the check box to change status and the action procedure to be called. The new status will be displayed immediately.

Two Check Boxes

The x and y parameters specify the lower-left corner of the check box (unless alignment is set to GUI.RIGHT, in which case they specify the lower-right corner of the check box). The text parameter specifies the text (or label) beside the check box. The actionProc parameter is the name of a procedure that is called when the status of the check box changes. The actionProcprocedure must have one boolean parameter which is the new status of the check box. In GUI.CreateCheckBox, the check box's text is always to the right of the actual check box. In GUI.CreateCheckBoxFull, the text can be set to the right or left of the check box with the alignment parameter.

For GUI.CreateCheckBoxFull, the alignment parameter specifies the position of the check box in relation to the text as well as the meaning of the x and y parameters. The alignment parameter is one of 0, GUI.LEFT, or GUI.RIGHT. An alignment of 0 is the default and is the same as GUI.LEFT. GUI.LEFT means the actual box in the check box appears to the left of the check box's label and (x, y) specifies the lower-left corner. An alignment of GUI.RIGHT means that the actual box appears to the right of the check box's label and (x, y) specifies the lower-right corner of the check box. The shortcut parameter is the keystroke to be used as the button's shortcut. The default parameter is a boolean indicating whether the button should be the default button. If there is already a default button, and default is set to true, then this button becomes the new default button.

A check box's size is not specified during creation. It is determined based on the size of the text. Instead the user specifies the lower-left corner of the check box (or the lower-right if the check box is right justified).

Example The following program creates two buttons, one which draws a random circle on the screen and one which quits the program

        import GUI

        procedure DoNothing (status : boolean)
        end DoNothing

        View.Set ("graphics:300;100,nobuttonbar")
        var cb1 : int := GUI.CreateCheckBox (10, 10, "Check Box 1",
            DoNothing)
        var cb2 : int := GUI.CreateCheckBoxFull (200, 10, "Check Box 2",
            DoNothing, GUI.RIGHT, '2')
        GUI.SetCheckBox (cb2, true)
        var quitBtn : int := GUI.CreateButton (230, 10, 0, "Quit", GUI.Quit)
        loop
            exit when GUI.ProcessEvent
        end loop
        var cb1Status : boolean := GUI.GetCheckBox (cb1)
        var cb2Status : boolean := GUI.GetCheckBox (cb2)
        if cb1Status then
            put "Check box 1: filled"
        else
            put "Check box 1: empty"
        end if
        if cb2Status then
            put "Check box 2: filled"
        else
            put "Check box 2: empty"
        end if

Execute

Details When GUI.CreateButton or GUI.CreateButtonFull is called, the newly created check box will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a check box is not enabled, the label beside the check box is grayed out and the check box no longer responds to any mouse clicks or keystrokes until the check box is enabled again.

Details The following GUI subprograms can be called with a check box as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.SetLabel, GUI.GetCheckBox, GUI.SetCheckBox

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateCheckBox, not by calling CreateCheckBox.

See also GUI.SetLabel for changing the chec box's text and GUI.GetCheckBox and GUI.SetCheckBox for reading and setting the check box's state.


GUI.CreateFrame

GUI.CreateFrame Part of GUI module

Syntax GUI.CreateFrame (x1, y1, x2, y2, kind : int) : int

Description Creates a frame and returns the frame's widget ID.

A frame is a box drawn around other GUI widgets to make the window look better and help organize the GUI elements.

Three Types of Frames With a Label in Each Frame

Frames are the only GUI widgets that can have other widgets placed within them. Frames are passive widgets, meaning that they do not respond to button clicks or keystrokes.

The x1 and y1 parameters specify the lower-left corner of the frame and the x2 and y2 parameters specify the upper-right corner of the frame. The kind parameter specifies the type of frame. This is one of 0, GUI.LINE, GUI.INDENT, or GUI.EXDENT. A kind of 0 is the default and is the same as GUI.LINE.

GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the contents frame appear indented or recessed. GUI.EXDENT makes the contents of the frame appear to stand out from the window.

Example The following program draws three frames in the window and draws a label in each one.

        import GUI
        View.Set ("graphics:250;90,nobuttonbar")
        GUI.SetBackgroundColor (gray)
        var lineFrame, indentFrame, exdentFrame : int
        var lineLabel, indentLabel, exdentLabel : int
        lineFrame := GUI.CreateFrame (10, 10, 80, 70, 0)
        indentFrame := GUI.CreateFrame (90, 10, 160, 70, GUI.INDENT)
        exdentFrame := GUI.CreateFrame (170, 10, 240, 70, GUI.EXDENT)
        % Label the lines.
        lineLabel := GUI.CreateLabelFull (10, 10, "Line", 70, 60,
            GUI.CENTER + GUI.MIDDLE, 0)
        indentLabel := GUI.CreateLabelFull (90, 10, "Indent", 70, 60,
            GUI.CENTER + GUI.MIDDLE, 0)
        exdentLabel := GUI.CreateLabelFull (170, 10, "Exdent", 70, 60,
            GUI.CENTER + GUI.MIDDLE, 0)

Execute

Details When GUI.CreateFrame is called, the newly created frame will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

A frame widget is a passive widget and cannot be enabled or disabled.

Details The following GUI subprograms can be called with a frame as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateFrame, not by calling CreateFrame.


GUI.CreateHorizontalScrollBar[Full]

GUI.CreateHorizontalScrollBar[Full] Part of GUI module

Syntax GUI.CreateHorizontalScrollBar (x, y, size : int,
min, max, start: int, actionProc : procedure x (value : int)) : int

GUI.CreateHorizontalScrollBarFull (x, y, size : int,
min, max, start : int,
actionProc : procedure x (value : int),
arrowInc, pageInc, thumbSize : int) : int

Description Creates a horizontal (left-right) scroll bar and returns the scroll bar's widget ID.

A scroll bar is a widget that allows users to see a piece of a document that cannot be displayed on the screen in its entirety. The picture below shows a horizontal scroll bar. To control a scroll bar, there are a few choices: the user can click on the thumb (the box in the scroll bar) and slide it left or right, or the user can click in the scroll bar itself to the left or right of the thumb (in which case the thumb is moved up or down one "page"), or the user can click on the left or right arrows at the ends of the scroll bar (in which case the thumb is moved left or right one "arrow increment").

A Horizontal Scroll Bar

The programmer defines a page or an arrow increment. When the value of the scroll bar changes, the action procedure of the scroll bar is called with the new value as a parameter. The action procedure should then redraw the contents using the new value of the scroll bar.

The range of values that the scroll bar will give is determined by the min and max parameters in the Create call. The left side of the scroll bar represents the minimum value, while the right represents the maximum value. There is also the "thumb size". This represents the range of values that can be seen at once on the screen.

By default, the arrow increment (the amount the value is changed when the scrolling arrows are pressed) is set to one. The page increment (the amount the value is changed when the user clicks in the bar to the right or left of the thumb) is set to one quarter the difference between the minimum and the maximum. The "thumb size" is set to zero (see the description of scroll bars for an explanation of the thumb size).

The x and y parameters specify the lower-left corner of the scroll bar. The size parameter specifies the length of the scroll bar (including the arrows) in pixels. The min and max parameters are the minimum and maximum values returned by the scroll bar. The start parameter is the initial value of the scroll bar and should be between min and max inclusive. The actionProc parameter is the name of a procedure that is called when the value of the scroll bar is changed. The parameter to the action procedure is the current value of the scroll bar.

Example The following program creates a horizontal scroll bar. Whenever the scroll bar's value is changed, a message is displayed in the window.

        import GUI

        View.Set ("graphics:300;60,nobuttonbar")
        var scrollBar : int

        procedure ScrollBarMoved (value : int)
            Text.Locate (2, 3)
            put "Horizontal Scroll Bar: ", value : 4
        end ScrollBarMoved

        scrollBar := GUI.CreateHorizontalScrollBar (10, 10, 250,
            50, 150, 50, ScrollBarMoved)
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Description For GUI.CreateHorizontalScrollBarFull, the arrowInc parameter specifies the arrow increment (the amount the scroll bar's value is changed when the scroll arrows are pressed). The pageInc specifies the page increment (the amount the scroll bar's value is changed when the user clicks in the page left/right section of the scroll bar). The thumbSize parameter specifies the "thumb size". (See the scroll bar explanation for more detail on a scroll bar's "thumb size").

For example, if you have a window that can display 20 lines of text at once and there are 100 lines of text, you would set min to 1, max to 100 and thumbSize to 20. The value returned by the scroll bar would then be the line number of the first line on the screen to be displayed. When the scroll bar was at its maximum value, it would return 81, since by doing so, lines 81-100 would be displayed.

Example Here is an example program that scrolls a large picture over a smaller window.

        % The "ScrollPic" program.
        import GUI

        var h, v : int      % The scroll bars.
        var canvas : int        % The canvas.
        var pic : int       % The picture.
        const width : int := 220    % The width of the canvas.

        procedure ScrollPic (ignore : int)
            % Get the current value of the scroll bars.
            var x : int := GUI.GetSliderValue (h)
            var y : int := GUI.GetSliderValue (v)
            GUI.PicDraw (canvas, pic, -x, -y, picCopy)
        end ScrollPic

        pic := Pic.FileNew ("Forest.jpg")
        if pic <= 0 then
            put "Error loading picture: ", Error.LastMsg
            return
        end if

        View.Set ("graphics:265;265")

        canvas := GUI.CreateCanvas (15, 15 + GUI.GetScrollBarWidth,
            width, width)
        % Note the frame of the canvas is:
        %   (14, 14 + ScrollbarWidth) - (235, 235 + ScrollbarWidth)
        h := GUI.CreateHorizontalScrollBarFull (14, 14,
            221, 0, Pic.Width (pic) , 0, ScrollPic, 3, 100, width)
        v := GUI.CreateVerticalScrollBarFull (235,
            14 + GUI.GetScrollBarWidth, 221, 0, Pic.Height (pic),
            Pic.Height (pic), ScrollPic, 3, 100, width)
        ScrollPic (0) % Draw the picture initially

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details In some instances, you will want the the minimum and maximum values of the scroll bar to be reversed (right/top is minimum). In that case, call the GUI.SetSliderReverse procedure to flip the values of the scroll bar.

Scroll bars always have a fixed height (for horizontal scroll bars) or width (for vertical scroll bars). To get a scroll bar's width, use the GUI.GetScrollBarWidth function.

When GUI.CreateHorizontalScrollBar or GUI.CreateHorizontalScrollBarFull is called, the newly created scroll bar will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a scroll bar is not enabled, the gray in the bar is set to white and the thumb is not displayed. The scroll bar no longer responds to any mouse clicks until the scroll bar is enabled again.

Details The following GUI subprograms can be called with a scroll bar as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.GetSliderValue, GUI.SetSliderValue, GUI.SetSliderMinMax, GUI.SetSliderSize, GUI.SetSliderReverse, GUI.SetScrollAmount

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateHorizontalScrollBar, not by calling CreateHorizontalScrollBar.

See also GUI.GetSliderValue and GUI.SetSliderValue for reading and setting the value of a scroll bar, GUI.SetSliderMinMax for changing the minimum and maximum values of a scroll bar, and GUI.SetScrollAmount for changing the scrolling increments and thumb size of a scroll bar. See also GUI.SetSliderSize for setting the length of a scroll bar and GUI.SetSliderReverse for reversing the sense of a scroll bar.


GUI.CreateHorizontalSlider

GUI.CreateHorizontalSlider Part of GUI module

Syntax GUI.CreateHorizontalSlider (x, y, length : int,
min, max, start : int, actionProc : procedure x (value : int)) : int

Description Creates a horizontal (left-right) slider and returns the slider's widget ID.

A slider is a widget that allows the user to set a continuous set of values. It has a real-life equivalent in things such as a stereo volume control.

A Horizontal Slider

To control a slider, the user clicks on the slider box and drags it back and forth. Every time the value changes, a procedure is called with the new value as a parameter.

The range of values that the slider will give is determined by the min and max parameters in the Create call. The left side of the slider represents the minimum value, while the right represents the maximum value.

The x and y parameters specify the lower-left corner of the slider track. This means that the slider actually extends above and below this point (and slightly to the left of it to take into account the rounded end of the track). The length parameter specifies the length of the track in pixels. (You can use GUI.GetX, GetY, GetWidth, and GetHeight to get the exact dimensions of the slider.) The min and max parameters are the minimum and maximum values returned by the slider. The start parameter is the initial value of the slider and should be between min and max inclusive. The actionProc parameter is the name of a procedure that is called when the value of the slider is changed. The parameter to the action procedure is the current value of the slider.

Example The following program creates a horizontal slider. Whenever the slider's value is changed, a message is displayed in the window.

        import GUI

        View.Set ("graphics:300;60,nobuttonbar")
        var slider : int
        procedure SliderMoved (value : int)
            Text.Locate (2, 3)
            put "Horizontal Slider: ", value : 4
        end SliderMoved

        slider := GUI.CreateHorizontalSlider (10, 10, 250,
            50, 150, 50, SliderMoved )
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details In some instances, you will want the the minimum and maximum values of the slider to be reversed (right is minimum). In that case, call the GUI.SetSliderReverse procedure to flip the values of the slider.

Sliders always have a fixed height (for horizontal sliders) or width (for vertical sliders).

When GUI.CreateHorizontalSlideror GUI.CreateHorizontalSliderFull is called, the newly created slider will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a slider is not enabled, the appearance does not change. However, the slider no longer responds to any mouse clicks until it is enabled again.

Details The following GUI subprograms can be called with a slider as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.GetSliderValue, GUI.SetSliderValue, GUI.SetSliderMinMax, GUI.SetSliderSize, GUI.SetSliderReverse

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateHorizontalSlider, not by calling CreateHorizontalSlider.

See also GUI.GetSliderValue and GUI.SetSliderValue for reading and setting the value of a slider, GUI.SetSliderMinMax for changing the minimum and maximum values of a slider. See also GUI.SetSliderSize for setting the length of a slider and GUI.SetSliderReverse for reversing the sense of a slider.


GUI.CreateLabel[Full]

GUI.CreateLabel[Full] Part of GUI module

Syntax GUI.CreateLabel (x, y : int, text : string) : int

GUI.CreateLabelFull (x, y : int, text : string,
width, height, alignment, fontID : int) : int

Description Creates a label and returns the label's widget ID.

The label widget is used to display text. It can be used to display text in a variety of fonts and sizes. Label widgets can also be aligned in a variety of ways.

Three Labels

The x and y parameters specify the lower-left corner of the area in which the text will be drawn. For GUI.CreateLabel, this is the lower-left corner of the text. The text parameter specifies the text of the label.

For GUI.CreateLabelFull, the width and height parameters specify the area in which the label is to appear. This is used for alignment purposes. See the program below for an example of aligning the text to different corners of the window. The alignment parameter specifies the alignment of the text in the text area. This value is the sum of horizontal alignment and the vertical alignment. The horizontal alignment is one of 0, GUI.LEFT, GUI.CENTER, or GUI.RIGHT. A horizontal alignment of 0 is the default and is the same as the alignment of GUI.LEFT. The vertical alignment is one of 0, GUI.TOP, GUI.MIDDLE, or GUI.BOTTOM. A horizontal alignment of 0 is the default and is the same as the alignment of GUI.BOTTOM. These alignments align the text in various ways in the text area. The fontID parameter specifies the font ID of the font to be used in the text field. The font ID is received from a Font.New call. Do not call Font.Free for this font ID until the label has been disposed of by calling GUI.Dispose.

By using the fondID parameter, labels can be have any size or typeface.

Labels are passive widgets, meaning that they do not respond to button clicks or keystrokes.

Example The following program creates three labels, one with the default alignment, the other two aligned to appear in the center and upper-right corner of the window.

        import GUI
        View.Set ("graphics:300;100,nobuttonbar ")
        var lowerLeft : int := GUI.CreateLabel (0, 0, "Lower-Left")
        var center : int := GUI.CreateLabelFull (0, 0, "Center", maxx, maxy,
            GUI.MIDDLE + GUI.CENTER, 0)
        var upperRight : int := GUI.CreateLabelFull (0, 0, "Upper-Right",
            maxx, maxy, GUI.RIGHT + GUI.TOP, 0)
Execute

Details When GUI.CreateLabel or GUI.CreateLabelFull is called, the newly created label will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

A frame widget is a passive widget and cannot be enabled or disabled.

Details The following GUI subprograms can be called with a label as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.GetSliderValue, GUI.SetSliderValue, GUI.SetSliderMinMax, GUI.SetLabel

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateLabel, not by calling CreateLabel.

See also GUI.SetLabel for changing the label's text.


GUI.CreateLabelledFrame

GUI.CreateLabelledFrame Part of GUI module

Syntax GUI.CreateLabelledFrame ( x1, y1, x2, y2, kind : int,
text : string ) : int

Description Creates a labelled frame and returns the frame's widget ID.

A labelled frame is a box with a text label drawn around other GUI widgets to make the window look better and help organize the GUI elements.

Three Types of Labelled Frames

Frames and labelled frames are the only GUI widgets that can have other widgets placed within them. Labelled frames are passive widgets, meaning that they do not respond to button clicks or keystrokes.

The x1 and y1 parameters specify the lower-left corner of the frame and the x2 and y2 parameters specify the upper-right corner of the frame. (The text will extend above the frame.) The kind parameter specifies the type of frame. This is one of 0, GUI.LINE, GUI.INDENT or GUI.EXDENT. A kind of 0 is the default and is the same as GUI.LINE.

GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the contents frame appear indented or recessed. GUI.EXDENT makes the contents of the frame appear to stand out from the window.

Example The following program draws three frames in the window.

        import GUI
        View.Set ("graphics:250;90,nobuttonbar")
        GUI.SetBackgroundColor (gray)
        var lineFrame, indentFrame, exdentFrame : int
        lineFrame := GUI.CreateLabelledFrame (10, 10, 80, 70, 0, "Line")
        indentFrame := GUI. CreateLabelledFrame (90, 10, 160, 70,
            GUI.INDENT, "Indent")
        exdentFrame := GUI. CreateLabelledFrame (170, 10, 240, 70,
            GUI.EXDENT, "Exdent")

Execute

Details When GUI.CreateLabelledFrame is called, the newly created labelled frame will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

A labelled frame widget is a passive widget and cannot be enabled or disabled.

Details The following GUI subprograms can be called with a labelled frame as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.SetLabel

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateLabelledFrame, not by calling CreateLabelledFrame.

See also GUI.SetLabel for changing the frame's text.


GUI.CreateLine

GUI.CreateLine Part of GUI module

Syntax GUI.CreateLine (x1, y1, x2, y2, kind : int) : int

Description Creates a line and returns the line's widget ID.

Lines are generally used to separate parts of a window. A line is used to make the window look better and help organize the GUI elements.

Three Types of Lines

Lines are passive widgets, meaning that they do not respond to button clicks or keystrokes.

The x1 and y1 parameters specify one end-point of the line and the x2 and y2 parameters specify the other end point. The line must either be horizontal or vertical (i.e. x1 must equal x2 or y1 must equal y2). The kind parameter specifies the type of line. This is one of 0, GUI.LINE, GUI.INDENT or GUI.EXDENT. A kind of 0 is the default and is the same as GUI.LINE.

GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the line appear indented or recessed. GUI.EXDENT makes the line appear to stand out from the window.

Example The following program draws three lines with three labels in the window.

        import GUI
        View.Set ("graphics:180;100,nobuttonbar")
        GUI.SetBackgroundColor (gray)
        var line, indentLine, exdentLine : int
        var lineLabel, indentLabel, exdentLabel : int

        line := GUI.CreateLine (30, 20, 30, 90, 0)
        indentLine := GUI.CreateLine (90, 20, 90, 90, GUI.INDENT)
        exdentLine := GUI.CreateLine (150, 20, 150, 90, GUI.EXDENT)% Label the lines.
        lineLabel := GUI.CreateLabelFull (30, 15, "Line", 0, 0,
            GUI.CENTER + GUI.TOP, 0)
        indentLabel := GUI.CreateLabelFull (90, 15, "Indent", 0, 0,
            GUI.CENTER + GUI.TOP, 0)
        exdentLabel := GUI.CreateLabelFull (150, 15, "Exdent", 0, 0,
            GUI.CENTER + GUI.TOP, 0)

Execute

Details When GUI.CreateLine is called, the newly created line will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

A line widget is a passive widget and cannot be enabled or disabled.

Details The following GUI subprograms can be called with a line as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateLine, not by calling CreateLine.


GUI.CreateMenu

GUI.CreateMenu Part of GUI module

Syntax GUI.CreateMenu (name : string) : int

Description Creates a menu and returns the menu's widget ID. The menu will be added after the other menus in the menu bar. If there are no previous menus, then a menu bar is automatically created and the menu added.

The name parameter specifies the text that appears in the menu bar.

A Menu With an Item Selected

Menus are used in most modern interfaces. In order to create a full set of menus, you must create the menu and then create the menu items in that menu. The menus are automatically added to the menu bar of the selected menu.

As of the v1.0 release of the GUI Library, it is an error to create a menu item without having created a menu first. In future releases it will be possible to create menus and attach and remove them from menu bars when desired.

Example The following program creates a series of menus with menu items in them. It then disables the second menu.

        import GUI in "%oot/lib/GUI"

        View.Set ("graphics:250;150,nobuttonbar")
        var first, second : int     % The menus.
        var item : array 1 .. 12 of int % The menu items.
        var name : array 1 .. 12 of string (20) :=
            init ("Quit", "---", "A", "B", "---", "C", "D",
            "Disable B Menu Item", "Enable B Menu Item", "---",
            "Disable Second Menu", "Enable Second Menu")

        procedure MenuSelected
            for i : 1 .. 12
                if item (i) = GUI.GetEventWidgetID then
                    Text.Locate (maxrow, 1)
                    put name (i) + " selected               " ..
                end if
            end for
        end MenuSelected

        procedure DisableB
            GUI.Disable (item (4))
        end DisableB

        procedure EnableB
            GUI.Enable (item (4))
        end EnableB

        procedure DisableFirst
            GUI.Disable (first)
        end DisableFirst

        procedure EnableFirst
            GUI.Enable (first)
        end EnableFirst

        % Create the menus
        first := GUI.CreateMenu ("First")
        item (1) := GUI.CreateMenuItem (name (1), GUI.Quit)
        for cnt : 2 .. 7
            item (cnt) := GUI.CreateMenuItem (name (cnt),
                MenuSelected)
        end for

        second := GUI.CreateMenu ("Second")
        item (8) := GUI.CreateMenuItem (name (8), DisableB)
        item (9) := GUI.CreateMenuItem (name (9), EnableB)
        item (10) := GUI.CreateMenuItem (name (10), MenuSelected)
        item (11) := GUI.CreateMenuItem (name (11), DisableFirst)
        item (12) := GUI.CreateMenuItem (name (12), EnableFirst)

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details When a menu is not enabled, the text in the menu bar is grayed out and clicking on the menu does not cause the menu to appear.

Details The following GUI subprograms can be called with a menu as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.Enable, GUI.Disable

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateMenu, not by calling CreateMenu.

See also GUI.CreateMenuItem for adding items to a menu. See also GUI.ShowMenuBar and GUI.HideMenuBar for showing and hiding the menu bar.


GUI.CreateMenuItem[Full]

GUI.CreateMenuItem[Full] Part of GUI module

Syntax GUI.CreateMenuItem (name : string,
actionProc : procedure x ()) : int

GUI.CreateMenuItemFull (name : string,
actionProc : procedure x (), shortCut : char, addNow : boolean) : int

Description Creates a menu item and returns the menu item's widget ID.

Menu items are the individual entries of a menu. To create menus for a window, you must create a menu, then create the menu items for that menu, then create the next menu, etc. All menu items are automatically added to the last menu and after the last menu item of the currently selected (not active!) window.

The menu item will be added to the last menu after the other menu items in the menu. If there are no menus defined, an error results.

The name parameter specifies the text that is to appear. A name of three dashes ("---") creates a separator across the menu. The actionProc parameter specifies the name of a procedure to be called when user the selects the menu item from the menu.

For GUI.CreateMenuItemFull, the shortCut parameter specifies the keystroke to be used as the menu item's shortcut. If no shortcut is desired, then '\0' can be used. The addNow parameter has no effect in the current version of the GUI Library. In future versions, it will allow you to create menu items that can then be added to a menu later in the program.

Examples See the example for GUI.CreateMenu.

Execute

Details When a menu item is not enabled, the text of the menu item is grayed out and clicking on the menu item does not cause the menu to appear.

Details The following GUI subprograms can be called with a menu as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.Enable, GUI.Disable

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateMenuItem, not by calling CreateMenuItem.


GUI.CreatePicture

GUI.CreatePicture Part of GUI module

Syntax GUI.CreatePicture ( x, y, picture : int,
mergePic : boolean ) : int

Description Creates a picture and returns the picture's widget ID.

The picture widget is used to display a picture. It can be used to display a picture either merged into the background or not.

The x and y parameters specify the lower-left corner of the picture. The picture parameter specifies the picture ID of the picture. The picture ID is received from a Pic.New or Pic.FileNew call. Do not call Pic.Free for this picture ID until the button has been disposed of by calling GUI.Dispose. The mergePic parameter is a boolean that specifies whether anything that was the background colour in the picture (usually colour 0) should be set to the background colour of the window.

A picture widget is a passive widget and cannot be enabled or disabled.

Two Pictures

Example The following program draws two pictures, merged and not merged.

        import GUI
        View.Set ("graphics:230;135,nobuttonbar")

        % We'll need to create a picture for our Picture widget. Normally
        % an external file (and Pic.FileNew) would be used.
        Draw.FillOval (50, 50, 50, 50, blue)
        Draw.FillBox (17, 17, 83, 83, brightred)
        Draw.FillStar (17, 17, 83, 83, brightgreen)
        Draw.FillMapleLeaf (37, 37, 63, 63, brightpurple)
        var pic : int := Pic.New (0, 0, 100, 100)
        var picture1, picture2 : int
        var label1, label2 : int

        GUI.SetBackgroundColor (gray)

        label1 := GUI.CreateLabel (15, 5, "Picture (no merge)")
        picture1 := GUI.CreatePicture (10, 25, pic, false)

        label2 := GUI.CreateLabel (135, 5, "Picture (merge)")
        picture2 := GUI.CreatePicture (120, 25, pic, true)

Execute

Details When GUI.CreatePicture is called, the newly created picture will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

A picture widget is a passive widget and cannot be enabled or disabled.

Details The following GUI subprograms can be called with a picture as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize

Status Exported qualified.

This means that you can only call the function by calling GUI.CreatePicture, not by calling CreatePicture.


GUI.CreatePictureButton[Full]

GUI.CreatePictureButton[Full] Part of GUI module

Syntax GUI.CreatePictureButton (x, y, picture : int,
actionProc : procedure x ()) : int

GUI.CreatePictureButtonFull (x, y, picture : int,
actionProc : procedure x (), width, height : int,
shortcut : char, mergePic : boolean) : int

Description Creates a picture button and returns the button's widget ID.

Picture buttons behave like buttons (see GUI.CreateButton) except that instead of text on the button, a picture specified by the user is displayed on the button. The picture button widget responds to mouse clicks and keystrokes in the same manner as a regular button widget.

The picture must be created by the program beforehand using Pic.New or Pic.FileNew. The resulting picture can then be used as a parameter to GUI.CreatePictureButton. In general, pictures should be a maximum of about 50 pixels high and wide, although there is no built-in limit in the GUI library.

The x and y parameters specify the lower-left corner of the picture button. The picture parameter specifies the picture ID of the picture to be displayed on the button. (Note that, in general, this picture should be fairly small.) The picture ID is received from a Pic.New or Pic.FileNew call. Do not call Pic.Free for this picture ID until the button has been disposed of by calling GUI.Dispose. The actionProc parameter specifies the name of a procedure that is called when the picture button is pressed.

For GUI.CreatePictureButtonFull, the width and height parameters specify the width and height of the button. If they are set to 0, then the picture radio button is automatically sized to fit the picture. If you need to know the precise size of the button, use the GUI.GetWidth and GUI.GetHeight functions. If width and height are larger than the picture, the picture is centered in the button. The shortCutparameter is the keystroke to be used as the button's shortcut. The mergePic parameter specifies whether anything that was the background colour in the picture (usually colour 0) should be set to the background colour of the button (which is usually gray). This defaults to true for CreatePictureButton.

Two Picture Buttons

Example The following program displays five picture buttons which output a message when pressed.

        import GUI
        View.Set ("graphics:100;70")

        const size : int := 25   % The buttons size.
        const border : int := 3

        var starButton, mapleButton, starPic, mapleLeafPic : int

        procedure StarPressed
            Text.Locate (1, 1)
            put "Star Pressed    "
        end StarPressed

        procedure MaplePressed
            Text.Locate (1, 1)
            put "Maple Pressed "
        end MaplePressed

        % Create the pictures.
        % The star.
        Draw.Star (border, border, border + size, border + size, black)
        Draw.Star (border + 1, border + 1, border + size - 1,
            border + size - 1, black)
        Draw.FillStar (border + 2, border + 2, border + size - 2,
            border + size - 2, brightred)
        starPic := Pic.New (0, 0, 2 * border + size, 2 * border + size)

        % The mapleleaf.
        Draw.FillBox (border, border, border + size, border + size, white)
        Draw.MapleLeaf (border, border, border + size, border + size, black)
        Draw.MapleLeaf (border + 1, border + 1, border + size - 1,
            border + size - 1, black)
        Draw.FillMapleLeaf (border + 2, border + 2, border + size - 2,
            border + size - 2, brightred)
        mapleLeafPic := Pic.New (0, 0, 2 * border + size, 2 * border + size)

        % Create the picture buttons.
        Draw.Cls
        starButton := GUI.CreatePictureButton (10, 10, starPic, StarPressed)
        mapleButton := GUI.CreatePictureButton (55, 10, mapleLeafPic,
            MaplePressed)

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details When GUI.CreatePictureButton or GUI.CreatePictureButtonFull is called, the newly created picture will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a picture button is not enabled, the picture button is grayed out and the picture button no longer responds to any mouse clicks or keystrokes until the button is enabled again.

Details The following GUI subprograms can be called with a picture button as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize

Status Exported qualified.

This means that you can only call the function by calling GUI.CreatePictureButton, not by calling CreatePictureButton.


GUI.CreatePictureRadioButton[Full]

GUI.CreatePictureRadioButton[Full] Part of GUI module

Syntax GUI.CreatePictureRadioButton (x, y, picture : int,
joinID : int, actionProc : procedure x ()):int

GUI.CreatePictureRadioButtonFull (x, y : int,
picture, joinID : int, actionProc : procedure x (), width,height : int,
shortcut : char, mergePic : boolean) : int
Description Creates a picture radio button and returns the button's widget ID.

Picture radio buttons behave like picture buttons (see GUI.CreatePictureButton) except that they have the "radio" property. That is, one of the buttons in the radio group is always selected, and if another button in the group is selected, the previously selected button is unselected.

A common example is the buttons on a paint program that indicate the current shape being painted. The maple leaf button is currently selected. If the star button is selected by the user, the maple leaf button becomes unselected. For picture buttons, the selected button appears depressed.

Four Picture Radio Buttons with the Maple Leaf Seledcted

A radio group is created by first creating a single radio button. To add another button to the group, a second radio button is created specifying the first radio button in the joinID parameter. Subsequent radio buttons are added, each specifying a previous member of the group in the joinID parameter.

The picture must be created by the program beforehand using Pic.New or Pic.FileNew. The resulting picture can then be used as a parameter to GUI.CreatePictureButton. In general, pictures should be a maximum of about 50 pixels high and wide, although there is no built-in limit in the GUI library.

The x and y parameters specify the lower-left corner of the picture radio button. If these are both 1 and joinID is not zero, then the button will be placed directly below the previous picture radio button in the group. The picture parameter specifies the picture ID of the picture to be displayed on the button. (Note that, in general, this picture should be fairly small.) The picture ID is received from a Pic.New or Pic.FileNew call. Do not call Pic.Free for this picture ID until the button has been disposed of by calling GUI.Dispose. The joinID parameter specifies a member of the radio group that this widget should join. A joinID of 0 sepecifies this radio button is not a member of any group. The actionProc parameter specifies the name of a procedure that is called when the picture button is pressed.

For GUI.CreatePictureRadioButtonFull, the width and height parameters specify the width and height of the button. If they are set to 0, then the picture radio button is automatically sized to fit the picture. If you need to know the precise size of the button, use the GUI.GetWidth and GUI.GetHeight functions. If width and height are larger than the picture, the picture is centered in the button. The shortCutparameter is the keystroke to be used as the button's shortcut. The mergePic parameter specifies whether anything that was the background colour in the picture (usually colour 0) should be set to the background colour of the button (which is usually gray). This defaults to true for CreatePictureRadioButton.

Example The following program creates and displays for picture radio buttons.

        import GUI
        View.Set ("graphics:150;200,nobuttonbar")

        const size : int := 25   % The buttons size.
        const border : int := 3

        var starButton, mapleButton, circleButton, squareButton : int
        var starPic, mapleLeafPic, circlePic, squarePic : int

        procedure StarPressed
            Text.Locate (1, 1)
            put "Star Pressed    "
        end StarPressed
        procedure MaplePressed
            Text.Locate (1, 1)
            put "Maple Pressed "
        end MaplePressed

        procedure CirclePressed
            Text.Locate (1, 1)
            put "Circle Pressed"
        end CirclePressed

        procedure SquarePressed
            Text.Locate (1, 1)
            put "Square Pressed"
        end SquarePressed

        % Create the pictures.
        % The star.
        Draw.Star (border, border, border + size, border + size, black)
        Draw.Star (border + 1, border + 1, border + size - 1,
            border + size - 1, black)
        Draw.FillStar (border + 2, border + 2, border + size - 2,
            border + size - 2, brightred)
        starPic := Pic.New (0, 0, 2 * border + size, 2 * border + size)

        % The mapleleaf.
        Draw.FillBox (border, border, border + size, border + size, white)
        Draw.MapleLeaf (border, border, border + size, border + size, black)
        Draw.MapleLeaf (border + 1, border + 1, border + size - 1,
            border + size - 1, black)
        Draw.FillMapleLeaf (border + 2, border + 2, border + size - 2,
            border + size - 2, brightred)
        mapleLeafPic := Pic.New (0, 0, 2 * border + size, 2 * border + size)

        % The circle.
        const radius : int := size div 2
        Draw.FillBox (border, border, border + size, border + size, white)
        Draw.Oval (border + radius, border + radius, radius, radius, black)
        Draw.Oval (border + radius, border + radius, radius - 1, radius - 1,
            black)
        Draw.FillOval (border + radius, border + radius, radius - 2,
            radius - 2, brightred)
        circlePic := Pic.New (0, 0, 2 * border + size, 2 * border + size)

        % The square.
        Draw.FillBox (border, border, border + size, border + size, white)
        Draw.Box (border, border, border + size, border + size, black)
        Draw.Box (border + 1, border + 1, border + size - 1,
            border + size - 1, black)
        Draw.FillBox (border + 2, border + 2, border + size - 2,
            border + size - 2, brightred)
        squarePic := Pic.New (0, 0, 2 * border + size, 2 * border + size)

        % Create the picture buttons.
        Draw.Cls
        starButton := GUI. CreatePictureRadioButton (10, maxy  80,
            starPic, 0, StarPressed)
        mapleButton := GUI. CreatePictureRadioButton (-1, -1,
            mapleLeafPic, starButton, MaplePressed)
        circleButton := GUI.CreatePictureRadioButton (-1, -1,
            circlePic, mapleButton, CirclePressed)
        squareButton := GUI.CreatePictureRadioButton (-1, -1,
            squarePic, circleButton, SquarePressed)

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details When GUI.CreatePictureRadioButton or GUI.CreatePictureRadioButtonFull is called, the newly created picture will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a picture radio button is not enabled, the picture radio button is grayed out and the picture button no longer responds to any mouse clicks or keystrokes until the button is enabled again.

Details The following GUI subprograms can be called with a picture radio button as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.SelectRadio

Status Exported qualified.

This means that you can only call the function by calling GUI.CreatePictureRadioButton, not by calling CreatePictureRadioButton.

See also GUI.SelectRadio for selecting a picture radio button in a program. See also GUI.CreatePictureButton and GUI.CreateRadioButton for information on picture buttons and radio buttons.


GUI.CreateRadioButton[Full]

GUI.CreateRadioButton[Full] Part of GUI module

Syntax GUI.CreateRadioButton (x, y : int, text : string,
joinID : int, actionProc : procedure x ()) : int

GUI.CreateRadioButtonFull (x, y : int, text : string,
joinID : int, actionProc : procedure x (), alignment : int, shortCut : char) : int

Description Creates a radio button and returns the radio button's widget ID.

A slider is a widget that allows the user to select one of a set of values. It has a real-life equivalent in the old car stereos where a single station is selected at a time. That is, one of the buttons in the radio group is always selected, and if another button in the group is selected, the previously selected button is unselected.

Six Radio Buttons in Two Groups

A radio group is created by first creating a single radio button. To add another button to the group, a second radio button is created specifying the first radio button in the joinID parameter. Subsequent radio buttons are added, each specifying a previous member of the group in the joinID parameter.

The x and y parameters specify the lower-left corner of the radio button (unless alignment is set to GUI.RIGHT, in which case they specify the lower-right corner of the radio button). If these are both 1 and joinID is not zero, then the button will be placed directly below the previous radio button in the group. The text parameter specifies the text (or label) beside the radio button. The joinID parameter specifies a member of the radio group that this widget should join. A joinID of 0 sepecifies this radio button is not a member of any group. The actionProc parameter is the name of a procedure that is called when the radio button is selected. In GUI.CreateRadioButton, the radio button's text is always to the right of the actual radio button. In GUI.CreateRadioButtonFull, the text can be set to the right or left of the radio button with the alignment parameter.

For GUI.CreateRadioButtonFull, the alignment parameter specifies the position of the radio button in relation to the text as well as the meaning of the x and y parameters. The alignment parameter is one of 0, GUI.LEFT, or GUI.RIGHT. An alignment of 0 is the default and is the same as GUI.LEFT. GUI.LEFT means the actual box in the check box appears to the left of the check box's label and (x, y) specify the lower-left corner. An alignment of GUI.RIGHT means that the actual box appears to the right of the radio button's label and (x, y) specify the lower-right corner of the radio button. The shortcut parameter is the keystroke to be used as the button's shortcut.

A radio button's size is not specified during creation. It is determined based on the size of the text. Instead the user specifies the lower-left corner of the radio button (or the lower-right if the radio button is right justified).

Example The following program creates six radio buttons in two groups.

        import GUI
        View.Set ("graphics:350;80")

        var radio : array 1 .. 6 of int % The radio button IDs.

        procedure RadioPressed
            Text.Locate (1, 1)
            put "Radio Button " ..
            for i : 1 .. 6
                if radio (i) = GUI.GetEventWidgetID then
                    put i ..
                end if
            end for
            put " Selected"
        end RadioPressed

        radio (1) := GUI.CreateRadioButton (15, maxy  35,
            "Radio Button 1", 0, RadioPressed)
        radio (2) := GUI.CreateRadioButton ( 1, 1, "Radio Button 2",
            radio (1), RadioPressed)
        radio (3) := GUI.CreateRadioButton ( 1, 1, "Radio Button 3",
            radio (2), RadioPressed)
        radio (4) := GUI.CreateRadioButtonFull (maxx  15, maxy  35,
            "Radio Button A (Shortcut: 'a')", 0, RadioPressed,
            GUI.RIGHT, 'a')
        radio (5) := GUI.CreateRadioButtonFull ( 1, 1,
            "Radio Button B (Shortcut: 'b')", radio (4), RadioPressed,
            GUI.RIGHT, 'b')
        radio (6) := GUI.CreateRadioButtonFull ( 1, 1,
            "Radio Button C (Shortcut: 'c')", radio (5), RadioPressed,
            GUI.RIGHT, 'c')

        loop
            exit when GUI.ProcessEvent
        end loop
Execute

Details When a group of radio buttons is selected, the first radio button created in the group will be the selected one. You can change this by using the GUI.SelectRadio procedure to select a different one.

When GUI.CreateRadioButton or GUI.CreateRadioButtonFull is called, the newly created picture will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a radio button is not enabled, the radio button is grayed out and the radio button no longer responds to any mouse clicks or keystrokes until the button is enabled again.

Details The following GUI subprograms can be called with a radio button as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.SetLabel, GUI.SelectRadio

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateRadioButton, not by calling CreateRadioButton.

See also GUI.SelectRadio for selecting a radio button in a program. See also GUI.SetLabel for changing the radio button's text.


GUI.CreateTextBox[Full]

GUI.CreateTextBox[Full] Part of GUI module

Syntax GUI.CreateTextBox (x, y, width, height : int) : int

GUI.CreateTextBoxFull (x, y, width, height : int,
border, fontID : int) : int

Description Creates a text box and returns the text box's widget ID.

A text box is a box used for displaying text. It has scroll bars that activate when text appears outside the border of the text box. The user cannot directly select, edit or modify the text in the text box.

The x and y parameters specify the lower-left corner of the area in which the text will be drawn. The width and height parameters specify the width and height of the text drawing area The text box border is just outside the text drawing area. Because of this, GUI.GetX and GUI.GetY will return a value slightly smaller than x and y and GUI.GetWidth and GUI.GetHeight will return values slightly larger than width and height.

For GUI.CreateTextBox, the border around the text box is always a line. For GUI.CreateTextBoxFull, the type of border is specified by the border parameter. The border parameter is one of 0, GUI.LINE, GUI.INDENT, or GUI.EXDENT. A border of 0 is the default and is the same as GUI.LINE. GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the text box appear indented or recessed. GUI.EXDENT makes the text box appear to stand out from the window. The fontID parameter specifies the font ID of the font to be used in the text box. The font ID is received from a Font.New call. Do not call Font.Free for this font ID until the label has been disposed of by calling GUI.Dispose.

By using the fondID parameter, text boxes can have any size or typeface.

A text box displaying the contents of a file.

Example The following program displays the contents of a file in a text box.

        import GUI
        View.Set ("graphics:300;300")

        const fileNameToBeViewed : string := "TextBxs.DEM"
        var textBox : int       % The Text Field ID.
        var title : int     % The label for the title.
        var f : int         % The stream number of the file.
        var line : string       % Lines to be read from the file.

        % Open the file.
        open : f, fileNameToBeViewed, get
        if f = 0 then
            put "Unable to open " + fileNameToBeViewed + " : ", Error.LastMsg
            return
        end if

        % Set background color to gray for indented text box.
        GUI.SetBackgroundColor (gray)

        % Create the title label and text box.
        title := GUI.CreateLabelFull (20, 280, fileNameToBeViewed, 250, 0,
            GUI.CENTER, 0)
        textBox := GUI.CreateTextBoxFull (10, 10, 280, 265,
            GUI.INDENT, 0)

        % Read the file and place it in the text box.
        loop
            exit when eof (f)
            get : f, line : *
            GUI.AddLine (textBox, line)
        end loop

        close : f   % Close the file.

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details When GUI.CreateTextBox or GUI.CreateTextBoxFull is called, the newly created picture will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

A text box widget is a passive widget and cannot be enabled or disabled.

Details The following GUI subprograms can be called with a text box as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.AddLine, GUI.AddText, GUI.ClearText, GUI.SetTopLine, GUI.SetScrollOnAdd

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateTextBox, not by calling CreateTextBox.

See also GUI.AddLine, GUI.AddText for adding text to the text box. See also GUI.SetTopLine to set the top line of text in the text box. See also GUI.SetScrollOnAdd to set stop the text box from scrolling when text is added to the text box. See also GUI.ClearText for clearing the text box.


GUI.CreateTextBoxChoice

GUI.CreateTextBoxChoice Part of GUI module

Syntax GUI.CreateTextBoxChoice (x, y, width, height : int,
border, fontID : int, actionProc : procedure x (line : int)) : int

Description Creates a text box that can be used for selecting individual items and returns the text box's widget ID.

A text box is a box used for displaying text. By using GUI.AddLine to add lines of text, the program can then wait for the user to double click on lines in the text box. The line highlights when the user clicks the line once, and calls the action procedure when the user clicks the highlighted line a second time. Like a text box, the text box choice has scroll bars that activate when text appears outside the border of the text box. The user cannot directly edit or modify the text in the text box choice.

The x and y parameters specify the lower-left corner of the area in which the text will be drawn. The width and height parameters specify the width and height of the text drawing area The text box border is just outside the text drawing area. Because of this, GUI.GetX and GUI.GetY will return a value slightly smaller than x and y and GUI.GetWidth and GUI.GetHeight will return values slightly larger than width and height.

For GUI.CreateTextBox, the border around the text box is always a line. For GUI.CreateTextBoxFull, the type of border is specified by the border parameter. The border parameter is one of 0, GUI.LINE, GUI.INDENT, or GUI.EXDENT. A border of 0 is the default and is the same as GUI.LINE. GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the text box appear indented or recessed. GUI.EXDENT makes the text box appear to stand out from the window. The fontID parameter specifies the font ID of the font to be used in the text box. The font ID is received from a Font.New call. Do not call Font.Free for this font ID until the label has been disposed of by calling GUI.Dispose.

By using the fontID parameter, text boxes can have any size or typeface.

A text box choice after a user double clicked a line.

Example The following program displays the contents of a file in a text box.

        import GUI

        procedure ChoseLine (line : int)
            location (1, 1)
            put "The user chose ", line
        end ChoseLine

        var x : int := GUI.CreateTextBoxChoice (20, 20, 200, 100, 0, 0, ChoseLine)

    GUI.AddLine (x, "Choose A")
    GUI.AddLine (x, "Choose B")
    GUI.AddLine (x, "Choose C")
    GUI.AddLine (x, "Choose D")
    GUI.AddLine (x, "Choose E")
    GUI.AddLine (x, "Choose F")
    GUI.AddLine (x, "Choose G")
    GUI.AddLine (x, "Choose H")
    GUI.AddLine (x, "Choose I")
    GUI.AddLine (x, "Choose J")

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details When GUI.CreateTextBox or GUI.CreateTextBoxFull is called, the newly created text box choice will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

Details The following GUI subprograms can be called with a text box as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.AddLine, GUI.AddText, GUI.ClearText, GUI.SetTopLine, GUI.SetScrollOnAdd

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateTextBoxChoice, not by calling CreateTextBoxChoice.

See also GUI.AddLine for adding text to the text box. See also GUI.SetTopLine to set the top line of text in the text box. See also GUI.SetScrollOnAdd to set stop the text box from scrolling when text is added to the text box. See also GUI.ClearText for clearing the text box.


GUI.CreateTextField[Full]

GUI.CreateTextField[Full] Part of GUI module

Syntax GUI.CreateTextField (x, y, width : int, text : string,
actionProc : procedure x (text : string)) : int

GUI.CreateTextFieldFull (x, y, width : int, text : string,
actionProc : procedure x (text : string),
border, fontID, inputKind : int) : int

Description Creates a text field and returns the text field's widget ID.

A text field is used to create a line of text that can be edited by the user. The user can use the mouse to select part of the text and can enter text into the text field.

If one or more text fields are enabled in a window, then one of the text fields will be active. This means that when any keystrokes are entered into the window, the active text field will receive the keystrokes. The active text field can be changed using the GUI.SetActive procedure.

The x and y parameters specify the lower-left corner of the area in which the text will be drawn. The text field border is just outside the text drawing area. The width parameter specifies the width of the text drawing area. The height of the text field is determined by the height of the font used by the text field. The border of the text field is just outside the text drawing area, so GUI.GetWidth will return values slightly larger than width. The actionProc parameter specifies the name of the procedure to be called when the user presses ENTER (RETURN on a Macintosh) when the text field is active. The parameter is the current text in the text field.

For GUI.CreateTextField, the border around the text field is always a line. For GUI.CreateTextFieldFull, the type of border is specified by the border parameter. The border parameter is one of 0, GUI.LINE, GUI.INDENT, or GUI.EXDENT. A border of 0 is the default and is the same as GUI.LINE. GUI.INDENT and GUI.EXDENT only display properly if the background colour has been set to gray using GUI.SetBackgroundColor. GUI.INDENT makes the text field appear indented or recessed. GUI.EXDENT makes the text field appear to stand out from the window. The fontID parameter specifies the font ID of the font to be used in the text field. The font ID is received from a Font.New call. Do not call Font.Free for this font ID until the label has been disposed of by calling GUI.Dispose. The inputKind parameter specifies the type of input accepted by the text field. This is one of 0, GUI.ANY, GUI.INT, or GUI.REAL. An input type of 0 is the default and is the same as GUI.ANY. GUI.ANY allows any type of input in the text field. GUI.INTEGER only allows positive integer input in the text field. GUI.REAL allows any real number input in the text field. Note that using

GUI.INTEGER or GUI.REAL does not guarantee that the text field string can be converted to an integer or a real. The text could be a null string, and for GUI.REAL could be part of a number such as the string "" or "1.25E" both of which are illegal numbers. (To check the conversion, use the strintok or strrealok functions before calling strint or strreal.)

Two Text Fields

Example The following program creates a text field and echoes it on the screen when the user presses ENTER.

        import GUI
        View.Set ("graphics:200;100")

        var nameTextField, addressTextField : int   % The Text Field IDs.

        procedure NameEntered (text : string)
            GUI.SetSelection (addressTextField, 0, 0)
            GUI.SetActive (addressTextField)
        end NameEntered

        procedure AddressEntered (text : string)
            GUI.SetSelection (nameTextField, 0, 0)
            GUI.SetActive (nameTextField)
        end AddressEntered

        GUI.SetBackgroundColor (gray)
        var quitButton := GUI.CreateButton (52, 5, 100, "Quit", GUI.Quit)
        nameTextField := GUI.CreateTextFieldFull (50, 70, 100, "",
            NameEntered, GUI.INDENT, 0, 0)
        addressTextField := GUI.CreateTextFieldFull (50, 40, 100, "",
            AddressEntered, GUI.INDENT, 0, 0)
        var nameLabel := GUI.CreateLabelFull (45, 70, "Name", 0, 0,
            GUI.RIGHT, 0)
        var addressLabel := GUI.CreateLabelFull (45, 40, "Address", 0, 0,
            GUI.RIGHT, 0)
        loop
            exit when GUI.ProcessEvent
        end loop

        GUI.Dispose (quitButton)
        colorback (gray)
        Text.Locate (maxrow - 1, 1)
        put "Name = ", GUI.GetText (nameTextField)
        put "Address = ", GUI.GetText (addressTextField) ..

Execute

Details Only one text field is active at a time. The active text field has a blinking cursor (or its selection highlighted). If a keystroke occurs when a window has an active text field in it, the keystroke will be directed to the active text field. You can change which text field is active with the GUI.SetActive procedure or by simply clicking on another text field with the mouse.

When multiple text fields are created in a window, the first text field created is active when the program begins.

The current version of the text field does not support cut and paste or keyboard commands to extend the selection.

Because strings are a maximum of 255 characters, this is the maximum number of characters in a text field.

The TAB character cycles between different text fields in a window. It cycles through the text fields in the order in which they were created. BACK TAB (shift+TAB) cycles through the fields in reverse order.

Details When GUI.CreateTextField or GUI.CreateTextFieldFull is called, the newly created picture will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a text field is not enabled, the text field cannot be made active and the text in the field cannot be edited.

Details The following GUI subprograms can be called with a text box as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.GetText, GUI.SetText, GUI.SetSelection, GUI.SetActive, GUI.SetEchoChar

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateTextField, not by calling CreateTextField.

See also GUI.GetText and GUI.SetText for reading and setting the text in the text field. See also GUI.SetEchoChar for setting the character echoed when the user enters a character in a text field (often used for entering passwords). See also GUI.SetSelection for setting the selected area of the text. See also GUI.SetActive for making the text field active.


GUI.CreateVerticalScrollBar[Full]

GUI.CreateVerticalScrollBar[Full] Part of GUI module

Syntax GUI.CreateVerticalScrollBar (x, y, size : int,
min, max, start : int, actionProc : procedure x (value : int)) : int

GUI.CreateVerticalScrollBarFull (x, y, size : int,
min, max, start : int,
actionProc : procedure x (value : int),
arrowInc, pageInc, thumbSize : int) : int

Description Creates a vertical (up-down) scroll bar and returns the scroll bar's widget ID.

A scroll bar is a widget that allows users to see a piece of a document that cannot be displayed on the screen in its entirety. The picture below shows a vertical scroll bar. To control a scroll bar, there are a few choices: the user can click on the thumb (the box in the scroll bar) and slide it up and down, or the user can click in the scroll bar itself above or below the thumb (in which case the thumb is moved up or down one "page"), or the user can click on the up or down arrows at the ends of the scroll bar (in which case the thumb is moved up or down one "arrow increment" or "line").

A Vertical Scroll Bar

The programmer defines a page or an arrow increment. When the value of the scroll bar changes, the action procedure of the scroll bar is called with the new value as a parameter. The action procedure should then redraw the contents using the new value of the scroll bar.

The range of values that the scroll bar will give is determined by the min and max parameters in the Create call. The left side of the scroll bar represents the minimum value, while the right represents the maximum value. There is also the "thumb size". This represents the range of values that can be seen at once on the screen.

By default, the arrow increment (the amount the value is changed when the scrolling arrows are pressed) is set to one. The page increment (the amount the value is changed when the user clicks in the bar to the right or left of the thumb) is set to one quarter the difference between the minimum and the maximum. The "thumb size" is set to zero (see the description of scroll bars for an explanation of the thumb size).

The x and y parameters specify the lower-left corner of the scroll bar. The size parameter specifies the length of the scroll bar (including the arrows) in pixels. The min and max parameters are the minimum and maximum valies returned by the scroll bar. The start parameter is the initial value of the scroll bar and should be between min and max inclusive. The actionProc parameter is the name of a procedure that is called when the value of the scroll bar is changed. The parameter to the action procedure is the current value of the scroll bar.

Example The following program creates a vertical scroll bar. Whenever the scroll bar's value is changed, a message is displayed in the window.

        import GUI

        View.Set ("graphics:125;200,nobuttonbar")
        var scrollBar : int

        procedure ScrollBarMoved (value : int)
            Text.Locate (9, 7)
            put "Scroll"
            Text.Locate (10, 8)
            put "Bar"
            Text.Locate (11, 8)
            put value : 3
        end ScrollBarMoved

        scrollBar := GUI.CreateVerticalScrollBar (10, 10, 180,
            50, 150, 50, ScrollBarMoved)
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Description For GUI.CreateVerticalScrollBarFull, the arrowInc parameter specifies the arrow increment (the amount the scroll bar's value is changed when the scroll arrows are pressed). The pageInc specifies the page increment (the amount the scroll bar's value is changed when the user clicks in the page left/right section of the scroll bar). The thumbSize parameter specifies the "thumb size". See the scroll bar explanation for more detail on a scroll bar's "thumb size".

For example, if you have a window that can display 20 lines of text at once and there are 100 lines of text, you would set min to 1, max to 100 and thumbSize to 20. The value returned by the scroll bar would then be the line number of the first line on the screen to be displayed. When the scroll bar was at its maximum value, it would return 81, since by doing so, lines 81-100 would be displayed.

Example For an example program that scrolls a large picture over a smaller window, see GUI.CreateHorizontalScrollBar.

Details In some instances, you will want the the minimum and maximum values of the scroll bar to be reversed (right/top is minimum). In that case, call the GUI.SetSliderReverse procedure to flip the values of the scroll bar.

Scroll bars always have a fixed height (for horizontal scroll bars) or width (for vertical scroll bars). To get the scroll bar's width, use the GUI.GetScrollBarWidth function.

When GUI.CreateVerticalScrollBar or GUI.CreateVerticalScrollBarFull is called, the newly created scroll bar will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a scroll bar is not enabled, the gray in the bar is set to white and the thumb is not displayed. The scroll bar no longer responds to any mouse clicks until the scroll bar is enabled again.

Details The following GUI subprograms can be called with a scroll bar as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.GetSliderValue, GUI.SetSliderValue, GUI.SetSliderMinMax, GUI.SetSliderSize, GUI.SetSliderReverse, GUI.SetScrollAmount

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateVerticalScrollBar, not by calling CreateVerticalScrollBar.

See also GUI.GetSliderValue and GUI.SetSliderValue for reading and setting the value of a scroll bar, GUI.SetSliderMinMax for changing the minimum and maximum values of a scroll bar, and GUI.SetScrollAmount for changing the scrolling increments and thumb size of a scroll bar. See also GUI.SetSliderSize for setting the length of a scroll bar and GUI.SetSliderReverse for reversing the sense of a scroll bar.


GUI.CreateVerticalSlider

GUI.CreateVerticalSlider Part of GUI module

Syntax GUI.CreateVerticalSlider (x, y, length : int,
min, max, start : int, actionProc : procedure x (value : int)) : int

Description Creates a vertical (up-down) slider and returns the slider's widget ID.

A slider is a widget that allows the user to set a continuous set of values. It has a real-life equivalent in things such as a stereo volume control.

A Vertical Slider

To control a slider, the user clicks on the slider box and drags it back and forth. Every time the value changes, a procedure is called with the new value as a parameter.

The range of values that the slider will give is determined by the min and max parameters in the Create call. The left side of the slider represents the minimum value, while the right represents the maximum value.

The x and y parameters specify the lower-left corner of the slider track. This means that the slider actually extends above and below this point (and slightly to the left of it to take into account the rounded end of the track). The length parameter specifies the length of the track in pixels. (You can use GUI.GetX, GetY, GetWidth, and GetHeight to get the exact dimensions of the slider.) The min and max parameters are the minimum and maximum valies returned by the slider. The start parameter is the initial value of the slider and should be between min and max inclusive. The actionProc parameter is the name of a procedure that is called when the value of the slider is changed. The parameter to the action procedure is the current value of the slider.

Example The following program creates a vertical slider. Whenever the slider's value is changed, a message is displayed in the window.

        import GUI

        View.Set ("graphics:125;200,nobuttonbar")
        var slider : int

        procedure SliderMoved (value : int)
            Text.Locate (9, 7)
            put "Slider"
            Text.Locate (10, 9)
            put value : 3
        end SliderMoved

        slider := GUI.CreateVerticalSlider (20, 10, 180,
            50, 150, 50, SliderMoved )
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details In some instances, you will want the the minimum and maximum values of the slider to be reversed (right is minimum). In that case, call the GUI.SetSliderReverse procedure to flip the values of the slider.

Sliders always have a fixed height (for horizontal sliders) or width (for vertical sliders).

When GUI.CreateVerticalSlider or GUI.CreateVerticalSliderFull is called, the newly created slider will be displayed immediately unless GUI.DisplayWhenCreated has been called with the display parameter set to false.

When a slider is not enabled, the appearance does not change. However, the slider no longer responds to any mouse clicks until it is enabled again.

Details The following GUI subprograms can be called with a slider as the widgetID parameter:

GUI.Show, GUI.Hide, GUI.Enable, GUI.Disable, GUI.Dispose, GUI.GetX, GUI.GetY, GUI.GetWidth, GUI.GetHeight, GUI.SetPosition, GUI.SetSize, GUI.SetPositionAndSize, GUI.GetSliderValue, GUI.SetSliderValue, GUI.SetSliderMinMax, GUI.SetSliderSize, GUI.SetSliderReverse

Status Exported qualified.

This means that you can only call the function by calling GUI.CreateVerticalSlider, not by calling CreateVerticalSlider.

See also GUI.GetSliderValue and GUI.SetSliderValue for reading and setting the value of a slider, GUI.SetSliderMinMax for changing the minimum and maximum values of a slider. See also GUI.SetSliderSize for setting the length of a slider and GUI.SetSliderReverse for reversing the sense of a slider.


GUI.Disable

GUI.Disable Part of GUI module

Syntax GUI.Disable (widgetID : int)

Description Disables a widget specified by widgetID.

Used in conjunction with GUI.Enable to enable and disable widgets.

Disabled widgets generally are "grayed out" to visually depict their disabled status.

Disabled widgets do not respond to keystrokes or mouse clicks.

Example The three color radio buttons are enabled only when the color check box is selected.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:100;100")

        var colorCheckBox, redRadio, greenRadio, blueRadio : int

        procedure DoNothing
        end DoNothing

        procedure ColorCheckBoxProc (filled : boolean)
            if filled then
                GUI.Enable (redRadio)
                GUI.Enable (greenRadio)
                GUI.Enable (blueRadio)
            else
                GUI.Disable (redRadio)
                GUI.Disable (greenRadio)
                GUI.Disable (blueRadio)
            end if
        end ColorCheckBoxProc

        colorCheckBox := GUI.CreateCheckBox (10, 80,
            "Use Color", ColorCheckBoxProc)
        redRadio := GUI.CreateRadioButton (33, 60, "Red", 0, DoNothing)
        greenRadio := GUI.CreateRadioButton (1, 1, "Green",
            redRadio, DoNothing)
        blueRadio := GUI.CreateRadioButton (1, 1, "Blue",
            greenRadio, DoNothing)
        ColorCheckBoxProc (false)

        loop
            exit when GUI.ProcessEvent
        end loop
Details The following types of widgets can be enabled or disabled:

Buttons, Check Boxes, Radio Buttons, Picture Buttons,

Picture Radio Buttons, Horizontal Scroll Bars, Horizontal Sliders,
Canvases, Text Fields, Vertical Scroll Bars, Vertical Sliders

Status Exported qualified.

This means that you can only call the procedure by calling GUI.Disable, not by calling Disable.

See also GUI.Enable.


GUI.Dispose

GUI.Dispose Part of GUI module

Syntax GUI.Dispose (widgetID : int)

Description Eliminates the widget specified by widgetID.

If the widget is visible, it is immediately made invisible before being deleted. It should be called in order to free up any memory that the widget might have allocated. Note that you cannot use the widget after it has been disposed of. If you wish to temporarily get rid of a widget, consider using the Hide method and then the Show method when you want to use it again.

Example The following program waits for the Quit button to be pressed. When it is, the Quit button is deleted and a message is displayed in the center of the screen.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:150;100")

        var button, message : int

        button := GUI.CreateButton (20, 40, 0, "Quit", GUI.Quit)

        loop
            exit when GUI.ProcessEvent
        end loop

        GUI.Dispose (button)
        message := GUI.CreateLabelFull (0, 0, "Done", maxx, maxy,
            GUI.CENTER + GUI.MIDDLE, 0)
Status Exported qualified.

This means that you can only call the procedure by calling GUI.Dispose , not by calling Dispose .


GUI.Draw...

GUI.Draw... Part of GUI module

Syntax GUI.DrawArc (widgetID, x, y, xRadius, yRadius : int,
initialAngle, finalAngle, Color : int )

GUI.DrawBox (widgetID, x1, y1, x2, y2, Color : int )

GUI.DrawCls (widgetID : int )

GUI.DrawDot (widgetID, x, y, Color : int )

GUI.DrawFill (widgetID, x, y : int,
fillColor, borderColor : int)

GUI.DrawFillArc (widgetID, x, y : int,
xRadius, yRadius : int,
initialAngle, finalAngle, Color : int)

GUI.DrawFillBox (widgetID, x1, y1, x2, y2 : int,
Color : int )

GUI.DrawFillMapleLeaf (widgetID, x1, y1 : int,
x2, y2, Color : int )

GUI.DrawFillOval (widgetID, x, y : int,
xRadius, yRadius : int, Color : int)

GUI.DrawFillPolygon (widgetID : int,
x, y : array 1 .. * of int, n : int, Color : int)

GUI.DrawFillStar (widgetID, x1, y1, x2, y2 : int,
Color : int)

GUI.DrawLine (widgetID, x1, y1, x2, y2, Color : int)

GUI.DrawMapleLeaf (widgetID, x1, y1, x2, y2 : int,
Color : int)

GUI.DrawOval (widgetID, x, y : int,
xRadius, yRadius, Color : int)

GUI.DrawPolygon (widgetID : int,
x, y : array 1 .. * of int, n : int, Color : int)

GUI.DrawStar (widgetID, x1, y1, x2, y2, Color : int )

GUI.DrawText (widgetID : int, textStr : string,
x, y : int, fontID, Color : int)

Description Performs a Draw… command to the canvas specified by widgetID.

All of these routines are essentially the same as the similarly-named procedures in the Draw module. All coordinates are based on the canvas and all drawing is clipped to the canvas drawing surface. If the canvas is in "xor mode", all the drawing will be done with "xor" set. (See View.Set for more information about "xor".)

The widgetID must specify a canvas widget.

Example See GUI.CreateCanvas for an example of GUI.DrawFillOval.

Status Exported qualified.

This means that you can only call the procedures by calling GUI.Draw…, not by calling Draw….

See also GUI.CreateCanvas.


GUI.Enable

GUI.Enable Part of GUI module

Syntax GUI.Enable (widgetID : int)

Description Enables a disabled widget specified by widgetID.

Used in conjunction with GUI.Disable to enable and disable widgets.

Disabled widgets generally are "grayed out" to visually depict their disabled status.

Disabled widgets do not respond to keystrokes or mouse clicks.

Example See GUI.Disable for an example of GUI.Enable.

Details The following types of widgets can be enabled or disabled:

Buttons, Check Boxes, Radio Buttons, Picture Buttons,

Picture Radio Buttons, Horizontal Scroll Bars, Horizontal Sliders,
Canvases, Text Fields, Vertical Scroll Bars, Vertical Sliders

Status Exported qualified.

This means that you can only call the procedure by calling GUI.Enable, not by calling Enable.

See also GUI.Disable.


GUI.FontDraw

GUI.FontDraw Part of GUI module

Syntax | GUI.FontDraw (widgetID : int, textStr : string, x, y, fontID, Color : int)
Description | Performs a Font.Draw command to the canvas specified by widgetID. This routine is essentially the same as the Font.Draw procedure in the Font module. All coordinates are based on the canvas and all drawing is clipped to the canvas drawing surface. If the canvas is in "xor mode", all the drawing will be done with "xor" set. (See View.Set for more information about "xor".) The widgetID must specify a canvas widget.
Status | Exported qualified. This means that you can only call the procedure by calling GUI.FontDraw, not by calling FontDraw.
See also | GUI.CreateCanvas.


GUI.GetCheckBox

GUI.GetCheckBox Part of GUI module

Syntax | GUI.GetCheckBox (widgetID : int) : boolean
Description | Returns the status of the check box specified by widgetID. If the check box is set (has an X in it), GetCheckBox returns true, otherwise it returns false.
Example | See GUI.CreateCheckBox for an example of GUI.GetCheckBox.
Status | Exported qualified. This means that you can only call the function by calling GUI.GetCheckBox, not by calling GetCheckBox.
See also | GUI.CreateCheckBox.


GUI.GetEventTime

GUI.GetEventTime Part of GUI module

Syntax GUI.GetEventTime : int

Description Returns the time in milliseconds when the event (mouse button or keystroke) took place. This value is the same value as Time.Elapsed returns if called when the event was processed. This function should only be called in an action procedure or in a default mouse, keystroke, or null event handler, as it will return 1 when there is no event being processed.

This event can be used as a timer for various functions such as determining whether a single click or a double click of the mouse button took place or for timing keyboard input.

Example The following program times the interval between two button presses.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:300;100")

        var startTime, startButton, finishButton : int

        procedure Start
            startTime := GUI.GetEventTime
        end Start

        procedure Finish
            Text.Locate (1, 1)
            put "The time between button pressed is ",
                GUI.GetEventTime  startTime, " msecs"
            GUI.Quit
        end Finish

        startButton := GUI.CreateButton (10, 10, 110, "Click First", Start)
        finishButton := GUI.CreateButton (180, 10, 110, "Click Second", Finish)

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.GetEventTime , not by calling GetEventTime .

See also GUI.ProcessEvent.


GUI.GetEventWidgetID

GUI.GetEventWidgetID Part of GUI module

Syntax GUI.GetEventWidgetID : int

Description Returns the widget ID of the widget that was activated by the mouse button press or the keystroke. This function should only be called in an action procedure, as it will return 1 when there is no event that activated a widget being processed.

This function is used when a several buttons use the same action procedure to determine which button was pressed.

Example The following program prints a message stating which button was selected.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:150;210")

        var buttonNames : array 1 .. 5 of string := init ("Red", "Green",
            "Blue", "Yellow", "Purple")
        var buttons : array 1 .. 5 of int

        procedure ButtonPush
            for i : 1 .. 5
                if GUI.GetEventWidgetID = buttons (i) then
                    Text.Locate (1, 1)
                    put buttonNames (i), " selected"
                end if
            end for
        end ButtonPush
        for i : 1 .. 5
            buttons (i) := GUI.CreateButton (10, 210  40 * i, 110,
                buttonNames (i), ButtonPush)
        end for
        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.GetEventWidgetID, not by calling GetEventWidgetID.

See also GUI.ProcessEvent.


GUI.GetEventWindow

GUI.GetEventWindow Part of GUI module

Syntax GUI.GetEventWindow : int

Description Returns the window ID of the window in which the event (mouse button or keystroke) took place. This function should only be called in an action procedure or in a default mouse or keystroke event handler, as it will return 1 when there is no event being processed.

This function is commonly used when several windows share the same layout. The same buttons in each window point to the same action procedures. To determine which button was actually pressed, the function is called to get the window.

Example The following program creates four windows in a row, each with a button that, when pressed, causes a star to be drawn in that window.

        import GUI in "%oot/lib/GUI"

        procedure DrawStar
            var windowID : int := GUI.GetEventWindow
            Window.Select (windowID)
            Draw.FillStar (25, 40, 175, 190, Rand.Int (10, 15))
        end DrawStar

        for i : 0 .. 3
            var window : int := Window.Open ("graphics:200;200")
            % Place window above task bar, across from previous one.
            Window.SetPosition (window, 220 * i, 27)
            var button : int := GUI.CreateButton (5, 5, 190, "Draw Star",
                DrawStar)
        end for

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.GetEventWindow, not by calling GetEventWindow.

See also GUI.ProcessEvent.


GUI.GetHeight

GUI.GetHeight Part of GUI module

Syntax GUI.GetHeight (widgetID : int) : int

Description Returns the actual height of a widget. Note that this may be different from the height specified in the Create call (especially since many widgets do not specify a height. The GUI module determines the actual height).

This function is used in conjunction with GUI.GetX, GUI.GetY and GUI.GetWidth to determine the bounds of a widget. The entire widget should always fit in the box (GUI.GetX, GUI.GetY) - (GUI.GetX + GUI.GetWidth 1, GUI.GetY + GUI.GetHeight 1)

The position and size of a widget is known only after it has been drawn to the screen. Attempting to get the location or dimesions of the widget may cause an uninitialized variable error.

Example The following procedure draws a red box around the widget specified by widgetID.

        import GUI in "%oot/lib/GUI"

        procedure BoxWidget (widgetID : int)
            var x, y, width, height : int
            x := GUI.GetX (widgetID)
            y := GUI.GetY (widgetID)
            width := GUI.GetWidth (widgetID)
            height := GUI.GetHeight (widgetID)
            Draw.Box (x  1, x  1, x + width, y + height, red)
            Draw.Box (x  2, x  2, x + width + 1, y + height + 1, red)
        end BoxWidget

        var title : int := GUI.CreateLabel (20, 20, "Frame This!")
        BoxWidget (title)
Status Exported qualified.

This means that you can only call the function by calling GUI.GetHeight, not by calling GetHeight.

See also GUI.GetX, GUI.GetY, and GUI.GetWidth.


GUI.GetMenuBarHeight

GUI.GetMenuBarHeight Part of GUI module

Syntax GUI.GetMenuBarHeight : int

Description Returns the height of the menu bar. Useful when drawing or placing widgets to make certain that they don't overlap the menu bar.

Example The following program draws a red box in the window just belowe the menu bar.

        import GUI in "%oot/lib/GUI"

        var menu : int := GUI.CreateMenu ("File")
        var item : int := GUI.CreateMenuItem ("Quit", GUI.Quit)

        Draw.FillBox (0, 0, maxx, maxy  GUI.GetMenuBarHeight  2,
            brightred)

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.GetMenuBarHeight, not by calling GetMenuBarHeight.

See also GUI.CreateMenu.


GUI.GetScrollBarWidth

GUI.GetScrollBarWidth Part of GUI module

Syntax | GUI.GetScrollBarWidth : int
Description | Returns the width of a scroll bar. Useful when placing a scroll bar widget beneath or beside another widget or object.
Example | See the ScrollPic program in GUI.CreateHorizontalScrollBarFull for an example of GUI.GetScrollBarWidth.
Status | Exported qualified. This means that you can only call the function by calling GUI.GetScrollBarWidth, not by calling GetScrollBarWidth.
See also | GUI.CreateHorizontalScrollBar and GUI.CreateVerticalScrollBar.


GUI.GetSliderValue

GUI.GetSliderValue Part of GUI module

Syntax | GUI.GetSliderValue (widgetID : int) : int
Description | Returns the current value of a slider or scroll bar specified by widgetID. The widgetID must specify either scroll bar or a slider (horizontal or vertical).
Example | See the ScrollPic program in GUI.CreateHorizontalScrollBarFull for an example of GUI.GetSliderValue.
Status | Exported qualified. This means that you can only call the function by calling GUI.GetSliderValue, not by calling GetSliderValue.
See also | GUI.SetSliderValue for setting a slider or scroll bar's value. See also GUI.CreateHorizontalScrollBar, GUI.CreateVerticalScrollBar, GUI.CreateHorizontalSlider, and GUI.CreateVerticalSlider.


GUI.GetText

GUI.GetText Part of GUI module

Syntax | GUI.GetText (widgetID : int) : string
Description | Returns the current text of a text field specified by widgetID. The widgetID must specify a text field widget.
Example | See GUI.CreateTextField for an example of GUI.GetText.
Status | Exported qualified. This means that you can only call the function by calling GUI.GetText, not by calling GetText.
See also | GUI.SetText for setting the text in a text field. See also GUI.CreateTextField.


GUI.GetVersion

GUI.GetVersion Part of GUI module

Syntax GUI.GetVersion : int

Description Returns the current version of the GUI Procedure Library. Because the GUI Procedure Library is expected to grow, new versions will probably be made available at our web site http://www.holtsoft.com/turing. If you wish to use features that do not appear in earlier versions of the library, you can have your program check that the current available version meets the programs needs. GUI.GetVersion returns an integer from 100 - 999 and is read as 1.00 to 9.99.

Example The following program fragment immediately exits if OOT does not support version 1.1 of the GUI Procedure Library

        import GUI in "%oot/lib/GUI"
        if GUI.GetVersion < 110 then
            put "You must update to at least version 1.1 of the"
            put "GUI Procedure Library to use this program."
            return
        end if
Details In version 1.00 (shipped with MacOOT 1.5), GUI.GetVersion did not exist.

Status Exported qualified.

This means that you can only call the function by calling GUI.GetVersion, not by calling GetVersion.


GUI.GetWidth

GUI.GetWidth Part of GUI module

Syntax GUI.GetWidth (widgetID : int) : int

Description Returns the actual width of a widget. Note that this may be different from the width specified in the Create call (especially since some widgets do not specify a width. The GUI module determines the actual width).

This function is used in conjunction with GUI.GetX, GUI.GetY and GUI.GetHeight to determine the bounds of a widget. The entire widget should always fit in the box (GUI.GetX, GUI.GetY) - (GUI.GetX + GUI.GetWidth 1, GUI.GetY + GUI.GetHeight 1)

The position and size of a widget is known only after it has been drawn to the screen. Attempting to get the location or dimesions of the widget may cause an uninitialized variable error.

Example The following procedure draws a red box around the widget specified by widgetID.

        import GUI in "%oot/lib/GUI"
        procedure BoxWidget (widgetID : int)
            var x, y, width, height : int
            x := GUI.GetX (widgetID)
            y := GUI.GetY (widgetID)
            width := GUI.GetWidth (widgetID)
            height := GUI.GetHeight (widgetID)
            Draw.Box (x  1, x  1, x + width, y + height, red)
            Draw.Box (x  2, x  2, x + width + 1, y + height + 1, red)
        end BoxWidget

        var title : int := GUI.CreateLabel (20, 20, "Frame This!")
        BoxWidget (title)
Status Exported qualified.

This means that you can only call the function by calling GUI.GetWidth, not by calling GetWidth.

See also GUI.GetX, GUI.GetY, and GUI.GetHeight.


GUI.Get{X,Y}

GUI.Get{X,Y} Part of GUI module

Syntax GUI.GetX (widgetID : int) : int

GUI.GetY (widgetID : int) : int

Description Returns the x coordinate of the left edge of a widget. Note that this may be different from the x coordinate specified in the widget's Create call. For example, if a radio button is created with right justification, the x coordinate in the Create method specifies the right edge while GUI.GetX will return the x coordinate of the left edge.

This function is used in conjunction with GUI.GetWidth and GUI.GetHeight to determine the bounds of a widget. The entire widget should always fit in the box (GUI.GetX, GUI.GetY) - (GUI.GetX + GUI.GetWidth - 1, GUI.GetY + GUI.GetHeight - 1)

The position and size of a widget is known only after it has been drawn to the screen. Attempting to get the location or dimesions of the widget may cause an uninitialized variable error.

Example The following procedure draws a red box around the widget specified by widgetID.

        import GUI in "%oot/lib/GUI"
        procedure BoxWidget (widgetID : int)
            var x, y, width, height : int
            x := GUI.GetX (widgetID)
            y := GUI.GetY (widgetID)
            width := GUI.GetWidth (widgetID)
            height := GUI.GetHeight (widgetID)
            Draw.Box (x  1, x  1, x + width, y + height, red)
            Draw.Box (x  2, x  2, x + width + 1, y + height + 1, red)
        end BoxWidget

        var title : int := GUI.CreateLabel (20, 20, "Frame This!")
        BoxWidget (title)
Status Exported qualified.

This means that you can only call the function by calling GUI.GetX, not by calling GetX.

See also GUI.GetHeight and GUI.GetWidth.


GUI.Hide

GUI.Hide Part of GUI module

Syntax | GUI.Hide (widgetID : int)
Description | Hides a widget specified by widgetID. Used in conjunction with Show to hide and show widgets. Hidden widgets cannot get events (i.e. respond to keystrokes or mouse clicks). If an active text field (see text field) is hidden, then any keystrokes in the window will be ignored. In most cases where a widget is to appear, then disappear, then appear again, it is advised to create the widget once and hide it until it is to appear, whereupon GUI.Show is called. When the user is finished with the widget, the widget is hidden using GUI.Hide. This saves the overhead of creating and disposing of the same widget several times.
Example | See GUI.SetDisplayWhenCreated for an example of GUI.Hide.
Status | Exported qualified. This means that you can only call the function by calling GUI.Hide, not by calling Hide.
See also | GUI.Show.


GUI.HideMenuBar

GUI.HideMenuBar Part of GUI module

Syntax | GUI.HideMenuBar
Description | Hides the menu bar in the selected window. No menu items can be selected when the menu bar is hidden. (Menu item shortcuts are ignored while the menu bar is hidden.)
Example | See GUI.SetMouseEventHandler for an example of GUI.HideMenuBar.
Status | Exported qualified. This means that you can only call the function by calling GUI.HideMenuBar, not by calling HideMenuBar.
See also | GUI.ShowMenuBar. See also GUI.CreateMenu.


GUI.HideWindow

GUI.HideWindow Part of GUI module

Syntax GUI.HideWindow (window : int)

Description Hides a window with widgets in it. This procedure makes certain that the GUI Library recognizes that the window no longer visible. This procedure will call Window.Hide, so there is no need for the user to do so.

Example The program opens up a window with two buttons. If the button labelled "Close and Open" is pressed, the window is closed and a new window with two buttons is opened in a random location on the screen.

        import GUI

        var windowA, windowB : int
        var buttonA, buttonB, buttonQuit : int
    var backToMainA, backToMainB : int

        procedure ShowWindowA
            GUI.HideWindow (defWinID)
            GUI.ShowWindow (windowA)
        end ShowWindowA

        procedure ShowWindowB
            GUI.HideWindow (defWinID)
            GUI.ShowWindow (windowB)
        end ShowWindowB

        procedure ShowMain
            GUI.HideWindow (Window.GetActive)
            GUI.ShowWindow (defWinID)
        end ShowMain

        View.Set ("graphics:280;100,nobuttonbar")
        % Place the buttons in the main window
        buttonA := GUI.CreateButton (10, 10, 0, "Show Window A", ShowWindowA)
        buttonB := GUI.CreateButton (150, 10, 0, "Show Window B", ShowWindowB)
        buttonQuit := GUI.CreateButton (100, 60, 0, "Quit", GUI.Quit)

        windowA := Window.Open  ("title:Window A,graphics:150;100,position:bottom;left")
        backToMainA := GUI.CreateButton (20, 20, 0, "Back to Main", ShowMain)
        Window.Hide (windowA)
        windowB := Window.Open  ("title:Window B,graphics:150;100,position:bottom;right")
        backToMainB := GUI.CreateButton (20, 20, 0, "Back to Main", ShowMain)
        Window.Hide (windowB)

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.HideWindow, not by calling HideWindow.

See also GUI.ShowWindow for showing a window with widgets in it. See also GUI.CloseWindow for closing a window with widgets in it.


GUI.OpenFile

GUI.OpenFile Part of GUI module

Syntax GUI.OpenFile (title : string) : string

Description Displays an "Open File" dialog box to obtain the name of an already existing file. The caption (a window title under MS Windows, a string in a Macintosh dialog box) is specified by the title parameter. The function uses a dialog box specific to the operating system the program is being run on.

If the user did not choose a file (i.e. hit the Cancel button in the dialog), the function returns "" (the empty string).

Note: This function is not available in the current version of the GUI Procedure Library (shipping with Turing 4.0 and MacOOT 1.5). It is documented here for use with future shipping version of Turing. It is likely to be implemented in the version of Turing released in September 2002. Check the release notes that are found in the on-line help to find out if this function is now available.

Example The following program asks the user for the name of a file and then echoes the contents of it.

        import GUI in "%oot/lib/GUI"

        var fileName, line : string
        var streamNumber : int

        fileName := GUI.OpenFile ("Choose a Text File")

        open : streamNumber, fileName, get
        assert streamNumber > 0
        loop
            exit when eof (streamNumber)
            get : streamNumber, line : *
            put line
        end loop
        close : streamNumber
Status Exported qualified.

This means that you can only call the function by calling GUI.OpenFile, not by calling OpenFile.


GUI.OpenFileFull

GUI.OpenFileFull Part of GUI module

Syntax GUI.OpenFileFull (title, filter: string,
startDir : string) : string

Description Displays an "Open File" dialog box to obtain the name of an already existing file. The caption (a window title under MS Windows, a string in a Macintosh dialog box) is specified by the title parameter. The list of files shown is specified by the filter parameter. The initial directory to be displayed is specified by the startDir parameter. The function uses a dialog box specific to the operating system the program is being run on.

The filter parameter is a file name suffix that should be displayed. Multiple suffixes can be specified by separating them with commas. If the user specifies the empty string for filter, then all the files in the directory are displayed. If the startDir parameter is empty, or if it specifies a non-existent directory, then the current directory is displayed in the "Open File" dialog box.

If the user did not choose a file (i.e. hit the Cancel button in the dialog), the function returns "" (the empty string).

Note: This function is not available in the current version of the GUI Procedure Library (shipping with Turing 4.0 and MacOOT 1.5). It is documented here for use with future shipping version of Turing. It is likely to be implemented in the version of Turing released in September 2002. Check the release notes that are found in the on-line help to find out if this function is now available.

Example The following program asks the user to select a file ending in ".txt". The initial directory is the root directory of the C drive.

        import GUI in "%oot/lib/GUI"

        var fileName : string
        fileName := GUI.OpenFileFull ("Choose a Text File", "txt", "C:\\")
Details If a suffix is placed in single quotes, it will be ignored on all but the Apple Macintosh, where it will specify a Macintosh file type.

Example The example makes the dialog box display all files ending in ".txt" or ".text" on all systems but the Macintosh. On the Apple Macintosh, only files of file type 'TEXT' will be displayed.

        fileName := GUI.OpenFileFull ("Open", "txt,text,'TEXT'", "")
Status Exported qualified.

This means that you can only call the function by calling GUI.OpenFileFull, not by calling OpenFileFull.


GUI.Pic...

GUI.Pic... Part of GUI module

Syntax | GUI.PicDraw (widgetID : int, picID, x, y, mode : int) GUI.PicNew (widgetID : int, x1, y1, x2, y2 : int ) : int GUI.PicScreenLoad (widgetID : int, fileName : string, x, y, mode : int) GUI.PicScreenSave (widgetID : int, x1, y1, x2, y2 : int, fileName : string)
Description | Performs a Pic… command to the canvas specified by widgetID. All of these routines are essentially the same as the similarly-named procedures in the Pic module. All coordinates are based on the canvas and all drawing is clipped to the canvas drawing surface.
Example | See the ScrollPic program in GUI.CreateHorizontalScrollBarFull for an example of GUI.PicDraw.
Status | Exported qualified. This means that you can only call the procedures by calling GUI.Pic…, not by calling Pic….
See also | GUI.CreateCanvas.


GUI.ProcessEvent

GUI.ProcessEvent Part of GUI module

Syntax GUI.ProcessEvent : boolean

Description This function processes a single event (a mouse button press or a keystroke). If the event activates a widget, then the action procedure of the widget is called.

The function returns false until GUI.Quit is called. It then returns true.

In order for the widgets to function once placed, the GUI.ProcessEvent must be called continually. Without a call to GUI.ProcessEvent, the widgets will appear, but will not react to mouse clicks or keystrokes.

Almost all programs involving the GUI Procedure Library have the following code fragment in the program. This code fragment is often called the event loop.

        loop
            exit when GUI.ProcessEvent
        end loop
The loop runs continuously until GUI.Quit is called, whereupon GUI.ProcessEvent will return true and the loop will exit. The rest of the program is reached through the action procedures that are called when the user interacts with various widgets.

Details It is usually desirable to allow the user some way of quitting the program without having to abort it. This can be done most simply by adding a Quit button and placing it in an appropriate location.

Example Here is program that does nothing but wait for the user to press the quit button.

        import GUI in "%oot/lib/GUI"
        var quitButton : int := GUI.CreateButton (10, 10, 0, "Quit", GUI.Quit)
        loop
            exit when GUI.ProcessEvent
        end loop
Details To find out which widget was activated and called the action procedure (necessary if several widgets have the same action procedure), you can call GUI.GetEventWidgetID. To get the exact time that the event occurred, you can call GUI.GetEventTime. To get the window in which the event took place, you can call GUI.GetEventWindow.

If a mouse click occured, but did not activate any widget, then the default mouse event handler is called. By default, this does nothing. However, if you want your program to respond to mouse events that do not affect a widget, call GUI.SetMouseEventHandler to specify your own default mouse event handler.

If a keystroke occurred, but did not activate any widget (i.e. it wasn't a short cut for a widget and there are no text fields in the window) then the default keystroke handler is called. By default, this does nothing. However, if you want your program to respond to keystroke events that do not affect a widget, call GUI.SetKeyEventHandler to specify your own default key event handler.

If no event occurred, then the null event handler is called. By default, this does nothing. However, if you want your program to perform some action repetetively when it is not doing anything else, then call GUI.SetNullEventHandler to specify your own null event handler. The null event handler is often used for such things as updating a clock and making certain that music is playing in the background.

Status Exported qualified.

This means that you can only call the procedures by calling GUI.PProcessEvent, not by calling ProcessEvent.

See also GUI.GetEventWidgetID, GUI.GetEventTime, and GUI.GetEventWindow for obtaining information about an event in an action procedure. See also GUI.SetMouseEventHandler, GUI.SetKeyEventHandler and GUI.SetNullEventHandler for handling mouse, keyboard an d null events in the event loop. See also GUI.Quit for information on exitting the event loop.


GUI.Quit

GUI.Quit Part of GUI module

Syntax GUI.Quit

Description This procedure causes GUI.ProcessEvent to return true. If the program is structured properly with a

        loop
            exit when GUI.ProcessEvent
        end loop
at the end of the program, then the program will exit the loop after finishing the current action procedure. This procedure is usually called from the action procedure of a Quit button or Exit menu item.

Example Here is program that does nothing but wait for the user to press the quit button or type the letter 'Q', 'q', 'X', or 'x'.

        import GUI

        procedure KeyHandler (ch : char)
            if ch = 'Q' or ch = 'q' or ch = 'X' or ch = 'x' then
                GUI.Quit
            end if
        end KeyHandler

        var quitButton : int := GUI.CreateButton (10, 10, 0, "Quit", GUI.Quit)
        GUI.SetKeyEventHandler (KeyHandler)

        loop
            exit when GUI.ProcessEvent
        end loop

        put "Done!"
Status Exported qualified.

This means that you can only call the procedures by calling GUI.Quit, not by calling Quit.

See also GUI.ProcessEvent. See also GUI.ResetQuit for resetting the "quit" flag, so that a second event loop can be used in the same program.


GUI.Refresh

GUI.Refresh Part of GUI module

Syntax | GUI.Refresh
Description | This routine redraws all the widgets in the currently-selected window. This is used when some form of drawing may have overwritten the widgets in a window. It is often used when there is some possibility that the widgets may have been drawn over. For example, a program that places buttons on top of a background image should call GUI.Refresh when the image is changed.
Details | GUI.Refresh is used by the GUI Library to redraw all the widgets when the background colour of a window has changed.
Status | Exported qualified. This means that you can only call the procedures by calling GUI.Refresh, not by calling Refresh.


GUI.ResetQuit

GUI.ResetQuit Part of GUI module

Syntax GUI.ResetQuit

Description The GUI.ResetQuit procedure resets the "quitting" flag that is set by the GUI.Quit program. The GUI.ResetQuit can be used whenever you want to have a program that exits from the main processing loop, does some work, and then reenters the processing loop.

Without GUI.ResetQuit, the program will exit the second loop immediately because GUI.ProcessEvent will return true.

Example This program allows the user to select the color that stars are to be drawn in. When the user presses the button, the program exits the first event loop and draws the stars. Before creating another button and entering a second event loop, it calls GUI.ResetQuit.

        import GUI
        var radio : array 1 .. 4 of int
        var button : int
        var starColor : int := red

        % Action procedures for the radio buttons
        procedure Red
            starColor := brightred
        end Red

        procedure Green
            starColor := brightgreen
        end Green

        procedure Blue
            starColor := brightblue
        end Blue

        procedure Cyan
            starColor := brightcyan
        end Cyan

        % Create the radio buttons
        radio (1) := GUI.CreateRadioButton (15, maxy - 35, "Red", 0, Red)
        radio (2) := GUI.CreateRadioButton (-1, -1, "Green", radio (1), Red)
        radio (3) := GUI.CreateRadioButton (-1, -1, "Blue", radio (2), Blue)
        radio (4) := GUI.CreateRadioButton (-1, -1, "Cyan", radio (3), Cyan)

        % Create the push button
        button := GUI.CreateButton (100, maxy - 70, 0, "Draw Stars", GUI.Quit)

        % Process events until the "Draw Stars" button is pressed
        loop
            exit when GUI.ProcessEvent
        end loop

        % Dispose of all the radio buttons and the push button
        for i : 1 .. 4
            GUI.Dispose (radio (i))
        end for
        GUI.Dispose (button)

        % Draw a bunch of stars - No more handling of events or widgets
        for i : 1 .. 100
            var x : int := Rand.Int (0, maxx - 20)
            var y : int := Rand.Int (0, maxy - 20)
            Draw.FillStar (x, y, x + 20, y + 20, starColor)
        end for

        % Create a new button
        button := GUI.CreateButton (300, 10, 0, "Quit", GUI.Quit)

        % Reset the quit flag. Without this statement, the loop following would
        % exit immediately because the quit flag was set in the previous loop
        GUI.ResetQuit

        % Process events until the "Quit" button is pressed
        loop
            exit when GUI.ProcessEvent
        end loop

        % Close the window
        GUI.CloseWindow (defWinID)

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.ResetQuit, not by calling ResetQuit.


GUI.SaveFile

GUI.SaveFile Part of GUI module

Syntax GUI.SaveFile (title : string) : string

Description Displays an "Save File" dialog box to obtain the name of a file. The caption (a window title under MS Windows, a string in a Macintosh dialog box) is specified by the title parameter. The function uses a dialog box specific to the operating system the program is being run on.

If the user did not choose a file (i.e. hit the Cancel button in the dialog), the function returns "" (the empty string).

Note: This function is not available in the current version of the GUI Procedure Library (shipping with Turing 4.0 and MacOOT 1.5). It is documented here for use with future shipping version of Turing. Check the release notes that are found in the on-line help to find out if this function is now available.

Example The following program asks the user for the name of a file and then writes the numbers 1 to 10 in it.

        import GUI in "%oot/lib/GUI"

        var fileName : string
        var streamNumber : int

        fileName := GUI.SaveFile ("Choose a Text File")

        open : streamNumber, fileName, put
        assert streamNumber > 0
        for i : 1 .. 10
            put : streamNumber, i
        end loop
        close : streamNumber
Status Exported qualified.

This means that you can only call the function by calling GUI.SaveFile, not by calling SaveFile.


GUI.SaveFileFull

GUI.SaveFileFull Part of GUI module

Syntax GUI.SaveFileFull (title, filter: string,
startDir : string) : string

Description Displays an "Save File" dialog box to obtain the name of an already existing file. The caption (a window title under MS Windows, a string in a Macintosh dialog box) is specified by the title parameter. The list of files shown is specified by the filter parameter. The initial directory to be displayed is specified by the startDir parameter. The function uses a dialog box specific to the operating system the program is being run on.

The filter parameter is a file name suffix that should be displayed. Multiple suffixes can be specified by separating them with commas. If the user specifies the empty string for filter, then all the files in the directory are displayed. If the startDir parameter is empty, or if it specifies a non-existent directory, then the current directory is displayed in the "Open File" dialog box.

If the user did not choose a file (i.e. hit the Cancel button in the dialog), the function returns "" (the empty string).

Note: This function is not available in the current version of the GUI Procedure Library (shipping with Turing 4.0 and MacOOT 1.5). It is documented here for use with future shipping version of Turing. Check the release notes that are found in the on-line help to find out if this function is now available.

Example The following program segment asks the user for the name of a file ending in ".txt". The initial directory is the root directory of the C drive.

        var fileName : string := GUI.SaveFileFull ("Choose a Text File",
            "txt", "C:\\")
Details If a suffix is placed in single quotes, it will be ignored on all but the Apple Macintosh, where it will specify a Macintosh file type.

Example The following program segment asks the user for the name of a file. It displays files of type 'TEXT'. The initial directory is the "Turing Programs" directory on the "Macintosh HD" volume.

        var fileName : string := GUI.SaveFileFull ("Choose a Text File",
            "'TEXT'", "Macintosh HD:Turing Programs")
Status Exported qualified.

This means that you can only call the function by calling GUI.SaveFileFull, not by calling SaveFileFull.


GUI.SelectRadio

GUI.SelectRadio Part of GUI module

Syntax GUI.SelectRadio (widgetID : int)

Description Selects a radio button specified by widgetID. The previously-selected radio button is "de-selected". The action procedure of the radio button is called.

Example The following program creates siz radio buttons. Selecting one of the buttons cause the bottom two radio buttons to become selected.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:350;110")

        var radio : array 1 .. 6 of int     % The radio button IDs.

        procedure RadioPressed
            Text.Locate (1, 1)
            for i : 1 .. 6
                if radio (i) = GUI.GetEventWidgetID then
                    put "Radio Button " , i, " Selected"
                end if
            end for
        end RadioPressed

        procedure Select
            GUI.SelectRadio (radio (3))
            GUI.SelectRadio (radio (6))
        end Select

        radio (1) := GUI.CreateRadioButton (15, maxy  35,
            "Radio Button 1", 0, RadioPressed)
        radio (2) := GUI.CreateRadioButton ( 1, 1, "Radio Button 2",
            radio (1), RadioPressed)
        radio (3) := GUI.CreateRadioButton ( 1, 1, "Radio Button 3",
            radio (2), RadioPressed)
        radio (4) := GUI.CreateRadioButtonFull (maxx  15, maxy  35,
            "Radio Button 4", 0, RadioPressed, GUI.RIGHT, GUI.NONE)
        radio (5) := GUI.CreateRadioButtonFull ( 1, 1, "Radio Button 5",
            radio (4), RadioPressed, GUI.RIGHT, GUI.NONE)
        radio (6) := GUI.CreateRadioButtonFull ( 1, 1, "Radio Button 6",
            radio (5), RadioPressed, GUI.RIGHT, GUI.NONE)

        var selectButton : int := GUI.CreateButton (15, 10, 100,
            "Select Bottom Buttons", Select)
        var quitButton : int := GUI.CreateButton (maxx  15  100, 10, 100,
            "Quit", GUI.Quit)loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the procedures by calling GUI.SelectRadio, not by calling SelectRadio.

See also GUI.CreateRadioButton and GUI.CreatePictureRadioButton.


GUI.SetActive

GUI.SetActive Part of GUI module

Syntax | GUI.SetActive (widgetID : int)
Description | Makes a text field specified by widgetID active. If the text field is not in an active window, then the text field will become active when the window does. If another text field was active in the window, it is deactivated.
Example | See GUI.CreateTextFieldfor an example of GUI.SetActive.
Status | Exported qualified. This means that you can only call the procedures by calling GUI.SetActive, not by calling SetActive.
See also | GUI.CreateTextField.


GUI.SetBackgroundColor

GUI.SetBackgroundColor Part of GUI module

Syntax | GUI.SetBackgroundColor (Color : int)
Description | Changes the background colour of the currently-selected window to the color specified by Color. This does not change the value of color 0 in the window. Instead it fills the entire window with the new background color and then redraws all the widgets. For indented and extended items, the background color is assumed to be set to gray. The alternate spelling is GUI.SetBackgroundColour
Example | See GUI.CreateFrame for an example of GUI.SetBackgroundColour.
Status | Exported qualified. This means that you can only call the procedures by calling GUI.SetBackgroundColor, not by calling SetBackgroundColor.


GUI.SetCheckBox

GUI.SetCheckBox Part of GUI module

Syntax | GUI.SetCheckBox (widgetID : int, status : boolean)
Description | Sets the status of a check box specified by widgetID. If status is true, the check box is filled (marked with an 'X'). If status is false, the check box is set empty. GUI.SetCheckBox calls the check box's action procedure with the new status and redraws the widget with the new status.
Example | See GUI.CreateCheckBox for an example of GUI.SetCheckBox.
Status | Exported qualified. This means that you can only call the procedures by calling GUI.SetCheckBox, not by calling SetCheckBox.
See also | GUI.CreateCheckBox.


GUI.SetColor

GUI.SetColor Part of GUI module

Syntax GUI.SetColor (widgetID : int, clrNumber : int)

Description The GUI.SetColor procedure is used buttons to change the color of a button. The color is specified by the clrNumber parameter. The edges of the button are a darker version of the color specified by clrNumber, so in general you should use brighter colors for buttons.

Example This program displays three buttons with different colors.

        import GUI

        procedure DoNothing
        end DoNothing

        var b1 := GUI.CreateButton (100, 100, 0, "Push Me", DoNothing)
        GUI.SetColor (b1, brightred)
        var b2 := GUI.CreateButton (100, 140, 0, "Push Me", DoNothing)
        GUI.SetColor (b2, brightgreen)
        var b3 := GUI.CreateButton (100, 180, 0, "Push Me", DoNothing)
        GUI.SetColor (b3, brightblue)

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.SetColor, not by calling SetColor.


GUI.SetDefault

GUI.SetDefault Part of GUI module

Syntax | GUI.SetDefault (widgetID : int, default : boolean)
Description | Sets the "default status" of a button specified by widgetID. If a button is the default button, then it is drawn with a heavy outline and it is activated when the user presses ENTER. Only one button can be the default button per window. If a button is set to be the default button, then the previous default button has its "default status" removed.
Status | Exported qualified. This means that you can only call the procedures by calling GUI.SetDefault, not by calling SetDefault.
See also | GUI.CreateButton.


GUI.SetDisplayWhenCreated

GUI.SetDisplayWhenCreated Part of GUI module

Syntax GUI.SetDisplayWhenCreated (display : boolean)

Description By default, whenever a widget is created with a GUI.Create… procedure, the widget instantly appears. Sometimes, this is not the desired behaviour. For example, if several widgets are to occupy the same location with only one being displayed at a time, then it is desirable not to have the widget appear when first created.

If a widget is not displayed when created, then GUI.Show must be called to make the widget visible.

If the display parameter is true, then widgets are displayed immediately upon creation. If the display parameter is set to false, then the widget is not made visible on creation and GUI.Show must be called to display the widget.

Example The following program toggles the visiblility of the frame when the button is pushed. The frame starts out invisible.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:150;100")

        var visible : boolean := false
        var button, frame : int

        procedure Toggle
            if visible then
                GUI.Hide (frame)
            else
                GUI.Show (frame)
            end if
            visible := not visible
        end Toggle

        button := GUI.CreateButton (25, 40, 0, "Toggle Frame", Toggle)
        GUI.SetDisplayWhenCreated (false)
        frame := GUI.CreateFrame (10, 10, 140, 90, 0)

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetDisplayWhenCreated, not by calling SetDisplayWhenCreated.


GUI.SetEchoChar

GUI.SetEchoChar Part of GUI module

Syntax GUI.SetEchoChar (widgetID : int, echoChar : char)

Description The GUI.SetEchoChar procedure is used with text fields, especially when using a text field to input a password. When the GUI.SetEchoChar is called with a text field, any character entered into the text field will appear as the character specified by inputChar.

This allows you to use the text field to enter a password. The characters that the user types will be echoed with the character specified by inputChar (often an asterisk).

Example This program displays a text field. As the user enters characters, each character is represented as a '*'. When the user enters return, the program exits after displaying the actual text entered into the text field.

        import GUI

        procedure EchoString (s : string)
            put "You entered \"", s, "\""
            GUI.Quit
        end EchoString

        var tf := GUI.CreateTextField (10, 100, 100, "", EchoString)
        GUI.SetEchoChar (tf, '*')
        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Details Note that the echoChar argument to GUI.SetEchoChar must be a character, not a string. This means the character should be enclosed in single quote marks ('), not double quotes (").

Status Exported qualified.

This means that you can only call the function by calling GUI.SetEchoChar, not by calling SetEchoChar.


GUI.SetKeyEventHandler

GUI.SetKeyEventHandler Part of GUI module

Syntax GUI.SetKeyEventHandler (
keyEventHandler : procedure x (ch : char))

Description Sets the new default keystroke event handler. The keyEventHandler parameter is the name of a procedure that is called every time GUI.ProcessEvent is called and there is a keystroke which is not handled by any widget. The ch parameter in the keyEventHandler is the keystroke typed by the user.

This procedure is often used to allow for more than one shortcut character for a given button.

Example The following program draws a star or quits depening on the button. The Draw Star button can be activated by clicking on it or typing 'D', 'd', 'S', 's' or Ctrl+S. The Quit button can be activate by typing 'Q', 'q' or Ctrl+Q. The Draw Star button is also the default button. It is activated whenever the user presses ENTER.

        import GUI
        View.Set ("graphics:220;200")
        procedure DrawStar
            Draw.FillStar (25, 40, 175, 190, Rand.Int (10, 15))
        end DrawStar

        procedure KeyHandler (ch : char)
            if ch = 'q' or ch = '^Q' then
                Draw.Cls
                GUI.Quit
            elsif ch = 'd' or ch = '^d' or ch = 'S' or ch = 's' or ch = '^s' then
                DrawStar
            end if
        end KeyHandler

        GUI.SetKeyEventHandler (KeyHandler)
        var button : int := GUI.CreateButtonFull (5, 5, 100, "Draw Star",
            DrawStar, 0, 'D', true)
        var quitButton : int := GUI.CreateButtonFull (115, 5, 100, "Quit",
            GUI.Quit, 0, 'Q', false)
        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetKeyEventHandler, not by calling SetKeyEventHandler.

See also GUI.ProcessEvent.


GUI.SetLabel

GUI.SetLabel Part of GUI module

Syntax GUI.SetLabel (widgetID : int, text : string)

Description Changes the text of a widget specified by widgetID to text. This procedure can accept a button, check box, radio button, label, or a labelled frame widget as the widgetID parameter.

In most cases, if the text will not fit in the widget's current size, the widget will be resized to fit the text. If the widget was made larger to fit the text and then the text is changed, the widget will be resized as appropriate for the original width specified and the new text.

Example The following program changes the text in the button whenever a keystroke occurs. When the text is changed back to "Quit", the button assumes a width of 100 again.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:220;50")

        var short : boolean := true
        var button : int

        procedure KeyHandler (ch : char)
            if short then
                GUI.SetLabel (button, "Press This Button to Quit")
            else
                GUI.SetLabel (button, "Quit")
            end if
            short := not short
        end KeyHandler

        GUI.SetKeyEventHandler (KeyHandler)
        button := GUI.CreateButton (10, 5, 100, "Quit", GUI.Quit)

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetLabel, not by calling SetLabel.

See also GUI.CreateButton, GUI.CreateCheckBox, GUI.CreateRadioButton, GUI.CreateLabel, and GUI.CreateLabelledFrame.


GUI.SetMouseEventHandler

GUI.SetMouseEventHandler Part of GUI module

Syntax GUI.SetMouseEventHandler (
mouseEventHandler : procedure x (mx, my : int))

Description Sets the new default mouse event handler. The mouseEventHandler parameter is the name of a procedure that is called every time GUI.ProcessEvent is called and there is a mouse button down which is not handled by any widget. The mx and my parameters in the mouseEventHandler are the location of mouse when the button was pressed.

This procedure is used by programs to allow for mouse input in a program that uses widgets.

Example This is a program that allows the user to place stars on the screen. The menu bar allows the user to quit the program at any time. The user can also toggle the appearance of the menu bar by pressing any key.

        import GUI

        var starX, starY, starColor : array 1 .. 100 of int
        var numStars : int := 0
        var menuVisible : boolean := true

        procedure DrawStar (i : int)
            if menuVisible then
                View.ClipSet (0, 0, maxx,
                    maxy  GUI.GetMenuBarHeight)
            end if
            Draw.FillStar (starX (i)  20, starY (i)  20, starX (i) + 20,
                starY (i) + 20, starColor (i))    View.ClipOff
        end DrawStar

        procedure Redraw
            for i : 1 .. numStars
                DrawStar (i)
            end for
            Text.Locate (maxrow, 1)
            put "Press any key to toggle menu bar" ..
        end Redraw

        procedure KeyHandler (ch : char)
            if menuVisible then
                GUI.HideMenuBar    else
                GUI.ShowMenuBar
            end if
            menuVisible := not menuVisible
            Redraw
        end KeyHandler

        procedure MouseHandler (x, y : int)
            if numStars = 100 then
                Text.Locate (maxrow, 1)
                put "Maximum number of stars exceeded!" ..
                return
            end if
            numStars += 1
            starX (numStars) := x
            starY (numStars) := y
            starColor (numStars) := Rand.Int (9, 15)
            DrawStar (numStars)
        end MouseHandler

        var menu : int := GUI.CreateMenu ("File")
        var menuItem : int := GUI.CreateMenuItemFull ("Quit",
            GUI.Quit, '^Q', false)
        GUI.SetKeyEventHandler (KeyHandler)
        GUI.SetMouseEventHandler (MouseHandler)
        Redraw
        loop
            exit when GUI.ProcessEvent
        end loop

Status Exported qualified.

This means that you can only call the function by calling GUI.SetMouseEventHandler, not by calling SetMouseEventHandler.

See also GUI.ProcessEvent.


GUI.SetNullEventHandler

GUI.SetNullEventHandler Part of GUI module

Syntax GUI.SetNullEventHandler (nullHandler : procedure x ())

Description Sets the new null event handler. The nullHandler parameter is the name of a procedure that is called every time GUI.ProcessEvent is called and there are no mouse button presses or keystrokes to be processed.

This is used by programs that need to call subprograms often, but do not wish to interrupt the action of user widgets.

Example The following program has a Quit button. When no widgets are being processed, a clock in the corner is updated.

        import GUI
        View.Set ("graphics:220;50")

        var oldTime : string := ""
        var button : int

        procedure NullHandler
            var newTime : string := Time.Date
            newTime := newTime (11 .. *)
            if newTime not= oldTime then
                Text.Locate (maxrow, maxcol  9)
                put newTime ..
                oldTime := newTime
            end if
        end NullHandler

        GUI.SetNullEventHandler (NullHandler)
        button := GUI.CreateButton (10, 5, 100, "Quit", GUI.Quit)

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetNullEventHandler, not by calling SetNullEventHandler.

See also GUI.ProcessEvent.


GUI.SetPosition

GUI.SetPosition Part of GUI module

Syntax GUI.SetPosition (widgetID, x, y : int)

Description Moves a widget specified by widgetID to the location (x, y). If the widget is visible, it is moved immediately to the new location. If the widget is hidden, it will appear at the new location when the Show procedure is called. Note that the x and y specified here are the same as in the Create method. For example, if you had specified a check box to be right justified in the CreateCheckBoxFull function, then (x, y) in a call to SetPosition would specify the lower-right corner as opposed to the lower-left corner.

Example The following program moves the button every time the button is pressed.

        import GUI in "%oot/lib/GUI"

        var button : int

        procedure MoveButton
            var newX, newY : int
            newX := Rand.Int (0, maxx  GUI.GetWidth (button))
            newY := Rand.Int (0, maxy  GUI.GetHeight (button))
            GUI.SetPosition (button, newX, newY)
        end MoveButton

        button := GUI.CreateButton (100, 100, 0, "Move Button",
            MoveButton)
        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetPosition, not by calling SetPosition.


GUI.SetPositionAndSize

GUI.SetPositionAndSize Part of GUI module

Syntax GUI.SetPositionAndSize (widgetID, x, y : int,
width, height : int)

Description Changes the position and size of the widget specified by widgetID simultaneously. The x, y, width and height parameters have the same meaning as in the GUI.Create function for that widget. Any widget except a menu or a menu item can be resized, although for some widgets, the width or height parameter may be ignored.

GUI.SetPositionAndSize works the same way as the GUI.SetPosition and GUI.SetSize procedures.

Example The following program moves and resizes the button every time the button is pressed.

        import GUI in "%oot/lib/GUI"

        var button, minWidth, minHeight  : int

        procedure MoveButton
            var newX, newY, newWidth, newHeight  : int
            newWidth := max (minWidth, Rand.Int (0, 200))
            newHeight := max (minHeight, Rand.Int (0, 100))
            newX := Rand.Int (0, maxx  newWidth)
            newY := Rand.Int (0, maxy  newHeight)
            GUI.SetPositionAndSize (button, newX, newY,
                newWidth, newHeight)
        end MoveButton

        button := GUI.CreateButton (100, 100, 0, "Move Button",
            MoveButton)
        minHeight := GUI.GetHeight (button)
        minWidth := GUI.GetWidth (button)
        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetPositionAndSize, not by calling SetPositionAndSize.


GUI.SetScrollAmount

GUI.SetScrollAmount Part of GUI module

Syntax GUI.SetScrollAmount (widgetID : int,
arrowInc, pageInc, thumbSize : int)

Description Sets a scroll bar's arrow increment, page increment and thumb size. Redraws the scroll bar to take into account the new thumb size. The widgetID specifies the scroll bar to be changed. The arrowInc parameter is the new arrow increment (the amount the scroll bar's value is changed when the scroll arrows are pressed). A value of 1 means to use the previously-defined arrow increment value. The pageInc parameter specifies the new page increment (the amount the scroll bar's value is changed when the user clicks in the page up/down section of the scroll bar). A value of 1 means to use the previously-defined page increment value. The thumbSize parameter specifies he new thumb size. See the scroll bar explanation for more detail on a scroll bar's thumb size. A value of 1 means to use the previously-defined thumb size.

Example The following program displays an image in a canvas in a window. If the image is larger than the canvas, scroll bars to the bottom and left are used to allow the user to see the entire image. A text field allows users to load additional images whenever the "Load File" button is pressed.

        % The "ScrollPic2" program.
        import GUI in "%oot/lib/GUI"

        % The maximum width/height of the canvas.
        const maxSize : int := 220
        const leftBorder : int := 15    % Left margin.
        const bottomBorder : int := 25  % Bottom margin.

        var h, v : int          % The scroll bars.
        var canvas : int            % The canvas.
        var pic : int               % The picture.
        var fileNameField : int     % The file name text field.
        var errorLabel : int        % The error message label.
        var loadButton : int        % The "Load Picture" button.

        procedure ScrollPic (ignore : int)
            % Get the current value of the scroll bars.
            var x : int := GUI.GetSliderValue (h)
            var y : int := GUI.GetSliderValue (v)
            GUI.PicDraw (canvas, pic, x, y, picCopy)
        end ScrollPic

        procedure LoadFile (fileName : string)
            var picWidth, picHeight, canvasWidth, canvasHeight : int
            var newPic : int := Pic.FileNew (fileName)
            if newPic <= 0 then
                GUI.SetLabel (errorLabel,
                    "Error loading picture: " + Error.LastMsg)
                GUI.SetSelection (fileNameField, 1, 1)
                return
            else
                GUI.SetLabel (errorLabel, "")
                pic := newPic
            end if
            picWidth := Pic.GetWidth (pic)
            picHeight := Pic.GetHeight (pic)
            canvasWidth := min (picWidth, maxSize)
            canvasHeight := min (picHeight, maxSize)
            % Hide the canvas and the three items, readjust them
            % and then show them.
            GUI.Hide (canvas)
            GUI.Hide (h)
            GUI.Hide (v)
            GUI.SetSize (canvas, canvasWidth, canvasHeight)
            GUI.SetSliderSize (h, canvasWidth + 1)
            GUI.SetPosition (v, 15 + canvasWidth,
                bottomBorder + GUI.GetScrollBarWidth - 1)
            GUI.SetSliderSize (v, canvasHeight + 1)
            GUI.SetSliderMinMax (h, 0, picWidth  1)
            GUI.SetSliderMinMax (v, 0, picHeight  1)
            GUI.SetScrollAmount (h, 3, 100, canvasWidth)
            GUI.SetScrollAmount (v, 3, 100, canvasHeight)
            GUI.SetSliderValue (h, 0)
            GUI.SetSliderValue (v, picHeight)
            GUI.Show (canvas)
            GUI.Show (h)
            GUI.Show (v)
            ScrollPic (0)
        end LoadFile

        procedure LoadFileButton
            var fileName : string := GUI.GetText (fileNameField)
            LoadFile (fileName)
        end LoadFileButton

        View.Set ("graphics:265;295")

        % We place the canvas first and everything else is placed
        % relative to the canvas.
        canvas := GUI.CreateCanvas (leftBorder,
            bottomBorder + GUI.GetScrollBarWidth, maxSize, maxSize)h := GUI.CreateHorizontalScrollBarFull (GUI.GetX (canvas),
            GUI.GetY (canvas)  GUI.GetScrollBarWidth,
            GUI.GetWidth (canvas), 0, 100, 0, ScrollPic, 3, 100, maxSize)
        v := GUI.CreateVerticalScrollBarFull (
            GUI.GetX (canvas) + GUI.GetWidth (canvas),
            GUI.GetY (canvas), GUI.GetHeight (canvas), 0, 100,
            100, ScrollPic, 3, 100, maxSize)
        fileNameField := GUI.CreateTextField (GUI.GetX (canvas),
            GUI.GetY (canvas) + GUI.GetHeight (canvas) + 10, 150, "",
            LoadFile)
        loadButton := GUI.CreateButton (GUI.GetX (fileNameField) +
            GUI.GetWidth (fileNameField) + 20,
            GUI.GetY (fileNameField), 0, "Load File", LoadFileButton)
        errorLabel := GUI.CreateLabel (GUI.GetX (canvas), 5, "")

        % Set the initial picture and return if it is not found.
        GUI.SetText (fileNameField, "Forest.bmp")
        LoadFileButton
        if pic = 0 then
            return
        end if

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetScrollAmount, not by calling SetScrollAmount.

See also GUI.CreateHorizontalScrollBar and GUI.CreateVerticalScrollBar


GUI.SetScrollOnAdd

GUI.SetScrollOnAdd Part of GUI module

Syntax GUI.SetScrollOnAdd (widgetID : int, scrollOnAdd : boolean)

Description The GUI.SetScrollOnAdd procedure allows you to specify whether a text box scrolls to the bottom of the text when new text is added (the default behaviour). By calling this procedure with scrollOnAdd set to false, the text box will not scroll unless the user manipulates the text box's scroll bars.
Example This program displays the contents of a file in a text box. After the file is displayed, the top line in the text box will be the first line in the file.

        import GUI
        View.Set ("graphics:300;300")

        const fileNameToBeViewed : string := "TextBxs.DEM"
        var textBox : int       % The Text Field ID.
        var title : int     % The label for the title.
        var f : int         % The stream number of the file.
        var line : string       % Lines to be read from the file.

        % Open the file.
        open : f, fileNameToBeViewed, get
        if f = 0 then
            put "Unable to open " + fileNameToBeViewed + " : ", Error.LastMsg
            return
        end if

        % Set background color to gray for indented text box.
        GUI.SetBackgroundColor (gray)

        % Create the title label and text box.
        title := GUI.CreateLabelFull (20, 280, fileNameToBeViewed, 250, 0,
            GUI.CENTER, 0)
        textBox := GUI.CreateTextBoxFull (10, 10, 280, 265,
            GUI.INDENT, 0)

    GUI.SetScrollOnAdd (textBox, false)

        % Read the file and place it in the text box.
        loop
            exit when eof (f)
            get : f, line : *
            GUI.AddLine (textBox, line)
        end loop

        close : f   % Close the file.

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.SetScrollOnAdd, not by calling SetScrollOnAdd.


GUI.SetSelection

GUI.SetSelection Part of GUI module

Syntax GUI.SetSelection (widgetID, fromSel, toSel : int)

Description Sets the selected text in the text field specified by widgetID. The value of the fromSel and toSel parameters indicate the characters where the selection will begin and end. For example, if the text was "Hello there", setting fromSel to 2 and toSel to 5 would select "ell". Setting fromSel and toSel to 1 automatically selects the entire text.

The fromSel parameter specifies the start of the selection. This ranges from 1 (before the first character) to the number of characters in the text + 1 (after the last character). A value of 1 for both fromSel and toSel selects the entire text.

The toSel parameter specifies the end of the selection. This ranges from 1 (before the first character) to the number of characters in the text + 1 (after the last character). A value of 1 for both fromSel and toSel selects the entire text.

Example The following program allows the user to type into a text field. When the user presses ENTER, it searches for any non-lowercase text and if it finds any, selects it to make it easy for the user to correct it. If all the input is lower-case text, the program terminates.

        import GUI in "%oot/lib/GUI"

        var textField, lbl : int

        procedure CheckInput (s : string)
            for i : 1 .. length (s)
                if (s (i) < 'a' or 'z' < s (i)) and s (i) not= ' ' then
                    GUI.SetSelection (textField, i, i + 1)
                    return
                end if
            end for
            GUI.Quit
        end CheckInput

        textField := GUI.CreateTextField (100, 100, 200, "", CheckInput)
        lbl := GUI.CreateLabelFull (100 + GUI.GetWidth (textField) div 2,
            100 + GUI.GetHeight (textField),
            "Only Allows Lower Case Letters", 0, 0,
            GUI.CENTER + GUI.BOTTOM, 0)

        loop
            exit when GUI.ProcessEvent
        end loop

        GUI.SetLabel (lbl, "Program Finished!")
Status Exported qualified.

This means that you can only call the function by calling GUI.SetSelection, not by calling SetSelection.

See also GUI.CreateTextField.


GUI.SetSize

GUI.SetSize Part of GUI module

Syntax GUI.SetSize (widgetID, width, height : int)

Description Changes the size of the widget specified by widgetID. If the widget is visible, its size is changed immediately, otherwise the widget will appear in its new size when the widget is next made visible. Note that the width and height parameters are no necessarily the actual width and height of the widget. For example, the TextField widget ignores the height parameter, calculating the widget's actual height from the height of the text in the TextField.

Example The following program resizes the button every time the button is pressed.

        import GUI in "%oot/lib/GUI"

        var button : int

        procedure ResizeButton
            var newWidth, newHeight  : int
            newWidth := Rand.Int (0, 200)
            newHeight := Rand.Int (0, 200)
            GUI.SetSize (button, newWidth, newHeight)
        end ResizeButton

        button := GUI.CreateButton (100, 100, 0, "Resize Button",
            ResizeButton)
        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetSize, not by calling SetSize.


GUI.SetSliderMinMax

GUI.SetSliderMinMax Part of GUI module

Syntax | GUI.SetSliderMinMax (widgetID, min, max : int)
Description | Sets the minimum and maximum values of the slider or scroll bar specified by widgetID. The min parameter specifies the new minimum value of the slider or scroll bar. The max parameter specifies the new maximum value of the slider or scroll bar. The max parameter must be greater than the min parameter. GUI.SetSliderMinMax redraws the thumb to take into account the new minimum and maximum. If the current value of the slider is outside the new minimum/maximum, then the value is adjusted appropriately.
Example | See GUI.SetScrollAmount for an example of GUI.SetSliderMinMax.
Status | Exported qualified. This means that you can only call the function by calling GUI.SetSliderMinMax, not by calling SetSliderMinMax.
See also | GUI.CreateHorizontalScrollBar, GUI.CreateVerticalScrollBar, GUI.CreateHorizontalSlider, and GUI.CreateVerticalSlider.


GUI.SetSliderReverse

GUI.SetSliderReverse Part of GUI module

Syntax GUI.SetSliderReverse (widgetID : int)

Description Sets a slider or scroll bar specified by widgetID into (or out of, if already into) "reverse mode". Normally, a slider or scroll bar is at its minimum value when the thumb is on the left hand side (bottom for a vertical slider). This reverses it, so the minimum value is when the thumb is at the right hand side (top for vertical sliders) of the track. Calling this routine a second time reverses it back to normal. This procedure redraws the slider to move the thumb to its new location.

Example The following program creates two sliders, one of which is reversed.

        import GUI in "%oot/lib/GUI"

        View.Set ("graphics:300;70")
        var sBar, sBarLabel, reverseSBar, reverseSBarLabel : int

        procedure SBarMoved (value : int)
            GUI.SetLabel (sBarLabel, intstr (value))
        end SBarMoved

        procedure ReverseSBarMoved (value : int)
            GUI.SetLabel (reverseSBarLabel, intstr (value))
        end ReverseSBarMoved

        sBar := GUI.CreateHorizontalScrollBar (10, 10, 250,
            50, 150, 50, SBarMoved)
        sBarLabel := GUI.CreateLabel (
            GUI.GetX (sBar) + GUI.GetWidth (sBar) + 10, 10, "50")

        reverseSBar := GUI.CreateHorizontalScrollBar (10, 40, 250,
            50, 150, 50, ReverseSBarMoved)
        GUI.SetSliderReverse (reverseSBar)
        reverseSBarLabel := GUI.CreateLabel ( GUI.GetX (reverseSBar) +
            GUI.GetWidth (reverseSBar) + 10, 40, "50")
        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetSliderReverse, not by calling SetSliderReverse.

See also GUI.CreateHorizontalScrollBar, GUI.CreateVerticalScrollBar, GUI.CreateHorizontalSlider, and GUI.CreateVerticalSlider.


GUI.SetSliderSize

GUI.SetSliderSize Part of GUI module

Syntax | GUI.SetSliderSize (widgetID, length : int)
Description | Changes the length of a slider or scroll bar specified by widgetID to the value specified by the length parameter. Redraws the slider or scroll bar and changes the position of the thumb to take into account the new size of the slider or scroll bar.
Example | See GUI.SetScrollAmount for an example of GUI.SetSliderSize.
Status | Exported qualified. This means that you can only call the function by calling GUI.SetSliderSize, not by calling SetSliderSize.
See also | GUI.CreateHorizontalScrollBar, GUI.CreateVerticalScrollBar, GUI.CreateHorizontalSlider, and GUI.CreateVerticalSlider.


GUI.SetSliderValue

GUI.SetSliderValue Part of GUI module

Syntax | GUI.SetSliderValue (widgetID, value : int)
Description | Sets the value of a slider or scroll bar specified by widgetID to value. It moves the thumb on the slider or scroll bar to the appropriate location and calls the slider's action procedure with the new value.
Example | See GUI.SetScrollAmount for an example of GUI.SetSliderValue.
Status | Exported qualified. This means that you can only call the function by calling GUI.SetSliderValue, not by calling SetSliderValue.
See also | GUI.GetSliderValue for reading a slider or scroll bar's value. See also GUI.CreateHorizontalScrollBar, GUI.CreateVerticalScrollBar, GUI.CreateHorizontalSlider, and GUI.CreateVerticalSlider.


GUI.SetText

GUI.SetText Part of GUI module

Syntax GUI.SetText (widgetID : int, text : string)

Description Sets the text of a text field specified by widgetID to text. The selection is set to 1, 1 (i.e. the cursor is at the beginning of the text).

Status Exported qualified.

This means that you can only call the function by calling GUI.SetText, not by calling SetText.

Example The following program converts all lower case input in the text field to upper case when the user presses ENTER.

        import GUI

        var textField, lbl : int

        procedure CheckInput (s : string)
            var newString : string := ""
            for i : 1 .. length (s)
                if 'a' <= s (i) and s (i) <= 'z' then
                    newString += chr (ord (s (i))  32)
                else
                    newString += s (i)
                end if
            end for
            GUI.SetText (textField, newString)
            GUI.SetSelection (textField, 1, 1)
        end CheckInput

        textField := GUI.CreateTextField (100, 100, 200, "", CheckInput)
        lbl := GUI.CreateLabelFull (100 + GUI.GetWidth (textField) div 2,
            100 + GUI.GetHeight (textField),  "Converts to Upper Case",
            0, 0, GUI.CENTER + GUI.BOTTOM, 0)

        loop
            exit when GUI.ProcessEvent
        end loop
Status Exported qualified.

This means that you can only call the function by calling GUI.SetText, not by calling SetText.

See also GUI.CreateTextField.


GUI.SetTopLine

GUI.SetTopLine Part of GUI module

Syntax GUI.SetTopLine (widgetID : int, lineNum : int)

Description The GUI.SetTopLine procedure scrolls the text in a text box so as to place the line number specified by lineNum at the top of the text box (if possible). This is often used to scroll the text back to the beginning of the text box by assigning a value of 1 to lineNum.
Example This program displays 100 lines of text in a text box, then sets the text box to display line 50 at the top of the box.

        import GUI

        var textBox : int     % The Text Field ID.
        textBox := GUI.CreateTextBoxFull (10, 10, 180, 275,
            GUI.INDENT, 0)

        GUI.SetBackgroundColor (gray)

        % Read the file and place it in the text box.
        for i : 1 .. 100
            GUI.AddLine (textBox, intstr (i))
        end for
        GUI.SetTopLine (textBox, 50)

        loop
            exit when GUI.ProcessEvent
        end loop
Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.SetTopLine, not by calling SetTopLine.


GUI.SetXOR

GUI.SetXOR Part of GUI module

Syntax GUI.SetXOR (widgetID : int, xor : boolean)

Description Sets the "xor mode" of the canvas specified by widgetID. If the xor parmeter is set to true, the canvas is set to xor mode. When in xor mode, all the Draw... procedures of a canvas are treated as if the View.Set ("xor") statement had been executed before the Draw procedure.

Example See GUI.SetDisplayWhenCreated for an example of GUI.Show.

        import GUI in "%oot/lib/GUI"
        View.Set ("graphics:400;300")
        var canvas1, label1, canvas2, label2 : int
        canvas1 := GUI.CreateCanvas (10, 20, maxx div 2  20, maxy  30)
        label1 := GUI.CreateLabelFull (10, 2, "XOR", maxx div 2  20, 0,
            GUI.CENTER, 0)
        canvas2 := GUI.CreateCanvas (maxx div 2 + 10, 20,
            maxx div 2  20, maxy  30)
        label2 := GUI.CreateLabelFull (maxx div 2 + 10, 2, "Normal",
            maxx div 2  20, 0, GUI.CENTER, 0)

        GUI.SetXOR (canvas1, true)
        for i : 1 .. 20
            var x : int := Rand.Int (0, maxx div 2  20)
            var y : int := Rand.Int (0, maxy  20)
            var c : int := Rand.Int (1, 15)
            GUI.DrawFillStar (canvas1, x  20, y  20, x + 20, y + 20, c)
        end for

        GUI.SetXOR (canvas2, false)
        for i : 1 .. 20
            var x : int := Rand.Int (0, maxx div 2  20)
            var y : int := Rand.Int (0, maxy  20)
            var c : int := Rand.Int (1, 15)
            GUI.DrawFillStar (canvas2, x  20, y  20, x + 20, y + 20, c)
        end for
Status Exported qualified.

This means that you can only call the function by calling GUI.SetXOR, not by calling SetXOR.

See also GUI.CreateCanvas.


GUI.Show

GUI.Show Part of GUI module

Syntax | GUI.Show (widgetID : int)
Description | Shows a widget specified by widgetID. Used in conjunction with GUI.Hide to show and hide widgets. Hidden widgets cannot get events (i.e. respond to keystrokes or mouse clicks). If an active text field (see text field) is hidden, then any keystrokes in the window will be ignored. In most cases where a widget is to appear, then disappear, then appear again, it is advised to create the widget once and hide it until it is to appear, whereupon GUI.Show is called. When the user is finished with the widget, the widget is hidden using GUI.Hide. This saves the overhead of creating and disposing of the same widget several times.
Example | See GUI.SetDisplayWhenCreated for an example of GUI.Show.
Status | Exported qualified. This means that you can only call the function by calling GUI.Show, not by calling Show.
See also | GUI.Hide.


GUI.ShowMenuBar

GUI.ShowMenuBar Part of GUI module

Syntax | GUI.ShowMenuBar
Description | Shows the menu bar in the selected window.
Example | See GUI.SetMouseEventHandler for an example of GUI.HideMenuBar.
Status | Exported qualified. This means that you can only call the function by calling GUI.ShowMenuBar, not by calling ShowMenuBar.
See also | GUI.HideMenuBar. See also GUI.CreateMenu.


GUI.ShowWindow

GUI.ShowWindow Part of GUI module

Syntax GUI.ShowWindow (window : int)

Description Hides a window with widgets in it. This procedure makes certain that the GUI Library recognizes that the window no longer visible. This procedure will call Window.Hide, so there is no need for the user to do so.

Example The program opens up a window with two buttons. If the button labelled "Close and Open" is pressed, the window is closed and a new window with two buttons is opened in a random location on the screen.

        import GUI

        var windowA, windowB : int
        var buttonA, buttonB, buttonQuit : int
    var backToMainA, backToMainB : int

        procedure ShowWindowA
            GUI.HideWindow (defWinID)
            GUI.ShowWindow (windowA)
        end ShowWindowA

        procedure ShowWindowB
            GUI.HideWindow (defWinID)
            GUI.ShowWindow (windowB)
        end ShowWindowB

        procedure ShowMain
            GUI.HideWindow (Window.GetActive)
            GUI.ShowWindow (defWinID)
        end ShowMain

        View.Set ("graphics:280;100,nobuttonbar")
        % Place the buttons in the main window
        buttonA := GUI.CreateButton (10, 10, 0, "Show Window A", ShowWindowA)
        buttonB := GUI.CreateButton (150, 10, 0, "Show Window B", ShowWindowB)
        buttonQuit := GUI.CreateButton (100, 60, 0, "Quit", GUI.Quit)

        windowA := Window.Open  ("title:Window A,graphics:150;100,position:bottom;left")
        backToMainA := GUI.CreateButton (20, 20, 0, "Back to Main", ShowMain)
        Window.Hide (windowA)
        windowB := Window.Open  ("title:Window B,graphics:150;100,position:bottom;right")
        backToMainB := GUI.CreateButton (20, 20, 0, "Back to Main", ShowMain)
        Window.Hide (windowB)

        loop
            exit when GUI.ProcessEvent
        end loop

Execute

Status Exported qualified.

This means that you can only call the function by calling GUI.ShowWindow, not by calling ShowWindow.

See also GUI.HideWindow for hiding a window with widgets in it. See also GUI.CloseWindow for closing a window with widgets in it.


handler

handler exception handler

Dirty

Syntax A exceptionHandler is:

handler ( id )
statementsAndDeclarations
end handler

Description An exception handler is an optional block of statements and declarations in a subprogram (or process). It is activated when the program (or process) fails. This occurs, for example when dividing by zero.

Example This program parses the input stream using a stack. If the stack overflows (its top exceeds its maximum), a quit statement in the push procedure aborts the parsing and gives control to the exception handler in the parse procedure. The parse procedure calls parseExpn which calls push. If push overflows the stack, it executes a quit and control is passed to the exception handler in the parse procedure. The interrupted procedures (parseExpn and push) are terminated and their local variables are deleted.

        const stackOverflow := 500
        const maxTop := 100
        var top : 0 .. maxTop := 0
        var stack : array 1 .. maxTop of int

        procedure push ( i : int )
            if top = maxTop then
                quit : stackOverflow
            end if
            top := top + 1
            stack ( top ) := i
        end push
        …
        procedure parse
            handler ( exceptionNumber )
                put "Failure number ", exceptionNumber
                case exceptionNumber of
                label stackOverflow :
                    put "Stack has overflowed!!"
                … other exceptions handled here …
                label :         % Unexpected failures
                    quit >      % Pass exception further
                end case
            end handler
            parseExpn           % Eventually push is called
        end parse
Details See the quit statement for an explanation of its quitReason (stackOverflow in the first quit statement above) and its guiltyParty (> in the second quit statement, meaning the exception is due to causes outside of this handler).

An exception handler can appear only in the body of a subprogram (or process), just preceding the declarations and statements. The form of a procedure is:

        procedure [ pervasive ] id
            [ ( [ paramDeclaration {,paramDeclaration } ] ) ]
            [ import [ [var] id {, [var] id } ] ]
            [ pre trueFalseExpn ]
            [ init id := expn {, id := expn } ]
            [ post trueFalseExpn ]
            [ exceptionHandler ]
            statementsAndDeclarations
        end id
Exactly the same declarations and statements can appear in a handler as can appear in the subprogram body following the handler. In the absence of exceptions, handlers have no observable effect. A particular handler is activated (it becomes ready to handle an exception) when it is encountered during execution. It remains active until the subprogram (or process) containing it has completed, or the handler is given control. Activation of a handler when a previous handler is already active will cause exceptions to be passed to the newly-activated handler. In other words, handlers have a dynamic scope that begins when the exception handler is encountered and ends when the subprogram (or process) containing the handler has terminated or the handler is given control.

When a handler is given control, it becomes, in effect, a replacement for the declarations and statements following it. If the handler is in a function, it must terminate with a result statement or with a quit. If the handler is in a procedure (or process), the handler must terminate with a return, a quit, or by encountering the end of the handler (which is equivalent to a return).

When a handler terminates with a result or return statement (or by reaching the end of a procedure's handler), the subprogram's post condition (if any) must be true. A quit statement does not need to establish the post condition.

Programming with exception handlers easily leads to incomprehensible software, due to the difficulty of keeping track of the flow of control. One of the most insidious situations is when an exception occurs in a module, class or monitor and is propagated outside of the unit. This can leave the contained data in an inconsistent state; in the case of a monitor, it is left locked forever. To avoid this possibility, you can use a handler in each exported subprogram. If an exception in a process is not handled, the entire program is aborted. If an implementation allocates dynamic arrays on the heap, an exception may prevent the deallocation of such an array.

Without exception handling, a program executes according to the language definition or else is aborted. If an exception handler is active, instead of aborting, control is given to the handler. The quitNumber for a system-detected failure is implementation-dependent. There is a file "%exceptions" which lists these numbers. The user program can simulate a system exception by doing a quit with the corresponding number.

If the user turns off checking explicitly, the system may not detect failures. In some cases the failure may yield incorrect data or arbitrary behavior.

Some exceptions are unpredictable or implementation-dependent. For example, in x := 24 div i + 24 / i, if i is zero, the exception could be either an integer or a real division by zero, because the order or evaluation is implementation-dependent.


hasch

hasch has character function

Syntax hasch : boolean

Description The hasch procedure is used to determine if there is a character that has been typed but not yet been read.

Example This program simulates the rolling of a pair of dice until the user pressed the keyboard.

        put "Press any key to stop the dice rolling"
        var die1, die2 : int
        var ch : string (1)
        loop
            exit when hasch
            randint (die1, 1, 6)
            randint (die2, 1, 6)
            locate (1, 1)
            put "You rolled ", die1 + die2
        end loop

        getch (ch)    % Discard the character

Execute

Details The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in "graphics" mode, it will automatically be set to "graphics" mode.

If there is the possibility that there are already keystrokes in the keyboard buffer, the Input.Flush command can be used to flush the keyboard buffer (remove all keystrokes from the buffer) before entering the loop to check for input.

See also getch and getchar.

See also the Input.Flush command for flushing the keyboard buffer.

See also predefined unit Input.


id

id (identifier) name of an item in a program

Description Variables, constants, types, procedures, etc. in Turing programs are given names such as incomeTax, x, and height. These names are called identifiers (ids).

An identifier must start with a letter (large or small) or an underscore ( _ ) and can contain up to 50 characters, each of which must be a letter, a digit (0 to 9) or an underscore ( _ ). Large and small letters are considered distinct, so that A and a are different names. This differs from Pascal where large and small letters in names are equivalent.

Every character in a name is significant in distinguishing one name from another.

By convention, words that make up an identifier are capitalized (except the first one), as in incomeTax and justInTime.

An item in a Turing program cannot be given the same name as a keyword such as get or as a reserved word such as index. See Appendix A for a list of keywords and reserved words. As well, there are some identifiers that are used by the Turing error recovery procedures and are thus unavailable for use as identifiers. Specifically, they are: endif, elseif, endloop and endfor.


#if

#if used for conditional compilation

Syntax A conditional compilation #if has the form:

#if expn then
 | … any source text …
{ #elsif expn then
 | … any source text … }
[ #else
 | … any source text … ]
#end if

Description An #if construct supports compile time selection of sections of source text to make up a program (or unit of a program), in other words conditional compilation. Any arbitrary source text (characters) can be selected.

Each of the selecting expressions (expns) have the form of a boolean expression, with the use of the operators and, or and not (but not =>) and parentheses. The short forms & and ~ are supported. The operands of the expressions must be preprocessor flags, which are set by a system- dependent mechanism not described here. A flag is considered to be true if it is explicitly set. If it is not explicitly set, it is considered false.

Unlike other parts of the language, the #if, #elsif, #else and #end if constructs are not free format. Specifically, they must be placed by themselves on a single line.

Example A pair of declarations is chosen if both stats and debug are set, otherwise the put statement is selected. The selected part becomes part of the program and the other parts are ignored.

        #if stats and debug then
            var count : array 1 .. 5 of real
            var message : string
        #else
            put "Debugging message"
        #end if


if

if statement

Syntax An ifStatement is:

if trueFalseExpn then
 | statementsAndDeclarations
{ elsif trueFalseExpn then
 | statementsAndDeclarations }
[ else
 | statementsAndDeclarations ]
end if

Description An if statement is used to choose among a set of statements (and declarations). One set (at most) is chosen and executed and then execution continues just beyond end if.

The expressions (the trueFalseExpressions) following the keyword if and each elsif are checked one after the other until one of them is found to be true, in which case the statements (and declarations) following the corresponding then are executed. If none of these expressions evaluates to true, the statements following else are executed. If no else is present and none of the expressions are true, no statements are executed and execution continues following the end if.

Example Output a message based on value of mark.

        if mark >= 50 then
            put "You pass"
        else
            put "You fail"
        end if
Example Output A, B, C, D or F depending on mark.

        if mark >= 80 then
            put "A"
        elsif mark >= 70 then
            put "B"
        elsif mark >= 60 then
            put "C"
        elsif mark >= 50 then
            put "D"
        else
            put "F"
        end if
Example If x is negative, change its sign.

        if x < 0 then
            x := - x
        end if
Example If x is less than zero or greater than maxx, put a message.

        if x < 0  or x > maxx then
            put "Out of bounds!"
        end if
Example If the boolean flag is true and name is “stop”, put a message and return.

        if flag  and name = "stop" then
            put "Exiting routine"
            return
        end if
Details Several statements and declarations can appear after a particular then.

See also case statements for another way to select among statements.


implement by

implement by clause

Syntax An implementByClause is:

implement by implementByItem

Description An implement-by clause is used to specify that a module, monitor or class C is to be automatically implemented by the implementByItem. C is called the interface and the implementByItem, which must contain an implement clause, is called the implementation. See implement clause for details and an example.

The implement-by clause can only be used in a unit. See unit for the definition of a unit.

An implementByItem is one of:

(a) | id
(b) | id in fileName

The second form is used when the implement-by clause is for a separate unit and the imported item is in a file whose name is different from the item's name, as in:

        implement by ledgerBody in "ledgbod.t"
The fileName must be an explicit character string, e.g., "ledgbod.t". See also unit. Parentheses are allowed around the items in an implement-by clauses, as in:

        implement by ( ledgerBody in "ledgbod.t" )


implement

implement clause

Syntax An implementClause is:

implement implementItem

Description An implement clause is used to specify that the module, monitor or class containing the clause is to be the implementation of another module, monitor or class. This implementation is a special kind of expansion. The module, monitor or class containing the clause gains access to (inherits) all the declarations inside the target item. See inherit clause for rules about expansions, which are also rules for implementations.

The implement clause can only be used in a unit. See unit for the definition of a unit.

Example Here is a stack module which defers all of its exported subprograms. This module is an interface but not an implementation. Following stack is the stackBody module that implements the stack module, giving the bodies for stack's subprograms. Any call to stack's push or pop procedures, such as stack.push("Ed"), will actually call the procedures given in stackBody.

        module stack                % Interface
            implement by stackBody
                                % stackBody has implementation
            export push, pop
            deferred procedure push ( s : string )
            deferred procedure pop ( var s : string )
        end stack
Next comes the expansion which gives the bodies for the deferred procedures push and pop. The stackBody body also adds declarations for the top and contents variables.

        module stackBody        % Implementation
            implement stack     % stack has interface
            var top : int := 0
            var contents : array 1 .. 100 of string

            body procedure push % ( s : string )
                top := top + 1
                contents ( top ) := s
            end push

            body procedure pop      % ( var s : string )
                s := contents ( top )
                top := top - 1
            end pop
        end stackBody
Details Module, monitor or class D can be in C's implement-by clause if, and only if, C is in D's implement clause. In other words, an interface must apply to exactly one implementation and vice versa. A module can implement only a module, a monitor only a monitor, and a class only a class. Classes (but not modules and monitors) can contain inherit clauses. A class cannot contain both an inherit and an implement clause.

An implementItem is one of:

(a) id
(b) id in fileName

The second form is used when the implement clause is for a separate unit and the imported item is in a file whose name is different from the item's name, as in:

        implement ledger in "ledg.t"
The fileName must be an explicit character string, e.g., "ledg.t". See also unit. Parentheses are allowed around the items in implement clauses, as in:

        implement ( ledger in "ledg.t" )
There is no restriction on the declarations that an interface may contain. In particular, an interface (any module, monitor or class containing an implement-by clause), can contain subprogram bodies and variable declarations, exactly as is the case in expansions. This is different from languages such as C++ in which there are strict rules limiting what you can put in an interface.

Even though D contains an implement clause, D can also contain an implement-by clause, which implies further implementation by further automatic expansion.

Suppose class D is in class C's implement-by clause and that p is a pointer to class C:

        var p : ^ C
Even though C is implemented by D, p remains a pointer to class C. Each creation of an object of class C actually creates an object of type D, for example:

        new p   % Creates object of class D
Class D, which implements C, could also have an implement-by clause, which causes its implementation to be automatically created and so on. If another class E inherits C, this expansion does not include D.

If the new statement contains an explicit class name E that is a descendant of C (but not actually C), as in

        new E, p
the object of the explicit class is created. If E has an implement-by clause, the expansion is created.

See also unit, module, monitor and class. See also implement by clause, inherit clause, export list, and import list. See also deferred subprograms.


import

import list

Syntax An importList is:

import [ howImport ] importItem
{, [howImport] importItem }

Description An import list is used to specify those items that a procedure, function, module, monitor, or a class uses from outside of itself. Note that a function or procedure is not allowed to have an import list and thus automatically imports whichever functions or procedures are used by the function or procedure. The compiler determines the list automatically by looking to see what items are actually used.

Example In this example, the type T is imported into the stack module and used as the type that can be pushed onto or popped off the stack. Since no other items are imported, the only identifiers from outside of stack that can be used in it must be predefined, such as sqrt, or declared to be pervasive.

        type T : string
        …
        module stack
            import T
            export push, pop
            var top : int := 0
            var contents : array 1..100 of T
            procedure push … end push
            procedure pop … end pop
        end stack
Details The importItem is one of:

(a) id
(b) id in fileName

The second form is used in OOT when the list is the import list for a separate unit (or the main program), and the imported item is in a file whose name is different from the item's name, for example:

        import ledger in "newledg.t"
The fileName must be an explicit character string. See also unit.

Parentheses are allowed around the items in an import lists, as in:

        import ( ledger in "newledg.t" )
There are various ways to import items, as determined by howImport. The form of howImport is one of:

(a) var
(b) const
(c) forward

Commonly the howImport is omitted, which means the default access for the item is the same access as the item has. In other words, a read-write item that is imported without a howImport is imported read-write. A read-only symbol that is imported without a howImport is imported read-only.

If the importItem is forward, the import list is part of a forward procedure or function declaration and the imported item is itself necessarily a procedure or function. See forward declarations for details and an example.

If the import list of a module, monitor or class is omitted, the implementation assumes that the list is import( ), meaning that no items are imported. For example, a module must explicitly import any global identifiers that are not predefined or pervasive.

Circular (recursive) imports are not allowed. For example, if unit A imports B then B cannot import A. However, circular usage of separately compiled units is possible by separating the units into interfaces and bodies and having the bodies import the interfaces. For example, if C is the parent class of D, D can import C, but not vice versa.

In an expansion (or implementation), the import list of the expansion augments the import list of the parent.

An overriding subprogram (in an expansion) ignores the import list of the target subprogram and uses its own import list.

Turing initializes modules and monitors in order of importation. Initialization begins with the main program, which first initializes its imports in the order given in its import list, and then initializes itself.

See also unit, module, monitor and class. See also export list, inherit clause, implement clause and implement by clause.


in

in member of a set

Syntax in

Description The in operator determines if an element is in a set.

Example

        type rankSet : set of 0 .. 10
        var rankings : rankSet := rankSet ( 0 )  % The set {0}
        …
        if 5 in rankings then …     % Is 5 in the rankings set?
Description The not in operator is exactly the opposite of in. For example, 7 not in rankings means the same as not (7 in rankings).

The element is required to be in the set's index type. In the above example this is satisfied because element 5 is in the index type 0 .. 10.

The keyword in is also used in lists such as import lists. See import list.

See also the set type, infix operators, and precedence of operators.


include

include source files

Syntax An includeConstruct is:

include fileName

Description An include is used to copy parts of files so that they become part of the Turing program. This copying is temporary, that is, no files are changed. The file name must be an explicit string constant such as "stdstuff".

Example On IBM PC compatible computers, there are arrow keys that produce character values such as 200 and 208. Let us suppose that a file called arrows contains definitions of these values:

        const upArrow := 200
        const downArrow := 208
        const rightArrow := 205
        const leftArrow := 203
These definitions can be included in any program in the following manner:

        include "arrows"
        …
        var ch : string ( 1 )
        getch ( ch )                % Read one character
        case ord ( ch ) of
            label upArrow :
                …handle up arrow…
            label downArrow :
                …handle down arrow…
            label rightArrow :
                …handle right arrow…
            label leftArrow :
                …handle left arrow…
            label :
                …handle any other key…
        end case
Details An include file can itself contain include constructs. This can continue to any level, although a circular pattern of includes would be a mistake, as it would lead to an infinitely long program.

It is common to save procedures, functions and modules in separate files. The files are collected together using include.

Details If the filename in the include statement starts with a "%", then Turing searches the system directory for the file. See the editor reference for the environment to see how to set the system directory. This method can be used to allow the system administrator to easily supply a set of routines in a file to a large number of users by placing it in one easy-to-find location.

Example If the system directory is set to "C:\TURING", then the line

        include "%sorting.t"
will include the file "C:\TURING\SORTING.T" in the program.

Details Under OOT, there are several system directories available. The "%oot" directory is the directory where all the OOT system files are located. The "%home" directory is the user's home directory.

Example If the oot directory is set to "/usr/local/lib/oot" then the line

        include "%oot/teacher/sorting.t"
will include the file "/usr/local/lib/oot/teacher/sorting.t" in the program.


index

index find pattern in string function

Syntax index (s , patt : string ) : int

Description The index function is used to find the position of patt within string s. For example, index ( "chair", "air" ) is 3.

Example This program outputs 2, because "ill" is a substring of "willing", starting at the second character of "willing".

        var word : string := "willing"
        put index ( word, "ill" )
Details If the pattern (patt) does not appear in the string (s), index returns 0 (zero). For example, here is an if statement that checks to see if string s contains a blank:

        if index ( s, " " ) not= 0 then …
The index is sometimes used to efficiently determine if a character is one of a given set of characters. For example, here is an if statement that checks to see if ch, which is declared using var ch : string (1), is a digit:

        if index ( "0123456789", ch) not= 0 then …
If a string contains more that one occurrence of the pattern, the leftmost location is returned. For example, index ("pingpong", "ng") returns 3.

If patt is the null string, the result is 1.


indexType

Syntax An indexType is one of:

(a) | subrangeType
(b) | enumeratedType
(c) | namedType | % Which is a subrange or enumerated type
(d) | char
(e) | boolean

Description An index type defines a range of values that can be used as an array subscript, as a case selector, as a selector (tag) for a union type, or as the base type of a set type.

Example

        var z : array 1 .. 9 of real    % 0..9 is an index type
        type smallSet : set of 0 .. 2   % 0..2 is an index type


indirection

indirection operator (@)

Dangerous

Syntax targetType @ ( expn )

Description The indirection operator @ is used to access values that lie at absolute machine addresses in the computer's memory. This is dangerous and implementation-dependent and can cause arbitrary corruption of data and programs.

Example Copy the byte value at memory location 246 into b and then set that memory byte to zero.

        var b : nat1            % One byte natural number
        b := nat1 @ (246)
        nat1 @ (246) := 0
Details The form of targetType must be one of:

        (a) [ id . ] typeId
        (b) int, int1, int2 or int4
        (c) nat, nat1, nat2 or nat4
        (d) boolean
        (e) char [ ( numberOfCharacters ) ]
        (f) string [ ( maximumLength ) ]
        (g) addressint
In form (a) the beginning identifier id must be the name of a module, monitor or class that exports the typeId. Each of numberOfCharacters and maximumLength must be compile time integer expressions. These are the same target types as in type cheats.

The indirection operator @ takes an integer as an address. This value must fit in the range of addressint. See addressint. See also pointer types and the ^ operator (which accesses objects located by pointers).

See also cheat. See also explicitIntegerConstant (which explains how to write hexadecimal constants, which are often used for addresses).


infix

infix operator

Syntax An infixOperator is one of:

(a) | + |  | % Integer and real addition; set union;
 |  | % string catenation
(b) | - |  | % Integer and real subtraction; set difference
(c) | * |  | % Integer and real multiplication; set intersection
(d) | / |  | % Real division
(e) | div |  | % Truncating integer division
(f) | mod |  | % Modulo
(g) | rem |  | % Remainder
(h) | ** |  | % Integer and real exponentiation
(i) | < |  | % Less than
(j) | > |  | % Greater than
(k) | = |  | % Equal
(l) | <= |  | % Less than or equal; subset
(m) | >= |  | % Greater than or equal; superset
(n) | not= |  | % Not equal
(o) | and |  | % And (boolean conjunction)
(p) | or |  | % Or (boolean disjunction)
(q) | => |  | % Boolean implication
(r) | in |  | % Member of set
(s) | not in |  | % Not member of set
(t) | shr |  | % Shift right
(u) | shl |  | % Shift left
(v) | xor |  | % Exclusive OR

Description An infix operator is placed between two values or operands to produce a third value. For example, the result of 5 + 7 is 12. In some cases the meaning of the operator is determined by its operands. For example, in "pine" + "apple", the + operator means string catenation while in 5 + 7 it means integer addition. There are also prefix operators (-, + and not), which are placed in front of a single value. See prefix operator.

In expressions with several operators, such as 3 + 4 * 5, the precedence rules determine the order in which the operation is done (see precedence for a listing of these rules). In this example, the multiplication is done before the addition, so the expression is equivalent to 3 + (4 * 5).

The numerical (integer or real) operators are +, -, *, /, div, mod, and **. All of these except div produce a real result when at least one of their operands is real. If both operands are integers, the result is an integer except in the case of real division (/) which always produces a real result regardless of the operands.

The div operator is like real division (/), except that it always produces an integer result, truncating any fraction to produce the nearest integer in the direction of zero.

The mod operator is the modulo and the rem operator is the remainder. The sign of the result of mod operator is the same as the sign of the second operand. The rem operator operates like the mod operator in Turing (and in most other languages). It produces the remainder, which is the difference between real division (/) and integer division (div). When both operands are positive, this is the modulo. For example, 14 mod 10 is 4. If one of the operands is negative, a negative answer may result, for example, 7 mod 2 is 1. See also the int and real types.

The comparison operators (<, >, =, <=, >=, not=) can be applied to numbers as well as to enumerated types. They can also be applied to strings to determine the ordering between strings (see string type for details). Arrays, records, unions and collections cannot be compared. Boolean values (true and false) can be compared only for equality (= and not=); the same applies to pointer values. Set values can be compared using <= and >=, which are the subset and superset operators. The not= operator can be written as ~=.

Strings are manipulated using catenation (+) as well as substring expressions (see substring) and the index function (see index). See also the string type.

The operators to combine true/false values are and, or, and => (implication), as well as equality (= and not=). See also the boolean type.

The set operators are union (+), intersection (*), set difference (-), subset (<=), superset (>=), and membership (in and not in). See also the set type.

The shr (shift right), shl (shift left) and xor (exclusive OR) operators accept and produce natural numbers. See shr, shl, and xor.


inherit

inherit inheritance clause

Syntax An inheritClause is:

inherit inheritItem

Description An inherit clause specifies that the class containing the clause is to be an expansion of another class. This expansion is called inheritance. The class containing the clause gains access to (inherits) all the declarations inside the target item. Expansions are used to add new declarations and exports and to support polymorphism (overriding subprograms).

Example Here is an example of a stack class. Following it, we show another class, called stackWithDepth, that inherits stack by adding a function called depth.

        class stack
            export push, pop

            var top : int := 0
            var contents : array 1 .. 100 of string

            procedure push ( s : string )
                top := top + 1
                contents (top ) := s
            end push

            procedure pop ( var s : string )
                s := contents ( top )
                top := top - 1
            end pop
        end stack
Next comes an expansion, which inherits the internal declarations of the stack class and adds the depth function.

        class stackWithDepth
            inherit stack
            export depth
            function depth : int
                result top
            end push
        end stackWithDepth
Details Objects of the inherited class stackWithDepth are like objects of the parent class stack, except there is an additional exported function named depth.

An inheritItem is one of:

(a) id
(b) id in fileName

The second form is used when the inherit clause is for a separate unit and the imported item is in a file whose name is different from the item's name, for example:

        inherit ledger in "newledg.t"
The fileName must be an explicit character string, e.g., "newledg.t". Parentheses are allowed around the item in an inherit clause, as in:

        inherit ( ledger in "newledg.t" )
There is a special form of inherit clause, called an implement clause, that is used to separate an interface from an implementation. Modules and monitors, as well as classes, use these clauses. See implement clause and implement by clause.

If class D inherits class C, we say that C is the parent and D is the child. Class B is said to be an ancestor of class D (and D is the descendant of B) if B and D are the same class, or if B is the parent of D, or if B is the parent of the parent of D, etc. We write this as follows:

        B <= D      % B is an ancestor of D
If B is an ancestor of D but not the same as D, we say B is a strict ancestor of D. We write this as:

        B < D       % B is a strict ancestor of D
We also use the notations D >= B, D > B and D = B with the obvious meanings. All of these notations can be used in a program. Their main use is in conjunction with objectclass, which determines the class of an object located by a pointer. For example, if p is declared to be a pointer to a stack, we can write the following to see if p currently locates an object with the depth operation:

        % Does the object located by p have the depth operation
        if stackWithDepth <= objectclass(p) then
A pointer that locates an object created as class E can be assigned to a pointer to class B, only if B is an ancestor of E. For example, a pointer to an object that is a stackWithDepth can be assigned to a pointer to stack, but not vice versa. The pointer nil can be assigned to any pointer variable, but the value nil(C) can only be assigned to a pointer to an ancestor of C.

An object (located by a pointer) can be assigned to another object only if they were created as objects of the same class. However, assignment of objects that are monitors or that contain dynamic arrays or collections is not allowed.

Circular (recursive) inherits are not allowed. For example, if unit B inherits A then A cannot inherit B. Only one item is allowed in an inherit clause; in other words, Turing supports single inheritance but not multiple inheritance.

See implement clause for a special kind of expansion that separates a module, monitor or class' interface from its implementation. See class for an example of polymorphism, in which an inheriting class overrides subprograms of its parent class.

The initialization of a module, a monitor or an object is immediately preceded by the initialization of the item that it inherits or implements (if any). Correspondingly, if the item has an implement by clause, the implementation is initialized immediately after the initialization of the current item.

Within a class C, with ancestor B, you can force a call to exported subprogram p using the form C.p (or B.p). This calls the subprogram declared in C (or in B in the case of B.p), regardless of the actual class of the object and any overriding of p. This is similar to the notation C::p of the C++ language. This notation can only be used inside class C.

See also unit, module, monitor and class. See also export list, import list, implement clause, implement by clause and deferred subprogram. See also objectclass.


init

init array initialization

Syntax init

Description The init (initialization) keyword is used for two different purposes in Turing. The most common is for initializing arrays, records and unions. The less common is for recording parameter values in subprograms for later use in post conditions.

Example

        var mensNames : array 1 .. 3 of string :=
            init ( "Tom", "Dick", "Harry" )
        put mensNames ( 2 )             % This outputs Dick
        var names : array 1 .. 2, 1 .. 3 of string :=
            init ( "Tom", "Dick", "Harry",
                 "Alice", "Barbara", "Cathy")
        put names ( 2, 1 )  % This outputs Alice
Details The order of initializing values for multi-dimensional arrays is based on varying the right subscripts (indexes) most rapidly. This is called row major order. Initialization of records and unions is analogous to initializing arrays. Values are listed in the order in which they appear in the type. See array, record, and union types.

Example This procedure is supposed to set integer variable i to an integer approximation of its square root. The init clause records the initial value of i as j so it can be used in the post condition to make sure that the approximation is sufficiently accurate. The name j can be used only in the post condition and nowhere else in the procedure.

        procedure intSqrt ( var i : int )
            pre i >= 0
            init j := i
            post abs ( i - sqrt ( j ) ) <= 1
            … statements to approximate square root…
        end intSqrt
See also pre and post assertions and procedure and process declarations.


Input

Description This unit contains the predefined procedures that deal with handling input on a character-by-character basis.

All routines in the Input module are exported unqualified. (This means you can call the entry points directly.)

Entry Points
getch | Gets the next character in the keyboard buffer (procedure with a string (1) argument).
hasch | Returns true if there are characters waiting in the keyboard buffer.
getchar | Gets the next character in the keyboard buffer (function returning a char).
Pause | Waits for a key to be pressed.
KeyDown | Detect which keys are currently pressed.
Flush | Empty the keyboard buffer.


Input.getch

Input.getch Part of Input module

Syntax getch ( var ch : string ( 1 ) )

Description The getch procedure is used to input a single character without waiting for the end of a line. The parameter ch is set to the next character in the keyboard buffer (the oldest not-yet-read character).

Example This program contains a procedure called getKey which causes the program to wait until a key is pressed.

        View.Set ("graphics")

        procedure getKey
            var ch : string (1)
            getch (ch)
        end getKey

        for i : 1 .. 1000
            put i : 4, " Pause till a key is pressed"
            getKey
        end for
Details The screen should be in a "screen" or "graphics" mode. See the View.Set procedure for details. If the screen is not in one of these modes, it will automatically be set to "screen" mode.

Some keys, such as the left arrow key, insert key, delete key, and function keys do not produce ordinary character values. These keystrokes are returned by getch as special values. See Appendix D for these values.

Status Exported unqualified.

This means that you can call the function by calling getch or by calling Input.getch.

See also hasch (has character) procedure which is used to see if a character has been typed but not yet read.


Input.getchar

Input.getchar Part of Input module

Syntax getchar : char

Description The getchar function is used to input a single character without waiting for the end of a line. The next character in the keyboard buffer (the oldest not-yet-read character) is returned.

Example This program contains a procedure called getKey which causes the program to wait until a key is pressed.

        View.Set ("graphics")

        procedure getKey
            var ch : char
            ch := getchar
        end getKey

        for i : 1 .. 1000
            put i : 4, " Pause till a key is pressed"
            getKey
        end for
Details The screen should be in a "screen" or "graphics" mode. See the View.Set procedure for details. If the screen is not in one of these modes, it will automatically be set to "screen" mode.

Some keys, such as the left arrow key, insert key, delete key, and function keys do not produce ordinary character values. These keystrokes are returned by getch as special values. See Appendix D for these values.

Status Exported unqualified.

This means that you can call the function by calling getchar or by calling Input.getchar.

See also hasch (has character) procedure which is used to see if a character has been typed but not yet read.


Input.hasch

Input.hasch Part of Input module

Syntax hasch : boolean

Description The hasch procedure is used to determine if there is a character that has been typed but not yet been read.

Example The flush procedure gets rid of any characters that have been typed but not yet read.

        procedure flush
            var ch : string ( 1 )
            loop
                exit when not hasch
                getch ( ch )    % Discard this character
            end loop
        end flush
Details The screen should be in a "screen" or "graphics" mode. See the View.Set procedure for details. If the screen is not in one of these modes, it will automatically be set to "screen" mode.

Status Exported unqualified.

This means that you can call the function by calling hasch or by calling Input.hasch.

See also getch and getchar.


Input.Flush

Input.Flush Part of Input module

Syntax Input.Flush

Description The Input.Flush procedure empties the keyboard buffer. It is often used to avoid accidentally reading multiple keystrokes because the user pressed a key for too long, causing autorepeat.

Example This program echoes input from the keyboard at a rate of 10 characters per second. If you hold down a key, the echoing will stop as soon as you stop pressing the key. Without the Input.Flush, the program continues to echo many more keystrokes that have accumulated in the keyboard buffer.

        loop
            if hasch then
                put getchar ..
                Input.Flush
                delay (100)
            end if
        end loop
Execute

Status Exported qualified.

This means that you can only call the function by calling Input.Flush, not by calling Flush.


Input.KeyDown

Input.KeyDown Part of Input module

Syntax Input.KeyDown (var chars : array char of boolean)

Description The Input.Keydown procedure allows a program to read which keys are currently being pressed. This procedure is different from getch in that it allows a program to detect when a user presses and releases a button. As such, it is not to be used in conjunction with getch.

The procedure can be used in games where an action takes place while a key is depressed.

Example Determine if the T key is pressed. Note that we check for the lower case letter.

        var chars : array char of boolean
        Input.KeyDown (chars)
        if chars ('t') then
            put "The T key is pressed"
        end if
Details The array returned is a list of all the characters. A key is currently pressed if the array element with the corresponding character is true. For example, the a key is pressed is chars ('a') is true. Note that each key is individually represented, so if the user has pressed Shift+a to get a 'A', then Input.KeyDown would register Shift and 'a' as pressed, but not 'A'.

A full list of all the possible characters that can be set with Input.KeyDown can be found in the Key Codes appendix.

Details The array returned is a list of all the characters. A key is currently pressed if the array element with the corresponding character is true. For example, the a key is pressed is chars ('a') is true. Note that each key is individually represented, so if the user has pressed Shift+a to get a 'A', then Input.KeyDown would register Shift and 'a' as pressed, but not 'A'.

Details The number of keys that can be pressed simultaneously is hardware dependent. Most keyboards can detect a minimum of two keys + Shift + Control + Alt. This means that if you are designing a two player game to be played at a single keyboard and you wish to make certain that players cannot “hog the keyboard” by holding down keys, you should not use more than 6 different keys and three of them should be the Shift, Control and Alt keys.

Example The program reads the keyboard and displays a message while the arrow keys are pressed. It can detect up to all four arrow keys pressed at once.

        var chars : array char of boolean
        loop
            Input.KeyDown (chars)
            locate (1, 1)
            if chars (KEY_UP_ARROW) then
                put "Up Arrow Pressed  " ..
            else
                put "                  " ..
            end if
            if chars (KEY_RIGHT_ARROW) then
                put "Right Arrow Pressed  " ..
            else
                put "                     " ..
            end if
            if chars (KEY_LEFT_ARROW) then
                put "Left Arrow Pressed  " ..
            else
                put "                    " ..
            end if
            if chars (KEY_DOWN_ARROW) then
                put "Down Arrow Pressed  " ..
            else
                put "                  " ..
            end if
        end loop

Execute

Example Another example is available that checks for all possible keys.
Status Exported qualified.

This means that you can only call the function by calling Input.KeyDown, not by calling KeyDown.


Input.Pause

Input.Pause Part of Input module

Syntax Input.Pause

Description The Input.Pause procedure simply waits for a key to be pressed and then returns. It echoes the key pressed if echo mode is set. (See View.Set for setting echo mode)

This subprogram helps avoid having to declare a variable declaration and then make a call to getchor getchar.

Example This program pauses after every name read from the file.

        var f : int
        var line : string
        open : f, "data.txt", get
        loop
            exit when eof (f)
            get : f, line : *
            put name
            Input.Pause
        end loop
        close : f

Execute

Status Exported qualified.

This means that you can only call the function by calling Input.Pause, not by calling Pause.


int

int integer type

Syntax int

Description The int (integer) type has the values … 2, 1, 0, 1, 2 … Integers can be combined by various operators such as addition (+) and multiplication (*). Integers can also be combined with real numbers, in which case the result is generally a real number. An integer can always be assigned to a real variable, with implicit conversion to real.

Example

        var counter, i : int
        var j : int := 9
        var tax := 0        % The type is implicitly int because 0 is an integer
Details See also explicitIntegerConstant. The real type is used instead of int when values have fractional parts as in 16.837. See the real type for details.

The operators on integers are +, -, * (multiply), div (truncating integer division), mod (integer remainder), ** (exponentiation), as well as comparisons (+, not=, >, >=, <, <=). The operators and, or and xor can be applied to non-negative integer values. The bit-wise boolean result is produced as an integer (actually, as a natural number). The shr (shift right) and shl (shift left) operators are also introduced.

Real numbers can be converted to integers using ceil (ceiling), floor, and round (see descriptions of these functions). Integers can be converted to real numbers using intreal, but in practice this is rarely used, because an integer value used in place of a real value will be automatically converted to real.

Integers can be converted to strings and back using intstr and strint. Integers can be converted to corresponding ASCII (or EBCDIC) characters using chr and ord. See the descriptions of these functions.

Pseudo-random sequences of integers can be generated using randint. See randint.

In current implementations of Turing, the range of integers is from -2147483647 to 2147483647. In other words, the maximum size of integer is 2**31 - 1. See maxint. This range exists because integers are stored in 4 bytes. The remaining negative value, -2147483648 records uninitialization. The types int1, int2 and int4 specify integers that fit into 1, 2 or 4 bytes. The int n types (int1, int2 and int4) are not checked for initialization and allow all their bit patterns as numbers.

The natural number type nat allows only the non-negative values: 0,1,2,3,… Natural number values can be used whenever integer values are expected and vice versa, given that the value does not exceed the range of the expected type.

See also nat and int n.


intn

intn n-byte integer type

Dirty

Syntax

(a) | int1 | % 1-byte integer
(b) | int2 | % 2-byte integer
(c) | int4 | % 4-byte integer

Description The intn (n-byte integer) types are machine-dependent types that occupy a specified number of bytes. By contrast, the int type is in principle a machine-independent and mathematical type (it overflows, however, when the value is too large or small, that is, when the value does not fit into 4 bytes).

Example

        var counter1 : int1 % Range is -128 .. 127
        var counter2 : int2 % Range is -32768 .. 32767
        var counter4 : int4 % Range is -2147483648 .. 2147483647
Details In current implementations of Turing, the range of the int is -2147483647 to 2147483647, which means that the int4 type allows one more value, -2147483648. This extra value is used in int to represent the state of being initialized. The intn types allow use of all possible values that fit into n bytes and thereby cannot check for initialization.

The intn types are like the C language types short int, int, and long int, except that the number of bytes occupied by the C types depends on the particular C compiler.

See also the nat n types which are n byte natural (non-negative) values. See also int and nat.


intreal

intreal integer-to-real function

Syntax | intreal ( i : int ) : real
Description | The intreal function is used to convert an integer to a real number. This function is rarely used, because in Turing, an integer value can be used where ever a real value is required. When the integer value is used where a real value is required, the intreal function is implicitly called to do the conversion from int to real.
See also | floor, ceil and round functions.


intstr

intstr integer-to-string function

Syntax intstr ( i : int [ , width : int [ , base : int ] ] ) : string

Description The intstr function is used to convert an integer to a string. The string is equivalent to i, padded on the left with blanks as necessary to a length of width, written in the given number base. For example, intstr (14, 4, 10)="bb14" where b represents a blank. The width and base parameters are both optional. If they are omitted, the string is made just long enough to hold the value, and the number base is 10. For example, intstr (14, 4) = "bb14" and intstr (23 ) = "23".

The width parameter must be non-negative. If width is not large enough to represent the value of i, the length is automatically increased as needed.

The string returned by intstr is of the form:

{blank}[-]digit{digits}

where {blank} means zero or more blanks, [-] means an optional minus sign, and digit{digit} means one or more digits. The leftmost digit is either non-zero or else a single zero digit. In other words, leading zeros are suppressed.

The letters A, B, C … are used to represent the digit values 10, 11, 12, … The base must be in the range 2 to 36 (36 because there are ten digits and 26 letters). For example, intstr (255, 0, 16) = "FF".

The intstr function is the inverse of strint, so for any integer i,

        strint ( intstr (i)) = i.
See also chr, ord and strint functions. See also the natstr and strnat functions. See also explicitIntegerConstants for the way to write non base 10 values in a program.


invariant

invariant assertion

Syntax An invariantAssertion is:

invariant trueFalseExpn

Description An invariant assertion is a special form of an assert statement that is used only in loop and for statements and in modules, monitors, and classes. It is used to make sure that a specific requirement is met. This requirement is given by the trueFalseExpn. The trueFalseExpn is evaluated. If it is true, all is well and execution continues. If it is false, execution is terminated with an appropriate message. See assert, loop and for statements and the module declarations for more details.

Example This program uses an invariant in a for loop. The invariant uses the function nameInList to specify that a key has not yet been found in an array of names.

        var name : array 1 .. 100 of string
        var key : string
        … input name and key …

        function nameInList ( n : int) : boolean
            for i : 1 .. n
                if key = name ( i ) then
                    result true
                end if
            end for
            result false
        end nameInList

        for j : 1 .. 100
            invariant not nameInList ( j - 1)
            if key = name ( j) then
                put "Found name at ", j
                exit
            end if
        end loop


Joystick

Description This unit contains the predefined subprogram that deal with reading the joystick in a Turing program. The routines allow you to get the current joystick position and whether either one of the two buttons are pressed.

All routines in the Joystick module are exported qualified (and thus must be prefaced with "Joystick."). All the constants are exported unqualified and thus do not need the Joystick prefix.

Entry Points
joystick 1, joystick2 | joystick name contants (exported unqualified)
GetInfo | Reads the current value of a joystick and status of the joystick buttons.


Joystick.GetInfo

Joystick.GetInfo Part of Joystick module

Syntax Joystick.GetInfo (joystick : int, var xPos, yPos : int,
btn1Pressed, btn2Pressed : boolean)

Description Reads the position and button status of the joystick specified by the joystack parameter. The x and y parameter are returned in the xPos and yPos parameters. If button 1 or button 2 on the joystick are currently pressed, btn1Pressed and btn2Pressed will be set to true. The joystick parameter can be either joystick1 or joystick2.

The x and y positions vary from joyMin to joyMax. To use them with respect to a screen, the coordinates returned from Joystick.GetInfo must be translated into screen coordinates. The following formula can be used:

        screenX = round (maxx * (xPos  joyMin) / (joyMax  joyMin))
        screenY = round (maxy * (yPos  joyMin) / (joyMax  joyMin))
Details The Joystick module contains undocumented subprograms for those who need to access more than two buttons or axes on a joystick. Contact Holt Software if you need more information.

Example The following program outputs the current location of joystick #1 and draws a cursor on the screen to point out where it is showing.

        var jx, jy, x, y, ox, oy : int := 1
        var b1, b2, oB1, oB2 : boolean := false
        loop
            Joystick.GetInfo (joystick1, jx, jy, b1, b2)
            % Convert joystick coordinates into screen coordinates.
            x = round (maxx * (jx  joyMin) / (joyMax  joyMin))
            y = round (maxy * (jy  joyMin) / (joyMax  joyMin))
            if x not= ox or y not= oy or  b1 not= oB1 or b2 not= oB2 then
                Text.Locate (1, 1)
                put "x = ", x, "  y = ", y, "  b1 = ", b1, "  b2 = ", b2
                View.Set ("xor")
                Draw.Line (ox  10, oy, ox + 10, oy, brightred)
                Draw.Line (ox , oy  10, ox , oy + 10, brightred)
                Draw.Line (x  10, y, x + 10, y, brightred)
                Draw.Line (x, y  10, x, y + 10, brightred)
                ox := x
                oy := y
                oB1 := b1
                oB2 := b2
            end if
        end loop
Status Exported qualified.

This means that you can only call the function by calling Joystick.GetInfo, not by calling GetInfo.


Keyboard

Description This unit contains all the constants representing both the characters and their ordinal values for all possible keystrokes that can be read by Turing.

Constants beginning with “KEY_” are char values. These are the values returned by getch and used as an index into the Input.KeyDown array. The constants that the constants KEY_KEYPAD_5, KEY_SHIFT, KEY_CTRL and KEY_ALT can only be used in conjunction with Input.KeyDown. The getch and getchar subprograms do not return these values. All other constants with with SHIFT, CTRL and ALT as part of the name cannot be checked for in the Input.KeyDown array.

Constants beginning with “ORD_” are int values and represent the ordinal values (values returned by the ord function) for all the possible keystrokes.

Here is a list of most of the constants

KEY_F1 .. KEY_F12 | KEY_CTRL_A .. KEY_CTRL_Z
KEY_SHIFT_F1 .. KEY_SHIFT_F12 | KEY_ALT_A .. KEY_ALT_Z
KEY_CTRL_F1 .. KEY_CTRL_F12 | KEY_ALT_1 .. KEY_ALT_0

KEY_ALT_F1 .. KEY_ALT_F12

KEY_HOME | KEY_CTRL_HOME
KEY_UP_ARROW | KEY_CTRL_UP_ARROW
KEY_PGUP | KEY_CTRL_PGUP
KEY_LEFT_ARROW | KEY_CTRL_LEFT_ARROW
KEY_RIGHT_ARROW | KEY_CTRL_RIGHT_ARROW
KEY_END | KEY_CTRL_END
KEY_DOWN_ARROW | KEY_CTRL_DOWN_ARROW
KEY_PGDN | KEY_CTRL_PGDN
KEY_INSERT | KEY_CTRL_INSERT
KEY_DELETE | KEY_CTRL_DELETE
KEY_BACKSPACE | KEY_KEYPAD_5 *
KEY_TAB | KEY_SHIFT *
KEY_ENTER | KEY_CTRL *
KEY_ESC | KEY_ALT *
KEY_CTRL_OPEN_BRACKET | KEY_CTRL_BACKSLASH
KEY_CTRL_CLOSE_BRACKET | KEY_CTRL_CARET
KEY_CTRL_UNDERSCORE | KEY_CTRL_BACKSPACE
KEY_ALT_MINUS | KEY_ALT_EQUALS
KEY_BACK_TAB | KEY_SHIFT_TAB

Above constants with “ORD_” instead of “KEY_”

ORD_A .. ORD_Z | ORD_0 .. ORD_9
ORD_LOWER_A .. ORD_LOWER_Z
ORD_SPACE | ORD_EXCALAMATION_MARK
ORD_QUOTATION_MARK | ORD_HAS_MARK
ORD_DOLLAR_SIGN | ORD_PERCENT_SIGN
ORD_AMPERSAND | ORD_SINGLE_QUOTE
ORD_OPEN_PARENTHESIS | ORD_CLOSE_PARENTHESIS
ORD_ASTERISK | ORD_PLUS
ORD_COMMA | ORD_MINUS
ORD_PERIOD | ORD_DOT
ORD_SLASH | ORD_COLON
ORD_SEMICOLON | ORD_LESS_THAN
ORD_EQUALS | ORD_GREATER_THAN
ORD_QUESTION_MARK | ORD_AT_SIGN
ORD_OPEN_BRACKET | ORD_BACKSLASH
ORD_CLOSE_BRACKET | ORD_CARET
ORD_UNDERSCORE | ORD_APOSTROPHE
ORD_OPEN_BRACE | ORD_BAR
ORD_CLOSE_BRACE | ORD_TILDE

Characters marked with an asterisk (*) are keys that can only be detected using Input.KeyDown.

All constants in the Keyboard module are exported unqualified. (This means you can use the constants directly without having to use the qualifier "Keyboard.".)

See also getch, getchar, and Input.KeyDown.


length

length of a string function

Syntax length ( s : string ) : int

Description The length function returns the number of characters in the string. The string must be initialized. For example, length("table") is 5.

Example This program inputs three words and outputs their lengths.

        var word : string
        for i : 1 .. 3
            get word
            put length ( word )
        end for
If the words are "cat", "robin" and "crow", the program will output 3, 5 and 4.

Details The length function gives the current length of the string. To find the maximum length of a string, use upper. For example, given the declaration var s : string (10), upper (s) returns 10.

See also upper.


Limits

Description This unit contains constants and functions used in determining the mathematical accuracy of the language.

All routines in the Limits module are exported qualified (and thus must be prefaced with "Limits.") except maxint, maxnat, minint and minnat, which are exported unqualified (this means you can call those entry points directly).

Entry Points
DefaultFW | Default fraction width used in printing using the "put" statement.
DefaultEW | Default exponent width used in printing using the "put" statement.
minint | The minimum integer in Turing (exported unqualified).
maxint | The maximum integer in Turing (exported unqualified).
minnat | The minimum natural number in Turing (exported unqualified).
maxnat | The maximum natural number in Turing (exported unqualified).

Real numbers are represented in Turing as:
f * (radix ** e) or 0
where for non-zero f:
(1 / radix) <= abs (f) and abs (f) < 1.0
minexp <= e and e <= maxexp.

Radix | The "radix" (usually 2).
NumDigits | The number of radix digits in f.
MinExp | "minexp" (the smallest exponent allowed).
MaxExp | "maxexp" (the largest exponent allowed).
GetExp | Function that returns the value of "e".
SetExp | Procedure that sets the value of "e".
Rreb | The relative round-off error bound.


ln

ln natural logarithm function

Syntax ln ( r : real ) : real

Description The ln function is used to find the natural logarithm (base e) of a number. For example, ln ( 1) is 0.

Example This program prints out the logarithms of 1, 2, 3, … up to 100.

        for i : 1 .. 100
            put "Logarithm of ", i, " is ", ln ( i )
        end for
Details See also the exp (exponential) function. You cannot take the logarithm of zero or a negative number.

Note logn (i ) = ln (i ) / ln (n )

See also exp (the exponentiation function).

See also predefined unit Math.


locate

locate procedure

Syntax locate ( row, column : int )

Description The locate procedure is used to move the cursor so that the next output from put will be at the given row and column. Row 1 is the top of the screen and column 1 is the left side of the screen.

Example This program outputs stars of random colors to random locations on the screen. The variable colr is purposely spelled differently from the word color to avoid the procedure of that name (used to set the color of output). The row number is purposely chosen so that it is one less than maxrow. This avoids the scrolling of the screen which occurs when a character is placed in the last column of the last row.

        setscreen ("screen")
        var row, column, colr : int
        loop
            randint ( row, 1, maxrow - 1)
            randint ( column, 1, maxcol)
            randint (colr, 0, maxcolor)
            color (colr)
            locate (row, column )
            put "*" ..  % Use dot-dot to avoid clearing end of line
        end loop
Details The locate procedure is used to locate the next output based on row and column positions. See also the locatexy procedure which is used to locate the output based x and y positions, where x=0, y=0 is the left bottom of the screen.

The screen should be in a "screen" or "graphics" mode. See the setscreen procedure for details. If the screen is not in one of these modes, it will automatically be set to"screen" mode.

See also setscreen and drawdot.

See also predefined unit Text.


locatexy

locatexy graphics procedure

Syntax locatexy ( x , y : int )

Description The locatexy procedure is used to move the cursor so that the next output from put will be at approximately (x, y). The exact location may be somewhat to the left of x and below y to force alignment to a character boundary.

Example This program outputs "Hello" starting at approximately (100, 50) on the screen.

        setscreen ("graphics")
        locatexy ( 100, 50 )
        put "Hello"
Details The locatexy procedure is used to locate the next output based on x and y positions, where the position x=0, y=0 is the left bottom of the screen. See also the locate procedure which is used to locate the output-based row and column positions, where row 1 is the top row and column 1 is the left column.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also setscreen and drawdot.

See also predefined unit Text.


loop

loop statement

Syntax A loopStatement is:

loop
statementsAndDeclarations
end loop

Description A loop statement causes the statements (and declarations) in it to be repeatedly executed. This continues until terminated by one of its enclosed exit statements (or by an enclosed return or result statement).

Example Output on separate lines: Happy, Happy, Happy, etc.

        loop
            put "Happy"
        end loop
Example Read words up to the word Stop.

        var word : string
        loop
            get word
            exit when word = "Stop"
        end loop
Details A loop statement can contain more than one exit, or none at all (in which case it is an infinite loop). When the exit when is at the beginning of the loop, the loop works like Pascal's do while; when at the end, the loop works like Pascal's repeat until.

Just preceding the statements and declarations, you are allowed to write an "invariant clause" of the form:

        invariant trueFalseExpn
This clause is equivalent to: assert trueFalseExpn.


lower

lower bound

Syntax | lower (reference [ , dimension ] ) : int
Description | The lower attribute is used to find the lower bound of an array, string, char(n) or non-opaque subrange type. Since the lower bound is necessarily known at compile time, lower is rarely used.
See also | upper which finds the upper bound.


Math

Description This unit contains all the mathematical routines. There are three routines that are part of the language, but are conceptually part of the Math unit.

All routines in the Math unit except Math.Distance and Math.DistancePointLine are exported unqualified. (This means you can call the entry points directly.) Math.Distance and Math.DistancePointLine are exported qualified. All constants in the Math unit are exported qualified. (Both Math.PI and Math.E must be prefaced with "Math.".)

Descriptions of all the subprograms in the Math module can be found in this chapter.

Constants
Math.PI | The constant p (3.14...).
Math.E | The natural base e (2.718...).

Entry Points
abs* | The absolute value function.
arccos | The arccos function (radians).
arccosd | The arccos function (degrees).
arcsin | The arcsin function (radians).
arcsind | The arcsin function (degrees).
arctan | The arctan function (radians).
arctand | The arctan function (degrees).
cos | The cosine function (radians).
cosd | The cosine function (degrees).
exp | The exponentiation function.
ln | The natural logarithm function.
max* | The maximum value function.
min* | The minimum value function.
sign | The sign function.
sin | The sine function (radians).
sind | The sine function (degrees).
tan | The tangent function (radians).
tand | The tangent function (degrees).
sqrt | The square root function.
Distance | The distance between two points.
DistancePointLine | The distance between a point and a line segment.

* Part of the language, conceptually part of the Math unit.


Math.Distance

Math.Distance Part of Math module

Syntax Math.Distance (x1, y1, x2, y2 : real) : real

Description Math.Distance is used to calculate the distance between two points. (x1, y1) is the location of the first point, and (x2, y2) is the location of the second point.

Details The parameters to Math.Distance are real, but you can pass integer variables and constants.

Example This progam draws two circles with radius 75 on the screen and outputs whether they touch.

        var x1, y1, x2, y2 : int
        const RADIUS : int := 75
        x1 := Rand.Int (RADIUS, maxx - RADIUS)
        y1 := Rand.Int (RADIUS, maxy - RADIUS)
        x2 := Rand.Int (RADIUS, maxx - RADIUS)
        y2 := Rand.Int (RADIUS, maxy - RADIUS)
        Draw.FillOval (x1, y1, RADIUS, RADIUS, brightred)
        Draw.FillOval (x2, y2, RADIUS, RADIUS, brightgreen)
        if Math.Distance (x1, y1, x2, y2) < RADIUS * 2 then
            put "The two circles touch"
        else
            put "The two circles do not touch"
        end if
Execute

Status Exported qualified.

This means that you can only call the function by calling Math.Distance, not by calling Distance.


Math.DistancePointLine

Math.DistancePointLine Part of Math module

Syntax Math.DistancePointLine (xp, yp, x1, y1, x2, y2 : real) : real

Description Math.DistancePointLine is used to calculate the distance between a point and a line segment. It is often used in games to determine if a collision has occurred. (xp, yp) is the location between the point. (x1, y1) and (x2, y2) are the end points of the line segment.

Details The parameters to Math.DistancePointLine are real, but you can pass integer variables and constants. The parameters are in the same order as the subprogram name (that is point, then line).

Example This progam draws a line segment and a circle with radius 75 on the screen and outputs whether they touch.

        var xp, yp, x1, y1, x2, y2 : int
        const RADIUS : int := 75
        xp := Rand.Int (RADIUS, maxx - RADIUS)
        yp := Rand.Int (RADIUS, maxy - RADIUS)
        x1 := Rand.Int (0, maxx)
        y1 := Rand.Int (0, maxy)
        x2 := Rand.Int (0, maxx)
        y2 := Rand.Int (0, maxy)
        Draw.FillOval (xp, yp, RADIUS, RADIUS, brightred)
        Draw.Line (x1, y1, x2, y2, brightgreen)
        if Math.DistancePointLine (xp, yp, x1, y1, x2, y2) < RADIUSthen
            put "The circle touches the line"
        else
            put "The circle does not touch the line"
        end if
Execute

Status Exported qualified.

This means that you can only call the function by calling Math.DistancePointLine, not by calling DistancePointLine.


max

max maximum function

Syntax max ( expn , expn )

Description The max function is used to find the maximum of two numbers (the two expn's). For example, max ( 5, 7 ) is 7. If both numbers are int, the result is int. If both numbers are nat (natural numbers), the result is nat. But if one or both of the numbers are real, the result is real. See also the min function.

Example This program outputs 85.72.

        var x : real := 74.61
        var y : real := 85.72
        put max ( x, y )        % Outputs 85.72
Example This program inputs 10 numbers and outputs their maximum.

        var m, t : real
        get m           % Input first number
        for i : 2 .. 10     % Handle remaining 9 numbers
            get t
            m := max ( m, t )
        end for
        put "The maximum is ", m
See also See also predefined unit Math.


maxcol

maxcol maximum column function

Syntax maxcol : int

Description The maxcol function is used to determine the number of columns on the screen.

Example This program outputs the maximum column number.

        put "Number of columns on the screen is ", maxrow
Details For IBM PC compatibles as well as most UNIX dumb terminals, in "text" or "screen" mode, maxcol = 80. For the default IBM PC compatible "graphics" mode (CGA), maxcol = 40.

See also locate procedure for an example of the use of maxcol.


maxcolor

maxcolor graphics function

Syntax maxcolor : int

Description The maxcolor function is used to determine the maximum color number for the current mode of the screen. The alternate spelling is maxcolour.

Example This program outputs the maximum color number.

        setscreen ("graphics")
        …
        put "The maximum color number is ", maxcolor
Details The screen should be in a "screen" or "graphics" mode. If it is not, it will automatically be set to "screen" mode. See setscreen for details.

For IBM PC compatibles in "screen" mode, maxcolor = 15. For the default IBM PC compatible "graphics" mode (CGA), maxcolor = 3.

See also drawdot and palette for examples of the use of maxcolor. See the color procedure which is used for setting the currently active color.


maxint

maxint maximum integer function

Syntax maxint : int

Description The maxint function is used to determine the largest integer (int) that can be used in a program.

Example This program outputs the maximum integer.

        put "The largest integer that can be used is ", maxint
Details In current Turing and OOT implementations, int values are stored in 4 bytes, i.e., 32 bits. This determines the maximum int value, which is 2**311, equaling 2147483647.

There is an anomaly in computer arithmetic in that the absolute value of the largest negative integer is one larger than maxint. Turing reserves this extra value to represent the uninitialized integer. This value can be computed but any attempt to assign it to an int variable is detected as an overflow. You can use this extra value by using the int4 type instead of int, but this type has no initialization checking.

See also maxnat and minint.

See also OOT predefined unit Math.


maxnat

maxnat maximum natural number function

Syntax maxnat : nat

Description The maxnat function is used to determine the largest natural number that can be used in a program.

Example This program outputs the maximum natural number.

        put "The largest natural number that can be used is ", maxnat
Details In current implementations, natural numbers are stored in 4 bytes, i.e., 32 bits. This determines the maximum natural number, which is 2**32 - 2, equaling 4294967294.

In four bytes it is possible to represent one more value, namely, 2**32 - 1 = 4294967295. This extra value is used in Turing to represent the uninitialized natural number. Although it can be computed, any attempt to assign it to a nat variable is detected as an overflow. You can use this extra value by using the nat4 type instead of nat, but this type has no initialization checking.

See also maxint and minnat.

See also predefined unit Limits.


maxrow

maxrow maximum row function

Syntax maxrow : int

Description The maxrow function is used to determine the number of rows on the screen.

Example This program outputs the maximum row number.

        put "Number of rows on the screen is ", maxrow
Details For IBM PC compatibles, maxrow = 25. For many UNIX dumb terminals, maxrow = 24.

See also locate procedure for an example of the use of maxrow.


maxx

maxx graphics function

Syntax maxx : int

Description The maxx function is used to determine the maximum value of x for the current graphics mode.

Example This program outputs the maximum x value.

        setscreen ("graphics")
        …
        put "The maximum x value is ", maxx
Details The screen should be in a "graphics" mode. If it is not, it will automatically be set to "graphics" mode. See setscreen for details.

For the default IBM PC compatible graphics mode (CGA), maxx = 319.

See also drawdot for an example of the use of maxx and for a diagram illustrating x and y positions.


maxy

maxy graphics function

Syntax maxy : int

Description The maxy function is used to determine the maximum value of y for the current graphics mode.

Example This program outputs the maximum y value.

        setscreen ("graphics")
        …
        put "The maximum y value is ", maxy
Details The screen should be in a "graphics" mode;. If it is not, it will automatically be set to "graphics" mode. See setscreen for details.

For the default IBM PC compatible graphics mode (CGA), maxy = 199.

See also drawdot for an example of the use of maxy and for a diagram illustrating x and y positions.


min

min minimum function

Syntax min ( expn , expn )

Description The min function is used to find the minimum of two numbers (the two expn's). For example, min ( 5, 7 ) is 5. If both numbers are int, the result is int. If both numbers are nat (natural numbers), the result is nat. But if one or both of the numbers are real, the result is real. See also the max function.

Example This program outputs 74.61.

        var x : real := 74.61
        var y : real := 85.72
        put min ( x, y )            % Outputs 74.61
Example This program inputs 10 numbers and outputs their minimum.

        var m, t : real
        get m               % Input first number
        for i : 2 .. 10         % Handle remaining 9 numbers
            get t
            m := min ( m, t )
        end for
        put "The minimum is ", m
See also See also predefined unit Math.


minint

minint minimum integer function

Syntax minint : int

Description The minint function is used to determine the smallest integer (int) that can be used in a program.

Example This program outputs the maximum integer.

        put "The smallest integer that can be used is ", minint
Details In current implementations, int values are stored in 4 bytes, i.e., 32 bits. This determines the minimum int value, which is -2**31-1, equaling -2147483647.

There is an anomaly in computer arithmetic in that the absolute value of the largest negative integer is one larger than maxint. Turing reserves this extra value to represent the uninitialized integer. This value can be computed but any attempt to assign it to an int variable is detected as an overflow. You can use this extra value by using the int4 type instead of int, but this type has no initialization checking.

See also minnat and maxint.

See also predefined unit Limits.


minnat

minnat minimum natural number function

Syntax minnat : nat

Description The minnat function is used to determine the smallest natural number that can be used in a program.

Example This program outputs the smallest natural number.

        put "The smallest natural number that can be used is ", minnat
Details In current Turing and OOT implementations, natural numbers are stored in 4 bytes, i.e., 32 bits. However, the minimum natural number in all implementations is 0. minnat is provided for purposes of symmetry with minint, maxint and maxnat.

In four bytes it is possible to represent one more value, namely, 2**32 - 1 = 4294967295. This extra value is used in Turing to represent the uninitialized natural number. Although it can be computed, any attempt to assign it to a nat variable is detected as an overflow. You can use this extra value by using the nat4 type instead of nat, but this type has no initialization checking.

See also minint and maxnat.

See also predefined unit Limits.


mod

mod modulo operator

Syntax mod

Description The mod (modulo) operator produces the modulo of one number with another. In other words, the result is always a number between 0 and the second operand. If both operands are positive, the result is identical to the remainder operator. For example, 7 mod 2 produces 1 and 12 mod 5 produces 3.

Example In this example, hours is the current time. It is moved back and forth by a random amount, but the final result must always be between 1 and 12 (the mod operation produces a number between 0 and 11 and then 0 becomes 12).

        var hours : int := 12
        var hoursPassed : int
        put "The time is now ", hours, " o'clock"
        loop
            randint (hoursPassed, -12, 12)
            exit when hoursPassed = 0
            if hoursPassed < 0 then
                put hoursPassed, " hours before " ..
            else
                put hoursPassed, " hours later " ..
            end if
            put hours, " o'clock" ..
            hours := (hours + hoursPassed) mod 12
            if hours = 0 then
                hours = 12
            end if
            put " it was ", hours, " o'clock"
        end loop
Details If the second operand is positive, then the result is always non-negative. Likewise, if the second operand is negative, then the result is always non-positive. If both operands are negative, the result is the same as the remainder operator.

See also infix operators, precedence of operators and the rem and div operators.


module

module declaration

Syntax A moduleDeclaration is:

module id
 | [ implement implementItem ]
 | [ implement by implementByItem ]
 | [ import [ var ] importItem
 |  | {, [ var ] importItem } ]
 | [ export [ howExport ] id {,[howExport ] id }]
 | statementsAndDeclarations
end id

Description A module declaration creates a package of variables, constants, types, subprograms, etc. The name of the module (id) is given in two places, just after module and just after end. Items declared inside the module can be accessed outside of the module only if they are exported. Items from outside the module that are to be used in the module need to be imported (unless they are predefined or pervasive).

Example This module implements a stack of strings.

        module stack            % Implements a LIFO list of strings
            export push, pop

            var top : int := 0
            var contents : array 1 .. 100 of string

            procedure push ( s : string )
                top := top + 1
                contents ( top ) := s
            end push

            procedure pop ( var s : string )
                s := contents ( top )
                top := top - 1
            end pop
        end stack

        stack . push ( "Harvey" )
        var name : string
        stack . pop ( name )        % This sets name to Harvey
Outside of the stack module, the procedures push and pop can be called using the notation stack.push and stack.pop. This access is allowed because push and pop are exported from the module. Other items declared in the module (top and contents) cannot be accessed from outside because they are not exported.

Details In some other programming languages, a module is called a package, cluster or object.

A module declaration is executed (it is initialized) by executing its declarations and statements. For example, the stack module is initialized by setting the top variable to 0. This initialization executes all the statements and declarations in the module that are not contained in procedures or functions. The initialization is completed before any procedure or function of the module can be called from outside the module. An exported subprogram must not be called until initialization of the module is complete.

A call to an exported procedure or function from outside the module executes the body of that procedure or function (the module is not initialized with each such call). See also monitor and class declarations.

The import list gives the names of items declared outside the module that can be accessed inside the module. Since stack has no import list, it is not allowed to access any names declared outside of it. See also import lists. Separately-compiled units that are imported are initialized before the importing unit.

The export list is used to implement information hiding, which isolates implementation details inside the module. The export list gives the names of items declared inside the module that can be used outside the module. For example, push and pop are exported from stack. Each such use of an exported item must be preceded by the module name and a dot, for example, stack.push. (See unqualified for advice on how to avoid using the prefix "stack."). Names that are not exported, such as top and contents, cannot be accessed outside the module.

Procedures, functions, variables, constants and types can be exported; modules, monitors or classes cannot be exported.

A class is essentially a template for creating individual modules (objects). See class for details. A monitor is essentially a module in which only one process can be active at a time. See monitor and process for details.

The opaque keyword is used (only) in export lists to precede exported type names that have declarations in the module. Outside of the module, the type will be distinct from all others types. This means, for example, that if the opaque type is a record, its fields cannot be accessed outside of the module. Opaque types are used to guarantee that certain items are inspected and manipulated in only one place, namely, inside the module. These types are sometimes called abstract data types. See also export lists, which also describes unqualified and pervasive exports.

Implement and implement-by lists are used to separate a module's interface from its body. This allows only a part of a module (its interface) to be visible to its users (its importers), while hiding its implementation. See implement and implement by lists.

Example Use an opaque type to implement complex arithmetic.

        module complex
            export opaque value, constant, add,
                            … other operations …
            type value :
                record
                    realPt, imagPt : real
                end record

            function constant (realPt, imagPt: real ) : value
                var answer : value
                answer . realPt := realPt
                answer . imagPt := imagPt
                result answer
            end constant

            function add (L, R : value ) : value
                var answer : value
                answer . realPt := L . realPt + R . realPt
                answer . imagPt := L . imagPt + R . imagPt
                result answer
            end add

        … other operations for complex arithmetic go here …
        end complex

        var c,d : complex .value :=complex.constant ( 1, 5 )
                % c and d become the complex number (1,5)
        var e : complex .value := complex.add (c, d )
                % e becomes the complex number (2,10)
Details Module declarations can be nested inside other modules but cannot be nested inside procedures or functions. A module must not contain a bind as one of its (outermost) declarations. A return statement cannot be used as one of the (outermost) statements in a module.

The syntax of a moduleDeclaration presented above has been simplified by leaving out pre, invariant and post clauses; the full syntax is:

        module id
            [ implement implementItem ]
            [ implement by implementByItem ]
            [ import [ var ] importItem {, [ var ] importItem } ]
            [ export [ howExport ] id {, [ howExport ] id } ]
            [ pre trueFalseExpn ]
            statementsAndDeclarations
            [ invariant trueFalseExpn ]
            statementsAndDeclarations
            [ post trueFalseExpn ]
        end id
The true/false expression in the pre and post clauses must be true when initialization reaches each of them. After that, these have no effect. The true/false expression in the invariant must be true any time the module is exited (when finishing initialization or when returning from an external call to an exported subprogram) or called (via an exported subprogram). These clauses (pre,post and invariant) are not inherited by expansions. For example, if module B inherits A, the subprograms of B are bound by B's clauses and not by A's.

See also unit, monitor and class. See also export list, import list, implement list, implement by list, inherit list and deferred subprogram.


monitor

monitor declaration

Syntax A monitorDeclaration is:

monitor id
 | [ implement implementItem ]
 | [ implement by implementByItem ]
 | [ import [ var ] importItem
 |  | {, [ var ] importItem } ]
 | [ export [ howExport ] id {,[howExport ] id }]
 | statementsAndDeclarations
end id

Description A monitor is a special purpose module (see module) that is used with concurrent processes (see process). At most, one concurrent process (see process) can be active in a monitor at a time. This means that a process will be blocked if it calls a monitor that is already active. The process will not be allowed to proceed until the monitor is inactive. The monitor provides mutually exclusive access to the monitor's internal data.

Example This monitor controls access to the count variable so it can be updated by two processes (the observer and the reporter) without being corrupted by this concurrent access. Generally, it is not safe to have one process update a variable that other processes are simultaneously accessing. The observer process repeatedly increments the counter when it observes an event. The reporter process repeatedly writes out the number of events that have occurred since the last report, resetting the counter to zero.

        monitor controller
            export observe, report

            var counter : int := 0

            procedure observe
                counter := counter + 1
            end observe

            procedure report (var n : int )
                n := counter
                counter := 0
            end report
        end controller
        process observer
            loop
                … observe one event …
                controller . observe
            end loop
        end observer

        process reporter
            var n : int
            loop
                controller.report ( n )
                … report n events …
            end loop
        end reporter

        fork observer       % Activate the observer
        fork reporter       % Activate the reporter
Details A monitor is essentially a module in which only one process can be active at a time. See module declarations for details about initialization. Initialization is the same for modules and monitors.

A monitor can contain wait statements (that put processes to sleep) and signal statements (that wake them up again). These statements operate on condition variables, which are essentially queues of sleeping processes.

A class is essentially a template for creating individual modules (objects). See class for details. If the class declaration is preceded by the keyword monitor, the created modules are actually monitors. Monitor classes can only inherit (inherit from) other monitor classes.

The body of a monitor has the same form as that of a module, except that modules, monitors and processes cannot be declared inside monitors, and certain statements (wait and signal) are allowed in monitors.

Details The syntax of a monitorDeclaration presented above has been simplified by leaving out pre, invariant and post clauses. See module for an explanation of these extra features. There is also an optional compilerTimeIntegerExpression in the first line, which is explained below. The full syntax is:

        monitor id [ : compileTimeIntegerExpn ]
            [ implement implementItem ]
            [ implement by implementByItem ]
            [ import [ var ] importItem {, [ var ] importItem } ]
            [ export [ howExport ] id {, [ howExport ] id } ]
            [ pre trueFalseExpn ]
            statementsAndDeclarations
            [ invariant trueFalseExpn ]
            statementsAndDeclarations
            [ post trueFalseExpn ]
        end id
If the optional compileTimeIntegerExpression is present, this is a device monitor. Its exclusive access is enforced by an implementation-dependent trick, such as executing it at a hardware priority level given by the expression. A device monitor is restricted from calling monitors (directly or indirectly). This restriction is imposed to eliminate the possibility of blocking a process with a non-zero hardware priority (as this would inadvertently allow multiple entry into a device monitor). It is the programmer's responsibility to meet this restriction; the compiler will not in general enforce the restriction. The current (1999) implementation ignores this compileTimeIntegerExpression.

Details An unexported parameterless procedure in a monitor can be specified to be an interrupt handling procedure by specifying a device in its header, using the form:

        procedure id [ : deviceSpecification ]
The deviceSpecification is a compile time natural number that designates, to the implementation, the class of interrupts that effectively call this procedure. Interrupt handling procedures cannot be called explicitly within the program.

There are two restrictions that the programmer must follow when using interrupt handling procedures; these restrictions will not necessarily be enforced by the software. The first is that an interrupt handling procedure must not execute a wait, either directly or indirectly, by calling another procedure. The second is that the interrupt handling procedure must not directly or indirectly cause an exception, unless the exception will be caught by an exception handler that is activated directly or indirectly by the interrupt handling procedure.

Details Declarations of monitors within monitors are disallowed. This would be redundant anyway, as only one process can be inside the outer monitor, so the inner monitor is guaranteed to be successful.

Declarations of classes within monitors are also disallowed.

Any subprogram declared within a subprogram is now allowed to be assigned to a subprogram variable, nor passed as a parametric subprogram.

See also unit, module and class. See also export list, import list, implement list, implement by list and deferred subprogram.


Mouse

Description This unit contains the predefined subprograms that deal with using the mouse in a Turing program. The routines allow you to get the current mouse cursor position, check if a button has been pressed and get the information if it has. There are also routines to hide and show the mouse on systems where it makes sense. (On GUI based systems like the Macintosh, the mouse can't be hidden as it may be needed by other applications running at the same time.)

All routines in the Mouse module are exported qualified (and thus must be prefaced with "Mouse.").

Entry Points
Where | Gets the current location of the mouse cursor and status of the mouse buttons.
ButtonMoved | Checks to see if a mouse button has been pressed.
ButtonWait | Gets information about a mouse button being pressed such as where it was pressed, which button was pressed, etc.
ButtonChoose | Selects the mode for the mouse (either single button mode or multi-button mode).


Mouse.ButtonChoose

Mouse.ButtonChoose Part of Mouse module

Syntax Mouse.ButtonChoose (choice : string)

Description The Mouse.ButtonChoose procedure is used to change the mode of the mouse. In Turing, the mouse can either be in "single-button mode" or in "multi-button mode". In "single-button mode" the mouse is treated as a one button mouse. A button is considered pressed when any button is pressed and released only when all buttons have been released.

In Turing, the mouse starts in "single-button mode".

The parameter choice can be one of "singlebutton", "onebutton" (which switch the mouse into "single-button mode") or "multibutton" (which switches the mouse into "multi-button mode").

Example A program that displays the status of the mouse at the top left corner of the screen.

        Mouse.ButtonChoose ("multibutton")
        var x, y, button, left, middle, right : int
        Mouse.Where (x, y, button)
        left := button mod 10           % left = 0 or 1
        middle := (button - left) mod 100   % middle = 0 or 10
        right := button - middle - left     % right = 0 or 100
        if left = 1 then
            put "left button down"
        end if
        if middle = 10 then
            put "middle button down"
        end if
        if right = 100 then
            put "right button down"
        end if
Status Exported qualified.

This means that you can only call the function by calling Mouse.ButtonChoose, not by calling ButtonChoose.

See also Mouse.ButtonMoved and Mouse.ButtonWait to get mouse events saved in a queue. See also Mouse.Where to get the current status of mouse button(s).


Mouse.ButtonMoved

Mouse.ButtonMoved Part of Mouse module

Syntax Mouse.ButtonMoved (motion : string) : boolean

Description The Mouse.ButtonMoved function indicates whether there is a mouse event of the appropriate type on the mouse queue. Events are either "up", "down", "updown" or "downup" events (although the "downup" and "updown" are the same event).

The parameter motion must be one of "up", "down", "updown" or "downup". If an event of the type requested is in the queue, Mouse.ButtonMoved returns true. If the event is not in the queue, then Mouse.ButtonMoved returns false.

In "single-button mode" (where the mouse is treated like a one-button mouse), a "down" event occurs whenever all the buttons are up and a button is pressed. An "up" event takes place when the last button is released so that no buttons remain pressed.

In "multi-button mode", a "down" event occurs whenever any button is pressed, and an "up" event occurs whenever any button is released.

Example This program draws random circles on the screen until the user clicks the mouse button, whereupon is starts drawing random boxes. Clicking the mouse button switches between the two.

        var circles: boolean := true
        loop
            var x, y, radius, clr: int
            if Mouse.ButtonMoved ("down") then
                var buttonnumber, buttonupdown : int
                Mouse.ButtonWait ("down", x, y, buttonnumber,
                                        buttonupdown)
                circles := not circles
            end if
            x := Rand.Int (0, maxx)
            y := Rand.Int (0, maxy)
            radius := Rand.Int (0, 100)
            clr := Rand.Int (0, maxcolor)
            if circles then
                Draw.FillOval (x, y, radius, radius, clr)
            else
                Draw.FillBox (x, y, x + radius, y + radius, clr)
            end if
        end loop
Example This is an example demonstrating how to check for both character and mouse input at the same time.

        var ch : string (1)
        var x, y, btnnum, btnupdown : int
        loop
            if hasch then
                getch (ch)
                Text.Locate (1, 1)
                put "The character entered is a: ", ch
            end if
            if Mouse.ButtonMoved ("down") then
                Mouse.ButtonWait ("down", x, y, btnnum, btnupdown)
                Text.Locate (1, 1)
                put "The button was clicked at position: ", x, ", ",y
            end if
        end loop
Details Mouse.ButtonMoved can be thought of as the mouse equivalent of hasch in that they both check for something in a queue and both return immediately.

Status Exported qualified.

This means that you can only call the function by calling Mouse.ButtonMoved, not by calling ButtonMoved.

See also Mouse.ButtonMoved to get mouse events saved in the queue. See also Mouse.ButtonChoose to switch between "single-button mode" and "multi-button mode".


Mouse.ButtonWait

Mouse.ButtonWait Part of Mouse module

Syntax Mouse.ButtonWait (motion : string,
var x, y, buttonNumber, buttonUpDown : int)

Description The Mouse.ButtonWait procedure gets information about a mouse event and removes it from the queue.

The parameter motion must be one of "up", "down", "updown" or "downup". If an event of the type requested is in the queue, Mouse.ButtonWait returns instantly. If there isn't such an event, Mouse.ButtonWait waits until there is one and then returns (much like getch handles keystrokes).

In "single-button mode" (where the mouse is treated like a one-button mouse), a "down" event occurs whenever all the buttons are up and a button is pressed. An "up" event takes place when the last button is released so that no buttons remain pressed.

In "multi-button mode", a "down" event occurs whenever any button is pressed, and an "up" event occurs whenever any button is released.

The parameters x and y are set to the position of the mouse cursor when the button was pressed. The parameter buttonnumber is set to 1 when in "single-button mode". In "multi-button mode", it is set to 1 if the left button was pressed, 2 if the middle button was pressed, and 3 if the right button was pressed. The parameter buttonupdown is set to 1, if a button was pressed and 0 if a button was released.

Example This program draws lines. It starts a line where the user presses down and continues to update the line while the mouse button is held down. When the button is released, the line is permanently draw and the user can draw another line.

        var x, y, btnNumber, btnUpDown, buttons : int
        var nx, ny : int
        loop
            Mouse.ButtonWait ("down", x, y, btnNumber, btnUpDown)
            nx := x
            ny := y
            loop
                Draw.Line (x, y, nx, ny, 0) % Erase previous line
                exit when Mouse.ButtonMoved ("up")
                Mouse.Where (nx, ny, buttons)
                Draw.Line (x, y, nx, ny, 1) % Draw line to position
            end loop
            Mouse.ButtonWait ("up", nx, ny, btnNumber, btnUpDown)
            Draw.Line (x, y, nx, ny, 2) % Draw line to final position
        end loop
Example This is an example demonstrating how to check for both character and mouse input at the same time.

        var ch : string (1)
        var x, y, btnNum, btnUpDown : int
        loop
            if hasch then
                getch (ch)
                Text.Locate (1, 1)
                put "The character entered is a: ", ch
            end if
            if Mouse.ButtonMoved ("down") then
                Mouse.ButtonWait ("down", x, y, btnNum, btnUpDown)
                Text.Locate (1, 1)
                put "The button was clicked at position: ", x, ", ",y
            end if
        end loop
Details Mouse.ButtonWait can be thought of as the mouse equivalent of getch in that they both read something in a queue and both wait until they get the thing they're looking for.

Status Exported qualified.

This means that you can only call the function by calling Mouse.ButtonWait, not by calling ButtonWait.

See also Mouse.ButtonWait to see if an appropriate event is in the queue. See also Mouse.ButtonChoose to switch between "single-button mode" and "multi-button mode".


Mouse.Where

Mouse.Where Part of Mouse module

Syntax Mouse.Where (var x, y, button : int)

Description The Mouse.Where procedure is used to get current information about the status of the mouse. The parameters x and y are set to the current location of the mouse cursor. If the program is running on a system using windows, the cursor may be outside the window. This means that x and y may be set to values outside of the bounds of 0 to maxx and 0 to maxy.

The parameter button is set depending on the current mode. In "single-button mode" (where the mouse is treated like a one-button mouse), button is set to 0 if all the mouse buttons are up, and 1 if any of the mouse buttons are down. In "multi-button mode", button is assigned the sum of 1 if the left button is down, 10 if the middle button is down, and 100 if the right button is down. Thus if button has the value of 101, then it means that the left and right mouse buttons were depressed.

Example A program that displays the status of the mouse at the top left corner of the screen.

        var x, y, button : int
        loop
            Mouse.Where (x, y, button)
            Text.Locate (1, 1)
            if button = 0 then
                put x : 4, "  ", y : 4, "  button up"
            else
                put x : 4, "  ", y : 4, "  button down"
            end if
        end loop
Status Exported qualified.

This means that you can only call the function by calling Mouse.Where, not by calling Where.

See also Mouse.ButtonMoved and Mouse.ButtonWait to get mouse events saved in a queue. See also Mouse.ButtonChoose to switch between "single-button mode" and "multi-button mode".


mousewhere

Syntax mousewhere (var x, y, button : int)

Description The mousewhere procedure is used to get current information about the status of the mouse. The parameters x and y are set to the current location of the mouse cursor. If the program is running on a system using windows, the cursor may be outside the window. This means that x and y may be set to values outside of the bounds of 0 to maxx and 0 to maxy.

The parameter button is set depending on the current mode. In "single-button mode" (where the mouse is treated like a one-button mouse), button is set to 0 if all the mouse buttons are up, and 1 if any of the mouse buttons are down. In "multi-button mode", button is assigned the sum of 1 if the left button is down, 10 if the middle button is down, and 100 if the right button is down. Thus if button has the value of 101, then it means that the left and right mouse buttons were depressed.

Example A program that displays the status of the mouse at the top left corner of the screen.

        var x, y, button : int
        loop
            mousewhere (x, y, button)
            locate (1, 1)
            if button = 0 then
                put x : 4, "  ", y : 4, "  button up"
            else
                put x : 4, "  ", y : 4, "  button down"
            end if
        end loop
See also buttonmoved and buttonwait to get mouse events saved in a queue. See also buttonchoose to switch between "single-button mode" and "multi-button mode".


Music

Description This unit contains the predefined subprograms that deal with sound and music. Some of these routines have not been implemented at the time of the writing of this manual and will be implemented in future releases.

All routines in the Music module are exported qualified (and thus must be prefaced with "Music.").

Entry Points
Play | Plays a series of notes.
PlayFile | Plays music from a file, returning when the file is finished playing. File must be in an allowable format.
PlayFileReturn | Plays music from a file, returning as soon as the music starts. File must be in an allowable format.
PlayFileLoop | Plays music from a file, looping over and over. Returns as soon as the music starts. File must be in an allowable format.
PlayFileStop | Immediately terminates any playing music files.
Sound | Plays a specified frequency for a specified duration.
SoundOff | Immediately terminates any sound playing.


Music.Play

Music.Play Part of Music module

Syntax Music.Play ( music : string )

Description The Music.Play procedure is used to sound musical notes on the computer.

Sounds are produced synchronously on a per process basis. This means that when a process executes a Music.Sound or Music.Play command, it stops until the command is finished. However, other processes will continue to executing.

Example This program sounds the first three notes of the C scale.

        Music.Play ( "cde" )
Example This program plays from middle C to one octave above middle C and down again in 8th notes.

        Music.Play ( "8cdefgab>c" )
        Music.Play ( "<bagfedc" )
Execute

Details The syntax of the play string may be enhanced in the future.

The Music.Play procedure takes strings containing characters that specify notes, rests, sharps, flats and duration. The notes are the letters a to g (or A to G). A rest is p (for pause). A sharp is + and a flat is -. The durations are 1 (whole note), 2 (half note), 4 (quarter note), 8 (eight note) and 6 (sixteenth note). The character > raises to the next octave and < lowers. For example, this is the way to play C and then C sharp one octave above middle C with a rest between them, all in sixteenth notes: Music.Play(">6cpc+"). Blanks can be used for readability and are ignored by Music.Play.

The Music.Play procedure requires that the machine have a sound card in order to play tones.

Status Exported qualified.

This means that you can only call the function by calling Music.Play, not by calling Play.

See also the Music.Sound procedure, which makes a sound of a given frequency (Hertz) and duration (milliseconds).


Music.PlayFile

Music.PlayFile Part of Music module

Syntax Music.PlayFile ( fileName : string )

Description The Music.PlayFile procedure is used to play a file of music. The file must be in one of the acceptable formats and the machine, must have the appropriate hardware.

The fileName parameter must give the format of the file:

WAV files | "WAV:filename" or "filename.WAV"
MP3 files | "MP3:filename" or "filename.MP3"
MIDI files | "MIDI:filename" or "filename.MIDI"

Sounds are produced synchronously on a per process basis. This means that when a process executes a Music.Sound, Music.Play or Music.PlayFile command, it stops until the command is finished. However, other processes will continue executing.

Details To play music while performing any other activity, the call to Music.PlayFile must be executed in its own process. The process is then called using the fork command. When a fork command is given, execution starts on the process (like a procedure call) and continues following the fork command at the same time.

Example This program plays the music in the file "branden3.wav" while drawing ovals on the screen.

        process DoMusic
            loop
                Music.PlayFile ("branden3.wav")
            end loop
        end DoMusic

        fork DoMusic
        var x, y, clr : int
        loop
            x := Rand.Int (0, maxx)
            y := Rand.Int (0, maxy)
            clr := Rand.Int (0, maxcolor)
            Draw.FillOval (x, y, 30, 30, clr)
        end loop
Execute

Details To play a sound file requires that the computer be equipped with a sound card and speakers.

Details The Turing 4.1 software can play files in the following audio formats: WAVE (.wav) files, MIDI files (.midi or .mid), and MP3 files (.mp3). In general, MIDI files are the most efficient and thus are the preferred form for longer music pieces like background music. WAVE files can record anything, not just music, so are often used for sound effects.

Details The Turing 4.1 software can also play music on a compact disk. To play the complete contents of the compact disk, the filename is “cd”. To play a single track from a compact disk, the filename is “cd:[track number]”.

        Music.PlayFile ("cd")       % Play the entire CD
        Music.PlayFile ("cd:3")     % Play the third track on the CD
Details On the PC, different formats of music can play simultaneously. This means that a program might use a MIDI file as a background soundtrack and then use WAVE files for individual sound effects. The sound effects would not interfere with the background music. Playing a second music file with the same format as an already playing piece immediately halts the first piece and starts the second. This can be used to stop a single type of music by playing a short silent piece of music.

Example This program bounces a maple leaf around the screen with background music and a sound effect when the maple leaf hits an edge. When the user presses any key, the program immediately exits.

        const STAR_SIZE : int := 80
        var pic, x, y, dx, dy : int
        var finished : boolean := false

        % Play sound effect once.
        process Boing
            Music.PlayFile ("boing.wav")
        end Boing

        % Loop playing background music until 'finished' is true.
        process BackgroundMusic
            loop
                exit when finished
                Music.PlayFile ("background.mid")
            end loop
        end BackgroundMusic

        % Get the original picture
        Draw.FillStar (3, 3, STAR_SIZE - 3, STAR_SIZE - 3, brightred)
        pic := Pic.New (0, 0, STAR_SIZE, STAR_SIZE)
        cls

        % Set the initial location and direction of movement
        x := Rand.Int (0, maxx - STAR_SIZE)
        y := Rand.Int (0, maxy - STAR_SIZE)
        dx := 1
        dy := 1

        fork BackgroundMusic    % Start background music playing

        loop
            if x + dx < 0 or x + dx > maxx - STAR_SIZE then
                dx := -dx
                fork Boing
            end if
            if y + dy < 0 or y + dy > maxy - STAR_SIZE then
                dy := -dy
                fork Boing
            end if
            x += dx
            y += dy
            Pic.Draw (pic, x, y, picCopy)
            exit when hasch
            Time.Delay (5)
        end loop

        % Stop the background music.
        finished := true
        Music.PlayFileStop
Execute

See also Music.PlayFileStop to halt a music file that is current playing, Music.PlayFileReturn for a procedure that starts a music file playing and returns immediately (meaning that you do not need to use process and fork statements), and Music.PlayFileLoop that starts a music file playing continuously until it is stopped without the use of process or fork.

Status Exported qualified.

This means that you can only call the function by calling Music.PlayFile, not by calling PlayFile.


Music.PlayFileLoop

Music.PlayFileLoop Part of Music module

Syntax Music.PlayFileLoop ( fileName : string )

Description The Music.PlayFileLoop procedure is used to play a file of music continuously, looping until the program is halted or the Music.PlayFileStop command is given. The file must be in one of the acceptable formats and the machine, must have the appropriate hardware.

The fileNameparameter must give the format of the file:

WAV files | "WAV:filename" or "filename.WAV"
MP3 files | "MP3:filename" or "filename.MP3"
MIDI files | "MIDI:filename" or "filename.MIDI"

The Music.PlayFileLoop procedure is used to provide continuous background music for a program. When called, the music starts playing, and the procedure returns immediately.

Details Unlike Music.PlayFile, the Music.PlayFileLoop procedure does not have to be called in a separate process. However, the music will not stop playing (nor will a program that calls this procedure terminate) until Music.PlayFileStop is called.

Example This program continuously plays the music in the file "branden3.wav" while drawing ovals on the screen.

        Music.PlayFileLoop ("branden3.wav")
        var x, y, clr : int
        loop
            x := Rand.Int (0, maxx)
            y := Rand.Int (0, maxy)
            clr := Rand.Int (0, maxcolor)
            Draw.FillOval (x, y, 30, 30, clr)
            exit when hasch
        end loop
        Music.PlayFileStop
Execute

Details To play a sound file requires that the computer be equipped with a sound card and speakers.

Details The Turing 4.1 software can play files in the following audio formats: WAVE (.wav) files, MIDI files (.midi or .mid), and MP3 files (.mp3). In general, MIDI files are the most efficient and thus are the preferred form for longer music pieces like background music. WAVE files can record anything, not just music, so are often used for sound effects.

Details The Turing 4.1 software can also play music on a compact disk. Toplay the complete contents of the compact disk, the filename is “cd”. To play a single track from a compact disk, the filename is “cd:[track number]”.

        Music.PlayFileLoop ("cd")       % Play the entire CD
        Music.PlayFileLoop ("cd:3")     % Play the third track on the CD
Details On the PC, different formats of music can play simultaneously. This means that a program might use a MIDI file as a background soundtrack and then use WAVE files for individual sound effects. The sound effects would not interfere with the background music. Playing a second music file with the same format as an already playing piece immediately halts the first piece and starts the second. This can be used to stop a single type of music by playing a short silent piece of music.

Example This program bounces a maple leaf around the screen with background music and a sound effect when the maple leaf hits an edge. When the user presses any key, the program immediately exits.

        const STAR_SIZE : int := 80
        var pic, x, y, dx, dy : int

        % Get the original picture
        Draw.FillStar (3, 3, STAR_SIZE - 3, STAR_SIZE - 3, brightred)
        pic := Pic.New (0, 0, STAR_SIZE, STAR_SIZE)
        cls

        % Set the initial location and direction of movement
        x := Rand.Int (0, maxx - STAR_SIZE)
        y := Rand.Int (0, maxy - STAR_SIZE)
        dx := 1
        dy := 1

        Music.PlayFileLoop ("background.mid") % Start background music playing

        loop
            if x + dx < 0 or x + dx > maxx - STAR_SIZE then
                dx := -dx
                Music.PlayFileReturn ("boing.wav")
            end if
            if y + dy < 0 or y + dy > maxy - STAR_SIZE then
                dy := -dy
                Music.PlayFileReturn ("boing.wav")
            end if
            x += dx
            y += dy
            Pic.Draw (pic, x, y, picCopy)
            exit when hasch
            Time.Delay (5)
        end loop

        % Stop the background music.
        Music.PlayFileStop
Execute

See also Music.PlayFileStop to halt a music file that is current playing.

Status Exported qualified.

This means that you can only call the function by calling Music.PlayFileLoop, not by calling PlayFileLoop.


Music.PlayFileReturn

Music.PlayFileReturn Part of Music module

Syntax Music.PlayFileReturn ( fileName : string )

Description The Music.PlayFileReturn procedure is used to play a file of music. The file must be in one of the acceptable formats and the machine, must have the appropriate hardware.

The fileNameparameter must give the format of the file:

WAV files | "WAV:filename" or "filename.WAV"
MP3 files | "MP3:filename" or "filename.MP3"
MIDI files | "MIDI:filename" or "filename.MIDI"

Unlike Music.PlayFile, the Music.PlayFileReturn procedure should not be called in a separate process. Instead, the procedure returns immediately. This makes Music.PlayFileReturn easier to use, but makes it unsuitable for playing a set of files sequentially.

Example This program plays the music in the file "branden3.wav" once while drawing ovals on the screen. If the music has not finished when the user presses a key, it is halted using Music.PlayFileStop

        Music.PlayFileReturn ("branden3.wav")
        var x, y, clr : int
        loop
            x := Rand.Int (0, maxx)
            y := Rand.Int (0, maxy)
            clr := Rand.Int (0, maxcolor)
            Draw.FillOval (x, y, 30, 30, clr)
            exit when hasch
        end loop
        Music.PlayFileStop
Execute

Details To play a sound file requires that the computer be equipped with a sound card and speakers.

Details The Turing 4.1 software can play files in the following audio formats: WAVE (.wav) files, MIDI files (.midi or .mid), and MP3 files (.mp3). In general, MIDI files are the most efficient and thus are the preferred form for longer music pieces like background music. WAVE files can record anything, not just music, so are often used for sound effects.

Details The Turing 4.1 software can also play music on a compact disk. Toplay the complete contents of the compact disk, the filename is “cd”. To play a single track from a compact disk, the filename is “cd:[track number]”.

        Music.PlayFileReturn ("cd")       % Play the entire CD
        Music.PlayFileReturn ("cd:3")     % Play the third track on the CD
Details On the PC, different formats of music can play simultaneously. This means that a program might use a MIDI file as a background soundtrack and then use WAVE files for individual sound effects. The sound effects would not interfere with the background music. Playing a second music file with the same format as an already playing piece immediately halts the first piece and starts the second. This can be used to stop a single type of music by playing a short silent piece of music.

Example This program bounces a maple leaf around the screen with background music and a sound effect when the maple leaf hits an edge. When the user presses any key, the program immediately exits.

        const STAR_SIZE : int := 80
        var pic, x, y, dx, dy : int

        % Get the original picture
        Draw.FillStar (3, 3, STAR_SIZE - 3, STAR_SIZE - 3, brightred)
        pic := Pic.New (0, 0, STAR_SIZE, STAR_SIZE)
        cls

        % Set the initial location and direction of movement
        x := Rand.Int (0, maxx - STAR_SIZE)
        y := Rand.Int (0, maxy - STAR_SIZE)
        dx := 1
        dy := 1

        Music.PlayFileLoop ("background.mid") % Start background music playing

        loop
            if x + dx < 0 or x + dx > maxx - STAR_SIZE then
                dx := -dx
                Music.PlayFileReturn ("boing.wav")
            end if
            if y + dy < 0 or y + dy > maxy - STAR_SIZE then
                dy := -dy
                Music.PlayFileReturn ("boing.wav")
            end if
            x += dx
            y += dy
            Pic.Draw (pic, x, y, picCopy)
            exit when hasch
            Time.Delay (5)
        end loop

        % Stop the background music.
        Music.PlayFileStop
Execute

See also Music.PlayFileStop to halt a music file that is current playing.

Status Exported qualified.

This means that you can only call the function by calling Music.PlayFileReturn, not by calling PlayFileReturn.


Music.PlayFileStop

Music.PlayFileStop Part of Music module

Syntax Music.PlayFileStop

Description The Music.PlayFileStop procedure is used to to stop all music files currently playing. This includes processes that are executing the Music.PlayFile procedure (they exit immediately and start executing the next statement in the process), and the Music.PlayFileReturn and Music.PlayFileLoop statements, which simply stop playing the music.

Details In Turing, a program will not halt execution until all processes have terminated. This means that if you are playing background music, the program will not terminate, even if execution returns from the main program unless the background music is halted.

Example This program plays the background music for 30 seconds and then terminates. Note that it is important to set the flag (finished) before calling Music.PlayFileStop. If Music.PlayFileStop comes first, it is possible for the process to return from Music.PlayFile, loop around, skip over the exit when, and call Music.PlayFile again before the finished flag is set.

        var finished : boolean := false

    % Loop playing background music until 'finished' is true.
        process BackgroundMusic
            loop
                exit when finished
                Music.PlayFile ("background.mid")
            end loop
        end BackgroundMusic

        fork BackgroundMusic    % Start the background music
        Time.Delay (30000)  % Wait for 30 seconds

        % Stop the background music.
        finished := true        % The flag must be set first
        Music.PlayFileStop  % Music.PlayFile will return immediately
Execute

See also Music.PlayFile for playing music files and a larger example.

Status Exported qualified.

This means that you can only call the function by calling Music.PlayFileStop, not by calling PlayFileStop.


Music.Sound

Music.Sound Part of Music module

Syntax Music.Sound ( frequency, duration : int )

Description The Music.Sound statement is used to cause the computer to sound a note of a given frequency for a given time. The frequency is in cycles per second (Hertz). The time duration is in milliseconds. For example, middle A on a piano is 440 Hertz, so Music.Sound(440, 1000) plays middle A for one second.

Sounds are produced synchronously on a per process basis. This means that when a process executes a Music.Sound or Music.Play command, it stops until the command is finished. However, other processes will continue executing.

Example This program plays a siren sound in the background.

        process siren
            loop
                for i : 100 .. 3000 by 100
                    Music.Sound ( i, 50 )   % Sound note
                end for
                for decreasing i : 2900 .. 200 by 100
                    Music.Sound ( i, 50 )   % Sound note
                end for
            end loop
        end siren

        fork siren
        … the rest of the program goes here while the siren continues …
Execute

Status Exported qualified.

This means that you can only call the function by calling Music.Sound, not by calling Sound.

See also Music.Play statement, which plays notes based on musical notation. For example, Music.Play("8C") plays an eighth note of middle C.


Music.SoundOff

Music.SoundOff Part of Music module

Syntax | Music.SoundOff
Description | The Music.SoundOff procedure stops any sound or music that is currently playing or is waiting to play.
Status | Exported qualified. This means that you can only call the function by calling Music.SoundOff, not by calling SoundOff.
See also | Music.Play, Music.PlayFile, and Music.Sound procedures, which make sounds that can be turned off with Music.SoundOff.


named

named type

Syntax A namedType is one of:

(a) | typeId
(b) | moduleId . typeId

Description A type can be given a name (typeId) and later this name can be used instead of writing out the type.

Example In this example, phoneRecord is a named type.

        type phoneRecord :
            record
                name : string ( 20 )
                phoneNumber : int
                address : string ( 50 )
            end record
        …
        var oneEntry : phoneRecord
        var phoneBook : array 1 .. 100 of phoneRecord
Details Form (a) is the most common kind of named type. Form (b) is used when the type name has been exported from a module.

Arrays whose bounds are not known at compile time cannot be named.


nargs

nargs number of arguments

Syntax nargs : int

Description The nargs function is used to determine the number of arguments that have been passed to a program from the command line. For example, if the program is run from the Turing environment using

        :r file1 file2
then nargs will return 2. If a program called prog.x is run under UNIX using this command:

        prog.x file1 file2
the value of nargs will similarly be 2.

The nargs function is usually used together with the fetcharg function to access the arguments that have been passed to the program.

See also fetcharg for an example of the use of nargs.


nat

nat natural number type

Syntax nat

Description The nat (natural number) type has the values 0, 1, 2, 3 … Natural numbers can be combined by various operators, such as addition (+) and multiplication (*). Natural numbers can be combined with integers (type int), in which case the result is an integer. Natural numbers can also be combined with real numbers, in which case the result is generally a real number. Natural numbers can always be assigned to real variables, with implicit conversion to real.

Example

        var counter : nat
        var j : nat := 9
Details See also explicitIntegerConstant. The nat type is used instead of int when the values are known to be non-negative.

The Turing operators on natural numbers are the same as those for integers: +, -, * (multiply), div (truncating integer division), mod (integer remainder), ** (exponentiation), as well as comparisons (+, not=, >, >=, <, <=). The operators and, or and xor to be applied to natural number values. The bit-wise boolean result is produced as a natural number. The shr (shift right) and shl (shift left) operators are also introduced.

In the current implementation, the range of natural numbers is from 0 to 4294967294. In other words, the maximum value of a natural number is 2**32 - 2. This range exists because natural numbers are stored in 4 bytes. The types nat1, nat2 and nat4 specify natural numbers that fit into 1, 2 or 4 bytes.

Explicit constants such as 213 and 0 are considered to be integers. As a result the type of tax in this declaration is int:

        var tax := 0    % The type is int
Natural number values can be used whenever integer values are expected and vice versa, given that the value does not exceed the range of the expected type.

When integer and natural numbers are combined using a binary operator such as +, the result is an integer. This means, for example, that if counter is a natural number, counter + 1 is considered to be an integer. As long as the result fits into the range that is the intersection of the ranges of int and nat, the result will be as expected. Anomalies occur when the result is (or would be) greater than the largest integer (maxint=2147483647). For example, if natural number n is greater than maxint, the expression n + 1 will overflow, because its result is an int (because 1 is an int). To avoid this problem, you must be careful that both operands are natural numbers.

Suppose we have this declaration:

        const natOne : nat := 1
We can safely compute n + natOne because both operands have type nat.

Natural numbers can be converted to real numbers using natreal, but in practice this is rarely used, because a natural value used in place of a real value will be automatically converted to real.

Natural numbers can be converted to strings and back using natstr and strnat.

In the C language, a natural number is said to be "unsigned".

See also maxnat, int, nat n, int n, natstr, strnat and natreal.


natn

natn n-byte natural number type

Dirty

Syntax

(a) | nat1 | % 1-byte natural number
(b) | nat2 | % 2-byte natural number
(c) | nat4 | % 4-byte natural number

Description The natn (n-byte natural number) types are machine-dependent types that occupy a specified number of bytes. By contrast, the nat type is in principle a machine-independent and mathematical type (it overflows, however, when the value is too large or small, that is, when the value does not fit into 4 bytes).

Example

        var counter1 : nat1     % Range is 0 .. 255
        var counter2 : nat2     % Range is 0 .. 65536
        var counter4 : nat4     % Range is 0 .. 4294967295
Details In Turing, the range of the nat is 0 to 4294967294, which means that the nat4 type allows one more value, 4294967295. This extra value is used in nat to represent the state of being uninitialized. The natn types allow use of all possible values that fit into n bytes and thereby eliminates checking for initialization.

The natn types are like the C language types short unsigned, unsigned, and long unsigned, except that the number of bytes occupied by the C types depends on the particular C compiler.

See also the int n types which are n byte integer values. See also nat and int.


natreal

natreal natural number to real function

Syntax | natreal ( n : nat ) : real
Description | The natreal function is used to convert a natural number to a real number. This function is rarely used, because in Turing, a natural number can be used anyplace a real value is required. When this is done, the natreal function is implicitly called to do the conversion from nat to real. The natreal function is similar to intreal, except that natreal handles values that are larger than int values and does not handle negative values.
See also | nat. See also the intreal, floor, ceil and round functions.


natstr

natstr natural-number-to-string function

Syntax natstr ( n : nat [ , width : int [, base : int ] ] ) : string

Description The natstr function is used to convert a natural number to a string. The string is equivalent to n, padded on the left with blanks as necessary to a length of width, written in the given number base. For example, natstr (14, 4, 10)="bb14" where b represents a blank. The width and base parameters are both optional. It they are omitted, the string is made just long enough to hold the value and the number base is 10. For example, natstr (23) = "23".

The width parameter must be non-negative. If width is not large enough to represent the value of i, the length is automatically increased as needed.

The string returned by natstr is of the form:

{blank}digit{digits}

where {blank} means zero or more blanks and digit{digit} means one or more digits. The leftmost digit is either non-zero, or a single zero digit; in other words, leading zeros are suppressed.

The letters A, B, C … are used to represent the digit values 10, 11, 12, … The base must be in the range 2 to 36 (36 because there are ten digits and 26 letters). For example, natstr (255, 0, 16) = "FF".

The natstr function is the inverse of strnat, so for any natural number n, strnat ( natstr(n) ) = n.

See also chr, ord and strnat functions. See also the intstr and strint functions. See also explicitIntegerConstant for the way to write values in base 2 and base 16 in a program.


Net

Description The Net module allows TCP/IP equipped machines to communicate. In the current implementation (WinOOT 3.0), this is available only under Win32 (Windows 95, 98, NT and later).

To allow two machines to communicate, there must be a server (which calls Net,WaitForConnection) and a client (which calls Net.OpenConnection). The server waits until a client connects and then starts communication between the two. When a connection is established, a net stream is returned that can be used in the same fashion as a file stream (i.e. using puts and gets). Once the connection is finished, the programs call Net.CloseConnection.

For ease of reading web pages, the Net.OpenURLConnection opens up a URL for reading with the get statement. It is up to the user program to interpret the HTML or file located at the URL.

All subprograms in the Net unit are exported qualified (and thus must be prefaced with "Net.").

Entry Points
WaitForConnection | Waits until a client connects to a specified port.
OpenConnection | Opens a connection to a specified machine.
OpenURLConnection | Opens a connection to a file specified by a URL.
CloseConnection | Closes a specified connection.
BytesAvailable | Returns the number of bytes available to be read from a net stream.
CharAvailable | Returns true if there is a character available to be read from a net stream.
LineAvailable | Returns true if there is a line of text available to be read from a net stream.
TokenAvailable | Returns true if there is a token available to be read from a net stream.
HostAddressFromName | Returns a host's address given its host name.
HostNameFromAddress | Returns a host's name given its address.
LocalAddress | Returns the host name of the local machine.
LocalName | Returns the TCP/IP address of the local machine.


Net.BytesAvailable

Net.BytesAvailable Part of Net module

Syntax | Net.BytesAvailable (netStream : int) : int
Description | Returns the number of bytes available for reading from the net stream specified by the netStream parameter.
Details | The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.
Status | Exported qualified. This means that you can only call the function by calling Net.BytesAvailable, not by calling BytesAvailable.
See also | Net.CharAvailable, Net.LineAvailable, and Net.TokenAvailable.


Net.CharAvailable

Net.CharAvailable Part of Net module

Syntax Net.CharAvailable (netStream : int) : boolean

Description Returns true if a character is waiting to be read from the net stream specified by the netStream parameter. If Net.CharAvailable returns true, then a single character can be read from the stream without blocking.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program fragment reads a character from netStream only if there is one waiting to be read.

        if Net.CharAvailable (netStream) then
            var ch : char
            get : netStream, ch
            put ch ..
        end if
Status Exported qualified.

This means that you can only call the function by calling Net.CharAvailable, not by calling CharAvailable.

See also Net.BytesAvailable, Net.LineAvailable, and Net.TokenAvailable.


Net.CloseConnection

Net.CloseConnection Part of Net module

Syntax Net.CloseConnection (netStream : int)

Description Closes a network connection made with Net.OpenConnection or Net.WaitForConnection. After the connection is closed, the net stream cannot be used for any purpose on either side of the connection.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program fragment connects to port 5300 on the machine specified by netAddress, sends the work OK to it and closes the connection.

        netStream := Net.OpenConnection (netAddress, chatPort)
        if netStream <= 0 then
            put "Unable to connect to ", netAddress
            return
        end if
        put : netStream, "OK"
        Net.CloseConnection (netStream)
Status Exported qualified.

This means that you can only call the function by calling Net.CloseConnection, not by calling CloseConnection.

See also Net.OpenConnection and Net.WaitForConnection.


Net.HostAddressFromName

Net.HostAddressFromName Part of Net module

Syntax Net.HostAddressFromName (
hostName : string) : string

Description Returns the numeric TCP/IP address of the machine whose hostname is specified by the hostName parameter.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program prints out the hostname of the current machine.

        var hostName : string := "www.holtsoft.com"
        put "The machine address of ", hostName , " is ",
            Net.HostAddressFromName (hostName)
Status Exported qualified.

This means that you can only call the function by calling Net.HostAddressFromName, not by calling HostAddressFromName.

See also Net.HostNameFromAddress.


Net.HostNameFromAddress

Net.HostNameFromAddress Part of Net module

Syntax Net.HostNameFromAddress (
hostAddr : string) : string

Description Returns the TCP/IP hostname of the machine whose numeric address is specified by the hostAddr parameter.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program prints out the hostname of the machine whose TCP/IP numeric address is "128.100.5.1".

        var hostAddr : string := "128.100.5.1"
        put "The machine name of ", hostAddr, " is ",
            Net.HostNameFromAddress (hostAddr)
Status Exported qualified.

This means that you can only call the function by calling Net.HostNameFromAddress, not by calling LocalName.

See also Net.HostAddressFromName.


Net.LineAvailable

Net.LineAvailable Part of Net module

Syntax Net.LineAvailable (netStream : int) : boolean

Description Returns true if a line of input is waiting to be read from the net stream specified by the netStream parameter. If Net.LineAvailable returns true, then a line of input can be read from the stream without blocking.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program fragment reads a character from netStream only if there is one waiting to be read.

        if Net.LineAvailable (netStream) then
            var line : string
            get : netStream, line : *
            put line
        end if
Status Exported qualified.

This means that you can only call the function by calling Net.LineAvailable, not by calling LineAvailable.

See also Net.BytesAvailable, Net.CharAvailable, and Net.TokenAvailable.


Net.LocalAddress

Net.LocalAddress Part of Net module

Syntax Net.LocalAddress : string

Description Returns the TCP/IP numeric address of the machine the program is running on. The numeric address is of the form xxx.yyy.zzz.www where each segment is a number from 0 to 255.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program prints out the TCP/IP numeric address of the current machine.

        put "Your machine address is ", Net.LocalAddress
Status Exported qualified.

This means that you can only call the function by calling Net.LocalAddress, not by calling LocalAddress.

See also Net.LocalName.


Net.LocalName

Net.LocalName Part of Net module

Syntax Net.LocalName : string

Description Returns the TCP/IP hostname of the machine the program is running on.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program prints out the hostname of the current machine.

        put "Your machine name is ", Net.LocalName
Status Exported qualified.

This means that you can only call the function by calling Net.LocalName, not by calling LocalName.

See also Net.LocalAddress.


Net.OpenConnection

Net.OpenConnection Part of Net module

Syntax Net.OpenConnection (netAddr : string,
port : int) : int

Description Attempts to open a connection to port specified by the port parameter on the machine specified by netAddr parameter. There must be a program listening to that port for the connection to be made. In OOT, this is done using the Net.WaitForConnection function.

If successful, Net.OpenConnection returns a network stream descriptor which can be used with the put, get, read, and write statements and eof function to send and receive data to the listening program. It is also the parameter used for the Net.CloseConnection, Net.BytesAvailable, Net.CharAvailable, Net.LineAvailable, and Net.TokenAvailable functions.

The netAddr parameter is a string specifying the net address of the machine to be connected to. This can either be the full hostname or the numerical address.

In general, system program listen in on ports with numbers below 1024. Port numbers above 1024 are generally available for use by user created programs.

The program will wait for an indeterminate amount of time to make the connection. If it fails, it will return a non-positive value.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program implements a "Chat" program. One user runs the program on their machine as a server, which waits for another machine to connect to it. The second user specifies the machine to connect to and then connects. The two can then type at each other.

        % The "Chat" program
        const chatPort : int := 5055
        var choice : int
        loop
            put "Enter 1 to run chat server"
            put "Enter 2 to run chat session"
            put "Choice: " ..
            get choice
            exit when choice = 1 or choice = 2
        end loop
        var netStream : int
        var netAddress : string

        if choice = 1 then
            netStream := Net.WaitForConnection (chatPort, netAddress)
        else
            put "Enter the address to connect to: " ..
            get netAddress
            netStream := Net.OpenConnection (netAddress, chatPort)
            if netStream <= 0 then
                put "Unable to connect to ", netAddress
                return
            end if
        end if
        Draw.Cls
        put "Connected to ", netAddress

        var localRow : int := 2
        var localCol : int := 1
        var remoteRow := maxrow div 2
        var remoteCol : int := 1
        var ch : char

        View.Set ("noecho")
        loop
            if hasch then
                ch := getchar
                put : netStream, ch
                if ch = '\n' then
                    localRow := localRow mod (maxrow div 2) + 1
                    localCol := 1
                    Text.Locate (localRow, localCol)
                    put "" % Clear to end of line
                    Text.Locate (localRow, localCol)
                else
                    Text.Locate (localRow, localCol)
                    put ch ..
                    localCol += 1
                end if
            end if

            if Net.CharAvailable (netStream) then
                get : netStream, ch
                if ch = '\n' then
                    remoteRow := remoteRow mod (maxrow div 2) +
                        1 + (maxrow div 2)
                    remoteCol := 1
                    Text.Locate (remoteRow, remoteCol)            put ""  % Clear to end of line
                    Text.Locate (remoteRow, remoteCol)
                else
                    Text.Locate (remoteRow, remoteCol)
                    put ch ..
                    remoteCol += 1
                end if
            end if
        end loop
Status Exported qualified.

This means that you can only call the function by calling Net.OpenConnection, not by calling OpenConnection.

See also Net.WaitForConnection and Net.CloseConnection.


Net.OpenURLConnection

Net.OpenURLConnection Part of Net module

Syntax Net.OpenURLConnection (urlAddr : string) : int

Description Attempts to open a http connection to pthe URL (Universal Resource Locator) specified by the urlAddr.

If successful, Net.OpenURLConnection returns a network stream descriptor which can be used with the get statement and eof function to read the web page located at the URL.

The program will wait for an indeterminate amount of time to make the connection. If it fails, it will return a non-positive value.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program prints out the contents of the file specified by the user.

        var url : string
        put "Enter the URL to load: " ..
        get url

        var netStream : int
        var line : string

        netStream := Net.OpenURLConnection (url)
        if netStream <= 0 then
            put "Unable to connect to ", url
            return
        end if
        loop
            exit when eof (netStream)
            get : netStream, line
            put line
        end loop
        Net.CloseConnection (netStream)
Status Exported qualified.

This means that you can only call the function by calling Net.OpenURLConnection, not by calling OpenURLConnection.

See also Net.CloseConnection.


Net.TokenAvailable

Net.TokenAvailable Part of Net module

Syntax Net.TokenAvailable (netStream : int) : boolean

Description Returns true if a line of input is waiting to be read from the net stream specified by the netStream parameter. If Net.TokenAvailable returns true, then a single token (character surrounded by whitespace) can be read from the stream without blocking.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example The following program fragment reads a character from netStream only if there is one waiting to be read.

        if Net.TokenAvailable (netStream) then
            var token : string
            get : netStream, token
            put token
        end if
Status Exported qualified.

This means that you can only call the function by calling Net.TokenAvailable, not by calling TokenAvailable.

See also Net.BytesAvailable, Net.CharAvailable, and Net.LineAvailable.


Net.WaitForConnection

Net.WaitForConnection Part of Net module

Syntax Net.WaitForConnection (port : int,
var netAddr : string) : int

Description Listens for a connection at the port specified by the port parameter. When another program connects to the port, then the function returns. The address of the connecting machine is specified in the netAddr parameter and the Net.WaitForConnection returns a network stream descriptor which can be used with the put, get, read, and write statements and eof function to send and receive data to the connecting program. It is also the parameter used for the Net.CloseConnection, Net.BytesAvailable, Net.CharAvailable, Net.LineAvailable, and Net.TokenAvailable functions.

In OOT, the connection to a port is made with the Net.OpenConnection function.

The netAddr parameter is a string specifying the net address of the machine that connected to the port. It is the machines numerical address.

In general, system program listen in on ports with numbers below 1024. Port numbers above 1024 are generally available for use by user created programs.

The program will wait for indefinitely for a connection to made to the port.

Details The Net module requires a TCP/IP stack to be installed and operating in order to function. It does not communicate using any other protocols

It is possible for Firewalls to interfere with the actions of the Net module, preventing connections from taking place.

Example See Net.OpenConnection for an example of Net.WaitForConnection.

Status Exported qualified.

This means that you can only call the function by calling Net.WaitForConnection, not by calling WaitForConnection.

See also Net.OpenConnection and Net.CloseConnection.


new

new statement

Syntax A newStatement is:

new [ collectionOrClassId , ] pointerVariableReference

Description A new statement creates (allocates) a new element and assigns its location to the pointer variable. This element can be an object of a collection or class or a value of a type. If the collectionOrClassId is omitted, the choice of element is determined by the type of the pointer. For example, if the pointer is to class C, an object of class C will be allocated.

Example Using a collection, declare a list of records and allocate one record.

        var list : collection of
            record
                contents : string ( 10 )
                next : pointer to list  % Short form: next : ^ list
            end record
        var first : pointer to list     % Short form: var first : ^ list
        new list, first         % Short form: new first
Example Using a class, create an object of that class. The object is located by the start pointer.

        class node
            export var next, var name
            name : string (25)
            next : pointer to node  % Short form: next : ^ node
        end node
        var start : pointer to node % Short form: var start : ^ node
        new node, start         % Short form: new start
Example Using a record type, declare a list of records and allocate one record.

        type item:
            record
                contents : string ( 10 )
                next : pointer to item  % Short form: next : ^ item
            end record
        var first : pointer to item     % Short form: var first : ^ item
        new first
Details As the examples in this section show, a pointer can locate one of three things: an object of a collection, an object of a class or a value of a type.

In the new statement, the collectionOrClassId can be omitted. If the pointer locates a type, it must be omitted. The free statement is used to deallocate an element.

An imported class can have one of its objects created (by the new statement) only if the class is imported var.

If there is no more space to allocate an element, new will set the pointer to be the nil value, and the program will continue executing.

If the pointer locates class C and C contains an implement by list, the object created by new is the inherited object (through any number of levels of implement by). The pointer, however, remains a pointer to C.

The form new p is a short form for new C, p when C is the class or collection given in p's type.

If p is a pointer to class C and C has a descendant (expansion) class D, a new statement can be used to allocate an object of type D, as in:

        new D, p    % Allocates an object of class D
If D has an implement by clause, the expansion is created.

Details The new statement can also be used to resize a flexible array. If an array has been declared flexible using the syntax .

        var name : flexible array indexType { , indexType } of typeSpec
The indices may have compile-time or run-time upper bounds (the lower bound must be compile-time). The upper bounds can be changed by using:

        new name , newUpper1 {,newUpper2}
The existing array entries will retain their values, except that any index made smaller will have the corresponding array entries lost. Any index made larger will have the new array entries uninitialized (if applicable).

Additionally, the upper bound (both in the declaration and the new statement) can be made one less than the lower bound. This effectively makes an array that contains 0 elements. It can later be increased in size with another new.

In the current implementation (1999), with a multi-dimensional array with a non-zero number of total elements, it is a run-time error to change any but the first dimension (unless one of the new upper bounds is one less than the corresponding lower bound, giving 0 elements in the array) as the algorithm to rearrange the element memory locations has not yet been implemented.

Currently, only variables can be declared in this form. There is no flexible array parameter type, although a flexible array can be passed to an array parameter with "*" as the upper bound.

Example See array for an example of flexible arrays.

See also class and collection declarations, pointer type, free statement, nil value and implement by list.

For flexible arrays, see also array and flexible.


nil

nil pointer to a collection

Syntax nil [ (collectionOrClassId ) ]

Description The nil pointer does not locate any element (object). Pointers locate items in collections, classes and types. The collectionOrClassId is optional.

This nil pointer is distinct from pointers to actual elements, and it can be compared to these pointers. It is also distinct from the uninitialized pointer value.

Example In this example, the pointer called first is set to the nil pointer of collection c, that is, to nil(c).

        var c : collection of
            record
                name : string ( 50 )
                next : pointer to c
            end record
        var first : pointer to c := nil ( c )
Details See also collection, class and pointer. When nil is written without the collectionOrClassId, it can be assigned to a pointer to any collection, class or type.

The type of nil without the collectionOrClassId is effectively a pointer to everyClass, an imaginary class that has no objects and is the descendant of all classes. This implies that it can be assigned to any other class pointer, because it is a descendant of all classes.

Turing allows you to write nil (id) after a forward declaration of id (the name of a collection, class or type) before (and after) the resolution of the id.


not

not true/false (boolean) operator

Syntax not

Description The not (boolean negation) operator produces the opposite of a true/false value. For example, not (x >y) is equivalent to x <= y.

Example

        var error : boolean := false
        var success : boolean
        …
        success := not error    % success becomes the opposite of error
Details The not operator takes true and produces false and takes false and produces true. The not operator can be written as ~. See also the boolean type, prefix operators, and precedence of operators.

The not operator can be applied to sets.


objectclass

objectclass of a pointer

Syntax objectclass ( pointerExpn )

Description The objectclass attribute is used to find the class of an object located by a pointer. The pointerExpn must be an expression that is a pointer to a class.

Example See class for an example of classes and inheritance, in which a class called TextFile is inherited by a class called Device. The Device class adds a new exported procedure called ioCtl. In the present example, objectclass is used to test to make sure that the textFilePtr currently locates an object that was created as a Device (or as a descendant of Device). The notation Device(textFilePtr) converts the pointer to be a pointer to a Device so that ioCtl can be called.

        var textFilePtr : ^ TextFile
        …
        if objectclass ( textFilePtr ) >= Device then
            % Can safely treat object as a Device
            Device ( textFilePtr ) . ioCtl
            …
        end if
Details This example uses the class comparison operator >= which means "is a descendant of". See class.

You can only use objectclass in class comparisons. In particular, objectclass cannot be used to declare pointers. For example, this:

        var p : ^objectclass (q)
is not allowed.


opaque

opaque type

Description | When a type T is exported from module, monitor or class M using the keyword opaque, the type M.T is distinct from all other types. Opaque types are used to guarantee that updates to values of the type are done within M.
See also | module declarations for an example of an opaque type used to implement complex arithmetic. See also equivalence of types for the definition of the type matching rules for opaque types.


open

open file statement

Syntax An openStatement is one of:

(a) | open : fileNumberVar, fileName, ioCapability
 |  | { , ioCapability }
(b) | open : fileNumberVar, argNum, ioCapability
 |  | { , ioCapability }

Description The open statement connects the program to a file so the program can perform operations such as read on the file. In form (a), the open statement translates a fileName, such as "Master", to a file number such as 5. Form (b), which is less-commonly used, opens a file whose name is given by a program argument. This is described below.

The read statement uses the file number, not the file name, to access the file. When the program is finished using the file, it disconnects from the file using the close statement. Each ioCapability is the name of an operation, such as read, that is to be performed on the file.

Example This programs illustrates how to open, read and then close a file.

        var fileName : string := "Master"   % Name of file
        var fileNo : int                % Number of file
        var inputVariable : string ( 100 )
        open : fileNo, fileName, read
        …
        read : fileNo, inputVariable
        …
        close : fileNo
Details The open statement always sets the fileNumber to a positive number. If the open fails (generally because the file does not exist), the fileNumber is set to a non-positive number. It is wise to check that the stream number is greater than zero before using it further.

An ioCapability is one of:

get, put, read, write, seek, mod

A file can be accessed using only the statements corresponding to the input/output capabilities with which it was opened. Note: tell is allowed only if the open is for seek.

The open statement truncates the file to length zero if the ioCapabilities includes put or write but not mod (which stands for modify). In all other cases, open leaves the existing file intact. The mod ioCapability specifies that the file is to be modified without being truncated. Each open positions to the beginning of a file. There is no mechanism to delete a file.

To open for appending to the end of the file, one has to open for seek, mod and for write or put and then seek to the end of the file. See the seek statement.

Mixed mode files, which combine get and read (or put and write), are supported by some operating systems, such as UNIX, but not by others, such as Microsoft Windows.

On Microsoft Windows, one should note that opening files in other directories uses the backslash character. This is because the backslash is a special character in Turing (as in \t for tab and \n for a newline). To get a single backslash, use \\.

        e.g. open : f, "C:\\STUDENTS\\SMITH\\ACCT.DAT", put
Form (b) of the syntax allows you to open a file whose name is given as a program argument on the command line. For example, under UNIX, the command line:

        prog.x infile outfile
specifies to execute prog.x with program arguments infile and outfile. Similarly, in the Turing programming environment, the run command can accept program arguments. The argNumber is the position of the argument on the command line. (The first argument is number 1.) The name of the file to be opened is the corresponding program argument. If there is no such argument, or if the file cannot be opened successfully, fileNumberVariable is set to zero. See also nargs, which gives the number of arguments, and fetcharg, which gives the n-th argument string.

Program argument files referenced by argument number and used in put, get, read or write statements need not be explicitly opened, but are implicitly opened with the capability corresponding to the input/output statement in which they are first used. (The fileNumbergives the number of the argument.)

The operating system standard files (error, output and input) are accessed using file numbers 0, -1, and -2, respectively (although this may be subject to change). These files are not opened explicitly, but are used simply by using form (b) with the number. Beware of the anomalous case of a failed open that gives you file number 0. A subsequent use of this number in a put will produce output that goes to the standard error stream, with no warning that the file you attempted to open is not actually being used.

To append to a file, the file must be opened with the mod and seek capability and then there must be a seek to the end of file. For example:

        var streamnumber : int
        open : streamnumber, "myfile", put, mod, seek
        seek : streamnumber, *
        put : streamnumber, "This appears at the end of the file"
There is an older and still acceptable version of open that has this syntax:

        open ( var fileNumber : int, fileName : string, mode : string)
The mode must be "r" (for get) or "w " (for put).

Details The path name specified in the open statement and elsewhere can always be in UNIX format (i.e. with forward slashes, an initial forward slash indicating an absolute directory). On the PC, absolute paths would have the form:

            a:/dir1/dir2/filename
On the Macintosh, they would have the form:

            /volume name/directory1/directory2/file name
Note that in addition to the UNIX path format, on the PC, you can always use standard PC path notation and on the Macintosh, you can use standard Macintosh path notation. On the Macintosh volume, directory and file names can have spaces in them.

All routines (such as the File and Dir module routines) will return files names in UNIX format, regardless of the machine the program is run on.

See also close, get, put, read, write, seek and tell statements.


or

or operator

Syntax A or B

Description The or (boolean) operator yields a result of true if at least one (or both) of the operands is true. or is a short circuit operator. For example, if A is true in A or B then B is not evaluated.

Example

        var success : boolean := false
        var continuing := true  % the type is boolean
        …
        continuing := continuing or success
Details continuing is set to false, if and only if, both continuing and success are false. Since Turing uses short circuit operators, once continuing is true, success will not be looked at.

The or operator can be applied to natural numbers. The result is the natural number that is the bit-wise or of the operands. See nat (natural number).

See also boolean (which discusses true/false values), explicitTrueFalseConstant (which discusses the values true and false), precedence and expn (expression).


ord

ord character-to-integer function

Syntax | ord ( ch : char ) : int
Description | The ord function accepts an enumerated value, char, or a string of length 1, and returns the position of the value in the enumeration, or of the character in the ASCII (or EBCDIC for IBM mainframes) sequence. Values of an enumerated type are numbered left to right starting at zero. For example, ord ( "A" ) is 65. The ord function is the inverse of chr, so for any character c, chr ( ord (c)) = c.
See also | chr, intstr and strint functions.


parallelget

parallelget parallel port function

Syntax parallelget : int

Description The parallelget procedure is used on a PC to read the value of certain pins on the parallel port. This port corresponds to the MS-DOS device "LPT1". This procedure can be used to control robots and peripherals.

Example This program reads and prints the values of the five data pins of the PC's parallel port.

        const val : int := parallelget  % Read in the set of pin values
        put "Pin 10 is: ", (val div 64) mod 2
        put "Pin 11 is: ", (val div 128) mod 2
        put "Pin 12 is: ", (val div 32) mod 2
        put "Pin 13 is: ", (val div 16) mod 2
        put "Pin 15 is: ", (val div 8) mod 2
Details The five pins that are used for parallel input are pins 10-15. The parallelget procedure returns the sum of

64 | Pin 10 high
128 | Pin 11 high
32 | Pin 12 high
16 | Pin 13 high
8 | Pin 15 high

The mod and div operators can be used to determine which pins are high or low.

See also the parallelput procedure for a diagram of the pins. That procedure is used to set the values on the parallel port.


parallelput

parallelput parallel port procedure

Syntax parallelput ( p : int )

Description The parallelput procedure is used on a PC to set the values on the data pins on the parallel port. This port corresponds to the MS-DOS device "LPT1". This procedure can be used to control robots and peripherals.

Example This program sets data bit 0, data bit 1 and so on to data bit 7.

        for i : 0 .. 7
            parallelput (2 ** i)    %Set data bit i on the  parallel port
            put "Data bit ", i, "  or Pin ", i + 2, "has just been set"
        end for
Details The parallelput procedure is used to set the eight data bits on the PC's parallel port. These data bits 0 - 7 correspond to pins 2 - 9 on the parallel port.

The value sent to parallelput is the sum of the following:

1 | Data bit 0 | 16 | Data bit 4
2 | Data bit 1 | 32 | Data bit 5
4 | Data bit 2 | 64 | Data bit 6
8 | Data bit 3 | 128 | Data bit 7

For example, the command parallelput (97) sets data bits 0, 5 and 6 high (97 = 1 + 32 + 64) and sets the other data pins low. Because there are only 8 data pins in the parallel port, the value passed to parallelput must be from 0 to 255.

The parallelput procedure is not meant for sending a stream of characters to the parallel port (for example, if you want to send the string "Hello" to the printer). If you want to do this, open the file "LPT1" using the open statement and put to the file.

See also the parallelget function, which is used to read the values of pins on the parallel port.


paramDeclaration

paramDeclaration parameter declaration

Syntax A paramDeclaration is one of:

(a) | [ var ] id {, id } : typeSpec
(b) | subprogramHeader

Description A parameter declaration, which is part of the header of a procedure or function, specifies a formal parameter (see also procedure and function declarations). Form (a) above is the most common case. Form (b) specifies procedures and functions that are themselves passed as parameters.

Example

        procedure putTitle ( title : string )
            % The parameter declaration is: title : string
            put title
        end putTitle

        procedure x (var s : array 1 .. * of string (*))
            % Set each element of s to the null string
            for i : 1 .. upper ( s )
                s ( i ) := ""
            end for
        end x
Details Parameters to a procedure may be declared using var, which means that the parameter can be changed inside the procedure. For example, s is changed in the x procedure. If a parameter is declared without var, it cannot be changed. (This differs from Pascal, where non-var parameters can be changed.) Parameters to functions cannot be declared to be var.

Parameters declared var are passed by reference, which means that a pointer to the value is passed to the procedure, rather than passing the actual value. This implies that in the call p ( a (i)), in which array element a(i) is passed to procedure p, a change to i in p does not change the element referred to by p's actual parameter. Every non-scalar (not integer, subrange, real, boolean, enumerated, pointer or the char type) parameter is passed by reference whether or not it is declared var. In all other cases (scalar non-var parameters) the parameter is passed by value (the actual value is copied to the procedure).

The upper bound of an array or string that is a formal parameter may be specified as an asterisk (*), as is done above for parameter s in procedure x. This specifies that the size of the upper bound is inherited from the corresponding actual parameter. Parameters declared using star are called dynamic parameters.

The names of the formal parameters must be distinct from each other, from the procedure or function name, and from pervasive identifiers. However, they need not be distinct from names outside of the procedure or function.

Example Find the zero of function f. This example illustrates form (b), which is a parameter that is a function. See also subprogramHeader.

        function findZero ( function f ( x : real) : real,
                        left, right, accuracy : real ) : real
            pre sign ( f ( left ) ) not= sign ( f ( right)) )
                    and accuracy > 0
            var L : real := left
            var R : real := right
            var M : real
            const signLeft := sign ( f ( left ) )
            loop
                M := ( R + L) / 2
                exit when abs ( R - L ) <= accuracy
                if signLeft =sign ( f ( M ) ) then
                    L := M
                else
                    R := M
                end if
            end loop
            result M
        end findZero
Details Form (b) of paramDeclaration is used to specify formal parameters that are themselves procedures or functions. For example, in the findZero function, f is a formal parameter that is itself a function. The subprogram type can be used to replace form (b). In particular, the header to the findZero function can be replaced by the following with no change in the action. The names g and x serve no purpose, except as place holders in the declaration of f.

        function findZero ( f : function g ( x : real) : real,
                        left, right, accuracy : real ) : real
Details Parameters that are declared non var should, in principle, be constant. Unfortunately, there is an anomalous situation in which these can change. This occurs when the parameter is passed by reference, because it is a non scalar such as a string. If the actual parameter is changed while the subprogram is executing, the formal parameter will change as well.

You can also optionally use the register keyword to request that the variable be placed in a machine register. This changes form (a) to allow the optional use of the register keyword. The syntax for form (a) is actually:

        [ var ] [ register ] id {, id } : [ cheat ] typeSpec
In the current (1999) implementation, programs are run interpretively using pseudo-code, which has no machine registers, and the register keyword is ignored. See register for restrictions on the use of register parameters.

The optional keyword cheat means that the parameter has a type cheat. See cheat. Any variable or constant non scalar (in other words, items passed by reference) can be passed to a type cheat parameter. The internal representation will be interpreted as a value of the specified type. This is dangerous as it provides unconstrained access to the underlying computer memory.

Example This procedure outputs the values of n bytes starting at the address of formal parameter a, using a parameter type cheat.

        procedure dump (a : cheat array 0 .. 10000 of nat1, n : int )
            for i : 0 .. n - 1
                put i, a ( i ) : 4
            end for
        end dump

        var s : string := "abc"
        dump ( s, 5 )       % Dumps 5 bytes, starting with "abc"


pause

pause statement

Syntax A pauseStatement is:

pause expn

Description The pause statement blocks the program (or just the process in the case of a concurrent program) for a given number of simulated time units. The expn must be a non-negative int value giving the number of time units. This is analogous to the delay statement, which causes blocking for a given amount of real time (actual physical time).

The interpreter maintains a counter which it considers to be simulated time. The only execution that causes this counter to increase is the pause statement. The process executing the pause is blocked until the counter has counted forward the number of units given by expn. All other statements (except wait) are considered to be infinitely fast. Several processes can be executing pause statements simultaneously.

The use of simulated time allows Turing to be used as a simulation language in which the pause statement simulates the passage of time in the simulated system.


PC

Description This unit contains the predefined subprograms that deal with direct access to the hardware under the IBM PC architecture.

All routines in the PC unit are exported qualified (and thus must be prefaced with "PC.").

Entry Points
ParallelGet | Returns the value of the pins set on the parallel port.
ParallelPut | Sets the values of the pins on the parallel port.


PC.ParallelGet

PC.ParallelGet Part of PC module

Syntax PC.ParallelGet (port : int) : nat1

Description The PC.ParallelGet function is used to read the value of certain pins on a parallel port. The port is specified with the port parameter which can have the value 1, 2 or 3 corresponding to "LPT1", "LPT2" and "LPT3". This procedure can be used to control robots and peripherals.

Example This program reads and prints the values of the five data pins of the PC's parallel port.

        % Read in the set of pin values from LPT1
        const val : int := PC.ParallelGet (1)
        put "Pin 10 is: ", (val div 64) mod 2
        put "Pin 11 is: ", (val div 128) mod 2
        put "Pin 12 is: ", (val div 32) mod 2
        put "Pin 13 is: ", (val div 16) mod 2
        put "Pin 15 is: ", (val div 8) mod 2
Details The five pins that are used for parallel input are pins 10-15. The PC.ParallelGet procedure returns the sum of

64 | Pin 10 high
128 | Pin 11 high
32 | Pin 12 high
16 | Pin 13 high
8 | Pin 15 high

The mod and div operators can be used to determine which pins are high or low.

Status Exported qualified.

This means that you can only call the function by calling PC.ParallelGet, not by calling ParallelGet.

See also PC.ParallelPut procedure for a diagram of the pins. That procedure is used to set the values on the parallel port.


PC.ParallelPut

PC.ParallelPut Part of PC module

Syntax PC.ParallelPut (port : int, value : int)

Description The PC.ParallelPut procedure is used on a PC to set the values on the data pins on the parallel port. The port is specified with the port parameter which can have the value 1, 2 or 3 corresponding to "LPT1", "LPT2" and "LPT3". This procedure can be used to control robots and peripherals.

Example This program sets data bit 0, data bit 1 and so on to data bit 7.

        for i : 0 .. 7
            %Set data bit i on parallel port LPT2
            PC.ParallelPut (2, 2 ** i)
            put "Data bit ", i, "  or Pin ", i + 2, "has just been set"
        end for
Details The PC.ParallelPut procedure is used to set the eight data bits on the PC's parallel port. These data bits 0 - 7 correspond to pins 2 - 9 on the parallel port.

The value sent to PC.ParallelPut is the sum of the following:

1 | Data bit 0 | 16 | Data bit 4
2 | Data bit 1 | 32 | Data bit 5
4 | Data bit 2 | 64 | Data bit 6
8 | Data bit 3 | 128 | Data bit 7

For example, the command PC.ParallelPut (97) sets data bits 0, 5 and 6 high (97 = 1 + 32 + 64) and sets the other data pins low. Because there are only 8 data pins in the parallel port, the value passed to PC.ParallelPut must be from 0 to 255.

The PC.ParallelPut procedure is not meant for sending a stream of characters to the parallel port (for example, if you want to send the string "Hello" to the printer). If you want to do this, open the file "LPT1" using the open statement and put to the file.

Status Exported qualified.

This means that you can only call the function by calling PC.ParallelPut, not by calling ParallelPut.

See also PC.ParallelGet function, which is used to read the values of pins on the parallel port.


pervasive

pervasive declaration modifier

Description When a variable, constant, type or subprogram is declared, you can specify that it is to be pervasive, which means that it does not need to be explicitly imported into modules, monitors or classes in the current scope. The keyword pervasive can be abbreviated as an asterisk (*).

Example

        var pervasive counter : int % Short form: var * count : int
        const * maxCounter : int := 100
        procedure * p ( x : real )
            …
        end p
Details The keyword pervasive is also used in export lists along with the keyword unqualified. See export list for details.

See also var declaration, const declaration, procedure declaration, function declaration, subprogram header and export list for uses of pervasive.


Pic

Description This unit contains the predefined subprograms that deal with taking pictures of part of the screen, displaying them and moving pictures from file to screen and back.

All routines in the Pic unit are exported qualified (and thus must be prefaced with "Pic.").

Entry Points
New | Creates a picture from a specified portion of the screen.
Draw | Draws a picture on the screen.
DrawSpecial | Draws a picture on the screen using special effects.
DrawSpecialBack | Draws a picture on the screen while continuing execution using special effects.
Free | Frees up the picture created by using New or FileNew.
FileNew | Creates a picture from a file in an allowed format.
Save | Saves a picture as a file in an allowed format.
ScreenLoad | Displays a file in an allowed format on the screen directly.
ScreenSave | Saves a specified portion of the screen as a file in an allowed format.
Rotate | Creates a new picture by rotating an existing picture.
Scale | Creates a new picture by scaling an existing picture.
Flip | Creates a new picture by flipping an existing picture upside-down.
Mirror | Creates a new mirror-image of an existing picture.
Blend | Creates a new picture by blending two existing pictures together.
Blur | Creates a new picture by blurring an existing pictures.
Width | Returns the width of a picture.
Height | Returns the height of a picture.
Frames | Returns the the number of frames in a multi-frame GIF file.
FileNewFrames | Creates an array of pictures from a multi-frame GIF file.
DrawFrames | Draws a series of pictures on the screen in sequence while continuing execution.
DrawFramesBack | Draws a series of pictures on the screen in sequence.
SetTransparentColor | Sets the color to be ignored when using picMerge mode.
SetTransparentColour | Sets the color to be ignored when using picMerge mode.


Pic.Blend

Pic.Blend Part of Pic module

Syntax Pic.Blend (picID1, picID2, pct : int) : int

Description Pic.Blend is used to create a new picture by blending two identically sized pictures. The resulting picture is created by taking pct % of the first picture and adding it to (100 - pct) % of the second picture.

Details Note that the blended picture is a newly created picture. When it is no longer needed, its memory should be released by using Pic.Free.

Note that if pct is 100, then the resulting picture will be identical to picID1. if pct is 0, then the resulting picture will be identical to picID2.

Example The program creates two identically sized pictures, blends them together and displays all three pictures. You can vary the blend percentage to obtain different results.

        View.Set ("graphics:340;140,nobuttonbar")
        % Create the original pictures
        var pic1, pic2, picBlended : int
        Draw.FillBox (0, 0, 100, 100, brightred)
        Draw.FillOval (50, 50, 50, 50, brightblue)
        pic1 := Pic.New (0, 0, 100, 100)
        cls
        Draw.FillStar (10, 10, 90, 90, brightgreen)
        Draw.FillMapleLeaf(10, 10, 90, 90, brightred)
        pic2 := Pic.New (0, 0, 100, 100)
        cls
        % Create new picture by blending 30% from pic1, 70% from pic2
        picBlended := Pic.Blend (pic1, pic2, 30)
        % Draw the three images
        Pic.Draw (pic1, 10, 10, picCopy)
        Pic.Draw (pic2, 120, 10, picCopy)
        Pic.Draw (picBlended, 230, 10, picCopy)
Output from the Program

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Blend, not by calling Blend.


Pic.Blur

Pic.Blur Part of Pic module

Syntax Pic.Blur (picID, blurAmount : int) : int

Description Pic.Blur is used to create a new picture by blurring an existing picture. The resulting picture is created by mixing pixels in a picture with pixels adjacent to it. As the blurAmount increases, the image grows more and more blurry.

Details Note that the blurred picture is a newly created picture. When it is no longer needed, its memory should be released by using Pic.Free.

Note that this is a fairly CPU intensive routine. On slow machines, it can take up to a second or more when blurAmount is large. In such cases, it is better to precompute the pictures before starting the program. The second example shows this being done.

Example The program creates a picture and then progressively blurs it.
        View.Set ("graphics:270;120,nobuttonbar")
        % Create the original picture
        var f := Font.New ("serif:60:bold,italic,noantialias")
    Font.Draw ("Turing", 10, 30, f, red)
        Draw.FillStar (70, 80, 90, 100, brightgreen)
        Draw.FillBox (240, 5, 270, 35, brightblue)

        var oldPic : int
        oldPic := Pic.New (0, 0, maxx, maxy)
        loop
                var newPic : int
                % Create the new picture by blurring the old picture
            newPic := Pic.Blur (oldPic, 10)
            % Free the old picture so we don't run out of memory
            Pic.Free (oldPic)
                Pic.Draw (newPic, 0, 0, picCopy)
                delay (300)
                oldPic := newPic
        end loop
Output at start
After several loops
Execute

Execute By precalculating and saving the results of the blurred picture, you can produce a visual effect where an object seems to come into focus.
The program below blurs an image, saving each step. It then draws the images in reverse order, making it appear as if the image is becoming successively sharper.
Status Exported qualified.

This means that you can only call the function by calling Pic.Blur, not by calling Blur.


Pic.Draw

Pic.Draw Part of Pic module

Syntax Pic.Draw (picID, x, y, mode : int)

Description Pic.Draw is used to draw a picture on the screen. The picture is drawn with the lower left corner at (x, y).

The mode parameter has one of the following values:

picCopy | This draws the picture on top of what was underneath, obscuring it completely.
picXor | This draws the picture XORing it with the background. In DOS, you can use this function to do animation. Drawing an object on top of itself with XOR erases it and restores the background.
picMerge | This draws the picture like picCopy except that any occurrence of the background color in the picture is not drawn to the screen. This allows you to draw an irregularly-shaped object and draw it to the screen.
picUnderMerge | This draws the picture, but only where the background color was displayed underneath it. The effect of this is to make the picture appear to be displayed behind the background.

Execute

Details If the Pic.Draw call fails, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Display Modes with Pic.Draw

Example The program draws a graphic on the screen and then repeats it 50 times in random positions.

        var picID: int
        var x, y : int
        Draw.FillBox (50, 50, 150, 150, red)
        Draw.FillStar (50, 50, 150, 150, green)
        Draw.FillOval (100, 100, 30, 30, blue)

        picID := Pic.New (50, 50, 150, 150)
        for i : 1 .. 50
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            Pic.Draw (picID, x, y, picCopy)
        end for
        Pic.Free (picID)
Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Draw, not by calling Draw.

See also View.Update for information on how to produce smooth animation.

Pic.DrawSpecial for information on how to make pictures appear using special effects such as wipes and slides.

Pic.DrawFrames for information on how to display multiple frame images such as are obtained from GIF files.


Pic.DrawFrames

Pic.DrawFrames Part of Pic module

Syntax Pic.DrawFrames (picIds : array 1 .. * of int, x, y, mode : int,
numFrames, delayBetweenFrames : int, eraseAfter : boolean)

Description Pic.DrawFrames is used to draw a set of pictures stored in an array of ints. The pictures are displayed one at a time, and there is a delay of delayBetweenFrames milliseconds between frames. The x, y, and mode parameters are the same as in Pic.Draw. The numFrames parameter specifies the number of frames to be drawn (the picIds array must be at least this big). The eraseAfter parameter specifies whether the last frame of the animation should be left on the Run window when the call finishes. If eraseAfter is set to true, then the background is restored after the last picture has been drawn and delayBetweenFrames milliseconds has passed.

Details GIF files can contain multiple frames (pictures). Animated GIFs function by each frame in the GIF one after another with a delay between them.

Turing allows users to load multiple frame GIF images into a series of pictures into an array using the Pic.FileNewFrames procedure. The user can determine how many frames are found in the GIF file using Pic.Frames. The frames can be sequentially displayed using either Pic.DrawFrames or Pic.DrawFramesBack which display the images one at a time. (Pic.DrawFrames returns once all the images have been displayed, Pic.DrawFramesBack returns immediately allowing the program to continue execution while the frames are being displayed.

Pic.Frames is a function which returns the number of frames found in the GIF. If it is used on a GIF that does not contain multiple images, or on a non-GIF image file, it returns 1.

Example The program loads a multiple frame GIF called "globe.gif" and displays it.
        % Determine the number of frames in "globe.gif"
        var numFrames := Pic.Frames ("globe.gif")
        % Load the picture
        var delayTime : int
        var pics : array 1 .. numFrames of int

    Pic.FileNewFrames ("globe.gif", pics, delayTime)
    Pic.DrawFrames (pics, 10, 10, picCopy, numFrames, 50, false)
    for i : 1 .. numFrames

        Pic.Free (pics (i))
    end for
Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.DrawFrames, not by calling DrawFrames.

See also Pic.Frames for information on how to determine the number of frames in a GIF image.

Pic.FileNewFrames for information on how to load a GIF image with multiple frames into an array of ints.

Pic.DrawFramesBack for information on how to sequentially display the images stored in array of pictures while continuing to execute the program.


Pic.DrawFramesBack

Pic.DrawFramesBack Part of Pic module

Syntax Pic.DrawFramesBack (picIds : array 1 .. * of int, x, y, mode : int,
numFrames, delayBetweenFrames : int, eraseAfter : boolean)

Description Pic.DrawFramesBack is very similar to Pic.DrawFrames. The only difference is that Pic.DrawFramesBack returns immediately after being called and program execution continues while the frames are being drawn. This allows you to continue to draw other graphics while the frames are being drawn.

For example, this procedure is necessary if you want to have two sets of frames being drawn simultaneously.

Details If you are wish to have several sets of images displayed at the same time, you must use Pic.DrawFramesBack to display each set of images but the last and then use Pic.DrawFrames to display the last set so that Turing will wait until they are completed before continuing execution.

If you want to draw the same set of frames continuously, do not use Pic.DrawFramesBack.

for i : 1 .. 20
    Pic.DrawFrames (pics, 10, 10, picCopy, 10, 50, false)
    % Do not use Pic.DrawFramesBack in the previous statement
end for

If you do, Turing will attempt to run each of the calls at the same time, and the animation will appear to only run once.

Details GIF files can contain multiple frames (pictures). Animated GIFs function by each frame in the GIF one after another with a delay between them.

Turing allows users to load multiple frame GIF images into a series of pictures into an array using the Pic.FileNewFrames procedure. The user can determine how many frames are found in the GIF file using Pic.Frames. The frames can be sequentially displayed using either Pic.DrawFrames or Pic.DrawFramesBack which display the images one at a time. (Pic.DrawFrames returns once all the images have been displayed, Pic.DrawFramesBack returns immediately allowing the program to continue execution while the frames are being displayed.

Pic.Frames is a function which returns the number of frames found in the GIF. If it is used on a GIF that does not contain multiple images, or on a non-GIF image file, it returns 1.

Example The program loads a multiple frame GIF called "globe.gif" and displays it.
        % Determine the number of frames in "globe.gif"
        var numFrames := Pic.Frames ("globe.gif")
        % Load the picture
        var delayTime : int
        var pics : array 1 .. numFrames of int

    Pic.FileNewFrames ("globe.gif", pics, delayTime)
    for i : 1 .. 50
        Pic.DrawFramesBack (pics, 10, 10, picMerge, numFrames, 50, false)
        Pic.DrawFramesBack (pics, 20 + Pic.Width (pics(1)), 10, picMerge, numFrames, 50, false)
        % All 50 iterations will execute at once if the next call is
        % Pic.DrawFramesBack, and not Pic.DrawFrames
        Pic.DrawFrames (pics, 30 + 2 * Pic.Width (pics(1)), 10, picMerge, numFrames, 50, false)
    end for
    for i : 1 .. numFrames

        Pic.Free (pics (i))
    end for
Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.DrawFrames, not by calling DrawFrames.

See also Pic.Frames for information on how to determine the number of frames in a GIF image.

Pic.FileNewFrames for information on how to load a GIF image with multiple frames into an array of ints.

Pic.DrawFramesBack for information on how to sequentially display the images stored in array of pictures while continuing to execute the program.


Pic.DrawSpecial

Pic.DrawSpecial Part of Pic module

Syntax Pic.DrawSpecial (picID, x, y, mode, transition, duration : int)

Description Pic.DrawSpecial is used to draw a picture on the screen with a special effect such as a wipe, a slide, or a fade-in. The picture is drawn with the lower left corner at (x, y). The duration specifies how long the transition should take in milliseconds. For example, a fade-in could be specified to last 1/2 a second by using a duration of 500.

The mode parameter is the same as in Pic.New and has one of the following values:

picCopy | This draws the picture on top of what was underneath, obscuring it completely.
picXor | This draws the picture XORing it with the background. In DOS, you can use this function to do animation. Drawing an object on top of itself with XOR erases it and restores the background.
picMerge | This draws the picture like picCopy except that any occurrence of the background color in the picture is not drawn to the screen. This allows you to draw an irregularly-shaped object and draw it to the screen.
picUnderMerge | This draws the picture, but only where the background color was displayed underneath it. The effect of this is to make the picture appear to be displayed behind the background.

The transition parameter indicates the special effect and has one of the following values:

picWipeLeftToRight | The picture appears as a solid black bar sweeps from left to right, "revealing" the new picture as the screen underneath the picture is replaced. In the picture below, "to Turing" is replacing the "Welcome" underneath as the bar sweeps from left to right. picWipeLeftToRight - half way through transition
picWipeRightToLeft, picWipeTopToBottom, picWipeBottomToTop | As picWipeLeftToRight, except the bar sweeps in different directions.
picWipeUpperLeftToLowerRight | The picture appears as a solid black bar sweeps from the upper left corner down to the lower right, "revealing" the new picture as the screen underneath the picture is replaced. In the picture below "to Turing" is replacing the "Welcome" underneath as the bar sweeps from upper-left to lower-right. picWipeUpperLeftToLowerRight - half way through transition
picWipeUpperRightToLowerLeft, picWipeLowerLeftToUpperRight, picWipeLowerRightToUpperLeft | As picWipeLeftToRight, except the bar sweeps in different directions.
picWipeCentreToEdge, picWipeCenterToEdge | The picture appears inside an expanding black outlined box as it sweeps from the centre out to the edges, "revealing" the new picture as the screen underneath the picture is replaced. In the picture below, "to Turing" is replacing the "Welcome" underneath as the box expands from the centre out. picWipeCentreToEdge - half way through transition
picWipeLeftToRightNoBar, picWipeRightToLeftNoBar, picWipeTopToBottomNoBar, picWipeBottomToTopNoBar picWipeUpperLeftToLowerRightNoBar, picWipeUpperRightToLowerLeftNoBar, picWipeLowerLeftToUpperRightNoBar, picWipeLowerRightToUpperLeftNoBar, picWipeCentreToEdgeNoBar, picWipeCenterToEdgeNoBar | As the constants above, expect there is no bar to mark the sweep across. The bar generally looks better when displaying an image over top of a similar one. No bar is usually preferable when the images are completely different (as in two photographs, and so on).
picSlideLeftToRight | The picture "slides in" from the left as a solid black bar sweeps from left to right, "pushing" the screen underneath off the right edge of the drawing area. In the picture below "to Turing" is replacing the "Welcome" originally present, "pushing" the "Welcome" to the right as "to Turing" slides in from the left. picSlideLeftToRight - half way through transition
picSlideRightToLeft, picSlideTopToBottom, picSlideBottomToTop | As picSlideLeftToRight, except the bar sweeps in different directions.
picSlideLeftToRightNoBar, picSlideRightToLeftNoBar, picSlideTopToBottomNoBar, picSlideBottomToTopNoBar | As the constants above, expect there is no bar to mark the sweep across. The bar generally looks better when displaying an image over top of a similar one. No bar is often preferable when the images are completely different (as in two photographs, and so on).
picGrowLeftToRight | The picture "grows" from the left as a solid black bar sweeps from left to right, "squeezing" the screen underneath off the right edge of the drawing area. In the picture below "to Turing" is replacing the "Welcome" originally present, "squeezing" the "Welcome" to the right as "to Turing" "grows" from the left. picGrowLeftToRight - half way through transition
picGrowRightToLeft, picGrowTopToBottom, picGrowBottomToTop | As picGrowLeftToRight, except the bar sweeps in different directions.
picGrowCentreToEdge, picGrowCenterToEdge | The picture "grows" from the centre as a outlined black box sweeps from outward, replacing the screen underneath. In the picture below "to Turing" is replacing the "Welcome" originally present, as "to Turing" grows for the centre. picGrowCentreToEdge - half way through transition
picGrowLowerLeftToUpperRight | The picture "grows" from the lower-left corner as a outlined black box sweeps right and upward, replacing the screen underneath. In the picture below "to Turing" is replacing the "Welcome" originally present, as "to Turing" "grows" from the lower-left. picGrowLowerLeftToUpperRight - half way through transition
picGrowUpperLeftToLowerRight, picGrowLowerRightToUpperLeft, picGrowUpperRightToLowerLeft | As picGrowLowerLeftToUpperRight, except the box sweeps in different directions.
picGrowLeftToRightNoBar, picGrowRightToLeftNoBar, picGrowTopToBottomNoBar, picGrowBottomToTopNoBar picGrowUpperLeftToLowerRightNoBar, picGrowLowerLeftToUpperRightNoBar, picGrowUpperRightToLowerLeftNoBar, picGrowLowerRightToUpperLeftNoBar, picGrowCentreToEdgeNoBar, picGrowCenterToEdgeNoBar | As the constants above, expect there is no bar to mark the sweep across. The bar generally looks better when displaying an image over top of a similar one. No bar is usually preferable when the images are completely different (as in two photographs, and so on).
picFadeIn | The picture "fades in" over top of the image underneath it. At the end of the transition, the new image completely replaces the image underneath it. picFadeIn - half way through transition
picBlend | This transition is somewhat different because it doesn't take any time to execute. Instead, picBlend causes the new image to be blended with the background. The picBlend constant can be used by itself, in which case, the final image is 70% the new image, 30% the old image. You can also add a number from 1 to 100 to picBlend, in which case, the blend is whatever was added from (1-100) of the new image over top of the old image. (i.e. a transition of picBlend + 15 would display an image that is composed of 15% the new image and 85% the old image.) picBlend - red star blended with blue circle

Execute

Details The Pic.DrawSpecial requires a moderately fast machine to operate successfully (Pentium III or higher). The picFadeIn and picBlend transitions do not work well on 8-bit (256 color) displays. On Microsoft Windows machines, you can determine the bit-depth of the display (the number of colors available) by selecting the Display control panel from the Start menu. You can also use the

       Config.Display (cdNumMaxColors)

function to determine the bit-depth of the display (anything over 256 colors will produce acceptable results).

Details If the Pic.DrawSpecial call fails, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program draws a blue star on the screen, then a red circle, then proceeds to have to have the two replace each other with a variety of transitions.

        var redID, blueID: int
        var x, y : int
        Draw.FillStar (50, 50, 150, 150, brightred)
        redID := Pic.New (50, 50, 150, 150)
        cls
        Draw.FillOval (100, 100, 50, 50, brightblue)
        blueID := Pic.New (50, 50, 150, 150)
    Pic.DrawSpecial (redID, 50, 50, picCopy, picWipeLeftToRight, 500)
    Pic.DrawSpecial (blueID, 50, 50, picCopy, picWipeTopToBottom, 500)
    Pic.DrawSpecial (redID, 50, 50, picCopy, picSlideLeftToRight, 500)
    Pic.DrawSpecial (blueID, 50, 50, picCopy, picSlideTopToBottom, 500)
    Pic.DrawSpecial (redID, 50, 50, picCopy, picFadeIn, 1000)
    Pic.DrawSpecial (blueID, 50, 50, picCopy, picBlend + 50, 0)
        Pic.Free (redID)
        Pic.Free (blueID)

Execute

Execute The following program demonstrates each of the different special effects, first using pictures containing text, then pictures loaded from photographs, then both at once.
Status Exported qualified.

This means that you can only call the function by calling Pic.DrawSpecial, not by calling DrawSpecial.

See also Pic.Draw for information on the meaning of the mode argument.

Pic.DrawSpecialBack for information on how to continue executing the program while a special effect is occurring. This allows one to produce several special effects at once.


Pic.DrawSpecialBack

Pic.DrawSpecialBack Part of Pic module

Syntax Pic.DrawSpecialBack (picID, x, y, mode, transition, duration : int)

Description Pic.DrawSpecialBack is very similar to Pic.DrawSpecial. The only difference is that Pic.DrawSpecialBack returns immediately after being called and program execution continues while the special effect continues. This allows you to continue to draw other graphics while the special effect is continuing.

For example, this procedure is necessary if you want to have two pictures being drawn using special effects simultaneously.

Details If you are wish to have several images displayed at the same time using special effects, you must use Pic.DrawSpecialBack to display all the images but the last and then use Pic.DrawSpecial to display the last image so that Turing will wait until the special effects are completed before continuing execution.

If you want to draw the several special effects continuously over the same location, do not use Pic.DrawSpecialBack.

Pic.DrawSpecial (pic1, 10, 10, picCopy, picWipeLeftToRight, 500)
Pic.DrawSpecial (pic2, 10, 10, picCopy, picFadeIn, 1000)

If you do, Turing will attempt to run each of the calls at the same time, and most of the special effects will not be seen.

Description Pic.DrawSpecialBack is used to draw a picture on the screen with a special effect such as a wipe, a slide, or a fade-in. Note that all the parameters are identical to the parameters of Pic.DrawSpecial. The picture is drawn with the lower left corner at (x, y). The duration specifies how long the transition should take in milliseconds. For example, a fade-in could be specified to last 1/2 a second by using a duration of 500.

The mode parameter is the same as in Pic.New and has one of the following values:

picCopy | This draws the picture on top of what was underneath, obscuring it completely.
picXor | This draws the picture XORing it with the background. In DOS, you can use this function to do animation. Drawing an object on top of itself with XOR erases it and restores the background.
picMerge | This draws the picture like picCopy except that any occurrence of the background color in the picture is not drawn to the screen. This allows you to draw an irregularly-shaped object and draw it to the screen.
picUnderMerge | This draws the picture, but only where the background color was displayed underneath it. The effect of this is to make the picture appear to be displayed behind the background.

See Pic.DrawSpecial for the list of possible values for the transition parameter.

Details The Pic.DrawSpecialBack requires a moderately fast machine to operate successfully (Pentium III or higher). The picFadeIn and picBlend transitions do not work well on 8-bit (256 color) displays. On Microsoft Windows machines, you can determine the bit-depth of the display (the number of colors available) by selecting the Display control panel from the Start menu. You can also use the

       Config.Display (cdNumMaxColors)

function to determine the bit-depth of the display (anything over 256 colors will produce acceptable results).

Details If the Pic.DrawSpecialBack call fails, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program draws a blue star on the screen, then a red circle, then proceeds to have to have the two replace each simultaneously, side-by-side.

        var redID, blueID: int
        Draw.FillStar (0, 0, 100, 100, brightred)
        redID := Pic.New (0, 0, 100, 100)
        cls
        Draw.FillOval (50, 50, 50, 50, brightblue)
        blueID := Pic.New (0, 0, 100, 100)
        cls
    Pic.DrawSpecialBack (redID, 10, 10, picCopy, picWipeLeftToRightNoBar, 1000)
    Pic.DrawSpecial (blueID, 160, 10, picCopy, picWipeRightToLeftNoBar, 1000)
    Pic.DrawSpecialBack (blueID, 10, 10, picCopy, picSlideLeftToRightNoBar, 1000)
    Pic.DrawSpecial (redID, 160, 10, picCopy, picSlideRightToLeftNoBar, 1000)
    Pic.DrawSpecialBack (redID, 10, 10, picCopy, picGrowRightToLeftNoBar, 1000)
    Pic.DrawSpecial (blueID, 160, 10, picCopy, picGrowLeftToRightNoBar, 1000)
    Pic.DrawSpecialBack (blueID, 10, 10, picCopy, picWipeTopToBottomNoBar, 1000)
    Pic.DrawSpecial (redID, 160, 10, picCopy, picWipeTopToBottomNoBar, 1000)
    Pic.DrawSpecialBack (redID, 10, 10, picCopy, picFadeIn, 1000)
    Pic.DrawSpecial (blueID, 160, 10, picCopy, picFadeIn, 1000)
        Pic.Free (redID)
        Pic.Free (blueID)

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.DrawSpecialBack, not by calling DrawSpecialBack.

See also Pic.Draw for information on the meaning of the mode argument.

Pic.DrawSpecial for information on how to draw special effects and wait for completion of the effect.


Pic.FileNew

Pic.FileNew Part of Pic module

Syntax Pic.FileNew (fileName : string) : int

Description Pic.FileNew is used to obtain a picture from a file. The Pic.FileNew procedure allocates the memory for the picture, which can be very large for pictures of large areas. The memory is freed up when the program calls Pic.Free with the picture ID. The picture can be used with the Pic.Draw and Pic.Save.

The fileNameparameter must give the format of the file:

GIF files | "GIF:filename" or "filename.GIF"
JPG files | "JPG:filename" or "filename.JPG"
BMP files | "BMP:filename" or "filename.BMP"

Details Various versions of Turing can convert different formats of files. Turing 4.1 for Windows can load BMP, GIF and JPG files.

Details For, multi-frame GIF files (GIF files that have several frames or pictures and are used for animation), Pic.FileNew will only load the first frame. See the Pic.FileNewFrames and Pic.Frame for information on loading and displaying a multi-frame GIF file.
Details If the Pic.FileNew call fails, then it returns 0. Also Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program reads a graphic from the file mypic.bmp and then draws it 50 times.

        var picID: int
        var x, y : int

        picID := Pic.FileNew ("mypic.bmp")
        for i : 1 .. 50
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            Pic.Draw (picID, x, y, picCopy)
        end for
        Pic.Free (picID)
Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.FileNew, not by calling FileNew.


Pic.FileNewFrames

Pic.FileNewFrames Part of Pic module

Syntax Pic.FileNewFrames (pathName : string, var picIDs : array 1 .. * of int, var delayTime : int)

Description Pic.FileNewFrames loads multiple pictures stored in a single multiframe GIF image file into an array of integers.
Details GIF files can contain multiple frames (pictures). Animated GIFs function by displaying each frame in the GIF one after another with a delay between them. This delay can also be specified in the GIF file.

Pic.FileNewFrames reads the series of frames from the multiframe GIF file, and turns each frame into a picture. The picture is then assigned to an element in the picIDs array. If the array is not large enough, then an error occurs and no pictures are loaded.

Pic.FileNewFrames also reads the delay specified in the GIF file and sets delayTime to the delay in milliseconds. Note that many multiple frame GIF files do not specify a delay, in which case delayTime will be set to 0.

In order to determine the number of frames in multiple frame GIF file, you must use the Pic.Frames function. This returns a number that can be used to declare the array that will be passed to Pic.FileNewFrames.

var numFrames = Pic.Frames ("mypic.gif")
var pics : array 1 .. numFrames of int
var delayTime : int
Pic.FileNewFrames ("mypic.gif", pics, delayTime)

The frames can be sequentially displayed using either Pic.DrawFrames or Pic.DrawFramesBack which display the images one at a time. (Pic.DrawFrames returns once all the images have been displayed, Pic.DrawFramesBack returns immediately allowing the program to continue execution while the frames are being displayed.

Details GIF files can have a transparent color. This color will be added to the color palette, if not already present. Thus you may notice that maxcolor changes after calling Pic.FileNew or Pic.FileNewFrames. The GIF image will be be displayed without the transparent color if mode parameter in any of the Pic.Draw... procedures is set to picMerge.

Details Each picture is in the array has been allocated by the system and should be freed separately once the program is finished with the pictures. Failing to do so can use up the system's memory.

Example The program loads a multiple frame GIF called "globe.gif" and displays it.
        % Determine the number of frames in "globe.gif"
        % Create the original picture
        var numFrames := Pic.Frames ("globe.gif")
        % Load the picture
        var delayTime : int
        var pics : array 1 .. numFrames of int

    Pic.FileNewFrames ("globe.gif", pics, delayTime)
    Pic.DrawFrames (pics, 10, 10, picCopy, numFrames, 50, false)

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.FileNewFrames, not by calling FileNewFrames.

See also Pic.Frames for information on how to determine the number of frames in a GIF image.

Pic.DrawFrames for information on how to sequentially display the images stored in array of pictures.

Pic.DrawFramesBack for information on how to sequentially display the images stored in array of pictures while continuing to execute the program.


Pic.Flip

Pic.Flip Part of Pic module

Syntax Pic.Flip (picID : int) : int

Description Pic.Flip is used to create a new picture by flipping the picture vertically. The resulting picture is exactly the same size as the original, except it appears “upside-down”.

Details Note that the upside-down picture is a newly created picture. When it is no longer needed, its memory should be released by using Pic.Free.

Example The program loads a picture from a file, flips it and then draws the original and the upside-down image side by side in a window after resizing the window to fit the two pictures.

        % Get the original picture
        var pic, newPic, width, height : int
        pic := Pic.FileNew ("lighthouse.jpg")
        newPic := Pic.Flip (pic)
        width := Pic.Width (pic)
        height := Pic.Height (pic)

        % Draw the two images: original and flipped
        View.Set ("graphics:" + intstr (2 * width + 30) + ";" +
            intstr (height + 25) + ",nobuttonbar")
        Pic.Draw (pic, 10, 20, picCopy)
        Draw.Text ("Original", 50, 5, defFontID, black)
        Pic.Draw (newPic, 20 + Pic.Width (pic), 20, picCopy)
        Draw.Text ("Flipped", 60 + Pic.Width (pic), 5, defFontID, black)
Output from the Program

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Flip, not by calling Flip.


Pic.Frames

Pic.Frames Part of Pic module

Syntax Pic.Frames (pathName : string) : int

Description Pic.Frames is used to determine the number of frames found in a multiple frame GIF file.

Details GIF files can contain multiple frames (pictures). Animated GIFs function by each frame in the GIF one after another with a delay between them.

Turing allows users to load multiple frame GIF images into a series of pictures into an array using the Pic.FileNewFrames procedure. The user can determine how many frames are found in the GIF file using Pic.Frames. The frames can be sequentially displayed using either Pic.DrawFrames or Pic.DrawFramesBack which display the images one at a time. (Pic.DrawFrames returns once all the images have been displayed, Pic.DrawFramesBack returns immediately allowing the program to continue execution while the frames are being displayed.

Pic.Frames is a function which returns the number of frames found in the GIF. If it is used on a GIF that does not contain multiple images, or on a non-GIF image file, it returns 1.

Example The program loads a multiple frame GIF called "globe.gif" and displays it.
        % Determine the number of frames in "globe.gif"
        var numFrames := Pic.Frames ("globe.gif")
        % Load the picture
        var delayTime : int
        var pics : array 1 .. numFrames of int

    Pic.FileNewFrames ("globe.gif", pics, delayTime)
    Pic.DrawFrames (pics, 10, 10, picCopy, numFrames, 50, false)

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Frames, not by calling Frames.

See also Pic.FileNewFrames for information on how to load a GIF image with multiple frames into an array of ints.

Pic.DrawFrames for information on how to sequentially display the images stored in array of pictures.

Pic.DrawFramesBack for information on how to sequentially display the images stored in array of pictures while continuing to execute the program.


Pic.Free

Music.Sound (440, 30) Pic.Free
Pic.Free Part of Pic module

Syntax Pic.Free (picID : int)

Description Pic.Free is used to release the memory allocated by Pic.New. It frees up the memory allocated to the parameter picID. This means that picID can not be used in a Draw.Pic or Draw.Save procedure after Pic.Free is called.

Turing has a limited number of pictures that are available at any one time (approximately 1,000). A program that continuously allocates pictures (using Pic.New or Pic.FileNew) will eventually fail if it does not free the pictures using Pic.Free. As well, if a program allocates hundreds of pictures and does not free any of them, the memory devoted to the pictures will not be freed and eventually the program may exhaust the memory on the machine.

Details If Pic.Free is passed an invalid picture ID, a fatal error occurs. If the Pic.Free call fails for other (non-fatal) reasons, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program animates a picture moving across a background. Each time the picture is about to move to a new location, a picture of the background at that location is taken. When the picture is to be moved to the next location, the background picture is drawn over top of the picture, thus "erasing" it. The Pic.Free command frees up each background picture once it is no longer in use. Without it, the program would use up all the picture identifiers and crash after one or two moves across the window.

The animation in the example flickers slightly. See View.Update for information on how to produce flicker-free animation.

        var picID, bgID : int
        var x, y, c, direction : int

        % Create the picture being moved
        Draw.FillBox (50, 50, 150, 150, brightred)
        Draw.FillStar (50, 50, 150, 150, brightgreen)
        Draw.FillOval (100, 100, 30, 30, brightblue)
        picID := Pic.New (50, 50, 150, 150)

        % Create a background
        for i : 1 .. 1000
            x := Rand.Int (0, maxx)
            y := Rand.Int (0, maxy)
            c := Rand.Int (9, 15)    % Use bright colors
            Draw.FillBox (x, y, x + 30, y + 30, c)
        end for

        x := 1
        y := 100
        direction := 1
        % Main loop
        loop
            % Take a picture of the background
            bgID := Pic.New (x, y, x + 100, y + 100)
            Pic.Draw (picID, x, y, picCopy)     % Draw the picture
            delay (20)                          % Delay 20 milliseconds
            Pic.Draw (bgID, x, y, picCopy)      % Draw the background over the picture
            Pic.Free (bgID)                     % Free the background
            if x <= 0 or (x + 100) >= maxx then
                direction := -direction
            end if
            x += direction
        end loop
Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Free, not by calling Free.


Pic.Height

Pic.Height Part of Pic module

Syntax Pic.Height (picID : int) : int

Description Pic.Height returns the width in pixels of the picture represented by picID.

This function is often used in conjunction with Pic.Width to obtain the dimensions of a picture loaded using Pic.FileNew.

Example The program draws loads a picture from the file lighthouse.jpg and proceeds to tile the entire run window with copies of the picture.

        var pic : int := Pic.FileNew ("lighthouse.jpg")
        var width : int := Pic.Width (pic)
        var height : int := Pic.Height (pic)
        var x, y : int := 0
        loop
            exit when y > maxy
            loop
                exit when x > maxx
                Pic.Draw (pic, x, y, picCopy)
                x := x + width
            end loop
            x := 0
            y := y + height
        end loop
Output of Example Program

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Height, not by calling Height.

See also Pic.Width to obtain a picture's width and Pic.FileNew to load a picture from a graphics file.


Pic.Mirror

Pic.Mirror Part of Pic module

Syntax Pic.Mirror (picID : int) : int

Description Pic.Mirror is used to create a new picture by flipping the picture horizontally. The resulting picture is exactly the same size as the original, except it appears as a “mirror image”.

Details Note that the mirror-imaged picture is a newly created picture. When it is no longer needed, its memory should be released by using Pic.Free.

Example The program draws a crescent on the screen, takes a picture of it and then creates a second picture by mirror-imaging the crescent. It then draws both the original picture and the mirror-imaged version.

        View.Set ("graphics:210;125,nobuttonbar")

        % Get the original picture
        var pic, newPic : int
        Draw.FillOval (50, 50, 50, 50, brightred)
        Draw.FillOval (70, 50, 50, 50, colorbg)
        Draw.Text ("BLUE", 40, 60, defFontID, brightblue)
        Draw.Text ("MOON", 40, 40, defFontID, brightblue)
        pic := Pic.New (0, 0, 100, 100)
        newPic := Pic. Mirror (pic)
        cls

        % Draw the two images: original and flipped
        Pic.Draw (pic, 10, 20, picCopy)
        Draw.Text ("Original", 10, 5, defFontID, black)
        Pic.Draw (newPic, 110, 20, picCopy)
        Draw.Text ("Flipped", 140, 5, defFontID, black)
Output from the Program

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Mirror, not by calling Mirror.


Pic.New

Pic.New Part of Pic module

Syntax Pic.New (x1, y1, x2, y2 : int) : int

Description Pic.New is used to obtain a picture of a portion of the screen. The Pic.New procedure allocates the memory for the picture, which can be very large for pictures of large areas. The memory is freed up when the program calls Pic.Free with the picture ID. The picture can be used with the Pic.Draw and Pic.Save.

The picture is of the screen area defined by the rectangle (x1, y1) - (x2, y2).

Details If the Pic.New call fails, then it returns 0. Also Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program draws a graphic on the screen and then draws it 50 times.

        var picID: int
        var x, y : int
        Draw.FillBox (50, 50, 150, 150, red)
        Draw.FillStar (50, 50, 150, 150, green)
        Draw.FillOval (100, 100, 30, 30, blue)

        picID := Pic.New (50, 50, 150, 150)
        for i : 1 .. 50
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            Pic.Draw (picID, x, y, picCopy)
        end for
        Pic.Free (picID)
Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.New, not by calling New.


Pic.Rotate

Pic.Rotate Part of Pic module

Syntax Pic.Rotate (picID, angle, x, y : int) : int

Description Pic.Rotate is used to create a new picture by rotating an already existing picture. Rotation can either be around a specific point in the picture (often used for rotating a picure in place) or just a general rotation.

The angle is specified in degrees. The rotation is done in a counter-clockwise direction. The original picture is not modified by the call to Pic.Rotate and must still be freed when no longer used. The picture produced by Pic.Rotate may be a different size than the original picture.

The (x, y) point is the point around which the rotation is to take place and is relative to the picture being rotated. If it is not important to rotate the picture in place, x and y should be set to -1, which make the new picture the minimum size required to fit the rotated image.

Details The Pic.Rotate command can fail, in which case it returns 0. The Error.LastMsg function can then be used to obtain more information about the failure.

Details If x and y are set to a point in the picture (rather than 1), it is possible for parts of the original picture to be rotated off the left and bottom edge of the new picture. This occurs because Pic.Rotate guarantees that the point specified by (x, y) in the original picture will be located at (x, y) in the rotated picture. You can avoid losing parts of the picture by making certain there is a margin of background color on the left and bottom sides of the picture.

As well, any pixels in the rotated picture that were not part of the original picture are set to the background color.

Details Rotation can be slow on older machines. Programs that are using animation should create and store all the rotated images that may be needed. Often pictures of an object at various angles are stored in an array.

Example This program draws “Hello” on the screen rotated at 0, 45 and 90 degrees.

        View.Set ("graphics:200;150,nobuttonbar")
        var f : int := Font.New ("Serif:36")
        Font.Draw ("Hello", 10, 10, f, black)
        var pic : int := Pic.New (5, 5, 120, 45)
        var pic45 : int := Pic.Rotate (pic, 45, -1, -1)
        var pic90 : int := Pic.Rotate (pic, 90, -1, -1)
        Pic.Draw (pic45, 5, 50, picCopy)
        Pic.Draw (pic90, 150, 5, picCopy)
Output from Program

Execute

Example This program moves a spinning “Hello” around the screen, bouncing it off the edges of the output window. Notice that the original picture contains adequate space on the left and bottom sides to contain the rotation.

        View.Set ("graphics:300;250,nobuttonbar")
        var pic : array 0 .. 35 of int
        var f : int := Font.New ("Serif:36")
        const CTR : int := 57
        Font.Draw ("Hello", 5, 45, f, black)
        Draw.FillOval (CTR, CTR, 3, 3, brightred)
        pic (0) := Pic.New (0, 0, 115, 115)
        cls
        for angle : 1 .. 35
            pic (angle) := Pic.Rotate (pic (0), angle * 10, CTR, CTR)
        end for

        var x : int := CTR
        var y : int := CTR
        var dx : int := 1
        var dy : int := 1
        loop
            for angle : 0 .. 35
                Pic.Draw (pic (angle), x  - CTR, y - CTR, picCopy)
                if x + dx < CTR or x + dx > maxx - CTR then
                    dx := dx
                end if
                if y + dy < CTR or y + dy > maxy - CTR then
                    dy := dy
                end if
                x += dx
                y += dy
                delay (50)
            end for
        end loop
Execute

Details Note that the rotated picture is a newly created picture. When it is no longer needed, its memory should be released by using Pic.Free.

Status Exported qualified.

This means that you can only call the function by calling Pic.Rotate, not by calling Rotate.


Pic.Save

Pic.Save Part of Pic module

Syntax Pic.Save (picID : int, fileName : string)

Description Pic.Save is used to save a picture on the screen to a file.

The fileNameparameter must give the format of the file:

BMP files "BMP:filename" or "filename.BMP"

Details Various versions of Turing can save different formats of files. Turing 4.1 for Windows can save only BMP format files, as they are loss-less and can handle 24-bit depth images.

Details If Pic.Save is passed an invalid picture ID, a fatal error occurs. If the Pic.Save call fails for other (non-fatal) reasons, Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program draws a graphic on the screen and then saves it as a BMP file.

        var picID: int
        var x, y : int
        Draw.FillBox (50, 50, 150, 150, red)
        Draw.FillStar (50, 50, 150, 150, green)
        Draw.FillOval (100, 100, 50, 50, blue)

        picID := Pic.New (50, 50, 150, 150)
        Pic.Save (picID, "BMP:mypic.dat")
        Pic.Free (picID)
Example The following two programs save and load a file in BMP format.

        % Program to save a picture in mypic.bmp
        var picID: int
        var x, y : int
        Draw.FillBox (50, 50, 150, 150, red)
        Draw.FillStar (50, 50, 150, 150, green)
        Draw.FillOval (100, 100, 50, 50, blue)
        picID := Pic.New (50, 50, 150, 150)
        Pic.Save (picID, "mypic.bmp")
        Pic.Free (picID)

        % Program to load the picture back again and draw 50 copies
        var picID: int
        var x, y : int

        picID := Pic.FileNew ("mypic.bmp")
        for i : 1 .. 50
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            Pic.Draw (picID, x, y, picCopy)
        end for
        Pic.Free (picID)
Status Exported qualified.

This means that you can only call the function by calling Pic.Save, not by calling Save.


Pic.Scale

Pic.Scale Part of Pic module

Syntax Pic.Scale (picID, newWidth, newHeight : int) : int

Description Pic.Scale is used to create a new picture by scaling (resizing) an already existing picture. Rotation can either be around a specific point in the picture (often used for rotating a picure in place) or just a general rotation.

The newWidth and newHeight parameters are the desired width and height of the new picture. The newWidth and newHeight parameters may be negative, in which case the picture is mirror image (newWidth is negative) or upside-down (newHeight is negative) and the absolute values are used for the new width and height values.

Details The Pic.Scale command can fail, in which case it returns 0. The Error.LastMsg function can then be used to obtain more information about the failure.

Details Creating a larger picture by scaling a smaller picture will result in a "grainy" image with each pixel being scaled up into 2 or 3 pixels. In general image quality is better if a large picture is scaled down. However, when a large picture is scaled down, thin one-pixel wide lines can "disappear".

In order to scale a picture while retaining its original aspect ratio, scale with multiples of the original width and height. The width and height of a picture can be obtained using Pic.Width and Pic.Height.

Details Scaling can be slow on older machines. Programs that are using animation should create and store all the scaled images that may be needed. Often pictures of an object at various sizes are stored in an array.

Details Note that the scaled picture is a newly created picture. When it is no longer needed, its memory should be released by using Pic.Free.

Example This program draws a set of stars scaled at 50%, 100% and 150% on different axes. Note how some single-pixel lines are removed when the picture is scaled down..

        % The "Pic.Scale Example" program.
        const STAR_SIZE : int := 70

        var pic : int
        var newPic : int
        var picWidth, picHeight : int

        % Get the original picture
        Draw.FillStar (0, 0, STAR_SIZE, STAR_SIZE, brightred)
        Draw.Box (0, 0, STAR_SIZE, STAR_SIZE, green)
        pic := Pic.New (0, 0, STAR_SIZE, STAR_SIZE)
        cls

        picWidth := Pic.Width (pic)
        picHeight := Pic.Height (pic)

        for x : 1 .. 3
            for y : 1 .. 3
                newPic := Pic.Scale (pic, x * picWidth div 2,
                    y * picHeight div 2)
                Pic.Draw (newPic, (x - 1) * maxx div 3 + 5,
                    (y - 1) * maxy div 3 + 20, picCopy)
                Pic.Free (newPic)
                Draw.Text (realstr (x / 2, 0) + " x " + realstr (y / 2, 0),
                            (x - 1) * maxx div 3 + 5, (y - 1) * maxy div 3 + 5,
                    defFontID, black)
            end for
        end for
Output from Program

Execute

Status Exported qualified.

This means that you can only call the function by calling Pic.Scale, not by calling Scale.


Pic.ScreenLoad

Pic.ScreenLoad Part of Pic module

Syntax Pic.ScreenLoad (fileName : string, x, y, mode : int)

Description Pic.ScreenLoad displays a picture from a file straight to the screen.

The fileNameparameter must give the format of the file:

JPG files | "JPG:filename" or "filename.JPG"
BMP files | "BMP:filename" or "filename.BMP"

The x and y parameters set the lower left hand corner of the picture.

The mode parameter has one of the following values:

picCopy | This draws the picture on top of what was underneath, obscuring it completely.
picXOR | This draws the picture XORing it with the background. In DOS, you can use this function to do animation. Drawing an object on top of itself with XOR erases it and restores the background.
picMerge | This draws the picture like picCopy except that any occurrence of the background color in the picture is not drawn to the screen. This allows you to draw an irregularly-shaped object and draw it to the screen.
picUnderMerge | This draws the picture, but only where the background color was displayed underneath it. The effect of this is to make the picture appear to be displayed behind the background.

Details Various versions of Turing can convert different formats of files. Turing 4.1 for Windows can load BMP files and JPG files. Unfortunately, due to strictly enforced patents on the GIF compression algorithm, Turing will not implement importation of GIF pictures until the patents expire in June 2004.

Details At the time of writing, MacOOT supported only PICT files. Consult the release notes to find out which file formats are currently supported.

Details If the Pic.ScreenLoad fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program displays a picture on the screen from the PCX file mypic.BMP.

        Pic.ScreenLoad ("mypic.bmp", 0, 0, picCopy)
Status Exported qualified.

This means that you can only call the function by calling Pic.ScreenLoad, not by calling ScreenLoad.


Pic.ScreenSave

Pic.ScreenSave Part of Pic module

Syntax Pic.ScreenSave (x1, y1, x2, y2 : int, fileName : string)

Description Pic.ScreenSave saves a portion of the screen into a file in a format specified by the file name.

The picture saved to the file is the portion of the screen defined by the rectangle (x1, y1) - (x2, y2).

The fileNameparameter must give the format of the file:

BMP files "BMP:filename" or "filename.BMP"

Details Various versions of Turing can save different formats of files. Turing 4.1 for Windows can save BMP. Unfortunately, due to strictly enforced patents on the GIF compression algorithm, Turing will not implement saving of GIF pictures until the patents expire in June 2004.

Details If the Pic.ScreenSave fails, then Error.Last will return a non-zero value indicating the reason for the failure. Error.LastMsg will return a string which contains the textual version of the error.

Example The program draws a graphic and saves it as a PICT file called draw.

        Draw.FillBox (50, 50, 150, 150, red)
        Draw.FillStar (50, 50, 150, 150, green)
        Draw.FillOval (100, 100, 50, 50, blue)

        picID := Pic.ScreenSave (50, 50, 150, 150, "PICT:draw")
Status Exported qualified.

This means that you can only call the function by calling Pic.ScreenSave, not by calling ScreenSave.


Pic.SetTransparentColor

Pic.SetTransparentColor Part of Pic module

Syntax Pic.SetTransparentColor (colorNumber : int)
Description The Pic.SetTransparentColor procedure sets the color in the picture that should be considered transparent when the picture is drawn using the picMerge or picUnderMerge modes. If no color is specified, then the default background color (colorbg, usually white) is used as the transparent color.

Details This call is often used when displaying images that were originally stored as GIFs and translated into another format. Many GIFs have a transparent color that can be non-white. To use this call, you must know the color number that represents the color in the image that is to be transparent.

Example This program displays two images loaded from the same file. In the second image,the transparent color has been set to bright red (that is, the parts of the image that are meant to be transparent are in bright red).

        var pic1 : int := Pic.FileNew ("airplane.bmp")
        var pic2 : int := Pic.FileNew ("airplane.bmp")
        Pic.SetTransparentColor (pic2, brightred)
        setscreen ("offscreenonly")
        for x : 100 .. maxx - 100
            cls
            put "The lower image has the transparent color set to bright red"
            Pic.Draw (pic1, x, 150, picMerge)
            Pic.Draw (pic2, x, 50, picMerge)
            View.Update
            delay (5)
        end for

Execute

Details Pic.SetTransparentColour is an alternate spelling for Pic.SetTransparentColor.
Status Exported qualified.

This means that you can only call the function by calling Pic.SetTransparentColor, not by calling SetTransparentColor.

See also Pic.Draw and Pic.FileNew.


Pic.Width

Pic.Width Part of Pic module

Syntax Pic.Width (picID : int) : int

Description Pic.Width returns the width in pixels of the picture represented by picID.

This function is often used in conjunction with Pic.Height to obtain the dimensions of a picture loaded using Pic.FileNew.

Example The program draws loads a picture from the file lighthouse.jpg and proceeds to tile the entire run window with copies of the picture..

        var pic : int := Pic.FileNew ("lighthouse.jpg")
        var width : int := Pic.Width (pic)
        var height : int := Pic.Height (pic)
        var x, y : int := 0
        loop
            exit when y > maxy
            loop
                exit when x > maxx
                Pic.Draw (pic, x, y, picCopy)
                x := x + width
            end loop
            x := 0
            y := y + height
        end loop
Status Exported qualified.

This means that you can only call the function by calling Pic.Width, not by calling Width.

See also Pic.Height to obtain a picture's height and Pic.FileNew to load a picture from a graphics file.


play

play procedure

Syntax play ( music : string )

Description The play procedure is used to sound musical notes on the computer.

Example This program sounds the first three notes of the C scale.

        play ( "cde" )
Example This program plays from middle C to one octave above middle C and down again in 8th notes.

        play ( "8cdefgab>c" )
        play ( "<bagfedc" )
Details The play procedure takes strings containing characters that specify notes, rests, sharps, flats and duration. The notes are the letters a to g (or A to G). A rest is p (for pause). A sharp is + and a flat is -. The durations are 1 (whole note), 2 (half note), 4 (quarter note), 8 (eight note) and 6 (sixteenth note). The character > raises to the next octave and < lowers. For example, this is the way to play C and then C sharp one octave above middle C with a rest between them, all in sixteenth notes: play(">6cpc+"). Blanks can be used for readability and are ignored by play.

Under some systems such as UNIX, the play procedure may have no effect.

The current (1999) implementation does not support play.

See also the playdone function, which is used to see if a note has finished sounding. See also the sound procedure, which makes a sound of a given frequency (Hertz) and duration (milliseconds).

See also predefined unit Music.


playdone

playdone function

Syntax playdone : boolean

Description The playdone function is used to determine when notes played by the play procedure have finished sounding.

Example This program sounds the first three notes of the C scale and outputs "All done" as soon as they are finished. Without the loop, the message would come out before the notes are finished.

        play ( "cde" )
        loop
            exit when playdone
        end loop
        put "All done"
Details Under some systems such as UNIX, the playdone procedure may be meaningless.

See also the play procedure. See also the sound procedure which makes a sound of a given frequency (Hertz) and duration (milliseconds).

See also predefined unit Music.


pointer

pointer type

Syntax A pointerType is one of:

(a) | [unchecked] pointer to collectionId
 |  | % Short form: ^ collectionId
(b) | [unchecked] pointer to classId
 |  | % Short form: ^ classId
(c) | [unchecked] pointer to typeSpec
 |  | % Short form: ^ typeSpec

Description A variable declared as a pointer type is used to locate an element of a collection or class or a value of a type. The new statement creates a new element (or value) and places the element's location in a pointer variable. The free statement destroys an element located by a pointer variable.

Example Using a collection, declare a list or records and allocate one record.

        var list : collection of
            record
                contents : string ( 10 )
                next : pointer to list
            end record
        var first : pointer to list
        new list, first
Example Create a collection that will represent a binary tree.

        var tree : collection of
            record
                name : string ( 10 )
                left, right : pointer to tree
            end record

        var root : pointer to tree
        new tree, root
        tree ( root ).name := "Adam"
Example Using a class, create an object of that class. The object is located by the start pointer. The name field of the object is set to Ed.

        class node
            export var next, var name
            name : string ( 25 )
            next : pointer to node  % Short form: next : ^ node
        end node
        var start : pointer to node % Short form: var start : ^ node
        new node, start         % Short form: new start
        node ( start ) . name := "Ed"   % Short form: start->name:="Ed"
Details For collections and classes, a pointer is effectively a subscript (an index) for that collection or class. Pointers can be assigned, compared for equality and passed as parameters.

The keywords pointer to can be replaced by the short form ^, as in

        var first : ^ item
Given a pointer p that locates an object of class or collection C, the object is referenced as C(p) or as the short form ^ p. A field f of the object is referenced as C(p).f or ^p.f or as the short form p->f. For example, in the class given above, the name field of the object located by the start pointer can be set to Alice by:

        start -> name := "Alice"
Pointers to types use the same notation, except that pointers to types are not allowed to use the form typeSpec(p). See class for an example of the use of a class with pointers.

The carat ^ is called the dereferencing operator and has the highest precedence. For example, in ^ p.a, the carat applies to p and not to p.a. To apply ^ to all of p.a, use parentheses: ^(p.a). Several carats can appear in a row, for example,

        var r : ^ ^ int
declares a pointer to a pointer to an integer and ^ ^ r is the notation for referencing the integer.

A reference cannot begin with a left parenthesis, but can be surrounded by ^(…), as in ^ (q.b). If f is a parameterless function declared without parentheses that returns a pointer, the form ^ f calls f before dereferencing the pointer.

By default, all pointers are checked. This means there is a run time test to make sure that references such as C(p) actually locate elements, i.e., that p is initialized, is not nil and is not dangling (locating an object that has been freed). This checking requires extra space (the implementation attaches a time stamp to each pointer and object) and time. In high-performance programs in which this extra space and time are not acceptable, the pointer can be declared to be unchecked. When this is done, the program becomes dangerous and it is the programmer's responsibility to make sure that all pointer usage is valid.

If this is not the case, the program becomes susceptible to uncontrolled crashes.

Checked pointers cannot be assigned to unchecked pointers nor vice versa. However, you may, at your peril, use an implementation-dependent type cheat, to convert a checked pointer to a unchecked pointer, as in:

        type checkedPtr : ^ R
        type uncheckedPtr : unchecked ^ R
        var c : checkedPtr          % c is an checked pointer
        var u : uncheckedPtr        % u is an unchecked pointer
        …
        u := cheat (uncheckedPtr, d)    % This is a type cheat
Unchecked pointers are equivalent to the pointers of the C language, which are inherently error prone and cause difficult to locate bugs. An entire collection (but not a class) can be declared unchecked, in which case all of its pointers are implicitly unchecked. See collection.

See also inherit lists for a description of the assignability rules for pointers. See classes and collections for more details about the use of pointers. See also new and free statements. See also nil, objectclass and anyclass.


post

post assertion

Syntax An postAssertion is:

post trueFalseExpn

Description A post assertion is a special form of an assert statement that is used in a procedure or function. It is used to give requirements that the body of the procedure or function is supposed to satisfy. These requirements are given by the trueFalseExpn. After the body has executed and just before the procedure or function returns, the trueFalseExpn is evaluated. If it is true, all is well and execution continues. If it is false, execution is terminated with an appropriate message. See assert statements and procedure and function declarations for more details. See also pre and invariant assertions.

Example This function is supposed to produce an integer approximation of the square root of integer i. The post condition requires that this result, which is called answer, must be within a distance of 1 from the corresponding real number square root.

        function intSqrt ( i : int) answer : int
            pre i >= 0
            post abs ( answer - sqrt ( i ) ) <= 1
            … statements to approximate square root…
        end intSqrt
Details A post assertion can also be used in a module, monitor, class or process declaration to make sure that the initialization satisfies its requirements.

See also module and process.


pre

pre assertion

Syntax An preAssertion is:

pre trueFalseExpn

Description A pre assertion is a special form of an assert statement that is used at the beginning of a procedure or function. It is used to give requirements that the caller of the procedure or functions is supposed to satisfy. These requirements are given by the trueFalseExpn. The trueFalseExpn is evaluated. If it is true, all is well and execution continues. If it is false, execution is terminated with an appropriate message. See assert statements and procedure and function declarations for more details. See also post and invariant assertions.

Example This function computes the average of n values. Its pre condition requires that n must be strictly positive, to avoid the possibility of dividing by zero when computing the average.

        function average ( a : array 1 .. * of real, n : int) : real
            pre n > 0
            var sum : real := 0
            for i : 1 .. n
                sum := sum + a ( i )
            end for
            result sum / n
        end average
Details A pre assertion can also be used in a module, monitor, class or process declaration to make sure that requirements for initialization are met.

See also module and process.


precedence

precedence of operators

Description Turing's precedence rules determine the order of applying operators in an expression such as 3 + 4 * 5. These rules state, for example, that multiplication is done before addition, so this expression is equivalent to 3+ (4 * 5).

Parenthesized parts of an expression are evaluated before being used. For example, in (1 + 2) * 3, the addition is done before the multiplication.

The precedence rules are defined by this table, in which operators appearing earlier in the table are applied first. For example, multiplication is applied before addition:

(1) | **, ^, #
(2) | prefix + and -
(3) | *, /, div, mod, rem, shr, shl
(4) | infix +, -, xor
(5) | <, >, =, <=, >=, not=, in, not in
(6) | not
(7) | and
(8) | or
(9) | => | ( boolean implication)

Operators appearing on a single line in this table are applied from left to right. For example, abc is the same is (ab)c.

Here are some examples illustrating precedence, in which the left and right expressions are equivalent:

1**2 |  | (1**2)
a+b*c |  | a+(b*c)
a*b/c |  | (a*b)/c
b or c and d | b or (c and d)
x < y and y < z | (x < y) and (y < z)

The final example illustrates the fact that in Turing, parentheses are not required when combining comparisons using and and or. These would be required in the Pascal language.

The type cheat operator # is applied after subscripting, subprogram calling, dotting, and >. For example, in each of the following, # applies to the entire reference to the right.

#a(i)
#r.y
#p->x

The pointer following operator ^ is applied before subscripting, subprogram calling, dotting, and ->. For example, in the following, ^ applies to a, r and p.

^a(i)
^r.y
^p->x

Use parentheses to force ^ to apply to more of the reference. For example, in ^(a(i)), the ^ applies to a(i).

See also infix and prefix operators. See the int, real, string, boolean, set, enum, char and char(n) types.


pred

pred predecessor function

Syntax pred ( expn )

Description The pred function accepts an integer, character, or an enumerated value and returns the integer minus one, the previous character, or the previous value in the enumeration. For example, pred ( 7 ) is 6.

Example This part of a Turing program fills up array a with the enumerated values red, yellow, green, red, yellow, green, etc.

        type colors : enum ( green, yellow, red )
        var a : array 1 .. 100 of colors
        var c : colors := colors . red
        for i : 1 .. 100
            a ( i ) := c
            if c = colors . green then
                c := colors . red
            else
                c := pred ( c )
            end if
        end for
Details It is illegal to apply pred to the first value of an enumeration.

See also succ, lower and upper functions.


prefix

prefix operator

Syntax A prefixOperator is one of:

(a) | + |  | % Integer and real identity
 |  | % (does not change value)
(b) |  | % Integer and real negation
(c) | not |  | % Not (Boolean negation)
(d) | # |  | % Type cheat
(e) | ^ |  | % Pointer following

Description A prefix operator is placed before a value or operand to produce another value. For example, if the value of x is seven, then -x is negative seven. There are also infix operators such as multiplication (*) and addition (+), which are placed between two values to produce a third value. See infix operator.

The + and prefix operators can be applied only to numeric values (integer, real and natural numbers). The not prefix can be applied only to true/false (boolean) values. For example not (x > y) is equivalent to x <= y. The not operator produces true from false and false from true.

The # operators is a type cheat (see cheat), and the ^ operator is pointer following (see pointer).

See also int, real and boolean types, as well as precedence (for the order of applying operators) and infix operators.


procedure

procedure declaration

Syntax A procedureDeclaration is:

procedure id [(paramDeclaration {, paramDeclaration })]
statementsAndDeclarations
end id

Description A procedure declaration creates (but does not run) a new procedure. The name of the procedure (id) is given in two places, just after procedure and just after end.

Example

        procedure greetings
            put "Hello world"
        end greetings

        greetings           % This outputs Hello world

        procedure sayItAgain ( msg : string, n : int )
            for i : 1 .. n
                put msg
            end for
        end sayItAgain

        sayItAgain ("Toot", 2 ) % Toot is output twice

        procedure double ( var x : real )
            x := 2 * x
        end double

        var y : real := 3.14
        double ( y )        % This doubles the value of y
Details The set of parameters declared with the procedure are called formal parameters. In the double procedure, for example, x is a formal parameter. A procedure is called (invoked) by a procedure call statement which consists of the procedure's name followed by the parenthesized list of actual parameters (if any). For example, double(y) is a call having y as an actual parameter. If there are no parameters (see the greet procedure above), the call does not have parentheses. The keyword procedure can be abbreviated to proc.

Ordinarily, a procedure returns (finishes and goes back to the place where it was called) by reaching its end. However, the return statement in a procedure causes it to return immediately. Note that return can also be used in the main program to cause it to halt immediately.

Only parameters declared using var may be changed in the procedure, for example, x is changed in the double procedure. The upper bounds of arrays and strings that are parameters may be declared to be an asterisk (*). This means that the bound is that of the actual parameter. See paramDeclaration for details about parameters.

Procedures and functions cannot be declared inside other procedures and functions.

The syntax of a procedureDeclaration presented above has been simplified by leaving out the optional import list, pre condition, init clause, post condition and exception handler. The full syntax is

        procedure [ pervasive ] id
            [ ( [ paramDeclaration {,paramDeclaration } ] ) ]
            [ : deviceSpecification ]
            [ pre trueFalseExpn ]
            [ init id := expn {, id := expn } ]
            [ post trueFalseExpn ]
            [ exceptionHandler ]
            statementsAndDeclarations
        end id
A procedure must be declared before being called. To allow for mutually recursive procedures, there are forward declarations of procedures with later declaration of each procedure body. See forward and body declarations for explanations.

See also import list, pre condition, init clause, post condition and exceptionHandler for explanations of these features. See pervasive for information on pervasive procedures. See exceptionHandler. The optional deviceSpecification is used only in procedures declared in monitors and is used to create an interrupt handling procedure. See monitor for details.


procedureCall

procedureCall statement

Syntax A procedureCall is:

procedureId [ ( [ expn { , expn } ] ) ]

Description A procedure call is a statement that calls (invokes or activates) a procedure. If the procedure has parameters, a parenthesized list of expressions (expns) must follow the procedure's name (procedureId).

Example

        procedure greet
            put "Hello"
        end greet

        greet       % This is a call to the greet procedure

        procedure times ( var i : int, factor : int)
            i := factor * i
        end times

        var j : int
        times ( j, 4 )      % Multiply j by 4
Details A parameter declared in the header of a procedure is a formal parameter. For example, i and factor above are formal parameters. Each expression in the call is an actual parameter. For example, j and 4 above are actual parameters.

If a formal parameter is declared using var, then the expression passed to that parameter must be a variable reference (so its value can potentially be changed by the procedure). This means, for example, that it would be illegal to pass j+3 as the first parameter to times. The variable reference and the formal parameter must have equivalent types (see equivalence for details).

Each actual parameter passed to a non-var formal parameter must be assignable to that parameter (see assignability for details). See also procedureDeclaration.

In this explanation of procedureCall, we have up to this point ignored the possibility of procedures exported from modules, monitors and classes. If the procedure is being called from outside of a module or monitor M from which it has been exported, the syntax of the procedureCall is:

        M . procedureId [ ( [ expn {, expn } ] ) ]
In other words, the module or monitor name and a dot must precede the procedure's name. If the procedure is being called from outside of a class from which it has been exported, the syntax of the procedureCall is one of:

        (a) classId (p) . procedureId [ ( [ expn {, expn } ] ) ]
        (b) p -> procedureId [ ( [ expn {, expn } ] ) ]
In these, p must the a pointer value that locates an object in the class. Form (b) is a short form for form (a).

See also class.


process

process declaration

Syntax A processDeclaration is:

process id [ ( [ paramDeclaration {,paramDeclaration } ] )]
statementsAndDeclarations
end id

Description A process declaration is much like a procedure declaration, but is activated by a fork statement rather than by a call. The fork statement starts concurrent (parallel) execution of the process while the statements following the fork continue to execute.

Example This program initiates (forks) two concurrent processes, one of which repeatedly outputs Hi and the other Ho. The resulting output is an unpredictable sequence of Hi's and Ho's as greetings executes twice concurrently, one instance with word set to Hi and the other with word set to Ho.

        process greetings ( word : string )
            loop
                put word
            end loop
        end greetings

        fork greetings ( "Hi" )
        fork greetings ( "Ho" )
Details The process declaration creates a template for a process (a concurrent activity), which is activated by a fork statement.

A process declaration can appear wherever a module declaration is allowed except that a process declaration is not allowed in a class. The declarations and statements in a process declaration are the same as those in a procedure.

See paramDeclaration for details about parameters. There is an anomaly in parameters to processes, that can lead to errors. In particular, non-var parameters that are non-scalars (such as strings and arrays) are passed by reference. The result is that the target of the reference may change value while the process is executing, which in turn means that the seemingly constant parameter is not really constant. For example, if the string variable s were passed to the greetings process and subsequently changed, the value of greetings' formal parameter would change.

The syntax of a processDeclaration presented above has been simplified by leaving out the optional stack size (compileTimeExpn), import list, pre condition, init clause, post condition and exception handler.

The full syntax is:

        process [ pervasive ] id
                [ ( [ paramDeclaration {,paramDeclaration } ] )]
                [ : compileTimeExpn ]
            [ pre trueFalseExpn ]
            [ init id := expn {, id := expn } ]
            [ post trueFalseExpn ]
            [ exceptionHandler ]
            statementsAndDeclarations
        end id
See pervasive for information on pervasive processes. The optional compileTimeExpn following the parameter list (if any) is used to specify the number of bytes for the process' stack.

See also import list, pre condition, init clause, post condition and exceptionHandler for explanations of these additional features.


program

program a (main) program

Syntax A program is:

statementsAndDeclarations

Description A Turing program consists of a list of statements and declarations.

Example This is a complete Turing program. It outputs Alan M. Turing.

        put "Alan M. Turing"
Example This is a complete Turing program. It outputs a triangle of stars.

        var stars : string := "*"
        loop
            put stars
            stars := stars + "*"
        end loop
Example This is a complete Turing program. It outputs Hello once and Goodbye twice.

        procedure sayItAgain ( what : string, n : int )
            for i : 1 .. n
                put what
            end for
        end sayItAgain

        sayItAgain ( "Hello", 1)
        sayItAgain ( "Goodbye", 2 )
Details In a program there can be many units (see unit), one of which is the program (called the main program), the others of which are modules, monitors and classes. The main program is optionally preceded by an import list, which lists the units that it uses.

See also import list.


put

put statement

Syntax A putStatement is:

put [ : fileNumber , ] putItem { , putItem } [ .. ]

Description The put statement outputs each of the putItems. Usually, a new line is started in the output after the final putItem. If the optional dot-dot (..) is present, though, subsequent output will be continued on the current output line. With character graphics, the omission of dot-dot causes the remainder of the output line to be cleared to blanks.

Ordinarily, the output goes to the screen. However, if the fileNumber is present, the output goes to the file specified by the file number (see the open statement for details). Also, output can be redirected from the screen to a file, in which case all put statements without a file number are sent to the file instead of the screen.

Example

            var n : int := 5
            put "Alice owes me $", n
                    % Output is: Alice owes me $5
                    % Note that no extra space is
                    % output before an integer such as n.
Example

        Statement           Output      Notes

        put 24          24
        put 1/10            0.1     % Trailing zeros omitted
        put 100/10          10      % Decimal point omitted
        put 5/3         1.666667    % 6 fraction digits
        put sqrt (2)            1.414214    % 6 fraction digits
        put 4.86 * 10**9        4.86e9  % Exponent for = 1e6
        put 121 : 5         bb121   % Width 5; b is blank
        put 1.37 : 6 : 3        b1.370  % Fraction width of 3
        put 1.37 : 11 : 3 : 2   bb1.370e+00% Exponent width of 2
        put "Say \"Hello\"" Say "Hello"
        put "XX" : 4, "Y"       XXbbY   % Blank shown as b
        put true and false  false       % Put out a boolean value
        put 1 < 2           true        % Put out a boolean value
Example A single blank line is output this way:

        put ""  % Output null string then new line
This put statement is sometimes used to close off a line that has been output piece by piece using put with dot-dot.

Details The general form of a putItem is one of:

(a) | expn [:widthExpn [:fractionWidth [:exponentWidth ] ] ]
(b) | skip

See the above examples for uses of widthExpn, fractionWidth and exponentWidth. For the exact meaning of these three widths, see the definitions of the functions realstr, frealstr and erealstr. The skip item is used to end the current output line and start a new line.

Details The put semantics allow put's of enum values. The values printed are the element names themselves, case sensitive. For example:

        type colors : enum ( red, green, blue )
        var c : colors := colors . red
        put c       % outputs "red" (without the quotes)
Details The put semantics allow put's of boolean values. The values printed are either “true” or “false” (without the quotes). For example:

        var c : boolean := true or false
        put c       % outputs "true" (without the quotes)


quit

quit fail statement

Syntax A quitStatement is:

quit [ guiltyParty ] [ : quitReason ]

Description The quit statement causes a program (or concurrent process) to fail. The failure (called an exception) either aborts the program (or process) or causes control to be passed to an exception handler.

Example In the inputLines procedure, halt the program if end of file is encountered before the string "stop" is read. Note that a return statement in the procedure would terminate the procedure but not the entire program.

        var line : array 1 .. 50 of string

        procedure inputLines
            var i : int := 0
            loop
                if eof then
                    put "Missing 'stop' in input"
                    quit        % Halt entire program
                end if
                i := i + 1
                get line ( i )
                exit when line ( i ) = "stop"
            end loop
        end inputLines

        inputLines
Details In the simple case, the optional guiltyParty and quitReason are omitted. The guiltyParty option is used to specify the position of failure. See exceptionHandler for an example of a quit statement used in conjunction with a handler. A handler, which is located at the beginning of a subprogram body, is given control when a quit is executed or a failure, such as division by zero, occurs in the subprogram.

The guiltyParty option is used to designate the location of the failure, for example, to tell the debugger what line is considered to be the location of the failure. A guiltyParty is one of:

(a) | <
(b) | >

If guiltyParty is omitted, the failure is considered to occur at the quit statement. If it is <, the failure is considered to occur at the call to the present subprogram. For example, if the present subprogram implements square root sqrt and is passed a negative argument, it can use < to specify that the caller provided a faulty argument. If guiltyParty is >, this means the failure has already occurred and is being passed on to the next handler or to the system. To summarize, the three possibilities for designating the location of the failure are:

(a) | < | Caller is cause of failure
(b) | > | The exception being handled is the cause.
(c) | (omitted guiltyParty) The present quit is the cause.

The quitReason is an integer expression which is used to identify the kind of failure. If it is omitted, a default value is chosen in the following manner. If guiltyParty is omitted or is <, the default is 1. If guiltyParty is > and an exception handler is active, the default is the quitReason of the exception being handled. If no exception is being handled, the default is 1. In the case of program abortion, the implementation may pass the quitReason to the operating system or programming environment.

See also exceptionHandler, return and result.


Rand

Description This unit contains the predefined subprograms that deal with random numbers.

All routines in the Rand unit are exported qualified (and thus must be prefaced with "Rand.").

Entry Points
Real | Returns a random real number.
Int | Returns a random integer.
Reset | Sets the seed in the default sequence to a default value.
Set | Sets the seed in the default sequence to a specified value.
Next | Returns a random real number from a sequence.
Seed | Sets a seed in a sequence.


Rand.Int

Rand.Int Part of Rand module

Syntax Rand.Int (low, high : int) : int

Description The Rand.Int statement is used to create a pseudo-random integer in the range low to high, inclusive. For example, if i is an integer, after i:=Rand.Int (i,1, 10), i would have a value such as 7 or 2 or 10.

Example This program simulates the repeated rolling of a six sided die.

        loop
            put "Rolled ", Rand.Int (1, 6)
        end loop
Details The Rand.Int statement sets its parameter to the next value of a sequence of pseudo-random integers that approximates a uniform distribution over the range low =i = high. It is required that low = high.

Each time a program runs, Rand.Int uses a different pseudo-random number sequence. To always get the same sequence (actually, to start the sequence at the same point), use the Rand.Set procedure.

To use several sequences of repeatable pseudo-random number sequences, use the Rand.Seed and Rand.Next procedures.

Status Exported qualified.

This means that you can only call the function by calling Rand.Int, not by calling Int.

See also Rand.Real, Rand.Set, Rand.Seed and Rand.Next.


Rand.Next

Rand.Next Part of Rand module

Syntax | Rand.Next (seq : 1 .. 10) : real
Description | The Rand.Next procedure is used when you need several sequences of pseudo-random numbers, and you need to be able to exactly repeat these sequences for a number of simulations. The Rand.Next procedure is the same as rand, except seq specifies one of ten independent and repeatable sequences of pseudo-random real numbers. The Rand.Seed procedure is used to start one of these sequences at a particular point.
Status | Exported qualified. This means that you can only call the function by calling Rand.Next, not by calling Next.
See also | Rand.Seed, Rand.Int, Rand.Real and Rand.Next.


Rand.Real

Rand.Real Part of Rand module

Syntax Rand.Real : real

Description The Rand.Real function returns a pseudo-random number in the range zero to one. For example, if x is a real number, after x := Rand.Real, x would have a value such as 0.729548 or 0.352879.

Example This program repeatedly and randomly prints out Hi ho, hi ho or It's off to work we go.

        loop
            if Rand.Real > 0.5 then
                put "Hi ho, hi ho"
            else
                put "It's off to work we go"
            end if
        end loop
Details The Rand.Real function sets its parameter to the next value of a sequence of pseudo-random real numbers that approximates a uniform distribution over the range 0<r <1.

Each time a program runs, Rand.Real uses a different pseudo-random number sequence. To always get the same sequence (actually, to start the sequence at the same point), use the Rand.Set procedure.

To use several sequences of repeatable pseudo-random number sequences, use the Rand.Seed and Rand.Next procedures.

Status Exported qualified.

This means that you can only call the function by calling Rand.Real, not by calling Real.

See also Rand.Int, Rand.Set, Rand.Seed and Rand.Next.


Rand.Reset

Rand.Reset Part of Rand module

Syntax Rand.Reset

Description This is a procedure with no parameters that resets the sequences of pseudo-random numbers produced by Rand.Real and Rand.Int. This allows identical executions of the same program to produce identical results.

Example This program simulates the repeated rolling of a six sided die. Each time the program runs, the same sequence of rolls occurs.

        Rand.Reset
        loop
            put "Rolled ", Rand.Int (1, 6)
        end loop
Details If Rand.Reset and Rand.Set are not used, each time a program runs Rand.Real and Rand.Int use a different pseudo-random number sequence. To get the same sequence each time (actually, to start the sequence at a different point), use Rand.Reset or Rand.Set.

The Rand.Reset procedure can be called any time. However, to make it work, it should only be called once per program. Any call to Rand.Reset after the first one is ignored.

To use several sequences of repeatable pseudo-random number sequences, use the Rand.Seed and Rand.Next procedures.

Status Exported qualified.

This means that you can only call the function by calling Rand.Reset, not by calling Reset.

See also Rand.Set, Rand.Int, Rand.Real, Rand.Seed and Rand.Next.


Rand.Seed

Rand.Seed Part of Rand module

Syntax | Rand.Seed (seed : nat4, seq : 1 .. 10)
Description | The Rand.Seed procedure restarts one of the sequences generated by Rand.Next. Each restart with the same seed causes Rand.Next to produce the same sequence for the given sequence.
Status | Exported qualified. This means that you can only call the function by calling Rand.Seed, not by calling Seed.
See also | Rand.Next, Rand.Int, Rand.Real, and Rand.Set.


Rand.Set

Rand.Set Part of Rand module

Syntax Rand.Set (seed : nat4)

Description This procedure sets the seed for sequences of pseudo-random numbers produced by Rand.Real and Rand.Int. This allows identical executions of the same program to produce identical results.

Example This program simulates the repeated rolling of a six sided die. Each time the program runs, the same sequence of rolls occurs.

        Rand.Set (16#1234ABCD)
        loop
            put "Rolled ", Rand.Int (1, 6)
        end loop
Details If Rand.Reset and Rand.Set are not used, each time a program runs Rand.Real and Rand.Int use a different pseudo-random number sequence. To get the same sequence each time (actually, to start the sequence at a different point), use Rand.Reset or Rand.Set.

To use several sequences of repeatable pseudo-random number sequences, use the Rand.Seed and Rand.Next procedures.

Status Exported qualified.

This means that you can only call the function by calling Rand.Set, not by calling Set.

See also Rand.Reset, Rand.Int, Rand.Real, Rand.Seed and Rand.Next.


rand

rand random real number procedure

Syntax rand (var r : real)

Description The rand statement is used to create a pseudo-random number in the range zero to one. For example, if x is a real number, after rand(x), x would have a value such as 0.729548 or 0.352879.

Example This program repeatedly and randomly prints out Hi ho, hi ho or It's off to work we go.

        var r : real
        loop
            rand ( r )
            if r > 0.5 then
                put "Hi ho, hi ho"
            else
                put "It's off to work we go"
            end if
        end loop
Details The rand statement sets its parameter to the next value of a sequence of pseudo-random real numbers that approximates a uniform distribution over the range 0<r <1.

Each time a program runs, rand uses a different pseudo-random number sequence. To get the same sequence (use Rand.Set).

To use several sequences of repeatable pseudo-random number sequences, use the randseed and randnext procedures.

In many languages, rand would be a function rather than a procedure. It has been designed as a procedure in Turing to respect the mathematical idea that every call to a function using the same arguments (or no arguments at all) should return the same value. If rand were a function, this would not be true.

See also randint, randomize, randseed and randnext.

See also predefined unit Rand.


randint

randint random integer procedure

Syntax randint ( var i : int, low, high : int )

Description The randint statement is used to create a pseudo-random integer in the range low to high, inclusive. For example, if i is an integer, after randint(i,1, 10), i would have a value such as 7 or 2 or 10.

Example This program simulates the repeated rolling of a six sided die.

        var roll : int
        loop
            randint ( i, 1, 6 )
            put "Rolled ", i
        end loop
Details The randint statement sets its parameter to the next value of a sequence of pseudo-random integers that approximates a uniform distribution over the range low =i = high. It is required that low = high.

Each time a program runs, randint uses the same pseudo-random number sequence. To get a different sequence (actually, to start the sequence at a different point), use the randomize procedure.

To use several sequences of repeatable pseudo-random number sequences, use the randseed and randnext procedures.

See also rand, randomize, randseed and randnext.


randnext

randnext procedure

Syntax | randnext ( var v : real, seq : 1 .. 10 )
Description | The randnext procedure is used when you need several sequences of pseudo-random numbers, and you need to be able to exactly repeat these sequences for a number of simulations. The randnext procedure is the same as rand, except seq specifies one of ten independent and repeatable sequences of pseudo-random real numbers. The randseed procedure is used to start one of these sequences at a particular point.
See also | randseed, randint, rand and randnext.


randomize

randomize procedure

Syntax | randomize
Description | This procedure is obsolete. It was originally used to produce a different sequence of random numbers each time a program executed. With current versions of Turing, the random number sequence is “randomized” each time a Turing program is executed, eliminating the need for this procedure. To reset the random number sequence and thus allow for a predetermined sequence of pseudo-random numbers, use Rand.Set.
See also | randint, rand, randseed and randnext. See also predefined unit Rand.


randseed

randseed procedure

Syntax | randseed ( seed : int, seq : 1 .. 10 )
Description | The randseed procedure restarts one of the sequences generated by randnext. Each restart with the same seed causes randnext to produce the same sequence for the given sequence.
See also | randnext, randint, rand, and randomize.


read

read file statement

Dangerous parts

Syntax A readStatement is:

read : fileNumber [ : status ] , readItem { ,readItem }

Description The read statement inputs each of the readItems from the specified file. These items are input directly using the binary format that they have on the file. In other words, the items are not in source (ASCII or EBCDIC) format. In the common case, these items have been output to the file using the write statement.

By contrast, the get and put statements use source format, which a person can read using an ordinary text editor.

Example This example shows how to input a complete employee record using a read statement.

        var employeeRecord :
            record
                name : string ( 30 )
                pay : int
                dept : 0 .. 9
            end record
        var fileNo : int
        open : fileNo, "payroll", read
        …
        read : fileNo, employeeRecord
Details The fileNumber must specify a file that is open with read capability (or a program argument file that is implicitly opened).

The optional status is an int variable that is set to implementation-dependent information about the read. If status is returned as zero, the read was successful. Otherwise status gives information about the incomplete or failed read (which is not documented here). You commonly use status when you are reading a record or array from a file and you are not sure if the entire item exists on the file. If it does not exist, the read will fail part way through, but your program can continue and diagnose the problem by inspecting status.

A readItem is:

        variableReference [ : requestedSize [ : actualSize ] ]
Each readItem specifies a variable to be read in internal form. The optional requestedSize is an integer value giving the number of bytes of data to be read. The requestedSize should be less than or equal to the size of the item's internal form in memory (else a warning message is issued). If no requestedSize is given, the size of the item in memory is used. The optional actualSize is an int variable that is set to the number of bytes actually read.

An array, record or union may be read and written as a whole.

It is dangerous to read into pointer variables, as this allows the possibility of creating incorrect addresses in the pointers. It is also dangerous to read more bytes than are in the readItem.

See also the write, open, close, seek, tell, get and put statements.


real

real the real number type

Syntax real

Description The real number type is used for numbers that have fractional parts, for example, 3.14159. Real numbers can be combined by various operators such as addition (+) and multiplication (*). Real numbers can also be combined with integers (whole numbers, such as 23, 0 and -9), in which case the result is generally a real number. An integer can always be assigned to a real variable, with implicit conversion to real.

Example

        var weight, x : real
        var x : real := 9.83
        var tax := 0.7      % The type is implicitly real because
                        % 0.7 is a real number
Details See also explicitRealConstant. The int type is used instead of real, when values are whole numbers. See int for details.

Real numbers can be converted to integers using ceil (ceiling), floor, or round. Real numbers can be converted to strings using erealstr, frealstr, and realstr. These conversion functions correspond exactly to the formatting used for the put statement with real numbers. Strings can be converted to real numbers using strreal. See descriptions of these conversion functions.

The predefined functions for real numbers include min, max, sqrt, sin, cons, arctan, sind, cosd, arcand, ln and exp. See the descriptions of these functions.

Pseudo-random sequences of real numbers can be generated using rand. See the description of this procedure.

The Turing Report gives a formal definition (not repeated here) of implemented real numbers in terms of their required accuracy relative to infinitely accurate (mathematical) real numbers.

Turing implements real numbers using 8 byte floating point representation. This provides 14 to 16 decimal digits of precision and an exponent range of at least -38 .. 38. The PC and Macintosh versions of Turing have 16 decimal digits of accuracy because they use IEEE standard floating point representation.

See also real n.


realn

realn n-byte real number type

Syntax

(a) | real4 | % 4-byte real number
(b) | real8 | % 8-byte real number

Description The realn (n-byte real number) types are machine-dependent types that occupy a specified number of bytes. By contrast, the real type is, in principle, a machine-independent and mathematical type (however, it overflows when the exponent of the value is too large or small and it has only a limited amount of precision).

Example

        var width : real4
        var height : real8
Details Turing implements the type real using 8 byte floating point representation. This provides 14 to 16 decimal digits of precision and an exponent range of at least -38 .. 38. The PC and Macintosh versions of Turing have 16 decimal digits of accuracy because they use IEEE standard floating point representation.

This implies that real8 and real are essentially the same type, so in practice there is no advantage to using real8 rather than real. However, real4 has the advantage of occupying half as much space (with correspondingly reduced precision).

Arithmetic for all real types (real, real4 and real8) is carried out with the accuracy and exponent range of 8-byte reals.

The type real4 is sometimes called single precision (because it occupies a single 4-byte word) and real8 is sometimes called double precision.


realstr

realstr real-to-string function

Syntax realstr ( r : real, width : int ) : string

Description The realstr function is used to convert a real number to a string. For example, realstr (2.5e1, 4)="bb25" where b represents a blank. The string is an approximation to r, padded on the left with blanks as necessary to a length of width.

The width parameter must be non-negative. If the width parameter is not large enough to represent the value of r it is implicitly increased as needed. The displayed value is rounded to the nearest decimal equivalent with this accuracy. In the case of a tie, the display value is rounded to the next larger value.

The string realstr (r, width ) is the same as the string frealstr (r, width, defaultfw ) when r =0 or when 1e-3 < abs (r ) < 1e6, otherwise the same as erealstr (r, width, defaultfw, defaultew), with the following exceptions. With realstr, trailing fraction zeroes are omitted, and the decimal point is omitted if the entire fraction is zero. (These omissions take place even if the exponent part is printed.) If an exponent is printed, any plus sign and leading zeroes are omitted. Thus, whole number values are in general displayed as integers.

Defaultfw is an implementation-defined number of fractional digits to be displayed. For most implementations, defaultfw will be 6.

Defaultew is an implementation-defined number of exponent digits to be displayed. For most implementations, defaultew will be 2.

The realstr function approximates the inverse of strreal, although round-off errors keep these from being exact inverses.

See also the erealstr, frealstr, strreal, intstr and strint functions.


record

record type

Syntax A recordType is:

record
 | id {, id } : typeSpec
 | { id {, id } : typeSpec }
end record

Description Each value of a record type consists of fields, one field for each name (id) declared inside the record. In the following example, the fields are name, phoneNumber and address.

Example

        type phoneRecord :
            record
                name : string ( 20 )
                phoneNumber : int
                address : string ( 50 )
            end record
        …
        var oneEntry : phoneRecord
        var phoneBook : array 1 .. 100 of phoneRecord
        var i : int
        oneEntry .name := "Turing, Alan"
        …
        phoneBook ( i ) := oneEntry % Assign whole record
Details In a record, id's of fields must be distinct. However, these need not be distinct from identifiers outside the record. Records can be assigned as a whole (to records of an equivalent type), but they cannot be compared. A semicolon can optionally follow each typeSpec.

Any array contained in a record must have bounds that are known at compile time.

The notation > can be used to access record fields. For example, if p is a pointer to phoneRecord, p>name locates the name field. See pointer.


register

register use machine register

Dirty

Description When a variable, constant or parameter is declared, you can request that the item be placed in a machine register. This should be done only for programs requiring considerable efficiency.

Example

        var register counter : int
        const register maxCounter : int := 100
        procedure p ( register x : real )
            …
        end p
Details Items can be requested to be in registers only if they are local to a subprogram (not global variables, declared in the main program, a module, monitor or class). Items requested to be in registers cannot be bound to, passed to reference parameters, have their address taken by addr, or have certain type cheats applied to them (since a machine register has no address).

The request to use a register may be ignored. For example, the current (1999) interpretive implementation uses pseudo-code, which has no machine registers, and so ignores the register keyword. For the syntax of using this keyword, see var declaration, const declaration and paramDeclaration.


rem

rem remainder operator

Syntax rem

Description The rem (remainder] operator produces the remainder of one number divided by another. For example, 7 rem 2 produces 1 and -12 rem 5 produces -2.

Example In this example, eggCount is the total number of eggs. The first put statement determines how many dozen eggs there are. The second put statement determines how many extra eggs there are beyond the last dozen.

        var eggCount : int
        get eggCount
        put "You have ", eggCount div 12, " dozen eggs"
        put "You have ", eggCount rem 12, " left over"
See also infix operators, precedence of operators and the mod and div operators.


repeat

repeat make copies of string

function

Syntax repeat ( s : string, i : int ) : string

Description The repeat function returns i copies of string s catenated together. For example, repeat ("X", 4) is XXXX.

Example This program outputs HoHoHo.

        var word : string := "Ho"
        put repeat ( word, 3 )
Details If i is less than or equal to zero, the null string "" is returned. The repeat function is often used for spacing of output. For example, this statement skips 20 blanks before outputting x.

        put repeat (" ", 20), x


result

result statement

Syntax A resultStatement is:

result expn

Description A result statement, which must appear only in a function, is used to provide the value of the function.

Example This function doubles its parameter.

        function double ( x : real ) : real
            result 2 * x
        end double
        put double ( 5.3 )      % This outputs 10.6
Example This function finds the position of a name in a list.

        function find ( a : array 1 .. 100 of string ) : int
            for i : 1 .. 100
                if a ( i ) = name then
                    result i
                end if
            end for
        end find
Details The execution of a result statement computes the value of the expression (expn) and terminates the function, returning the value as the value of the function.

The expression must be assignable to the result type of the function, for example, in double, 2*x is assignable to real. (See the assignmentStatement for the definition of assignable.)

A function must terminate by executing a result statement and not by reaching the end of the function.


return

return statement

Syntax A returnStatement is:

return

Description A return statement terminates the procedure (or main program) in which it appears. Ordinarily, a procedure (or main program) terminates by reaching its end; the return statement is used to cause early termination.

Example This procedure takes no action if the errorHasOccurred flag has been set to true.

        procedure double
            if errorHasOccurred then
                return  % Terminate this procedure
            end if
            … handle usual case in this procedure …
        end double
Details A return must not appear as a statement in (the outermost level of) a module, nor can it appear in a function.


RGB

Description This unit contains the predefined constants for the basic colors and the subprograms to change the color palette.

All subprograms in the RGB unit are exported qualified (and thus must be prefaced with "RGB."). All the color constants are exported unqualified and thus do not need the RGB prefix.

Details For a program that displays the 256 predefined colors (and their associated color numbers) in Turing, run the "Colors.t" program.

Details The following names can be used for colors. They represent color numbers and thus will not be accurate if RGB.SetColor has been used to change color numbers 0 through 15.

black, blue, green, cyan, red, magenta, purple, brown, white, gray, grey, brightblue, brightgreen, brightcyan, brightred, brightmagenta, brightpurple, yellow, brightwhite, darkgray, darkgrey

The remaining four colors represent the foreground color (black on Windows or the Macintosh, white on a DOS system) and the background color (white on Windows or Macintosh, black on a DOS system). Using these four colors allows you to write programs that work on both Windows and DOS versions of Turing.

colorfg, colourfg, colorbg, colourbg

Details Turing uses a palette to access colors for display. This palette is a list of color numbers and their associated actual color. The Turing palette starts with 256 entries (the color numbers from 0 to 255). With 16, 24, and 32-bit color displays, however, a Turing program can display thousands of colors at once. These colors, however, will all have color numbers associated with them. For example, if a Turing program loads a JPEG image, there may be thousands of colors on the screen, but the number of color numbers will stay at 256. Likewise, 16, 24, and 32-bit color displays, if you load a picture in GIF format that has a 256 colors that are different from the initial Turing color palette, they will appear in the run window. However, they will not be added to Turing's color palette.

If you attempt to determine the color number of a particular pixel that does not match any of the colors in Turing's color palette, then Turing will return the color number of the color in the Turing palette that most closely matches that color of the pixel.

Entry Points
GetColor GetColour | Gets the current red, green and blue values of a specified color number.
SetColor SetColour | Sets the red, green and blue values of a specified color number.
AddColor AddColour | Creates a new color number with a specified red, green and blue value.


RGB.AddColor

RGB.AddColor Part of RGB module

Syntax RGB.AddColor (redComp, greenComp, blueComp : real) : int

Description The RGB.AddColor function attempts to create a new color with the red, green and blue components specified. If successful, the function returns a new color number (usually one greater than maxcolor) and maxcolor is updated by adding 1 to it. If it is unsuccessful, the function returns 1 and Error.Last and Error.LastMsg can be used to determine the cause of the problem.

The red, green and blue values must normalized to be between 0 and 1. Thus to add the pure red to the color palette, you would call:

        newColor := RGB.AddColor (1.0, 0.0, 0.0)
newColor would be set to the color added, or 1 if the attempt to add a color failed.

Example This program adds a palette of 16 blues to the end of the color palette.

        var clr : int
        for blueShade : 0 .. 15
             clr = RGB.AddColor (0, 0, blueShade / 15)
             if clr = 1 then
                put "Color add failed on shade number ", blueShade
                exit
            else
                put "Added color number ", clr
            end if
        end for
Details RGB.AddColour is an alternate spelling for RGB.AddColor.

Status Exported qualified.

This means that you can only call the function by calling RGB.AddColor, not by calling AddColor.

See also RGB.GetColorand RGB.SetColor.


RGB.GetColor

RGB.GetColor Part of RGB module

Syntax RGB.GetColor (colorNumber : int,
var redComp, greenComp, blueComp : real)

Description The RGB.GetColor procedure returns the red, green and blue components to the color associated with the colorNumber parameter. The red, green and blue values are normalized to be between 0 and 1. Thus color white returns 1.0 for the redComp, greenComp and blueComp values and color black returns 0.0 for all three.

Example This program gets the components of all the available colors.

        put "Color   Red     Green     Blue"
        for clr : 0 .. maxcolor
            var redComp, greenComp, blueComp : int
            RGB.GetColor (clr, redComp, greenComp, blueComp)
            put clr : 4, "  ", redComp : 6 : 4 , "  ", greenComp : 6 : 4, " ",
                                        blueComp : 6 : 4
        end for
Details RGB.GetColour is an alternate spelling for RGB.GetColor.

Status Exported qualified.

This means that you can only call the function by calling RGB.GetColor, not by calling GetColor.

See also RGB.SetColorand RGB.AddColor.


RGB.maxcolor

RGB.maxcolor Part of RGB module

Syntax maxcolor : int

Description The maxcolor function is used to determine the maximum color number for the current mode of the screen. The alternate spelling is maxcolour.

Example This program outputs the maximum color number.

        setscreen ("graphics")
        …
        put "The maximum color number is ", maxcolor
Details The screen should be in a "screen" or "graphics" mode. If it is not, it will automatically be set to "screen" mode. See View.Set for details.

For IBM PC compatibles in "screen" mode, maxcolor = 15. For the default IBM PC compatible "graphics" mode (CGA), maxcolor = 3.

Status Exported unqualified.

This means that you can call the function by calling maxcolor or by calling RGB.maxcolor.

See also Draw.Dot for examples of the use of maxcolor. See the Text.Color procedure which is used for setting the currently-active color.


RGB.SetColor

RGB.SetColor Part of RGB module

Syntax RGB.SetColor (colorNumber: int,
redComp, greenComp, blueComp : real)

Description The RGB.SetColor function sets the red, green and blue components of the color associated with the colorNumber parameter. The red, green and blue values must normalized to be between 0 and 1. Thus to set the color associated with the colorNumber parameter to pure red, you would call:

        RGB.SetColor (colorNumber, 1.0, 0.0, 0.0)
It is wise to use Error.Last and Error.LastMsg to check to see if the color change is successful.

Example This program sets all the available colors to shades of red

        for clr : 0 .. maxcolor
             if not RGB.SetColor (clr, clr / maxcolor, 0, 0) then
                put "Color set failed on color number ", clr
                exit
            end if
        end for
Details RGB.SetColour is an alternate spelling for RGB.SetColor.

Details On monitors set to 8-bit color display (256 colors), the color change will happen almost instantaneously, and only those pixels that have matching color numbers will be changed. For example, colors 7 and 255 both represent black. Changing color 255 to red will not change pixels drawn in color 7.

On monitors set to 16, 24, or 32-bit displays (thousands or millions of colors), the color change happens very slowly, and any pixel that matches the color represented by the color number will be changed. For example, setting color 255, which is initially black, to red will change all black pixels in the run window to red. After this occurs, drawing in color 7 will produce black, while drawing in color 255 will produce red.

This behaviour is caused by the fact that in 16-bit or higher color, the pixels on the screen are stored as actual colors, rather than color numbers and thus the system has no way of distinguising between pixels drawn in different color numbers that produce identical colors.

Status Exported qualified.

This means that you can only call the function by calling RGB.SetColor, not by calling SetColor.

See also RGB.GetColorand RGB.AddColor.


round

round real-to-integer function

Syntax | round ( r : real ) : int
Description | The round function is used to convert a real number to an integer. The result is the nearest integer to r. In the case of a tie, the numerically larger value is returned. For example, round (3) is 3, round (2.85) is 3 and round (-8.43) is -8.
See also | the floor and ceil functions.


scalar

scalar type

Syntax A scalarType is one of:

(a) | standardType | % int, real, boolean or string
(b) | enumeratedType
(c) | subrangeType
(d) | pointerType
(e) | char
(f) | int n
(g) | nat n
(h) | real n
(i) | namedType |  | % Must name one of the above types

Description Scalar types are sometimes called simple or primitive types. The non-scalar types are strings, sets, arrays, records, unions and in OOT char(n). They are defined using scalar types. Scalar types are passed by value to parameters, while non-scalars are passed by reference (by passing an implicit pointer to the non-scalar value).

Description In current Turing implementations scalar types are directly represented in 1, 2, 4 or 8 bytes in a computer's memory. This implies that they can be efficiently passed by value.


seek

seek (file) statement

Syntax A seekStatement is one of:

(a) | seek : fileNumber , filePosition
(b) | seek : fileNumber , *

Description Random access of both source (ASCII or EBCDIC) and internal form (binary) files is provided by the seek and tell statements. The seek statement repositions the specified file so that the next input/output operation will begin at the specified point (filePosition) in the file.

The fileNumber must specify a file that is open with seek capability. The filePosition is a non-negative integer offset in bytes from the beginning of the file. Usually, this is a number returned by the tell statement. (The first position in the file is position zero.)

Form (b) specifies that the next operation is to begin at the position immediately following the current end of the file. A filePosition of zero specifies that the next operation is to start at the beginning of the file. Seeking to a position beyond the current end of the file and then writing, automatically fills the intervening positions with the internal representation of zero.

Example This example shows how to use seek to append to the end of a file.

        var employeeRecord :
            record
                name : string ( 30 )
                pay : int
            end record
        var fileNo : int
        open : fileNo, "payroll", write, seek, mod
        seek : fileNo, *        % Seek to the end of the file
        write : fileNo, employeeRecord
                        % This record is added to the end of the file
See also read, write, open, close, tell, get and put statements. Another example use of seek is given with the explanation of the tell statement.


self

self pointer to current object

Syntax self

Description The self function produces a pointer to the current object. This function can be used only inside a class declaration. See class.

Example Enter the current object onto a list of displayable objects. The module called displayable has exported a procedure called enter whose parameter type is pointer to anyclass. Since self is a pointer to C and C is a descendant of anyclass, it is legal to pass self to displayable.enter.

        class C
            import displayable
            …
            displayable.enter ( self ) …
            …
        end C
Details It is illegal to call the exported entries of a class until the current object has been completely initialized, so, many calls to the current object using self will not be legal.

The notation to call exported subprogram p of an enclosing class C or of its ancestor D, is C.p or D.p. Calls of this form, which can appear only within class C, call the subprogram in C (or in D in the case of D.p) regardless of the object type, or of any overriding, or of the status of initialization.


separator

separator between tokens in a program

Description A Turing program is made up of a sequence of tokens (see tokens), such as var, x, :, and int. These tokens may have separators between them. A separator is a comment (see comment), blank, tab, form feed or an end of line.


set

set type

Syntax A setType is:

set of typeSpec

Description Each value of a set type consists of a set of elements. The typeSpec, which is restricted to being a subrange or an enumerated type, gives the type of these elements.

Example The smallSet type is declared so that it can contain any and all of the values 0, 1 and 2. Variable s is initialized to be the set containing 1 and 2.

        type smallSet : set of 0 .. 2
        var s : smallSet := smallSet ( 0, 1 )
        …
        if 2 in s then …
Details In classical mathematics, the set consisting of 0 and 1 is written as {0,1}. This is written in Turing using a set constructor consisting of the name of the set type followed by a parenthesized list of elements, which in this example is smallInt (0,1). The empty set is written, for example, as smallInt (). The full set is written as smallInt (all), so smallInt (all) = smallInt (0,1,2).

Sets can be assigned as a whole (to sets of an equivalent type). See also equivalence of types.

The operators to combine two sets are union (+), intersection (*), set subtraction (-), equality (=), inequality (not=), subset (<=), strict subset (<), superset (>=), strict superset (>), and xor ("exclusive or" also known as symmetric difference). Only sets with equivalent types (equal bounds on their index types) can be combined by these operators. The operators which determine if an element is, or is not, in a set are in and not in. For example, the test to see if 2 is in set s is written in the above example as: 2 in s.

The indexType of a set type must contain at least one element. For example, the range 1 .. 0 would not be allowed. See also indexType. In Turing, sets are limited to at most 31 elements. OOT allows a very large number of elements.

Details It is illegal to declare an "anonymous" set. The only legal declaration for an set is in a type declaration. For example, the following is now illegal:

        var a : array 1 .. 10 of set of 0 .. 3
Given that there is no (easy) way of generating a set value without it being a named type, this should not impact any but the most bizarre code.

See also precedence of operators for the order of applying set operations.


setConstructor

Syntax A setConstructor is:

setTypeId ( membersOfSet )

Description Each value of a set type consists of a set of elements. In classical mathematics, the set consisting of 0 and 1 is written as {0,1}. This is written in Turing using a set constructor consisting of the name of the set type (setTypeId) followed by a parenthesized list of elements.

Example The smallSet type is declared so that it can contain any and all of the values 0, 1 and 2. Variable s is initialized to be the set containing 1 and 2. The set {0,1} is written in this Turing example as smallInt (0,1).

        type smallSet : set of 0 .. 2
        var s : smallSet := smallSet ( 0, 1 )
        …
        if 2 in s then …
Details The form of membersOfSet is one of:

        (a) expn { , expn}  % List of members of set
        (b) all         % All member of index type of set
        (c)             % Nothing, meaning the empty set
The empty set is written, for example, as smallInt (). The full set is written as smallInt (all), so smallInt (all) = smallInt (0,1,2). See also the set type.

The syntax of setConstructor as given above has been simplified by ignoring the fact that set types can be exported from modules. When a set type is exported and used outside of a module, you must write the module name, a dot and then the type name. For example, the set constructor above would be written as m.smallSet(1,2), where m is the module name.


setpriority

setpriority procedure

Syntax | setpriority ( p : nat )
Description | The setpriority procedure is used to set the priority of a process in a concurrent program. This priority cannot be counted on to guarantee critical access to shared variables. A smaller value of p means increased speed. The argument to setpriority may be limited to the range 0 to 2**15 - 1.
See also | getpriority, fork and monitor. See also predefined unit Concurrency.


setscreen

setscreen graphics procedure

        setscreen ("graphics:300;100")
This program outputs the square roots for the first 200 numbers. The user can inspect all the output and print the values after the program has finished execution

        setscreen ("text")
        for value : 1 .. 200
            put value : 3, "   ", sqrt (value)
        end for
This program creates a window without a button bar at the top that is sized to fit the screen. It then draws an “X” in red in the window.

        setscreen ("graphics:max;max,nobuttonbar")
        drawline (0, 0, maxx, maxy, red)
        drawline (maxx, 0, 0, maxy, red)
Syntax setscreen ( s : string )

Example Here are example uses of the setscreen procedure. In many cases, these will appear as the first statement of the program. They can, however, appear any place in a program.

        setscreen ( "graphics" )            % Enter graphics mode
        setscreen ( "graphics:400;300" )    % Change window to 400x300
        setscreen ( "nocursor" )            % Turn off cursor
        setscreen ( "noecho" )          % Do not echo keys
Description The setscreen statement is used to change the mode of the screen, as well as the way in which Turing does input and output. The parameter to setscreen is a string, such as "graphics". The string contains one or more options separated by commas, such as "text, noecho".

Details Users should look at View.Set in order to find out the implementation specified details of setscreen on their systems.

There are two screen modes, text and graphics. In text mode, output to the window is only allowed using put and get. Attempting to use graphics or moving the cursor using locate will result in an error. However, a window in text mode will keep all text output sent to it. Any output that scrolls off the edge of the window can be read by adjusting the scroll bars of the window. Printing a text output window prints all the output sent to the window, not just the output currently visible in the window. Programs often use text mode when they are displaying large amounts of text data that the user may wish to view or print later. Saving the contents of a text output window creates a text file containing all the output sent to the window.

In graphics mode, a program can use both put and get, locate and graphics commands to send output to the window. However, any output that scrolls off the window is lost. Printing the window outputs the current contents of the window. Saving a graphics output window saves the current contents of the window as a BMP file.

Where the options to setscreen are mutually exclusive, they are listed here with the default underlined. Here are the options:

"graphics", "text", Sets the mode of the window to the given mode. A size can for the window can be specified at the same time. If the window mode or size changes, then the window will be cleared.

To specify the size of a window in graphics mode, the graphics can have a modifier in the form "graphics:<width>;<height>". This sets the window to be <width> pixels by <height> pixels in size. The maximum size of a window is the size of the screen.

To specify the size of a window in text mode, the text can have a modifier in the form "text:<rows>;<columns>". This sets the window to be <rows> text lines in height by <columns> characters in width. The maximum size of a window is the size of the screen.

To set a window to the maximum size available on the screen, you can use "max" for the <width>, <height>, <rows> or <columns> parameters.

"cursor", "nocursor" Causes the cursor to be shown (or hidden). The cursor only appears when the program is waiting for keyboard input from the user.

"echo", "noecho" Causes (or suppresses) echoing of characters that are typed. Echoing is commonly turned off in interactive programs to keep typed characters from being echoed at inappropriate places on the screen.

"nooffscreenonly", "offscreenonly" Causes or (suppresses) output from being sent to the visible window. When the offscreenonly option is active, any text and graphics output is drawn to the offscreen buffer that is maintained for every Run window but not drawn to the screen. View.Update is then used to copy the entire contents of the offscreen buffer to the Run window. By allowing numerous drawing commands to be sent to the offscreen buffer and then updating the window at one time, it is possible to get smoother animation.

"msdos", "nomsdos" Causes the window to use the MS-DOS character set (with line drawing characters) instead of the Windows ANSI character set. The "nomsdos" option causes the window to use the Windows ANSI character set. Note that the "msdos" option only works if the Windows font (usually Courier New) supports it.

"buttonbar", "nobuttonbar" Causes or (suppresses) the display of a button bar at the top of the output window which allows the user to easily stop program execution or save and print the output window.

Example This program creates a graphics window that is 300 pixels by 100 pixels.

See also the Draw module, the draw… subprograms and the View.Update procedure for doing smooth animation. See also View.Set for further setscreen options including positioning the output window on the screen.


shl

shl shift left operator

Syntax A shl B

Description The shl (shift left) operator produces the value of A shifted B bits to the left. Both A and B must be non-negative integers (natural numbers).

Example Assign the base 2 value 11 to i and then shift it left by 2 places and assign the resulting base 2 value 1100 to j.

        var i, j : int
        i := 2 # 11     % 2#11 = 3 (base 10)
        j := i shl 2        % j becomes 2#1100 = 12 (base 10)
Details The shl operator is defined mathematically (in a machine-independent way) as follows: A shl B = A * ( 2**B ). Overflow occurs when the result exceeds the maximum value of the nat4 (4-byte natural number) type.

Value A can be of any integer type (as long as it is non-negative) or any natural number type.

The shl operator has the same precedence as the * operator.

See also shr (shift right), or, and and xor, which also are bit manipulation operators that act on non-negative values. See also explicitIntegerConstant which describes values such as 2#1100.


shr

shr shift right operator

Syntax A shr B

Description The shr (shift right) operator produces the value of A shifted B bits to the right. Both A and B must be non-negative integers (natural numbers).

Example Assign the base 2 value 1101 to i and then shift it right by 2 places and assign the resulting base 2 value 11 to j.

        var i, j : int
        i := 2 # 1101   % 2#1101 = 13 (base 10)
        j := i shr 2        % j becomes 2#11 = 3 (base 10)
Details The shr operator is defined mathematically (in a machine- independent way) as follows: A shr B = A div 2**B.

Value A can be of any integer type (as long as it is non-negative) or any natural number type.

The shr operator has the same precedence as the * operator.

See also shl (shift left), or, and and xor, which also are bit manipulation operators that act on non-negative values. See also explicitIntegerConstant which describes values such as 2#1101.


sign

sign function

Syntax sign ( r : real ) : -1 .. 1

Description The sign function is used to determine whether a number is positive, zero or negative. It returns 1 if r > 0, 0 if r = 0, and -1 if r < 0. For example, sign (5) is 1 and sign (-23) is -1.

Example This program reads in numbers and determines if they are positive, zero or negative:

        var x : real
        get x
        case sign ( x ) of
            label 1 : put "Positive"
            label 0 : put "Zero"
            label -1 : put "Negative"
        end case
See also See also predefined unit Math.


signal

signal wake up a process statement

Syntax A signalStatement is:

signal variableReference

Description A signal statement is used in a concurrent program to wake up a process that is blocked (waiting on a condition variable). The statement can only be used inside a monitor (a special kind of module that handles concurrency). A signal statement operates on a condition variable (the variableReference), which is essentially a queue of sleeping processes. See condition for an example of a signal statement.

Details A signal statement wakes up one process that is doing a wait on the specified condition queue, if such a process exists. If the condition is deferred (or timeout; see condition), the signaler continues in the monitor, and the awakened process is allowed to continue only when the monitor becomes inactive. A signal to an immediate (non-deferred) condition causes the signaled process to begin running in the monitor immediately. The signaling process waits to re-enter the monitor when the monitor becomes inactive.

See also condition and wait. See also monitor and fork. See also empty. See also pause.


simutime

simutime simulated time function

Syntax simutime : int

Description The simutime function returns the number of simulated time units that have passed since program execution began.

Details Simulated time only passes when all process are either paused or waiting. This simulates the fact that CPU time is effectively infinitely fast when compared to "pause" time.

Example This prints out the simulated time passing between two processes. This will print out 3, 5, 6, 9, 10, 12, 15, 15, 18, 20, 21, …

        process p (t : int)
            loop
                pause t
                put simutime
            end loop
        end p

        fork p (3)
        fork p (5)
Execute

See also See also predefined unit Concurrency.


sin

sin sine function (radians)

Syntax sin ( r : real ) : real

Description The sin function is used to find the sine of an angle given in radians. For example, sin (0) is 0.

Example This program prints out the sine of p/6, 2p/6, 3p/6, up to 12p/6 radians.

        const pi := 3.14159
        for i : 1 .. 12
            const angle := i * pi / 6
            put "Sin of ", angle, " is ", sin ( angle )
        end for
Execute

See also the cos and tan functions for calculating cosine and tangent.

the sind function which finds the sine of an angle given in degrees. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


sind

sind sine function (degrees)

Syntax sind ( r : real ) : real

Description The sind function is used to find the sine of an angle given in degrees. For example, sind (0) is 0.

Example This program prints out the sine of 30, 60, 90, up to 360 degrees.

        for i : 1 .. 12
            const angle := i * 30
            put "Sin of ", angle, " is ", sind ( angle )
        end for
Execute

See also the cosd and tand functions for calculating cosine and tangent.

the sin function which finds the sine of an angle given in radians. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


sizeof

sizeof size of a type

Dirty

Syntax sizeof (typeNameOrVariableReference)

Description The sizeof attribute is used to find the number of bytes used to represent the type or variable. This is implementation-dependent (dirty).

Example The size of int2 and nat2 is 2.

        var i : int2
        const nat2size := sizeof ( i )  % size is 2
Details The typeNameOrVariableReference must be the name of a user-defined type, a variable reference, a basic type (such as real), or a constant.

In principle, sizeof returns the number of storage units which would not necessarily be 8-bit bytes. For example, in some older machines, such as the CDC 6000 series, the storage units are 60 bit words. However, almost all modern computers use 8-bit bytes so these are the units of sizeof.

Beware that sizes may reflect alignment constraints in the underlying computer. For example, string sizes may be rounded up to even values (2-byte word alignments).

See also the indirection operator @, cheat, explicitIntegerConstant (how to write hexadecimal constants), and pointers (in particular unchecked pointers). See also addr, which returns the address of a variable.


sizepic

sizepic graphics function

Syntax sizepic ( x1, y1, x2, y2 : int) : int

Description The sizepic function is used to determine the size buffer needed to record a picture from the screen (see description of takepic ). This gives the minimum number of elements of the int array used by takepic. The buffer is used by drawpic to make copies of the picture on the screen.

Example This program outputs the size of array needed to hold a picture with left bottom corner at x=10, y=20 and right top corner at x=50, y=60.

        setscreen ("graphics")
        …
        put "The size of the array needs to be",
            sizepic ( 10, 20, 50, 60 )
Details See takepic for an example of the use of sizepic and for further information about buffers for drawing pictures.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

See also drawpic. See also setscreen, maxx, maxy, drawdot, drawline, drawbox, and drawoval.

See also predefined unit Pic.


skip

skip used in get statement

Syntax skip

Description Using skip as an input item in a get statement causes the current input to be skipped until a non-whitespace token is encountered. Whitespace includes all blanks, tabs, form feeds and newlines.

Example The skip input item was originally intended to be used to see if more input exists in an input file. This use has been largely made redundant by a change in the Turing language. The new version of Turing reads a token, as in get s but not in get s:* or get s:3, and automatically skips any white space following the input value, but will not go beyond the beginning of the next input line. Originally this automatic skipping did not take place, so skip was required. The form of an input loop that used skip was as follows:

        loop
            get skip            % This is line now redundant
            exit when eof
            get …
            …
        end loop
Details The skip bypasses all whitespace characters including any trailing newlines and blank lines. By skipping these characters, a true end-of-file condition was detected. Otherwise, the end-of-file could have been hidden by any whitespace following the last input item. With the change in Turing, the line get skip is no longer needed (although it still works correctly).

Example The skip can also be used to correctly identify the start of a long string (usually to be read in line or counted mode). Here, it skips the whitespace and trailing newline as follows:

        var i : int
        var line : string
        loop
            get i, skip, line:*
            …
        end loop
Details The first item in the get statement reads an integer by skipping all whitespace and reading digits until whitespace is encountered. The input stream is then left with the whitespace as the next input character. The skip then skips past the whitespace, effectively beginning the next input at the next non-whitespace character. This truncates leading blanks and has another, potentially more important, effect. If the integer is the last data on a line and the string is on a following line, the skip is necessary to avoid setting line to a null string value.

See also get statement and loop statement.


skip

skip used in put statement

Syntax skip

Description Using skip as an output item in a put statement causes the current output line to be ended and a new line to be started.

Example This example, To be is output on one line and Or not to be on the next.

        put "To be", skip, "Or not to be"
Details Using skip is equivalent to outputting the newline character "\n".


sound

sound statement

Syntax sound ( frequency, duration : int )

Description The sound procedure is used to cause the computer to sound a note of a given frequency for a given time. The frequency is in cycles per second (Hertz). The time duration is in milliseconds. For example, middle A on a piano is 440 Hertz, so sound(440, 1000) plays middle A for one second.

Example This program sounds the frequencies 100, 200 up to 1000 each for half a second.

        for i : 1 .. 10
            put i
            sound ( 100 * i, 500 )  % Sound note for 1/2 second
        end for
Details On IBM PC compatibles, the hardware resolution of duration is in units of 55 milliseconds. For example, sound(440, 500) will delay the program by about half a second, but may be off by as much as 55 milliseconds.

Details The sound procedure does not currently work under MacOOT.

See also play statement, which plays notes based on musical notation. For example, play("8C") plays an eighth note of middle C. See also the delay, clock, sysclock, wallclock, time and date statements.

See also predefined unit Music.


Sprite

Description Sprites are a way of doing animation in Turing bypassing the Pic module. A sprite is essentially a picture with a specific location and "depth". You create a sprite by calling Sprite.New with a picID received from Pic.New. You can then move the sprite around by calling Sprite.SetPosition. When you are finished with the sprite, you call Sprite.Free.

Note that sprites work best when they are moderately small. If you have large sprites, you will continue to have flashing.

All subprograms in the Sprite unit are exported qualified (and thus must be prefaced with "Sprite.").

Entry Points
New | Creates a new sprite from a picture.
Free | Disposes of a sprite and free up its memory.
SetHeight | Sets the height of a sprite. Sprites with a greater height appear above sprites with a lesser height. The background is considered height 0. The height may be negative.
SetPosition | Sets the location of the sprite. Can specify the center of the sprite or the lower-left corner.
SetFrameRate | Sets the maximum number of times a second the sprites will be moved on screen.
ChangePic | Changes the picture associated with a sprite.
Animate | Changes the location and the picture associated with a sprite. Used for animating a moving changing image.
Show | Shows a previously hidden sprite.
Hide | Hides a visible sprite.


Sprite.Animate

Sprite.Animate Part of Sprite module

Syntax Sprite.Animate (spriteID, picID, x, y : int,
centered : boolean)

Description Moves the sprite specified by spriteID to the location specified by (x, y). If centered is true, then the sprite is centered on (x, y). Otherwise (x, y) specifies the lower-left corner of the sprite. At the same time, it changes the picture associated with the sprite.

A simple example of the Sprite.Animate procedure would be of a man walking. The picture associated with the sprite would constantly change as the figure was walking. At the same time, the location of the figure would also change.

Example Here is a program that loads a series of images from an animated GIF file called "mypic.gif". It works by loading the images from the GIF file into an array (see Pic.FileNewFrames for more information) and then displays the images sequentially on the screen, moving the image eight pixels each time.

        var numFrames := Pic.Frames ("mypic.gif")
        % Load the picture
        var delayTime : int
        var pics : array 1 .. numFrames of int
    Pic.FileNewFrames ("mypic.gif", pics, delayTime)

        var sprite: int
        sprite:= Sprite.New (pics (1))
        Sprite.SetPosition (sprite, 0, 100, false)
        Sprite.Show (sprite)
        for x : 8 .. maxx by 8
            Sprite.Animate (sprite, pics ((x div 8) mod numFrames + 1), x, 100, false)
            delay (40)    % Stop sprite from moving too quickly
        end for
        Sprite.Free (sprite)

Execute

Status Exported qualified.

This means that you can only call the function by calling Sprite.Animate, not by calling Animate.

See also Sprite.New, Sprite.SetPosition and Sprite.ChangePic.


Sprite.ChangePic

Sprite.ChangePic Part of Sprite module

Syntax Sprite.ChangePic (spriteID, picID : int)

Description Changes the picture associated with a sprite while maintaining the sprites height and visibility status. A typical use Sprite.ChangePic would be to animate a sprite that stays in position.

Example Here is a program that t that loads six images from files Pic1.bmp through Pic6.bmp and then displays them sequentially in the center of the screen.

        var pics : array 0 .. 5 of int
        var sprite: int
        for i : 1 .. 6
            pics (i  1) := Pic.FileNew ("Pic" + intstr (i) + ".bmp")
            if Error.Last not= 0 then
                put "Error loading image: ", Error.LastMsg
                return
            end if
        end for
        figure := Sprite.New (pics (0))
        Sprite.SetPosition (sprite, maxx div 2, maxy div 2, true)
        Sprite.Show (sprite)
        for i : 1 .. 100
            Sprite.ChangePic (sprite, pics (i mod 6))
        end for
        Sprite.Free (sprite)
Status Exported qualified.

This means that you can only call the function by calling Sprite.ChangePic, not by calling ChangePic.

See also Sprite.New.


Sprite.Free

Sprite.Free Part of Sprite module

Syntax | Sprite.Free (spriteID : int)
Description | Destroys the sprite and frees up the memory the sprite used. It is an error to use the spriteID after the sprite has been freed.
Example | See Sprite.Animate for an example of Sprite.Free.
Status | Exported qualified. This means that you can only call the function by calling Sprite.Free, not by calling Free.
See also | Sprite.New.


Sprite.Hide

Sprite.Hide Part of Sprite module

Syntax Sprite.Hide (spriteID : int)

Description Hides a previously visible sprite. Sprite.Hide has no effect if the sprite is already invisible.

Example The following program animates four balls on the screen. When the balls are close to each other or to a wall, they appear, otherwise they are hidden.

        var pic, sprite, x, y, dx, dy, radius : array 1 .. 6 of int
        var visible : array 1 .. 6 of boolean

        setscreen ("nocursor")

        % Create all the sprites.
        for i : 1 .. 6
            radius (i) := Rand.Int (10, 25)
            Draw.FillOval (25, 25, radius (i), radius (i), 8 + i)
            Font.Draw (intstr (i), 20, 20, 0, black)
            pic (i) := Pic.New (0, 0, 50, 50)
            Draw.FillBox (0, 0, 50, 50, 0)
            x (i) := Rand.Int (radius (i), maxx ‹ radius (i))
            y (i) := Rand.Int (radius (i), maxy ‹ radius (i))
            dx (i) := Rand.Int (3, 3)
            dy (i) := Rand.Int (3, 3)
            sprite (i) := Sprite.New (pic (i))
            Sprite.SetPosition (sprite (i), x (i), y (i), true)
            Sprite.SetHeight (sprite (i), i)
            visible (i) := false
        end for

        % Now move all the sprites around the screen.
        loop
            for i : 1 .. 6
                if x (i) + dx (i) < radius (i) or
                        x (i) + dx (i) > maxx  radius (i) then
                    dx (i) := dx (i)
                end if
                x (i) := x (i) + dx (i)
                if y (i) + dy (i) < radius (i) or
                        y (i) + dx (i) > maxy  radius (i) then
                    dy (i) := dy (i)
                end if
                y (i) := y (i) + dy (i)
            end for
            for i : 1 .. 6
                var near : boolean := false
                if (x (i) < 50) or (x (i) > maxx  50) or
                        (y (i) < 50) or (y (i) > maxy  50) then
                    near := true
                end if
                if not near then
                    for j : 1 .. 6
                        if i not= j then
                            if sqrt ( (x (i) ‹ x (j)) ** 2 +
                                (y (i) ‹ y (j)) ** 2) < 100 then
                                near := true
                                exit
                            end if
                        end if
                    end for
                end if
                if near and not visible (i) then
                    Sprite.Show (sprite (i))
                    visible (i) := true
                elsif not near and visible (i) then
                    Sprite.Hide (sprite (i))
                    visible (i) := false
                end if
                Sprite.SetPosition (sprite (i), x (i), y (i), true)
            end for
            Time.Delay (40)
            exit when hasch
        end loop
        for i : 1 .. 6
            Sprite.Free (sprite (i))
        end for
Status Exported qualified.

This means that you can only call the function by calling Sprite.Hide, not by calling Hide.

See also Sprite.Show.


Sprite.New

Sprite.New Part of Sprite module

Syntax Sprite.New (picID : int) : int

Description Creates a new sprite from a picture specified by picID. The sprite starts invisible and should be given a depth using Sprite.SetHeight and a position, given Sprite.SetPosition before being made visible using Sprite.Show. When you are finished using the sprite, the sprite should be freed using Sprite.Free.

Sprites work best when they are of moderate size. Large sprites will cause flashing when moved across the screen.

Anything that is is color 0 in the picture will not appear when the sprite is drawn. In other words, color 0 is transparent. (This is by default. You can set the transparent color for a sprite by setting the picture's transparent colour using Pic.SetTransparentColor.

Example See Sprite.Animate for an example of Sprite.New.

Status Exported qualified.

This means that you can only call the function by calling Sprite.New, not by calling New.

See also Sprite.SetHeight, Sprite.SetPosition, Sprite.Show and Sprite.Free.


Sprite.SetFrameRate

Sprite.SetFrameRate Part of Sprite module

Syntax Sprite.SetFrameRate (framesPerSec : int)

Description Specifies the maximum number of times per second that sprite positions will be changed on the screen. The higher the number, the smoother the animation will appear (and the more processor time will be used to perform the animation).
Details When you change the position or appearance of a sprite, Turing does not update the window immediately. Instead, it waits a certain length of time and then updates all sprites that have moved since the last update. This allows for relatively smooth animation.

This means that you have a simple loop that calls Sprite.SetPosition 200 times a second, the image of the sprite on the screen is still only being moved (by default) 33 times a second.

You can specify how many times a second Turing checks to see if a sprite has moved by using the Sprite.SetFrameRate procedure. Rates of 5-10 will make the movement of the sprites seem very choppy. Rates of 100 are more or less completely smooth (the maximum is 120) and most CRT's will not notice any difference after 60. The default rate is 33 frames per second. You should note that if you set the rate higher than your computer can handle, every other part of your program will slow down as Turing will be checking for sprite movement rather than executing your program.

A modern PC (2+ GHz with a decent graphics card) can probably handle a frame rate of 60+, depending on the number of sprites. A Pentium III should probably use the default rate. Slower machines should probably use a lower rate (around 20). Experimentation is the best way to determine the ideal frame rate.

Status Exported qualified.

This means that you can only call the function by calling Sprite.SetFrameRate, not by calling SetFrameRate.


Sprite.SetHeight

Sprite.SetHeight Part of Sprite module

Syntax Sprite.SetHeight (spriteID, newHeight : int)

Description Sets the height of the sprite specified by spriteID to the value specified by newHeight.

The height of a sprite determines which sprite appears above another when they overlap. The "higher" sprite (the one with the greater height) will appear on top of the sprite with the lower height, even if the lower sprite is drawn second.

The background (i.e. any non-sprite) is considered to be in height 0. Sprites with a negative height will appear "behind" the background. Note that if two sprites have the same height, the one drawn last will appear above the first one.

Example See Sprite.Hide for an example of Sprite.SetHeight.

Details It should be noted that a lot more computation must be done to display sprites with a negative height. If you are on a slower machine and performance is not sufficient, consider trying to eliminate the use of sprites moving behind the background.

Status Exported qualified.

This means that you can only call the function by calling Sprite.SetPosition, not by calling SetPosition.

See also Sprite.New.


Sprite.SetPosition

Sprite.SetPosition Part of Sprite module

Syntax | Sprite.SetPosition (spriteID, x, y : int, centered : boolean)
Description | Moves the sprite specified by spriteID to the location specified by (x, y). If centered is true, then the sprite is centered on (x, y). Otherwise (x, y) specifies the lower-left corner of the sprite.
Example | See Sprite.Hide for an example of Sprite.SetPosition.
Status | Exported qualified. This means that you can only call the function by calling Sprite.SetPosition, not by calling SetPosition.
See also | Sprite.New.


Sprite.Show

Sprite.Show Part of Sprite module

Syntax | Sprite.Show (spriteID : int)
Description | Displays a previously hidden sprite. Sprite.Show has no effect if the sprite is already visible.
Example | See Sprite.Hide for an example of Sprite.Show.
Status | Exported qualified. This means that you can only call the function by calling Sprite.Show, not by calling Show.
See also | Sprite.Hide.


sqrt

sqrt square root function

Syntax sqrt ( r : real ) : real

Description The sqrt function is used to find the square root of a number. For example, sqrt (4) is 2.

Example This program prints out the square roots of 1, 2, 3, … up to 100.

        for i : 1 .. 100
            put "Square root of ", i, " is ", sqrt ( i )
        end for
Details It is illegal to try to take the square root of a negative number. The result of sqrt is always positive or zero.

The opposite of a square root is the square. For example, the square of x is written is x**2.

See also See also predefined unit Math.


standardType

Syntax A standardType is one of:

(a) | int
(b) | real
(c) | string [ ( maximumLength ) ]
(d) | boolean
(e) | nat |  | % natural number
(f) | int n |  | % n-byte integer (n=1, 2, 4)
(g) | nat n |  | % n-byte natural (n= 1, 2, 4)
(h) | real n | % n-byte real (n=4, 8)
(i) | char |  | % single character
(j) | char(n) | % n characters

Description The standard types can be used throughout a program. They should not be included in an import list.

See also int, real, string and boolean. See also nat, int n, nat n, real n, char, char(n)


statement

Syntax A statement is one of:

(a) | assignmentStatement |  | % variableReference := expn
(b) | openStatement |  | % open …
(c) | closeStatement |  | % close …
(d) | putStatement |  | % put …
(e) | getStatement |  | % get …
(f) | readStatement |  | % read …
(g) | writeStatement |  | % write …
(h) | seekStatement |  | % seek …
(i) | tellStatement |  | % tell …
(j) | forStatement |  | % for … end for
(k) | loopStatement |  | % loop … end loop
(l) | exit [ when trueFalseExpn ]
(m) | ifStatement |  | % if … end if
(n) | caseStatement |  | % case … end case
(o) | assert trueFalseExpn
(p) | begin
 |  | statementsAndDeclarations
 | end
(q) | procedureCall |  | % procedureId [(parameters)]
(r) | return
(s) | result expn
(t) | new [ collectionId , ] pointerVariableReference
(u) | free [ collectionId , ] pointerVariableReference
(v) | tag unionVariableReference , expn
(w) | forkStatement |  | % fork …
(x) | signal variableReference
(y) | wait variableReference [ , expn ]
(z) | pause expn
(aa) | quit [ guiltyParty ] [ : quitReason ]
(bb) | unchecked
(cc) | checked

Description A statement (or command) causes a particular action, for example, the putStatement:

        put "Hello"
outputs Hello. See the descriptions of the individual statements for explanations of their actions. Each statement can optionally by followed by a semicolon (;).

Example

        width := 24         % Assignment statement
        put "Hello world"   % Put statement
        exit when i = 100       % Exit statement
        assert width < 320  % Assert statement
Details You can use a result statement only in a function. You can use a return statement only to terminate a procedure or the main program (but not to terminate the initialization of a module). See also result and return.

There are a number of predefined procedures, such as drawline, which are not listed as statements above. These are considered procedure calls, which is one form of statement.


statementsAndDeclarations

Syntax StatementsAndDeclarations are:

{ statementOrDeclaration }

Description StatementsAndDeclarations are a list of statements and declarations. For example, a Turing program consists of a list of statements and declarations. The body of a procedure is a list of statements and declarations.

Each statementOrDeclaration is one of:

        (a) statement
        (b) declaration
See also statement and declaration.

Example This list of statements and declarations is a Turing program that outputs Hello Frank.

        var name : string
        name := "Frank"
        put "Hello ", name


Str

Description This unit contains the predefined constants for manipulating strings.

Several routines in the Str module are exported unqualified.

Entry Points

Lower | Convert a string to lower case.
Upper | Convert a string to upper case.
Trim | Remove leading and trailing blanks.
index | Finds a specified string in another string.
length | Returns the length of a string.
repeat | Creates a string by repeating a specified string a number of times.


Str.Lower

Str.Lower Part of Str module

Syntax Str.Lower (s : string) : string
Description The Str.Lower function takes the string s and returns a string in which all the upper case letters are converted to lower case. For example, Str.Lower ("ABC123def") returns "abc123def".

Example This program obtains lines of text from the user and outputs the lines converted to lower case.

        var line : string
        loop
            put "Enter a line of text (empty to quit): " ..
            get line : *
            exit when line = ""
            put "The lower case version: ", Str.Lower (line)
        end loop
Execute

Status Exported qualified.

This means that you can only call the function by calling Str.Lower, not by calling Lower.

See also Str.Upper and Str.Trim.


Str.Trim

Str.Trim Part of Str module

Syntax Str.Trim (str : string) : string
Description The Str.Trim function takes the string str and returns a string in all the leading and trailing spaces (the spaces at the beginning and the end) are deleted. For example, Str.Trim (" This is a test ") returns "This is a test". If str only has spaces in it, then Str.Trim will return an empty string.

Example This program obtains input from the user until the user enters a line with non-whitespace characters in it.
        var line : string
        loop
            put "Enter a non-empty line of text: " ..
            get line : *
            exit when Str.Trim (line) not= ""
        end loop
        put "You entered ", line
Execute

Status Exported qualified.

This means that you can only call the function by calling Str.Trim, not by calling Trim.

See also Str.Lower and Str.Upper.


Str.Upper

Str.Upper Part of Str module

Syntax Str.Upper (s : string) : string
Description The Str.Upper function takes the string s and returns a string in which all the lower case letters are converted to upper case. For example, Str.Upper ("ABC123def") returns "ABC123DEF".

Example This program obtains lines of text from the user and outputs the lines converted to upper case.

        var line : string
        loop
            put "Enter a line of text (empty to quit): " ..
            get line : *
            exit when line = ""
            put "The upper case version: ", Str.Upper (line)
        end loop
Execute

Status Exported qualified.

This means that you can only call the function by calling Str.Upper, not by calling Upper.

See also Str.Lower and Str.Trim.


Stream

Description This unit contains the predefined subprograms that deal with I/O streams. The basic I/O in Turing is done with I/O statements. However, extra functions are all part of the Stream unit.

All routines in the Stream unit are exported qualified (and thus must be prefaced with "Stream."), with the exception of eof which is part of the language but conceptually part of this unit and is considered to be exported unqualified.

Entry Points
eof* | Determines if the end of file has been reached.
Flush | Flushes a specified stream.
FlushAll | Flushes all open output streams.

* Part of the language, conceptually part of the Stream unit.


Stream.eof

Stream.eof Part of Stream module

Syntax eof ( streamNumber : int ) : boolean

Description The eof (end of file) function is used to determine if there is any more input. It returns true when there are no more characters to be read. The parameter and its parentheses are omitted when referring to the standard input (usually this is the keyboard); otherwise the parameter specifies the number of a stream. The stream number has been determined (in most cases) by an open statement.

Example This program reads and outputs all the lines in the file called "info".

        var line : string
        var fileNumber : int
        open : fileNumber, "info", get
        loop
            exit when eof (fileNumber)
            get : fileNumber, line : *
            put line
        end loop
Details See also the description of the get statement, which gives more examples of the use of eof. See also the open and read statements.

When the input is from the keyboard, the user can signal end-of-file by typing control-Z on a PC (or control-D on UNIX). If a program tests for eof on the keyboard, and the user has not typed control-Z (or control-D) and the user has typed no characters beyond those that have been read, the program must wait until the next character is typed. Once this character is typed, the program knows whether it is at the end of the input, and returns the corresponding true or false value for eof.

Status Part of the language and only conceptually part of the Stream unit.

This means that you can only call the function by calling eof, not by calling Stream.eof.


Stream.Flush

Stream.Flush Part of Stream module

Syntax | Stream.Flush ( streamNumber : int )
Description | The Stream.Flush procedure is used to flush any buffered output associated with the streamNumber parameter.
Details | Turing automatically flushes any buffered output when a stream is closed. Turing also automatically closes any open files when execution is terminated.
Status | Exported qualified. This means that you can only call the function by calling Stream.Flush, not by calling Flush.


Stream.FlushAll

Stream.FlushAll Part of Stream module

Syntax | Stream.FlushAll
Description | The Stream.FlushAll procedure is used to flush any buffered output in any open file.
Details | Turing automatically flushes any buffered output when a stream is closed. Turing also automatically closes any open files when execution is terminated.
Status | Exported qualified. This means that you can only call the function by calling Stream.FlushAll, not by calling FlushAll.


string

string type

Syntax A stringType is:

string [ ( maximumLength ) ]

Description Each variable whose type is a stringType can contain a sequence (a string ) of characters. The length of this sequence must not exceed the stringType's maximum length.

Example

        var name : string
        name := "Nancy"
        var licenceNumber : string ( 6 )
        licenceNumber := "175AJN"
Details Strings can be assigned and they can be compared for both equality and for ordering. See also string comparison and assignment statement.

Strings can be catenated (joined together) using the + operator and separated into substrings. See catenation and substring. String functions are provided to find the length of a string, to find where one string appears inside another, and to make repeated copies of a string all joined together. See length, index, and repeat.

A string type written without a maximum length is limited to holding a maximum of 255 characters.

The maximumLength of a string, if given as a part of the type, must be known at compile time, and must be at least 1 and at most 255. The maximum length of a string is given by upper, for example, upper(licenceNumber) is 6. See also upper.

In the declaration of a string that is a var formal parameter of a procedure or function, the maximumLength can be written as an asterisk (*). Here, the maximum length is taken to be that of the corresponding actual parameter, as in:

        procedure deblank (var s : string (*) ).
The star can also be used when the parameter is an array of strings.

See also explicitStringConstants for exact rules for writing string values such as "Nancy". See also char(n) and char types.


string

string comparison

Syntax A stringComparison is one of:

(a) | stringExpn = stringExpn
(b) | stringExpn not= stringExpn
(c) | stringExpn > stringExpn
(d) | stringExpn < stringExpn
(e) | stringExpn >= stringExpn
(f) | stringExpn <= stringExpn

Description Strings (stringExpns) can be compared for equality (= and not=) and for ordering (>, <, >= and <=).

Example

        var name : string := "Nancy"
        var licenceNumber : string ( 6 )
        licenceNumber := "175AJN"
Details Two strings are considered to be equal (=) if they have the same length and are made up, character by character, of the same characters. If they differ, they are considered to be unequal (not=).

Ordering among strings is essentially alphabetic order. String S is considered to come before string T, that is S < T, if the two are identical up to a certain position and after that position, either the next character of S comes before the next character of T, or else there are no more characters in S while T contains more characters.

S > T (S comes after T ) means the same thing as T < S. S >= T means the same thing as S > T or S = T. S <= T means the same thing as S < T or S=T.

ASCII gives the ordering among individual characters. It specifies, among other things, that letter capital L comes alphabetically before capital letter M and similarly for small (lower case) letters.

On IBM mainframe computers, the EBCDIC specification of characters may be used instead of ASCII.


strint

strint string-to-integer

function

Syntax strint ( s : string [ , base : int ] ) : int

Description The strint function is used to convert a string to an integer. The integer is equivalent to string s. The number base parameter is optional, for example, strint ("47") = 47. In Turing proper, the base is not allowed and is assumed to be 10.

String s must consist of a possibly null sequence of blanks, then an optional plus or minus sign, and finally a sequence of one or more digits. For number bases larger than 10, the digits can include a, b, c … (alternately A, B, C …) which represent the digit values 10, 11, 12 … The base, if given, must be in the range 2 to 36 (36 because there are 10 base ten digits and 26 letters). For example, strint ("FF", 16) = 255.

The intstr function is the inverse of strint, so for any integer i,

        strint ( intstr ( i ) ) = i.
See also chr, ord, intstr and strnat functions.


strintok

strintok string-to-integer

function

Syntax | strintok ( s : string [ , base : int ] ) : boolean
Description | The strintok function is used determine whether the strint function can be used to convert the string to an integer without causing an error. If the string can be successfully converted, then strintok returns true, otherwise it returns false. String s should consist of a possibly null sequence of blanks, then an optional plus or minus sign, and finally a sequence of one or more digits. For number bases larger than 10, the digits can include a, b, c … (alternately A, B, C …) which represent the digit values 10, 11, 12 … If s is correctly constructed, then strnatok will return true, otherwise it returns false. The base, if given, must be in the range 2 to 36 (36 because there are 10 base ten digits and 26 letters). For example, strintok ("FF", 16) = true.
See also | strint function that does the actual conversion.


strnat

strnat string to natural number function

Syntax strnat ( s : string [ , base : int ] ) : nat

Description The strnat function is used to convert a string to a natural number. The natural number is equivalent to string s. The number base parameter is optional, for example, strnat("47") = 47.

String s must consist of a possibly null sequence of blanks, then an optional plus sign, and finally a sequence of one or more digits. For number bases larger than 10, the digits can include a, b, c … (alternately A, B, C …) which represent the digit values 10, 11, 12 … The base, if given, must be in the range 2 to 36 (36 because there are 10 base ten digits and 26 letters). For example, strnat("FF", 16) = 255.

The natstr function is the inverse of strnat, so for any natural number n, strnat( natstr (n)) = n.

The strnat function is similar to strint, except that strnat handles values that are larger than int values and does not handle negative values.

See also the chr, ord, intstr and strint functions.


strnatok

strnatok string to natural number function

Syntax | strnatok ( s : string [ , base : int ] ) : boolean
Description | The strnatok function is used determine whether the strnat function can be used to convert the string to a natural number without causing an error. If the string can be successfully converted, then strnatok returns true, otherwise it returns false. String s should consist of a possibly null sequence of blanks, then an optional plus sign, and finally a sequence of one or more digits. For number bases larger than 10, the digits can include a, b, c … (alternately A, B, C …) which represent the digit values 10, 11, 12 … If s is correctly constructed, then strnatok will return true, otherwise it returns false. The base, if given, must be in the range 2 to 36 (36 because there are 10 base ten digits and 26 letters). For example, strnatok ("FF", 16) = true.
See also | strnat function that does the actual conversion.


strreal

strreal string-to-real function

Syntax strreal ( s : string ) : real

Description The strreal function is used to convert a string to a real number. For example, strreal ("2.5e1") will produce an approximation to the number 25.0.

String s must consist of a possibly null sequence of blanks, then an optional plus or minus sign and finally an explicit unsigned real or integer constant.

The realstr, erealstr and frealstr functions approximate the inverse of strreal, although round-off errors keep these from being exact inverses.

See also realstr, erealstr, frealstr, intstr and strint functions.


strrealok

strrealok string-to-real function

Syntax | strrealok ( s : string ) : boolean
Description | The strrealok function is used determine whether the strreal function can be used to convert the string to a real number without causing an error. If the string can be successfully converted, then strrealok returns true, otherwise it returns false. String s should consist of a possibly null sequence of blanks, then an optional plus or minus sign and finally an explicit unsigned real or integer constant. If it does so, then strrealok will return true, otherwise it returns false.
See also | strreal function that does the actual conversion.


subprogramHeader

Syntax A subprogramHeader is one of:

(a) | procedure [ pervasive ] id
 |  | [ ([ paramDeclaration {, paramDeclaration} ])]
(b) | function [ pervasive ] id
 |  | [ ([ paramDeclaration {, paramDeclaration} ])]
 |  | [ id ] : typeSpec

Description A subprogram header is used to describe the interface to a subprogram. Subprogram headers are used within other language features such as subprogram types and external declarations.

Parameterless subprograms may use parentheses (with nothing between them), as is required in the C programming language. These parentheses can be used to disambiguate between the call to the subprogram (parentheses present) and a reference the subprogram (parentheses missing).

Suppose f is a parameterless subprogram declared without parentheses and g is a parameterless subprogram declared with parentheses. Their headers are:

        procedure f
        procedure g ()
In a program, f and g() are calls to these functions, while g is a reference to (not a call to) the procedure. There is no way to write a reference to f. When in doubt, use parentheses in the declaration, as in the case for g, so that calls always have parentheses and references always do not. A reference to a subprogram can be assigned to a subprogram variable. See subprogram type.

Example Specify that t is the type of procedure with a var integer parameter and a real parameter. See also subprogramType.

        type t : procedure q ( var j : int, y : real )
Details The keyword pervasive can be inserted just after procedure or function. When this is done, the subprogram is visible inside all subconstructs of the subprogram's scope. Without pervasive, the subprogram is not visible inside modules unless explicitly imported. Pervasive subprograms need not be imported. You can abbreviate pervasive as an asterisk (*).

See also pervasive.


subprogramType

Syntax A subprogramType is:

subprogramHeader

Description A variable or constant can contain a reference to a subprogram. The type of the variable or constant is a subprogramType. See also subprogramHeader.

Example In the following t is a subprogram type, and u is a variable of type t initialized to refer to procedure rnd.

        procedure rnd ( var i : int, x : real)
            i := round ( x )
        end rnd

        type t : procedure q ( var j : int, y : real )
        var u : t := rnd    % Procedure variable u refers to rnd
        …
        var j : int
        u ( j, 24.6 )       % Call procedure u referring to rnd
        …
        var v := u      % Subprogram variable v initialized to u
Details The name of the subprogram, for example q, and the parameters, for example i and x, have no meaning in a subprogram type. They are present only because of the form of subprogram headers.

If v is a variable or constant that refers to a subprogram, v can be called, compared for equality to other subprogram variables, assigned and passed as a parameter. Variable v is not an integer, string or pointer and cannot participate in their corresponding operations.

A reference to a subprogram, rather that the code of the subprogram, is contained in a variable v whose type is a subprogram type. This implies that addr (v) is the address of the reference to subprogram, rather than the address of the subprogram. The address of the code is given by #v. See cheat for an explanation of the # operator.

You cannot assign a reference to a subprogram exported from a class. This restriction exists because these subprograms are meaningless without an accompanying reference to an object.

Many potential uses of subprogram variables are better programmed using classes and overriding exported subprograms. See class.


subrangeType

Syntax A subrangeType is:

expn .. expn

Description A subrange type defines a set of values, for example, the subrange 1 .. 4 consists of 1, 2, 3 and 4.

Example

        var i : 1 .. 10         % i can be 1, 2 … up to 10
        type xRange : 0 .. 319      % Define integer subrange
        var pixels : array xRange of int
                            % Array elements are
                            % numbered 0, 1, … 319
        for k : xRange          % k ranges from 0 to 319
            pixels ( k ) := 0
        end for
Details A subrange must contain at least one element. In other words, the second expression (expn) must be at least as large as the first expression.

The lower bound of a subrange must be known at compile time. The upper bound is allowed to be a run time value only in one situation and that is when it gives the upper bound of an array being declared in a variable declaration, in other words when declaring a dynamic array.

Subranges are usually a subset of the integers, as in 1 .. 10. You can also have subranges of enumerated types and characters (the char type).

You can apply lower and upper to subrange types.


substring

substring of another string

Syntax A substring is one of:

(a) | stringReference ( leftPosition .. rightPosition )
(b) | stringReference ( charPosition )

Description A substring selects a part of another string. In form (a) the substring starts at the left position and runs to the right position. In form (b), the substring is only a single character. Turing support substrings of char(n) values.

Example

        var word : string := "bring"
        put word (2 .. 4)       % Outputs rin
        put word (3)        % Outputs i
        put word (2 .. *)       % Outputs ring; the star (*) means
                        % the end of the string.
        put word (* - 2 .. * - 1 )  % Outputs in
Details The leftmost possible position in a string is numbered 1. The last position in a string can be written as an asterisk (*). For example, word (2 .. *) is equivalent to word (2 .. length(word)).

Each of leftPosition, rightPosition, and charPosition must have one of these forms:

(a) expn
(b) *
(c) * - expn

The exact rules for the allowed values of leftPosition and rightPosition are:

(1) leftPosition must be at least 1,
(2) rightPosition must be at most length (stringReference), and
(3) the length of the selected substring must zero or more.

This specifically allows null substrings such as word (1, 0) in which rightPosition is 0 and word (6, 5) in which leftPosition is one more that length (stringReference).

Note that substrings are not assignable. For example, if s is a string, the statement s (3) := "a" is illegal in Turing.

Turing supports substrings of char(n) values. See char(n). If a substring of char(n) value t has two operands, as in t(2..77), the result type of this operation is a string. If the substring has one operand, as in t(7), this becomes, in effect, a subscript into an array of characters. The result is a reference to a char, which can be assigned to or passed to a var parameter.

See also string, char, char(n), explicitStringConstant, explicitCharConstant, catenation and length.


succ

succ successor function

Syntax succ ( expn )

Description The succ function accepts an integer, character or an enumerated value and returns the integer plus one, the next character, or the next value in the enumeration. For example, succ (7) is 8.

Example This part of a Turing program fills up array a with the enumerated values green, yellow, red, green, yellow, red, etc.

        type colors : enum ( green, yellow, red  )
        var a : array 1 .. 100 of colors
        var c : colors := colors .green
        for i : 1 .. 100
            a ( i ) := c
            if c = colors . red then
                c := colors . green
            else
                c := succ ( c )
            end if
        end for
Details You cannot apply succ to the last value of an enumeration.

See also the pred, lower and upper functions.


Sys

Description This unit contains the predefined subprograms that deal with the operating system directly (getting the process id, getting run time arguments and executing commands in the operating system, etc.).

All routines in the Sys unit are exported qualified (and thus must be prefaced with "Sys.").

Entry Points
GetComputerName | Gets the name of the computer.
GetEnv | Gets a string associated with an environment variable.
GetPid | Gets the current process ID for Turing.
GetUserName | Gets the name of the user currently logged on.
Exec | Executes a program or opens a data file using the operating system.
Nargs | Gets the number of run time arguments (exported unqualified).
FetchArg | Gets a specified run time argument (exported unqualified).


Sys.Exec

Sys.Exec Part of Sys module

Syntax Sys.Exec ( command : string ) : boolean

Description The Sys.Exec function is used to execute an application or more often, open a data file with its associated application. Sys.Exec can be used to launch such programs as the Internet Browser by specifying a URL. Sys.Exec launches the application associated with file's suffix. (In essence, it performs the same operation as if a user double clicked on the file.)

Example This program launches an internet browser and points it to Holt Software's home page. It then launches a movie using the default video player.

        if not Sys.Exec ("http://www.holtsoft.com/turing/support") then
            put "The Sys.Exec call failed"
            put "Error: ", Error.LastMsg
        end if
        if not Sys.Exec ("skate.avi") then
            put "The Sys.Exec call failed"
            put "Error: ", Error.LastMsg
        end if
Details When the Sys.Exec procedure is used, the executing program continues execution immediately while the launched application is running.

Status Exported qualified.

This means that you can only call the function by calling Sys.Exec, not by calling Exec.

See also Sys.Nargs, Sys.FetchArg and Sys.GetEnv functions.


Sys.FetchArg

Sys.FetchArg Part of Sys module

Syntax System.FetchArg ( i : int ) : string

Description The Sys.FetchArg function is used to access the i-th argument that has been passed to a program from the command line. For example, if the program is run from the Turing environment using

:r file1 file2

then Sys.FetchArg (2) will return "file2". If a program called prog.x is run under UNIX using this command:

prog.x file1 file2

the value of Sys.FetchArg(2) will similarly be "file2".

The Sys.Nargs function, which gives the number of arguments passed to the program, is usually used together with the Sys.FetchArg function. Parameter i passed to Sys.FetchArg must be in the range 0 .. Sys.Nargs.

The 0-th argument is the name of the running program.

Example This program lists its own name and its arguments.

        put "The name of this program is : ", Sys.FetchArg ( 0 )
        for i : 1 .. Sys.Nargs
            put "Argument ", i, " is ", Sys.FetchArg ( i )
        end for
Status Exported qualified.

This means that you can only call the function by calling Sys.FetchArg, not by calling FetchArg.

See also Sys.Nargs


Sys.GetComputerName

Sys.GetComputerName Part of Sys module

Syntax Sys.GetComputerName : string

Description The Sys.GetComputerName function is used to determine the name of the computer. On the PC, this is the NetBIOS name. It returns “No Name” if a name could not be determined.

Example This program outputs a greeting to the user .

        var computerName, userName : string
        computerName := Sys.GetComputerName
        userName := Sys.GetUserName
        put "Hello ", userName, " on ", computerName
Status Exported qualified.

This means that you can only call the function by calling Sys. GetComputerName, not by calling GetComputerName.

See also Sys.GetUserName to obtain the user name of the user currently logged in.


Sys.GetEnv

Sys.GetEnv Part of Sys module

Syntax Sys.GetEnv ( symbol : string ) : string

Description The Sys.GetEnv function is used to access the environment string whose name is symbol. These strings are determined by the shell (command processor) or the program that caused your program to run. See also the Sys.Nargs and Sys.FetchArg functions.

Example On a PC, this retrieves the environment variable USERLEVEL and prints extra instructions if USERLEVEL had been set to NOVICE. USERLEVEL can be set to NOVICE with the command SET USERLEVEL = NOVICE in the autoexec.bat file or in any batch file.

        const userLevel : string
        userLevel := Sys.GetEnv ("USERLEVEL")
            if userLevel = "NOVICE" then
            …           % put a set of instructions
        end if
Status Exported qualified.

This means that you can only call the function by calling Sys.GetEnv, not by calling GetEnv.


Sys.GetPid

Sys.GetPid Part of Sys module

Syntax | Sys.GetPid : int
Description | The Sys.GetPid function is used to determine the I.D. (number) that identifies the current operating system task (process). Beware that there are processes, activated by the fork statement, that are independent of the operating systems tasks. Under UNIX, the number is used, for example, for creating a unique name of a file.
Status | Exported qualified. This means that you can only call the function by calling Sys.GetPid, not by calling GetPid.
See also | Sys.Nargs, Sys.FetchArg and Sys.GetEnv.


Sys.GetUserName

Sys.GetUserName Part of Sys module

Syntax Sys.GetUserName : string

Description The Sys.GetUserName function is used to determine the name of the current user. It returns “Unknown” if a name could not be determined.

Example This program outputs a greeting to the user .

        var computerName, userName : string
        computerName := Sys.GetComputerName
        userName := Sys.GetUserName
        put "Hello ", userName, " on ", computerName
Status Exported qualified.

This means that you can only call the function by calling Sys.GetUserName, not by calling GetUserName.

See also Sys.GetComputerName to obtain the name of the computer.


Sys.Nargs

Sys.Nargs Part of Sys module

Syntax Sys.Nargs : int

Description The Sys.Nargs function is used to determine the number of arguments that have been passed to a program from the command line. For example, if the program is run from the Turing environment using

        :r file1 file2
then Sys.Nargs will return 2. If a program called prog.x is run under UNIX using this command:

        prog.x file1 file2
the value of Sys.Nargs will similarly be 2.

The Sys.Nargs function is usually used together with the Sys.FetchArg function to access the arguments that have been passed to the program.

Status Exported qualified.

This means that you can only call the function by calling Sys.Nargs, not by calling Nargs.

See also Sys.FetchArg for an example of the use of Sys.Nargs.


sysclock

sysclock millisecs used procedure

Syntax sysclock ( var c : int )

Description The sysclock statement is used on a multitasking system such as UNIX to determine the amount of time that has been used by this program (process). Variable c is assigned the number of central processor milliseconds assigned to this program. This is of little use on a personal computer, where sysclock returns the same value as clock.

Example On a UNIX system, this program tells you how much time it has used.

        var timeUsed : int
        sysclock ( timeUsed )
        put "This program has used ", timeUsed,
                " milliseconds of CPU time"
See also delay, time, clock, wallclock and date statements.

See also predefined unit Time.


system

system statement

Syntax system ( command : string, var ret : int )

Description The system statement is used to execute the shell (operating system) command, as if it were typed at the terminal. The return code is in ret. A return code of 0 (zero) means no detected errors. A return code of 127 means the command processor could not be accessed. A return code of 126 means the command processor did not have room to run on the PC.

Example This program creates a directory listing when run under DOS on an IBM PC compatible computer. The same program will run under UNIX by changing "dir" to "ls".

        var success : int
        system ( "dir", success )
        if success not= 0 then
            if success= 127 then
                put "Sorry, can't find 'command.com'"
            elsif success = 126 then
                put "Sorry, no room to run 'dir'"
            else
                put "Sorry, 'dir' did not work"
            end if
        end if
Details When the system procedure is used, the executing program usually remains in memory while the system command is executing, and once execution of the system command is finished, control returns to the original program. However, on the PC, there is variant of the system procedure that allows "chaining". This means that when the system command is executed, the originally running program is "thrown away" (i.e. removed from memory). When the executed program terminates, one is returned to DOS.

To chain another program, one prepends "chain:" to the start command.

        i.e.    system ("chain:myprog.exe", retCode)
Note that this command is "hazardous". Specifically, if you call it from Turing (as opposed to a program compiled with TComp) and you have not saved your source file, you will lose it! Turing will be removed from memory without any warning when the system procedure is executed. Likewise any open files will be closed instantly. This means there is a danger if all files were not properly closed before the system procedure was called.

The "chain:" command is often used for starting menu programs, where the user selects a program to run and doesn't want Turing to remain in memory. It can also be used with extraordinarily large Turing programs that can be split into different parts. By using TComp and compiling each part separately, one can have each program call the other and never have all parts in memory at once.

Example This program uses chaining to launch one of several possible programs based on user choice. It gives an error if for some reason the system command fails to work. It assumes that c:\chemistry.exe, c:\math.exe, c:\english.exe and c:\history.exe already exist.

        var choice, success : int
        put "Enter the subject (1-4): "..
        get choice
        var command : string
        case choice of
            % Note the use of the double backslash in the file name. This
            % is because the backslash is a special character in Turing (as
            % in \t for tab and \n for a newline). To get a single backslash,
            % one uses \\.
            label 1 :   command := "c:\\chemistry.exe"
            label 2 :   command := "c:\\math.exe"
            label 3 :   command := "c:\\english.exe"
            label 4 :   command := "c:\\history.exe"
            label :     put "Choice must be from 1-4."
                    assert false    % Wasn't a 1-4. Terminate.
        end case
        system ( "chain:" + command, success)
        % If I reach this line, the system command failed and one should give
        % an error message.
        put "System called failed."
        put "Program \"", command, "\"  couldn't be run."
        assert false    % Terminate the program
Details Here are the possible errors under PC-Turing

-1 | Not enough memory to load COMMAND.COM
-2 | Not enough memory to run command
-3 | Argument list greater than 128 bytes or environment info
is greater than 32k
-4 | Couldn't find COMMAND.COM
-5 | COMMAND.COM corrupt
-6 | -noshell option is selected, the system procedure is
disallowed

See also nargs, fetcharg and getenv functions.

See also predefined unit Sys.


tag

tag statement

Syntax A tagStatement is:

tag unionVariableReference , expn

Description A tag statement is a special-purpose assignment that is used for changing the tag of a union variable.

Example In this example, the tag field of union variable v is set to be passenger, thereby activating the passenger field of v.

        type vehicleInfo :
            union kind : passenger .. recreational
                label passenger :
                    cylinders : 1..16
                label farm :
                    farmClass : string ( 10 )
                label : % No fields for "otherwise" clause
            end union
        var v : vehicleInfo
        …
        tag v, passenger        % Activate passenger part
Details A tag statement is the only way to modify the tag field of a union variable (other than by assigning an entire union value to the union variable).

You cannot access a particular set of fields of a union unless the tag is set to match the corresponding label value.

See also union types.


takepic

takepic graphics procedure

        setscreen ("graphics")
        … draw happy face in the box (0,0) to (100,100) …
        % Create buffer big enough to hold happy face
        var face : array 1 .. sizepic ( 0, 0, 100, 100 ) of int
        % Copy picture into the buffer, which is the face array
        takepic ( 0, 0, 100, 100, face )
        % Redraw the picture with its left bottom at (200,0)
        drawpic ( 200, 0, face, 0 )
Syntax takepic (x1, y1, x2, y2 : int, var buffer : array 1 .. * of int)

Description The takepic procedure is used to record the pixel values in a rectangle, with left bottom and right corners of (x1, y1) and (x2, y2), in the buffer array. This requires a sufficiently-large buffer (see sizepic ). The drawpic procedure is used to make copies of the recorded rectangle on the screen.

Example After drawing a happy face, this program copies the face to a new location.

Execute

Details The integer values that takepic places in the buffer can be read or written (using the read and write statements). Unfortunately, if a value happens to be the pattern used to represent the uninitialized value (the largest negative number the hardware can represent) assignment (by:=) and put of the individual integer values in the buffer will fail.

The screen should be in a "graphics" mode. See the setscreen procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

Details The drawpic, takepic, and sizepic subprograms have been made obsolete by the subprograms Pic.Draw and Pic.New of the Pic module. Users are strongly suggested to use those routines instead. The Pic module also contains subprograms to load images from files.

See also sizepic and drawpic. See also setscreen, maxx, maxy, drawdot, drawline, drawbox, and drawoval.

See also predefined unit Pic.


tan

tan tangent function (radians)

Syntax tan ( r : real ) : real

Description The tan function is used to find the tangent of an angle given in radians. For example, tan (p/4) is 0.5.

Example This program prints out the tangent of 0, p/6, 2p/6, 3p/6, up to 12p/6 radians.

        for i : 0 .. 12
            const angle := i * Math.PI / 6
            put "Tangent of ", angle, " is ", tan ( angle )
        end for
Execute

Details An argument to tan of p/2, 3*p/2, etc. may result in an overflow (and halt of the program) as the result is technically ¥. (It may not cause an overflow due to rounding, in which case the result will simply be a very large number.)
See also the sin and cos functions for calculating sine and cosine.

the tand function which finds the tangent of an angle given in degrees. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


tand

tand tangent function (degrees)

Syntax tand ( r : real ) : real

Description The tand function is used to find the tangent of an angle given in degrees. For example, tand (45) is 1.

Example This program prints out the tangent of 0, 30, 60, 90, up to 360 degrees.

        for i : 0 .. 12
            const angle := i * 30
            put "Tan of ", angle, " is ", tand ( angle )
        end for
Execute

Details An argument to tan of 90, 270, etc. may result in an overflow (and halt of the program) as the result is technically ¥. (It may not cause an overflow due to rounding, in which case the result will simply be a very large number.)
See also the sind and cosd functions for calculating sine and cosine.

the tan function which finds the tangent of an angle given in radians. (2p radians are the same as 360 degrees.)

See also predefined unit Math.


tell

tell file statement

Syntax An tellStatement is:

tell : fileNumber , filePositionVar

Description The tell statement sets filePositionVar, whose type must be int, to the current offset in bytes from the beginning of the specified file. The fileNumber must specify a file that is open with seek capability (or else a program argument file that is implicitly opened). The tell statement is useful for recording the file position of a certain piece of data for later access using seek.

Example This example shows how to use tell to record the location of a record in a file. This location is later used by seek to allow the record to be read.

        var employeeRecord :
            record
                name : string ( 30 )
                pay : int
                dept : 0 .. 9
            end record
        var fileNo : int
        var location : int
        open : fileNo, "payroll", write, seek
        …
        tell : fileNo, location         % Make note of this location
        write : fileNo, employeeRecord  % Write record at this location
        …
        seek : fileNo, location     % Go back to location
        read : fileNo, employeeRecord   % Read the record
                            % that was previously written
See also the read, write, open, close, seek, get and put statements.


Text

Description This unit contains the predefined subprograms that handle character (text) output on the screen (i.e. output using put).

All routines in the Text unit are exported qualified (and thus must be prefaced with "Text.") with the exception of maxrow and maxcol which are exported unqualified.

Entry Points
Cls | Clears the screen to the text background color.
Color | Sets the text color used by put.
Colour | Sets the text color used by put.
ColorBack | Sets the text background color used by put.
ColourBack | Sets the text background color used by put.
Locate | Moves the cursor to the specified row and column.
LocateXY | Moves the cursor to the cursor location closest to a specified pixel position.
maxcol | The number of columns on the screen (exported unqualified).
maxrow | The number of rows on the screen (exported unqualified).
WhatRow | Returns the current cursor row.
WhatCol | Returns the current cursor column.
WhatColor | Returns the current text color.
WhatColour | Returns the current text color.
WhatColorBack | Returns the current text background color.
WhatColourBack | Returns the current text background color.


Text.Cls

Text.Cls Part of Text module

Syntax | Text.Cls
Description | The Text.Cls (clear screen) procedure is used to blank the screen to the text background color. The cursor is set to the top left (to row 1, column 1).
Details | The screen should be in a "screen" or "graphics" mode. If the screen mode has not been set, it will automatically be set to "screen" mode. See View.Set for details.
Status | Exported qualified. This means that you can only call the function by calling Text.Cls, not by calling Cls.


Text.Color

Text.Color Part of Text module

Syntax Text.Color ( Color : int )

Description The Text.Color procedure is used to change the currently-active color. This is the color of characters that are to be put on the screen. The alternate spelling is Text.Colour.

Example This program prints out the message "Bravo" three times, each in a different color.

        View.Set ( "graphics" )
        for i : 1 .. 3
            Text.Color ( i )
            put "Bravo"
        end for
Example This program prints out a message. The color of each letter is different from the preceding letter. For letter number i the color number is i mod maxcolor + 1. This cycles repeatedly through all the available colors.

        View.Set ( "screen" )
        const message := "Happy New Year!!"
        for i : 1 .. length ( message )
            Text.Color ( i mod maxcolor + 1 )
            put message ( i ) ..
        end for
Details In "screen" mode on the IBM PC, the color specified can actually range from 0 - 31. The upper 16 colors (16-31) are the same as the lower 16, except that they blink.

See View.Set for the number of colors available in the various "graphics" modes.

The screen should be in a "screen" or "graphics" mode. If the screen mode has not been set, it will automatically be set to "screen" mode. See View.Set for details.

Status Exported qualified.

This means that you can only call the function by calling Text.Color, not by calling Color.

See also Text.ColorBack, Text.WhatColor, Text.WhatChar and View.maxcolor.


Text.ColorBack

Text.ColorBack Part of Text module

Syntax Text.ColorBack ( Color : int )

Description The Text.ColorBack procedure is used to change the current text background color. The alternate spelling is Text.ColourBack.

The Text.ColorBack procedure sets the text background color to the specified color. This is the color that surrounds characters when they are put onto the screen. On an IBM PC in "screen" mode, the color can be from 0 - 7. (You can not have the upper 8 colors as text background colors. On UNIX dumb terminals, Text.ColorBack(1) turns on highlighting and Text.ColorBack(0) turns it off. On other systems, this procedure may have no effect.

Example Since this program is in "screen" mode, changing the background color has no immediately observable effect. When the message "Greetings" is output, the background surrounding each letter will be red.

        View.Set ( "screen" )
        …
        Text.ColorBack ( red )
        put "Greetings"
Details The screen should be in a "screen" or "graphics" mode. If the screen mode has not been set, it will automatically be set to "screen" mode. See View.Set for details

Status Exported qualified.

This means that you can only call the function by calling Text.ColorBack , not by calling ColorBack.

See also Text.Color and Text.WhatColorBack.


Text.Locate

Text.Locate Part of Text module

Syntax Text.Locate ( row, column : int )

Description The Text.Locate procedure is used to move the cursor so that the next output from put will be at the given row and column. Row 1 is the top of the screen and column 1 is the left side of the screen.

Example This program outputs stars of random colors to random locations on the screen. The variable colr is purposely spelled differently from the word color to avoid the procedure of that name (used to set the color of output). The row number is purposely chosen so that it is one less than maxrow. This avoids the scrolling of the screen which occurs when a character is placed in the last column of the last row.

        View.Set ("screen")
        var row, column, colr : int
        loop
            row := Rand.Int (1, maxrow)
            column := Rand.Int (1, maxcol)
            colr := Rand.Int (0, maxcolor)
            Text.Color (colr)
            Text.Locate (row, column )
            put "*" ..  % Use dot-dot to avoid clearing end of line
        end loop
Details The Text.Locate procedure is used to locate the next output based on row and column positions. See also the Text.LocateXY procedure which is used to locate the output based x and y positions, where x=0, y=0 is the left bottom of the screen.

The screen should be in a "screen" or "graphics" mode. See the View.Set procedure for details. If the screen is not in one of these modes, it will automatically be set to"screen" mode.

Status Exported qualified.

This means that you can only call the function by calling Text.Locate , not by calling Locate.

See also View.Set and Draw.Dot.


Text.LocateXY

Text.LocateXY Part of Text module

Syntax Text.LocateXY ( x , y : int )

Description The Text.LocateXY procedure is used to move the cursor so that the next output from put will be at approximately (x, y). The exact location may be somewhat to the left of x and below y to force alignment to a character boundary.

Example This program outputs Hello starting at approximately (100, 50) on the screen.

        View.Set ("graphics")
        Text.LocateXY ( 100, 50 )
        put "Hello"
Details The Text.LocateXY procedure is used to locate the next output based on x and y positions, where the position x=0, y=0 is the left bottom of the screen. See also the Text.Locate procedure which is used to locate the output-based row and column positions, where row 1 is the top row and column 1 is the left column.

The screen should be in a "graphics" mode. See the View.Set procedure for details. If the screen is not in a "graphics" mode, it will automatically be set to "graphics" mode.

Status Exported qualified.

This means that you can only call the function by calling Text.LocateXY , not by calling LocateXY.

See also View.Set and Draw.Dot.


Text.maxcol

Text.maxcol Part of Text module

Syntax maxcol : int

Description The maxcol function is used to determine the number of columns on the screen.

Example This program outputs the maximum column number.

        put "Number of columns on the screen is ", maxrow
Details For IBM PC compatibles as well as most UNIX dumb terminals, in "text" or "screen" mode, maxcol = 80. For the default IBM PC compatible "graphics" mode (CGA), maxcol = 40.

Status Exported unqualified.

This means that you can call the function by calling maxcol or by calling Text.maxcol.

See also Text.Locate procedure for an example of the use of maxcol.


Text.maxrow

Text.maxrow Part of Text module

Syntax maxrow : int

Description The maxrow function is used to determine the number of rows on the screen.

Example This program outputs the maximum row number.

        put "Number of rows on the screen is ", maxrow
Details For IBM PC compatibles, maxrow = 25. For many UNIX dumb terminals, maxrow = 24.

Status Exported unqualified.

This means that you can call the function by calling maxrow or by calling Text.maxrow.

See also Text.Locate procedure for an example of the use of maxrow.


Text.WhatCol

Text.WhatCol Part of Text module

Syntax Text.WhatCol : int

Description The Text.WhatCol function is used to determine the cursor position's column.

Example This program outputs The current row is 5, the current column is 15.

        Text.Locate  ( 5, 10 )
        put "12345"..
        put "The current row is", Text.WhatRow
        put "The current column is", Text.WhatCol
Details The screen should be in a "screen" or "graphics" mode. Text.WhatCol functions properly even if the cursor is invisible.

Status Exported qualified.

This means that you can only call the function by calling Text.WhatCol , not by calling WhatCol .

See also the Text.WhatRow function, which is used to determine the cursor row. See also the Text.Locate, Text.maxrow and Text.maxcol procedure.


Text.WhatColor

Text.WhatColor Part of Text module

Syntax Text.WhatColor : int

Description The Text.WhatColor function is used to determine the current text (foreground) color, ie., the color used for characters that are output using put. The alternate spelling is Text.WhatColour.

Example This program outputs the currently-active color number. The message is also given in the currently-active color.

        View.Set ("graphics")
        …
        put "This writing is in color number ", Text.WhatColor
Details The screen should be in a "screen" or "graphics" mode. See View.Set for details.

Status Exported qualified.

This means that you can only call the function by calling Text.WhatColor, not by calling WhatColor.

See also the Text.Color procedure, which is used to set the color. See also Text.ColorBack and Text.WhatColorBack.


Text.WhatColorBack

Text.WhatColorBack Part of Text module

Syntax Text.WhatColorBack : int

Description The Text.WhatColorBack function is used to determine the current text background color. The alternate spelling is whatcolourback.

Example This program outputs the currently-active background color number. The background color of the message is determined by this number.

        View.Set ("screen")
        …
        put "The background of this writing"
        put  "is in color number ", Text.WhatColorBack
Details The screen should be in a "screen" or "graphics" mode. Beware that the meaning of background color is different in these two modes. See Text.ColorBack for details.

Status Exported qualified.

This means that you can only call the function by calling Text.WhatColorBack, not by calling WhatColorBack.

See also Text.Color and Text.WhatColor.


Text.WhatRow

Text.WhatRow Part of Text module

Syntax Text.WhatRow : int

Description The Text.WhatRow function is used to determine the cursor position's row.

Example This program outputs The current row is 5, the current column is 15.

        Text.Locate  ( 5, 10 )
        put "12345"..
        put "The current row is", Text.WhatRow
        put "The current column is", Text.WhatCol
Details The screen should be in a "screen" or "graphics" mode. Text.WhatRow functions properly even if the cursor is invisible.

Status Exported qualified.

This means that you can only call the function by calling Text.WhatRow, not by calling WhatRow.

See also the Text.WhatCol function, which is used to determine the cursor column. See also the Text.Locate, Text.maxrow and Text.maxcol procedure.


Time

Description This unit contains the predefined subprograms that handle anything to do with time, either as a date or as a timer.

All routines in the Time unit are exported qualified (and thus must be prefaced with "Time.").

Entry Points
Sec | Returns the number of seconds since 1/1/1970 00:00:00 GMT.
Date | Returns the current date and time as a string.
SecDate | Converts a number of seconds into a date / time string.
DateSec | Converts a date / time string to a number of seconds.
SecParts | Converts the number of seconds since 1/1/1970 00:00:00 GMT into a day of month, month, year, day of week, hour, minute and second integers.
PartsSec | Converts a day of month, month, year, hour, minute and second integers into the number of seconds since 1/1/1970 00:00:00 GMT.
SecStr | Converts the number of seconds since 1/1/1970 00:00:00 GMT into a user specified formatted string representing the date.
Elapsed | Returns the number of milliseconds elapsed since the program started to run.
ElapsedCPU | Returns the number of milliseconds of CPU time elapsed since the program started to run.
Delay | Sleeps for a specified number of milliseconds.
DelaySinceLast | Sleeps until a specified number of milliseconds since the last call to Time.DelaySinceLast.


Time.Date

Time.Date Part of Time module

Syntax Time.Date : string

Description The Time.Date function returns the current date and time as a string. The returned string in the format "dd mmm yy hh:mm:ss", where mmm is the first 3 characters of the month, e.g., "Apr". For example, if the date is Christmas 1989 at 9:02:37 in the morning, Time.Date will return "25 Dec 89 09:02:37". Twenty-four hour time is used, so eleven thirty at night the same day would return "25 Dec 89 23:30:00"

Example This program greets you and tells you the date and time.

        var theDateTime, theDate, theTime : string
        theDateTime := Time.Date
        theDate := theDateTime (1 .. 9)
        theTime := theDateTime (11 .. *)
        put "Greetings!!  The date and time today is ", Time.Date
Details Be warned that on some computers, such as IBM PC compatibles or Apple Macintoshes, the date may not be set correctly in the operating system; in that case, the Time.Date procedure will give incorrect results.

The string form of the date can be converted to a numeric form for comparison purposes using the Time.DateSec function. The numeric form can be converted to a string using the Time.SecDate function. The numeric form of the time can be obtained using the Time.Sec function.

Status Exported qualified.

This means that you can only call the function by calling Time.Date, not by calling Date.

See also Time.Sec, Time.DateSec and Time.SecDate functions.


Time.DateSec

Time.DateSec Part of Time module

Syntax Time.DateSec (dateString : string) : int

Description The Time.DateSec function is used to convert a date and time string into a number, specifically, the number of seconds since 00:00:00 GMT Jan 1, 1970.

The function can also convert just the date ("dd mmm yy"), in which case it returns the number of seconds since 00:00:00 GMT Jan 1, 1970 from midnight of the entered day. It will also convert a time without the date ("hh:mm:ss"), in which case it returns the number of seconds that have passed since midnight of that day.

If the format is incorrect or can't be interpreted, then Time.DateSec will return 1 and Error.Last and Error.LastMsg will be set to the appropriate error.

Example This program gives the number of seconds since 00:00:00 GMT Jan 1, 1970.

        var theDateTime, theDate, theTime : string
        theDateTime := Time.Date
        theDate := theDateTime (1 .. 9)
        theTime := theDateTime (11 .. *)
        put "The number of seconds from 00:00:00 GMT Jan 1, 1970",
            "from midnight ", theDate, "is ", Time.DateSec (theDate)
        put "The number of seconds from midnight to ", theTime "is ",
            Time.DateSec (theTime)
        put "The number of seconds from 00:00:00 GMT Jan 1, 1970",
            "from ", theDateTime, "is ", Time.DateSec (theDateTime)
Status Exported qualified.

This means that you can only call the function by calling Time.DateSec, not by calling DateSec.

See also Time.Sec, Time.Date and Time.SecDate functions.


Time.Delay

Time.Delay Part of Time module

Syntax Time.Delay ( duration : int )

Description The Time.Delay procedure is used to cause the program to pause for a given time. The time duration is in milliseconds.

Example This program prints the integers 1 to 10 with a second delay between each.

        for i : 1 .. 10
            put i
            Time.Delay ( 1000 ) % Pause for 1 second
        end for
Status Exported qualified.

This means that you can only call the function by calling Time.Delay, not by calling Delay.

See also Time.Elapsed and Time.ElapsedCPU.


Time.DelaySinceLast

Time.DelaySinceLast Part of Time module

Syntax Time.DelaySinceLast ( duration : int )

Description The Time.DelaySinceLast procedure is used to cause the program to pause for a given time since the last call to Time.DelaySinceLast. The time duration is in milliseconds.

Example This program outputs from 1 to 100,000, then outputs how long it took to do this (in milliseconds). It then calls Time.DelaySinceLast to wait until 10 seconds has passed since the beginning of the program (regardless of how long it took to execute the loop). Finally it outputs how many milliseconds has passed since the program started. This should be close to 10,000 milliseconds.

        var t : int := Time.Elapsed
        put "Starting now, count to 100,000"
        for i : 1 .. 100000
            put i ..
            locate (whatrow, 1)
        end for
        put "Finished counting to 100,000"

        put "Elapsed time: ", Time.Elapsed - t, " milliseconds"
        Time.DelaySinceLast (10000)
        put "Elapsed time: ", Time.Elapsed - t, " milliseconds"
Execute

Details The Time.DelaySinceLast is usually used to time a process so that it operates on the same speed no matter what the machine. For example, in the above example, the program will alwyas take 10 seconds to execute, regardless of the speed of the machine (up to a point). Fast machines will spend little time in the for loop and longer waiting to return from Time.DelaySinceLast. Slower machines will take longer to execute the loop and will consequently wait less time before returning from Time.DelaySinceLast.

The Time.DelaySinceLast procedure is often used to time the speed of animation in games.

Note that this only works up to a point. On a very slow machine, the for loop may take longer than 10 seconds to execute, in which case the call to Time.DelaySinceLast will return instantly.

Status Exported qualified.

This means that you can only call the function by calling Time.DelaySinceLast, not by calling DelaySinceLast.

See also Time.Elapsed and Time.ElapsedCPU.


Time.Elapsed

Time.Elapsed Part of Time module

Syntax Time.Elapsed : int

Description The Time.Elapsed function returns the amount of time since a program (process) started running. The number of milliseconds since the program started running is returned.

Example This program tells you how much time it has used.

        var timeRunning : int
        timeRunning := Time.Elapsed
        put "This program has run ", timeRunning, " milliseconds"
Details On IBM PC compatibles, this is the total time since the Turing system was started up. The hardware resolution of duration is in units of 55 milliseconds. For example, Time.Elapsed may be off by as much as 55 milliseconds.

On Apple Macintoshes, this is the total time since the machine was turned on. The hardware resolution of duration is in units of 17 milliseconds (1/60-th of a second).

Status Exported qualified.

This means that you can only call the function by calling Time.Elapsed, not by calling Elapsed.

See also Time.ElapsedCPU and Time.Delay subprograms.


Time.ElapsedCPU

Time.ElapsedCPU Part of Time module

Syntax Time.ElapsedCPU : int

Description The Time.ElapsedCPU function is used on a multitasking system such as UNIX to determine the amount of time that has been used by this program (process). The number of central processor milliseconds assigned to this program is returned. This is of little use on a personal computer, where Time.ElapsedCPU returns the same value as Time.Elapsed.

Example On a UNIX system, this program tells you how much time it has used.

        var timeUsed : int
        timeUsed := Time.ElapsedCPU
        put "This program has used ", timeUsed,
                " milliseconds of CPU time"
Status Exported qualified.

This means that you can only call the function by calling Time.ElapsedCPU, not by calling ElapsedCPU.

See also Time.Elapsed and Time.Delay subprograms.


Time.PartsSec

Time.PartsSec Part of Time module

Syntax Time.PartsSec (year, month, day, hour, minute, second : int) : int

Description The Time.PartsSec function is used to convert the numeric parts of a date (specifically the year, month, day, hour, minute and second) into the number of seconds since 00:00:00 GMT Jan 1, 1970 and the date specified by the parts.

The function can also convert a time without a date (year, month and day are all 0), in which case it returns the number of seconds that have passed since midnight of the current day.

If the numbers don't make any sense or can't be interpreted, then Time.PartsSec will return 1 and Error.Last and Error.LastMsg will be set to the appropriate error.

Example This program gives the number of seconds between 00:00:00 GMT Jan 1, 1970 and 9:27 in the morning, Christmas Day, 1989).

        put "The number of seconds from 00:00:00 GMT Jan 1, 1970",
            "is ", Time.PartsSec (1989, 12, 25, 9, 27, 0)
Status Exported qualified.

This means that you can only call the function by calling Time.PartsSec, not by calling PartsSec.

See also Time.SecParts, Time.Date and Time.Sec functions.


Time.Sec

Time.Sec Part of Time module

Syntax Time.Sec : int

Description The Time.Sec function returns the current date and time as a number. The returned integer is the time in seconds since 00:00:00 GMT (Greenwich Mean Time) January 1, 1970.

Example This program tells you how many seconds since 1970.

        put "The number of seconds since 1970 is ", Time.Sec
Details Be warned that on some computers, such as IBM PC compatibles or Apple Macintoshes, the date may not be set correctly in the operating system; in that case, the Time.Date procedure will give incorrect results.

The string form of the date can be converted to a numeric form for comparison purposes using the Time.DateSec function. The numeric form can be converted to a string using the Time.SecDate function. The numeric form of the time can be obtained using the Time.Sec function.

Status Exported qualified.

This means that you can only call the function by calling Time.Sec, not by calling Sec.

See also Time.Date, Time.DateSec and Time.SecDate functions.


Time.SecDate

Time.SecDate Part of Time module

Syntax Time.SecDate (timeInSecs : int) : string

Description The Time.SecDate function is used to convert the number of seconds since 00:00:00 GMT Jan 1, 1970 into a date and time string.

If timeInSecs is incorrect or can't be interpreted, then Time.SecDate will return the empty string and Error.Last and Error.LastMsg will be set to the appropriate error.

Example This program gives the number of seconds since 00:00:00 GMT Jan 1, 1970 and the date in string form.

        var timeInSecs : int := Time.Sec
        var theDateTime: string
        theDateTime := Time.SecDate (timeInSecs)
        put "The number of seconds since 1970 is ", timeInSecs
        put "Greetings!!  The date and time today is ", theDateTime
Status Exported qualified.

This means that you can only call the function by calling Time.SecDate, not by calling SecDate.

See also Time.Sec, Time.Date and Time.DateSec functions.


Time.SecParts

Time.SecParts Part of Time module

Syntax Time.SecParts (sec : int, var year, month, day,
dayOfWeek, hour, minute, second : int)

Description The Time.SecParts function is used to convert a single number form of the time (the number of seconds since 00:00:00 GMT Jan 1, 1970) into a date with numeric component parts.

The dayOfWeek parameter is 1 for Monday, 2 for Tuesday through 7 for Sunday.

If the sec parameter doesn't make any sense or can't be interpreted, then Time.PartsSec will set all the var parameters to 1 and Error.Last and Error.LastMsg will be set to the appropriate error.

Example This program returns the current day of the week.

        var year, month, day, dayOfWeek, hour, minute, second : int
        Time.SecParts (Time.Sec, year, month, day, dayOfWeek,
                                hour, minute, second )
        var days : array 1 .. 7 of string (10) := init ("Monday", "Tuesday",
            "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
        put "The current day of the week is ", days (dayOfWeek)
Status Exported qualified.

This means that you can only call the function by calling Time.SecParts , not by calling SecParts .

See also Time.PartsSec, Time.Date and Time.Sec functions.


Time.SecStr

Time.SecStr Part of Time module

Syntax Time.SecStr (timeInSecs : int, formatString : string) : string

Description The Time.SecStr function is used to convert the number of seconds since 00:00:00 GMT Jan 1, 1970 into a date and time string.

If timeInSecs is incorrect or can't be interpreted, then Time.SecStr will return the empty string and Error.Last and Error.LastMsg will be set to the appropriate error.

Detailsn The formatString parameter specifies how the output string will look. The formatString consists of different letters specifying the different formats and spaces or commas between these letters. The different letters can be combined to provide different date formats.

Here are the letters:

a | Abbreviated weekday name
A | Full weekday name
b | Abbreviated month name
B | Full month name
c | Date and time representation appropriate for locale
d | Day of month as decimal number (01 - 31)
H | Hour in 24-hour format (00 - 23)
I | Hour in 12-hour format (01 - 12)
j | Day of year as decimal number (001 - 366)
m | Month as decimal number (01 - 12)
M | Minute as decimal number (00 - 59)
p | Current locale’s A.M./P.M. indicator for 12-hour clock
S | Second as decimal number (00 - 59)
U | Week of year as decimal number, with Sunday as first day of week (00 - 53)
w | Weekday as decimal number (0 - 6; Sunday is 0)
W | Week of year as decimal number, with Monday as first day of week (00 - 53)
x | Date representation for current locale
X | Time representation for current locale
y | Year without century, as decimal number (00 - 99)
Y | Year with century, as decimal number
z,Z | Time-zone name

Example This program outputs the current date and the day number in the year.
Example output: Thursday November 13, 2003 is day number 317 of 2003

        put Time.SecStr (Time.Sec, "A B d, Y"), " is day number ",
            Time.SecStr (Time.Sec, "j"), " of ", Time.SecStr (Time.Sec, "Y")
Execute

Execute This example demonstrates each of the formatting letters.
Status Exported qualified.

This means that you can only call the function by calling Time.SecStr, not by calling SecStr.

See also Time.Sec and Time.SecParts functions.


time

time time of day as a string procedure

Syntax time ( var t : string )

Description The time statement is used to determine the current time of day. Variable t is assigned a string in the format "hh:mm:ss". For example, if the time is two minutes and 47 seconds after nine A.M., t will be set to "09:02:47". Twenty-four hour time is used. For example, eleven thirty P.M. gives the string "23:30:00".

Example This program greets you and tells you the time of day.

        var timeOfDay : string
        time ( timeOfDay )
        put "Greetings!!  The time is ", timeOfDay
Details Be warned that on some computers such as IBM PC compatibles or Apple Macintoshes, the time may not be set correctly in the operating system. In this case, the time procedure will give incorrect results.

See also delay, clock, sysclock, wallclock and date statements.

See also predefined unit Time.


token

token in input

Description A token is essentially a word, a number or a special symbol such as :=. In a Turing program there are four kinds of tokens: keywords such as get, identifiers such as incomeTax, operators and special symbols, such as + and :=, and explicit constants, such as 1.5 and "Hello". Some keywords, such as index, are reserved and cannot be used in programs to name variables, procedures, etc.

A get statement, such as

        get incomeTax
uses token-oriented input. This means that white space (blanks, tabs, etc.) is skipped before reading the input item and after the item (up to the beginning of the next line). See the get statement for details.

Example In this example, the tokens are var, x, :, real, x, := and 9.84.

        var x : real
        x := 9.84


true

true boolean value (not false)

Syntax true

Description A boolean (true/false) variable can be either true or false (see boolean type).

Example

        var passed : boolean := true
        var mark : int
        for i : 1 .. 10
            get mark
            passed := passed and mark >= 60
        end for
        if passed = true then
            put "You passed all ten subjects"
        end if
Details The line if passed=true then can be simplified to if passed then with no change to the meaning of the program.


type

type declaration

Syntax A typeDeclaration is one of:

(a) | type id : typeSpec
(b) | type id : forward

Description A type declaration gives a name to a type. This name can be used in place of the type.

Example

        type nameType : string ( 30 )
        type range : 0 .. 150
        type entry :
            record
                name : nameType
                age : int
            end record
Details The keyword pervasive can be inserted just after type. When this is done, the type is visible inside all subconstructs of the type scope. Without pervasive, the type is not visible inside modules, monitors and classes unless explicitly imported. Pervasive types need not be imported. You can abbreviate pervasive as an asterisk (*).

A forward type allows pointers to be declared to the type before the type is resolved. To resolve a type, you must follow a forward with a declaration of the same name and in the same scope. This type declaration must include a typeSpec.


TypeConv

Description This unit contains the predefined subprograms that convert between different Turing standard types. There are also six routines that are part of the language, rather than part of the unit, but are conceptually part of this unit.

All routines in the TypeConv unit are exported unqualified.

Description of the routines in the TypeConv module can be found in this chapter.

Entry Points
intreal | Converts an integer to a real.
intstr* | Converts an integer to a string.
natreal | Converts a natural number to a real.
natstr* | Converts a natural number to a string.
round | Converts a real to an integer (rounding).
floor | Converts a real to an integer (round down).
ceil | Converts a real to an integer (round up).
realstr | Converts a real to a string.
erealstr | Converts a real to a string (exponential notation).
frealstr | Converts a real to a string (no exponent).
strint* | Converts a string to an integer.
strintok* | Returns whether a string can legally be converted to an integer.
strnat* | Converts a string to a natural number.
strnatok* | Returns whether a string can legally be converted to a natural number.
strreal | Converts a string to a real.
strrealok | Returns whether a string can legally be converted to a real.
chr* | Returns the ASCII value of a specified string of length one.
ord* | Returns a string of length one with the ASCII value specified.

* Part of the language, conceptually part of the TypeConv unit.


typeSpec

typeSpec type specification

Syntax A typeSpec (type specification) is one of:

(a) | int
(b) | real
(c) | boolean
(d) | stringType | % Example: string ( 20 )
(e) | subrangeType | % Example: 1 .. 150
(f) | enumeratedType | % Example: enum ( red, green, blue )
(g) | arrayType | % Example: array 1 .. 150 of real
(h) | setType | % Example: set of 1 .. 10
(i) | recordType | % Example: record … end record
(j) | unionType | % Example: union … end union
(k) | pointerType | % Example: pointer to collectionVar
(l) | namedType | % Example: colorRange
(m) | nat | % natural number
(n) | int n | % n-byte integer (n=1, 2, 4)
(o) | nat n | % n-byte natural (n= 1, 2, 4)
(p) | real n | % n-byte real (n=4, 8)
(q) | char | % single character
(r) | char(n) | % n characters
(s) | subprogramType

Description A type specification determines the allowed values for a variable or constant. For example, if variable x is an integer (its typeSpec is int), the possible values for x are numbers such as -15, 0, 3 and 348207. If x is a real number (its typeSpec is real), then its possible values include 7.8, -35.0, and 15e12. If x is a boolean, its possible values are true and false. If x is a string, its possible values include Hello and Good-bye.

Example

        var numberOfSides : int
        var x, y : real
        type range : 0 .. 150   % The typeSpec here is 0 .. 150
        type entry :            % Here is a record typeSpec
            record
                name : string ( 25 )
                age : range
            end record
See also int, real, boolean, string, subrangeType, enum, array, set, record, union, pointer, named, nat, int n, nat n, real n, char, and char(n) types.


unchecked

unchecked compiler directive

Dangerous

Description OOT adds the concept of "unchecked" to Turing. Here, you can request that certain run time tests, which take place by default, can be eliminated. This makes the program more efficient at the risk of unreliability.

Example Declare p to be an unchecked pointer to an integer (see pointers for details). Pointer p will be dangerous to use, because the run time system will not check to see if it actually locates an integer, as opposed to arbitrary computer memory. In other words, unchecked pointers are like C language pointers.

        var p : unchecked ^ int
Example Declare C to be an unchecked collection of records of type R (see collections for details). Pointers to C will be unchecked.

        var C : unchecked collection of R
Example Remove checking from the body of a loop.

        for i : 1 .. 500
            unchecked
            if a ( i ) = key then
                exit
            end if
        end for
Details In the above example, the unchecked keyword requests that all checking, in particular, array bounds checking for array a, are to be omitted. The disabling lasts from the occurrence of the keyword unchecked to the end of the surrounding construct, in this case, until end for. In a similar way, the checked keyword will request that checking be re-enabled from the occurence of checked to the end of the surrounding construct.

In the current (1999) implementation, the use of unchecked to turn off checking in a block of statements is ignored. In general, an implementation may choose to ignore requests to disable checking.


union

union type

Syntax A unionType is:

        union [ id ] : indexType of
            label labelExpn { , labelExpn } :
                        { id {, id } : typeSpec }
            { label labelExpn { , labelExpn } :
                        { id {, id } : typeSpec } }
            [ label :       { id {, id } : typeSpec } ]
        end union
Description A union type (also called a variant record) is like a record in which there is a run time choice among sets of accessible fields. This choice is made by the tag statement, which deletes the current set of fields and activates a new set.

Example This union type keeps track of various information about a vehicle, depending on the kind of vehicle.

        const passenger := 0
        const farm  := 1
        const recreational  := 2

        type vehicleInfo :
            union kind : passenger .. recreational of
                label passenger :
                    cylinders : 1..16
                label farm :
                    farmClass :string ( 10 )
                label :     % No fields for "otherwise" clause
            end union
        var v : vehicleInfo
        …
        tag v, passenger    % Activate passenger part v.cylinders := 6
Details The optional identifier following the keyword union is the name of the tag of the union type. If the identifier is omitted, the tag is still considered to exist, although its value cannot be accessed. The tag must be of an index type, for example 1..7. You should limit the range of this index type, as the compiler may have a limit (at least 255) on the maximum range it can handle.

Each labelExpn must be known at compile time and must lie within the range of the tag's type. The fields, including the tag, of a union value are referenced using the dot operator, as in v.cylinders and these can be used as variables or constants. A field can be accessed only when the tag matches one of the label expressions corresponding to the field. The tag can be changed by the tag statement but it cannot be assigned to, passed to a var parameter, or bound to using var.

In a union, id's of fields, including the tag, must be distinct. However, these need not be distinct from identifiers outside the union. Unions can be assigned as a whole (to unions of an equivalent type), but they cannot be compared. A semicolon can optionally follow each typeSpec.

Any array contained in a union must have bounds that are known at compile time.

The notation > can be used to access union fields. For example, if p is a pointer to vehicleRecord, p>farmClass locates the farmClass field.

See also pointer.


unit

unit file containing module, monitor, or class

Syntax A compilationUnit is one of:

(a) | [ importList ] mainProgram
(b) | unit moduleDeclaration
(c) | unit monitorDeclaration
(d) | unit classDeclaration

Description A program can be divided up into units, each in a separate file. All of these files except the main program begin with the keyword unit. The unit contains the main program, a module, a monitor or a class.

Example Here is stack module that is separated out into a file whose name is stack.

        unit        % The keyword unit begins each separate file
        module stack
            export push, pop

            var top : int := 0
            var contents : array 1 .. 100 of int

            procedure push ( i : int )
                top += 1
                contents ( top ) := i
            end push

            procedure pop ( i : int )
                i := contents ( top )
                top -= 1
            end pop
        end stack
The main program, which is in another file, gains access to the stack by importing it. Here is the main program:

        import var stack    % Use the stack
        var n : int
        …
        stack . push ( n )
        …
        stack . pop ( n )
Details In this example, the keyword var in the import list is required because the main program causes a change in the stack, by calling push and pop. The import lists of units that are modules, monitors and classes are used to gain access to further units.

If the stack were in a file with a different name, say stk.t, the import list would be rewritten to use an in clause, as follows:

        import var stack in "stk.t"
A mainProgram is simply a program. See program.

See also module, monitor and class. See also export list, import list, inherit list, implement list and implement by list.


unqualified

unqualified export

Description When an identifier x is exported from a module, monitor or class M using the keyword unqualified, it can be used outside of M without the qualification "M.". In other words, outside of M, it can be referred to as simply x. The keyword unqualified can be written in its short form as ~. which is pronounced "not dot", as in:

        export ~. x
See als
o export list.


upper

upper bound

Syntax upper ( reference [ , dimension ] ) : int

Description The upper attribute is used to find the upper bound of an array, string, char(n) or non-opaque subrange type. (See lower for finding the lower bound.)

Example In a procedure, see if the bound of array parameter a is large enough that it can be subscripted by i. If it is large enough, it is set a(i) to zero.

        procedure test ( var a : array 1 .. * of real )
            if i <= upper ( a ) then
                a ( i ) := 0.0
            end if
        end test
Details In a similar way, if s is a string, its upper bound (not length!) is given by upper (s). If an array has more than one dimension, as in var b : array 1..10, 1 .. 60 of int, you must specify the dimension. For example, upper (b, 2) returns 60.


var

var declaration

Syntax A variableDeclaration is one of:

(a) | var id { ,id } [ :typeSpec] [:=initializingValue]
(b) | collectionDeclaration

Description A variable declaration creates a new variable (or variables). Only form (a) will be explained here. See collectionDeclaration for explanation of form (b). The typeSpec of form (a) can be omitted only if the initializing value is present.

Example

        var j, k : int := 1     % j and k are assigned value 1
        var t := "Sample"       % The type of t is string
        var v : array 1 .. 3 of string ( 6 ) :=
                init ( "George", "Fred", "Alice" )
Details The initializing value, if present, must be an expression or else a list of items separated by commas inside init ( … ). The syntax of initializingValue is one of:

(a) | expn
(b) | init ( initializingValue {, initializingValue } )

Each init ( … ) corresponds to an array, record or union value that is being initialized. These must be nested for initialization of nested types.

If the typeSpec is omitted, the variable's type is taken to be the (root) type of the initializing expression, for example, int or string. The typeSpec cannot be omitted for dynamic arrays or when the initializing value is of the form init ( … ). The values inside init ( … ) must be known at compile time.

The keyword pervasive can be inserted just after var. When this is done, the variable is visible inside all subconstructs of the variable's scope. Without pervasive, the variable is not visible inside modules unless explicitly imported. Pervasive variables need not be imported. You can abbreviate pervasive as an asterisk (*).

OOT extends Turing in the following way. OOT changes form (a) to allow the optional use of the register keyword to request that the variable be placed in a machine register. The OOT syntax for form (a) is actually:

        var [pervasive] [register] id { , id } [ : typeSpec ] [ := initializingValue ]
In the current (1994) OOT implementation, programs are run interpretively using pseudo-code, which has no machine registers, and the register keyword is ignored. See register for restrictions on the use of register variables.

See also collection, bind, procedure and function declarations, parameter declarations, export lists and import lists for other uses of the keyword var.


variableReference

variableReference use of a variable

Syntax A variableReference is:

variableId { componentSelector }

Description In a Turing program, a variable is declared and given a name (variableId) and then used. Each use is called a variable reference.

If the variable is an array, collection, record or union, its parts (components) can be selected using subscripts and field names (using componentSelectors). The form of a componentSelector is one of:\

(a) | ( expn {, expn} )
(b) | . fieldId

Form (a) is used for subscripting (indexing) arrays and collections. The number of array subscripts must be the same as in the array's declaration. A collection has exactly one subscript, which must be a pointer to the collection. Form (b) is used for selecting a field of a record or union.

Example Following the declarations of k, a and r, each of k, a (k) and r.name are variable references.

        var k : int
        var a : array 1 .. 100 of real
        var r :
            record
                name : string ( 20 )
                phone : string ( 8 )
            end record
        …
        k := 5
        a ( k ) := 3.14159
        r . name := "Steve Cook"
Details A variable reference can contain more than one component selector, for example, when the variable is an array of records. For an example, see the record type. See also constantReference and var declaration.


View

Description This unit contains the predefined subprograms that deal with the current output surface, which is a window.

All routines in the View unit are exported qualified (and thus must be prefaced with "View.") with the exception of maxx, maxy, maxcolor and maxcolour which are exported unqualified.

Entry Points
maxx | Returns the maximum x coordinate (width 1) (exported unqualified).
maxy | Returns the maximum y coordinate (height 1) (exported unqualified).
maxcolor | Returns the maximum color number (# colors 1) (exported unqualified).
maxcolour | Returns the maximum color number (# colors 1) (exported unqualified).
Set | Changes the configuration of the output surface.
ClipSet | Clips output to a specified rectangle.
ClipAdd | Adds another specified rectangle to the clipping region.
ClipAddOval | Adds another specified oval to the clipping region.
ClipOff | Stops all clipping.
WhatDotColor |  | Gets the color of the pixel at a specified location.
WhatDotColour | Gets the color of the pixel at a specified location.
Update | Updates the onscreen window from the offscreen bitmap.
UpdateArea | Updates part of the onscreen window from the offscreen bitmap.
SetTransparentColor | Sets the transparent color to be ignored when using picUnderMerge mode.
SetTransparentColour | Sets the transparent colour to be ignored when using picUnderMerge mode.


View.ClipAdd

View.ClipAdd Part of View module

Syntax View.ClipAdd (x1, y1, x2, y2 : int)

Description The View.ClipAdd procedure adds another rectangle specified by (x1, y1) - (x2, y2) to the clipping region. This only works on systems that support complex clipping regions. If no clipping region has been specified, then the rectangle becomes the complete clipping region.

A clipping region is the region that the output will appear in. If the rectangle is specified as the clipping region, any drawing done outside the rectangle will not appear.

To set the initial clipping, or remove the old region and replace it with a new one, use View.ClipSet. To set the clipping region back to the entire screen or window, use View.ClipOff.

These commands only work in "graphics" mode.

Example This program sets the clipping region to five rectangles and then draws random circles. The circles will only appear (or partially appear) in the rectangles.

        const maxx13 : int := maxx div 3
        const maxx23 : int := 2 * maxx div 3
        const maxy13 : int := maxy div 3
        const maxy23 : int := 2 * maxy div 3
        View.ClipSet (0, 0, maxx13, maxy13)
        View.ClipAdd (maxx23, 0, maxx, maxx13)
        View.ClipAdd (maxx13, maxy13, maxx23, maxy23)
        View.ClipAdd (0, maxy23, maxx13, maxy)
        View.ClipAdd (maxx23, maxy23, maxx, maxy)

        % Draw the random ovals in the box
        var x, y, clr : int
        loop
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            clr := Rand.Int (0, maxcolor)   % Random color
            Draw.FillOval (x, y, 30, 30, clr)
        end loop
Status Exported qualified.

This means that you can only call the function by calling View.ClipAdd, not by calling ClipAdd.

See also View.ClipSet and View.ClipOff functions.


View.ClipAddOval

View.ClipAddOval Part of View module

Syntax View.ClipAddOval (x, y, xradius, yradius : int)

Description The View.ClipAddOval procedure adds another oval specified by (x, y) and xradius and yradius) to the clipping region. If no clipping region has been specified, then the oval becomes the complete clipping region.

A clipping region is the region that the output will appear in. If the rectangle is specified as the clipping region, any drawing done outside the oval will not appear.

To set the initial clipping, or remove the old region and replace it with a new rectangle, use View.ClipSet. To set the clipping region back to the entire screen or window, use View.ClipOff.

These commands only work in "graphics" mode.

Example This program sets the clipping region to five circles and then draws random squares. The squares will only appear (or partially appear) in the ovals.

        const c1 : int := maxy div 4
        const c2 : int := 3* maxy div 4
        const radius : int := maxy div 4
        View.ClipAddOval (c1, c1, radius, radius)
        View.ClipAddOval (c1, c2, radius, radius)
        View.ClipAddOval (c2, c1, radius, radius)
        View.ClipAddOval (c2, c2, radius, radius)

        % Draw the random squares in the box
        var x, y, clr : int
        loop
            x := Rand.Int (0, maxx - 30)     % Random x
            y := Rand.Int (0, maxy - 30)     % Random y
            clr := Rand.Int (0, maxcolor)    % Random color
            Draw.FillBox (x, y, x + 30, y + 30, clr)
        end loop
Execute

Execute By combining animation using View.Update and View.ClipAddOval, you can achieve a moving spotlight effect.

Status Exported qualified.

This means that you can only call the function by calling View.ClipAddOval, not by calling ClipAddOval.

See also View.ClipSet, View.ClipAdd and View.ClipOff functions.


View.ClipOff

View.ClipOff Part of View module

Syntax View.ClipOff

Description The View.ClipOff procedure turns off clipping. This means that any drawing commands can appear on the entire drawing surface (the screen or the window, depending on the system).

These commands only work in "graphics" mode.

Status Exported qualified.

This means that you can only call the function by calling View.ClipOff, not by calling ClipOff.

See also View.ClipAdd and View.ClipSet functions.


View.ClipSet

View.ClipSet Part of View module

Syntax View.ClipSet (x1, y1, x2, y2 : int)

Description The View.ClipSet procedure sets the clipping region to the rectangle specified by (x1, y1) - (x2, y2). If a clipping region already exist, it is replaced by the specified rectangle.

A clipping region is the region in which the output will appear. If the rectangle is specified as the clipping region, any drawing done outside the rectangle will not appear.

To set the initial clipping, or remove the old region and replace it with a new one, use View.ClipSet. To set the clipping region back to the entire screen or window, use View.ClipOff.

These commands only work in "graphics" mode.

Example This program sets the clipping region to five rectangles and then draws random circles. The circles will only appear (or partially appear) in the rectangles.

        const maxx13 : int := maxx div 3
        const maxx23 : int := 2 * maxx div 3
        const maxy13 : int := maxy div 3
        const maxy23 : int := 2 * maxy div 3
        View.ClipSet (0, 0, maxx13, maxy13)
        View.ClipAdd (maxx23, 0, maxx, maxy13)
        View.ClipAdd (maxx13, maxy13, maxx23, maxy23)
        View.ClipAdd (0, maxy23, maxx13, maxy)
        View.ClipAdd (maxx23, maxy23, maxx, maxy)

        % Draw the random ovals in the box
        var x, y, clr : int
        loop
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            clr := Rand.Int (0, maxcolor)   % Random color
            Draw.FillOval (x, y, 30, 30, clr)
        end loop
Status Exported qualified.

This means that you can only call the function by calling View.ClipSet, not by calling ClipSet.

See also View.ClipAdd and View.ClipOff functions.


View.maxcolor

View.maxcolor Part of View module

Syntax View.maxcolor : int

Description The maxcolor function is used to determine the maximum color number for the current mode of the screen. The alternate spelling is maxcolour.

Example This program outputs the maximum color number.

        setscreen ("graphics")
        …
        put "The maximum color number is ", View.maxcolor
Details The screen should be in a "screen" or "graphics" mode. If it is not, it will automatically be set to "screen" mode. See View.Set for details.

For IBM PC compatibles in "screen" mode, maxcolor = 15. For the default IBM PC compatible "graphics" mode (VGA), maxcolor = 15.

Details View.maxcolor is identical to RGB.maxcolor. It is placed here for consistency with other screen information routines.

Status Exported qualified.

This means that you can only call the function by calling View.maxcolor. Note that RGB.maxcolor is exported unqualified, so that one can call maxcolor.

See also Draw.Dot for examples of the use of maxcolor. See the Text.Color procedure which is used for setting the currently-active color.


View.maxx

View.maxx Part of View module

Syntax maxx : int

Description The maxx function is used to determine the maximum value of x for the current graphics mode.

Example This program outputs the maximum x value.

        setscreen ("graphics")
        …
        put "The maximum x value is ", maxx
Details The screen should be in a "graphics" mode. If it is not, it will automatically be set to "graphics" mode. See setscreen for details.

For the default IBM PC compatible graphics mode (CGA), maxx = 319.

Status Exported unqualified.

This means that you can call the function by calling maxx or by calling View.maxx.

See also Draw.Dot for an example of the use of maxx and for a diagram illustrating x and y positions.


View.maxy

View.maxy Part of View module

Syntax maxy : int

Description The maxy function is used to determine the maximum value of y for the current graphics mode.

Example This program outputs the maximum y value.

        setscreen ("graphics")
        …
        put "The maximum y value is ", maxy
Details The screen should be in a "graphics" mode. If it is not, it will automatically be set to "graphics" mode. See setscreen for details.

For the default IBM PC compatible graphics mode (CGA), maxy = 199.

Status Exported unqualified.

This means that you can call the function by calling maxy or by calling View.maxy.

See also Draw.Dot for an example of the use of maxy and for a diagram illustrating x and y positions.


View.Set

View.Set Part of View module

Syntax View.Set ( s : string )

Example Here are example uses of the View.Set procedure. In many cases, these will appear as the first statement of the program. However, they can appear any place in a program.

        View.Set ("graphics")       % Switch to graphics mode
        View.Set ("screen")     % Switch to screen mode
        View.Set ("nocursor")       % Turn off cursor
        View.Set ("noecho")     % Do not echo keystrokes
Description The View.Set statement is used to change the mode of the screen, as well as the way in which Turing does input and output. The parameter to View.Set is a string, such as "graphics". The string contains one or more options separated by commas, such as "text, noecho". View.Set affects the active window.

Details There are two window modes, text and graphics.

text mode does not allow any graphics whatsoever (including cursor positioning, etc.). Only put and get are allowed. Any output that scrolls off the top of the window is preserved and can viewed or printed later.

graphics mode allows character graphics and pixel graphics commands such and Text.Locate and Draw.Box.

The default graphics mode is defined in the Turing preferences. It is good practice to set the desired mode so that the program will function properly regardless of thedefault graphics mode. Note that if the user prints the output window, in text mode, all output sent to the window is printed. In graphics mode, only the current output of the window is printed. If the user saves the output window, a text mode window will produce a text file containing all the output sent to the window. A graphics window will produce a BMP graphics file containing the current contents of the window.

Details Where the options to View.Set are mutually exclusive, they are listed here with the default underlined. Here are the options:

"cursor", "nocursor" - Causes the cursor to be shown (or hidden). The cursor is only displayed when the program is awaiting input.

"echo", "noecho" - Causes (or suppresses) echoing of characters that are typed. Echoing is commonly turned off in interactive programs to keep typed characters from being echoed at inappropriate places on the screen.

"noxor", "xor" - noxor mode means that all drawing is done normally. In xor mode, all pixel graphics are drawn XOR'ed on the background (with the exception of the Pic routines, where the drawing mode is specified). The most important property of an XOR'ed object is that it can be erased and the background restored by XOR'ing the object on top of itself.

"msdos", "nomsdos" - Causes the window to use the MS-DOS character set (with line drawing characters) instead of the Windows ANSI character set. The "nomsdos" option causes the window to use the Windows ANSI character set. Note that the "msdos" option only works if the Windows font (usually Courier New) supports it.

"visible", "invisible", "popup" - Causes the active window to become visible (invisible or, for popup, invisible until input or output occurs in the window).

"title:<text>" - Causes the title of the active window to be set to <text>.

"position:<x>;<y>" - Causes the position of the upper left corner of the active window to be set to (x, y). The <x> parameter can also be one of: “left”, “center”, “center” or “right”, in which case the window will be placed on the left, center or right side of the screen. The <y> parameter can also be one of: “top”, “middle”, “truemiddle”, or “bottom” in which case the window will be placed at the top, middle about 1/3 from the top, middle or bottom of the screen. Note that when a window is supposed to be centered in the middle of the screen, “middle” usually looks better than “truemiddle”.

"nooffscreenonly", "offscreenonly" Causes or (suppresses) output from being sent to the visible window. When the offscreenonly option is active, any text and graphics output is drawn to the offscreen buffer that is maintained for every Run window but not drawn to the screen. View.Update is then used to copy the entire contents of the offscreen buffer to the Run window. By allowing numerous drawing commands to be sent to the offscreen buffer and then updating the window at one time, it is possible to get smoother animation.

"buttonbar", "nobuttonbar" Causes or (suppresses) the display of a button bar at the top of the output window which allows the user to easily stop program execution or save and print the output window.

"text", "screen", "graphics" - Sets window to the given mode and always erases the screen, even when already in the requested mode.

The text mode can have a modifier in the form "text:<rows>;<cols>". This sets the window to be <rows> by <cols> of text in size.

The screen mode actually sets the window to graphics mode. It can have a modifier in the form "screen:<rows>;<cols>". This sets the window to be <rows> by <cols> of text in size.

The graphics mode can have a modifier in the form "graphics:<width>;<height>". This sets the window to be <width> by <height> pixels in size.

To set a window to the maximum size available on the screen, you can use “max” for the <width>, <height>, <rows> or <columns> parameters. If the window requested is larger than will fit on the screen, the window will fill the entire screen and scroll bars will be added to the output window to allow the window user to see the rest of the window.

Example This program creates a graphics window that is 300 pixels by 100 pixels.

        View.Set ("graphics:300;100")
This program outputs the square roots for the first 200 numbers. The user can inspect all the output and print the values after the program has finished execution

        View.Set ("text")
        for value : 1 .. 200
            put value : 3, "   ", sqrt (value)
        end for
This program creates a window without a button bar at the top that is sized to fit the screen. It then draws an “X” in red in the window.

        View.Set ("graphics:max;max,nobuttonbar")
        Draw.Line (0, 0, maxx, maxy, red)
        Draw.Line (maxx, 0, 0, maxy, red)
This program resizes the window to 200x200, moves the output window to the bottom-left of the screen and hides the button bar. It then sets the window title to “Bottom Left Window” and outputs the word “Hello”.

        View.Set ("graphics:200;200,position:bottom;left,nobuttonbar")
        View.Set ("title:Bottom Left Window")
        put "Hello"
See also setscreen for further information.

Status Exported qualified.

This means that you can only call the function by calling View.Set, not by calling Set.


View.SetTransparentColor

View.SetTransparentColor Part of View module

Syntax View.SetTransparentColor (colorNumber : int)
Description The View.SetTransparentColor procedure sets the color in the Run window that should be considered transparent when a picture is drawn on the window using the picUnderMerge mode. If no color is specified, then the default background color (colorbg, usually white) is used as the transparent color. You can change this background color using RGB.SetColor on color 0.

Details This call is often used when you want the Run window to have a background color other than color 0.

Example This program displays two images loaded from the same file. In the second image,the transparent color has been set to bright red (that is, the parts of the image that are meant to be transparent are in bright red).

        const SIZE : int := 20
        procedure DrawCheckerBoard
            cls
            for x : 0 .. maxx by SIZE
                for y : 0 .. maxy by SIZE
                    if ((x + y) div SIZE) mod 2 = 0 then
                        Draw.FillBox (x, y, x + SIZE, y + SIZE, brightgreen)
                    end if
                end for
            end for
        end DrawCheckerBoard

        var pic : int := Pic.FileNew ("data files/airplane.bmp")
        Pic.SetTransparentColor (pic, brightred)
        RGB.SetColor (0, 1., 0., 0.)
        DrawCheckerBoard
        Pic.Draw (pic, 100, 100, picUnderMerge)
        View.SetTransparentColor (brightgreen)
        Pic.Draw (pic, 400, 100, picUnderMerge)
Execute

Details View.SetTransparentColour is an alternate spelling for View.SetTransparentColor.
Status Exported qualified.

This means that you can only call the function by calling View.SetTransparentColor, not by calling SetTransparentColor.

See also Pic.SetTransparentColor.


View.Update

View.Update Part of View module

Syntax View.Update

Description The View.Update procedure updates a Run window from an offscreen bitmap. It is used with the command View.Set ("offscreenonly") which prevents the Run window from being updated until the View.Update command is given.

Example This program displays 30 circles bouncing around the screen. To see the effect without View.Update, comment out the line View.Set ("offscreenonly")

        % Place some circles around the screen
        const RADIUS : int := 30
        const NUM_BALLS : int := 20
        var x, y, dx, dy, clr : array 1 .. NUM_BALLS of int
        for i : 1 .. NUM_BALLS
            x (i) := Rand.Int (RADIUS, maxx - RADIUS)
            y (i) := Rand.Int (RADIUS, maxy - RADIUS)
            dx (i) := Rand.Int (-3, 3)
            dy (i) := Rand.Int (-3, 3)
            clr (i) := Rand.Int (1, 15)
        end for

        % Now, any drawing to the screen won't appear until a
        % View.Update is given.
        View.Set ("offscreenonly")
        loop
            cls % Clear the offscreen window
            for i : 1 .. NUM_BALLS
                if x (i) + dx (i) < RADIUS or
                        x (i) + dx (i) > maxx - RADIUS then
                    dx (i) := -dx (i)
                end if
                if y (i) + dy (i) < RADIUS or
                        y (i) + dy (i) > maxy - RADIUS then
                    dy (i) := -dy (i)
                end if
                x (i) := x (i) + dx (i)
                y (i) := y (i) + dy (i)
                Draw.FillOval (x (i), y (i), RADIUS, RADIUS, clr (i))
            end for
            % All the circles have been drawn.  Now update the screen.
            View.Update
            Time.Delay (5)
        end loop
Execute

Details All Turing Run windows have both an onscreen visible window and an offscreen window. Whenever any output is sent to the screen, both the onscreen window and the offscreen window are updated. When the Run window needs to be updated (for example when another window is moved over top of it and then removed), Turing copies the offscreen window onto the onscreen window.

When the View.Set ("offscreenonly") command is given, Turing no longer draws to the onscreen window when any drawing command is given. However, it does update the offscreen window. When the View.Update command is given, the entire offscreen window is copied to the onscreen window.

This can be used to provide smooth, flicker-free animation. Animated objects flicker when the object being animated disappears from the onscreen window for a period of time. By using View.Set ("offscreenonly") / View.Update, the onscreen window is never blank. Instead, the offscreen window drawn over top off the on screen window, replacing it. This means that the on-screen window is never blanked out, eliminating the flickering found in the animation.

Details It's very easy to forget that no output will appear in the Run window when using View.Update. Remember to use View.Set("nooffscreenonly") to turn off this feature sending output for debugging purposes.

Details View.Update should not be used in conjunction with the Sprite module. Sprites can be considered a limited version of this technique. View.Update also works well when the entire background is changing.

Status Exported qualified.

This means that you can only call the function by calling View.Update, not by calling Update.

See also View.Set for the "offscreenonly" and "nooffscreenonly" options.

View.UpdateArea for updating part of the window at a time.


View.UpdateArea

View.UpdateArea Part of View module

Syntax View.UpdateArea (x1, y1, x2, y2)

Description The View.UpdateArea procedure updates a rectanglular area Run window, specified by (x1, y1) - (x2, y2) from the offscreen bitmap. It is used with the command View.Set ("offscreenonly") which prevents the Run window from being updated until the View.UpdateArea or View.Update command is given.

Because the entire screen is not updated each time, the animation can be much faster, especially on slow machines. This procedure does take more effort to use than View.Update as it requires the programmer to calculate which portion of the screen must be updated.

Example This program moves a star back and forth across the screen. To compare the speed up View.UpdateArea with View.Update, replace the calls to View.UpdateArea with View.Update.

        View.Set ("offscreenonly")
        var SIZE : int := 50
        loop
            for x : 0 .. maxx - SIZE
                Draw.FillStar (x, 100, x + SIZE, 100 + SIZE, brightgreen)
                View.UpdateArea (x - 1, 100, x + SIZE, 100 + SIZE)
                Draw.FillStar (x, 100, x + SIZE, 100 + SIZE, colorbg)
            end for
            for decreasing x : maxx - SIZE .. 0
                Draw.FillStar (x, 100, x + SIZE, 100 + SIZE, brightgreen)
                View.UpdateArea (x, 100, x + SIZE + 1, 100 + SIZE)
                Draw.FillStar (x, 100, x + SIZE, 100 + SIZE, colorbg)
            end for
        end loop
Execute

Details If the entire screen is being updated each time through the animation loop (for example if the background image is changing), then use View.Update instead.

When using View.UpdateArea, it is important to correctly calculate the region to be updated. This region must not only contain the item being drawn, but also any area where the background should be replaced. For example, in the program above, the area updated included the one pixel to the left of the star when the star was moving right-ward and one pixel to the right of the star when the star was moving left-ward.

Execute Here is an example program that allows you to compare the speed of animation using View.Update with View.UpdateArea. The program animates an object on a background of stars. Pressing any key switches between the two calls.
Details All Turing Run windows have both an onscreen visible window and an offscreen window. Whenever any output is sent to the screen, both the onscreen window and the offscreen window are updated. When the Run window needs to be updated (for example when another window is moved over top of it and then removed), Turing copies the offscreen window onto the onscreen window.

When the View.Set ("offscreenonly") command is given, Turing no longer draws to the onscreen window when any drawing command is given. However, it does update the offscreen window. When the View.Update command is given, the entire offscreen window is copied to the onscreen window.

This can be used to provide smooth, flicker-free animation. Animated objects flicker when the object being animated disappears from the onscreen window for a period of time. By using View.Set ("offscreenonly") / View.Update, the onscreen window is never blank. Instead, the offscreen window drawn over top off the on screen window, replacing it. This means that the on-screen window is never blanked out, eliminating the flickering found in the animation.

Details It's very easy to forget that no output will appear in the Run window when using View.UpdateArea. Remember to use View.Set("nooffscreenonly") to turn off this feature sending output for debugging purposes.

Details View.UpdateArea should not be used in conjunction with the Sprite module. Sprites can be considered a limited version of this technique. View.UpdateArea also works well when the entire background is changing.

Status Exported qualified.

This means that you can only call the function by calling View.UpdateArea, not by calling UpdateArea.

See also View.Set for the "offscreenonly" and "nooffscreenonly" options.

View.Update for procedure to update the entire screen at one time.


View.WhatDotColor

View.WhatDotColor Part of View module

Syntax View.WhatDotColor ( x, y : int ) : int

Description The View.WhatDotColor function is used to determine the color number of the specified pixel. The alternate spelling is View.WhatDotColour.

Example This program draws a line which bounces off the edges of the screen and makes a beep when it finds a pixel that has already been colored.

        View.Set ( "graphics" )
        var x, y : int := 0
        var dx, dx : int := 1
        loop
            if View.WhatDotColor ( x, y ) not= 0 and
                View.WhatDotColor ( x, y ) not= brightred then
                Draw.FillOval (x, y, 10, 10, brightred)
            end if
            Draw.Dot ( x, y, 1 )
            x := x + dx
            y := y + dy
            if x = 0 or x = maxx then
                dx := -dx
            end if
            if y = 0 or y = maxy then
                dy := -dy
            end if
        end loop
Execute

Example Another example illustrates the use of View.WhatDotColor to determine the color of pixels in a window painted with multi-color blocks. The actual color number appears in the block. The color of the dot under the mouse cursor appears in the upper-left corner of the window. Note that you can also place the mouse cursor over the black text indicating the color number.
Details The screen should be in a"graphics" mode. If is not set to "graphics" mode, it will automatically be set to "graphics" mode. See View.Set for details.

Status Exported qualified.

This means that you can only call the function by calling View.WhatDotColor, not by calling WhatDotColor.

See also Draw.Dot, which is used for setting the color of a pixel. See also maxx and maxy, which are used to determine the number of pixels on the screen.


wait

wait block a process statement

Syntax A waitStatement is:

wait variableReference [ , expn ]

Description The wait statement is used in a concurrent program to cause the executing process to be blocked (to go to sleep) until it is awakened by a signal statement. The statement can only be used inside a monitor (a special kind of module that handles concurrency). A wait statement operates on a condition variable (the variableReference), which is essentially a queue of sleeping processes. See condition for an example of a wait statement.

Details A wait statement for a priority condition must include the optional expn,. This expression must be a non-negative int value which is used to order processes waiting for the condition, low numbers first.

A wait statement for a timeout condition must include the optional expn, which must be a non-negative int value which gives the timeout interval. A process waiting for a timeout condition is implicitly awakened if it waits longer than its timeout interval.

See also condition and signal. See also monitor and fork. See also empty. See also pause.


wallclock

wallclock seconds since 1/1/1970 procedure

Syntax wallclock ( var c : int )

Description The wallclock statement is used to determine the time in seconds since 00:00:00 GMT (Greenwich Mean Time) January 1, 1970.

Example This program tells you how many seconds since 1970.

        var seconds : string
        wallclock ( seconds )
        put "The number of seconds since 1970 is ", seconds
Details Be warned that on some computers such as IBM PC compatibles or Apple Macintoshes, the time may not be set correctly in the operating system; in that case, the wallclock procedure will give incorrect results. Also, on IBM PC compatibles, the call is dependent on having the time zone TZ variable correctly set. On an IBM PC, the default time zone is set to PST (6 hours from GMT).

On the Apple Macintosh, the wallclock procedure returns the number of seconds since 00:00:00 local time Jan. 1, 1970.

See also delay, time, clock, sysclock and date statements.

See also predefined unit Time.


whatcol

whatcol cursor position function

Syntax whatcol : int

Description The whatcol function is used to determine the cursor position's column.

Example This program outputs The current row is 5, the current column is 15.

        locate  ( 5, 10 )
        put "12345"..
        put "The current row is", whatrow
        put "The current column is", whatcol
Details The screen should be in a "screen" or "graphics" mode. whatcol functions properly even if the cursor is invisible.

See also the whatrow function, which is used to set the determine the cursor row. See also the locate, maxrow and maxcol procedure.

See also predefined unit Text.


whatcolor

whatcolor text color graphics function

Syntax whatcolor : int

Description The whatcolor function is used to determine the current (foreground) color, ie., the color used for characters that are output using put. The alternate spelling is whatcolour.

Example This program outputs the currently-active color number. The message is also given in the currently-active color.

        setscreen ("graphics")
        …
        put "This writing is in color number ", whatcolor
Details The screen should be in a "screen" or "graphics" mode. See setscreen for details.

See also the color procedure, which is used to set the color. See also colorback and whatcolorback.

See also predefined unit Text.


whatcolorback

whatcolorback color of background function

Syntax whatcolorback : int

Description The whatcolorback function is used to determine the current background color. The alternate spelling is whatcolourback.

Example This program outputs the currently-active background color number. The background color of the message is determined by this number.

        setscreen ("screen")
        …
        put "The background of this writing"
        put  "is in color number ", whatcolorback
Details The screen should be in a "screen" or "graphics" mode. Beware that the meaning of background color is different in these two modes. See colorback for details.

See also color and whatcolor.

See also predefined unit Text.


whatdotcolor

whatdotcolor graphics function

Syntax whatdotcolor ( x, y : int ) : int

Description The whatdotcolor function is used to determine the color number of the specified pixel. The alternate spelling is whatdotcolour.

Example This program draws a line which bounces off the edges of the screen and makes a beep when it finds a pixel that has already been colored.

        setscreen ( "graphics" )
        var x, y : int := 0
        var dx, dx : int := 1
        loop
            if whatdotcolor ( x, y ) not= 0 then
                sound ( 400, 50 )
            end if
            drawdot ( x, y, 1 )
            x := x + dx
            y := y + dy
            if x = 0 or x = maxx then
                dx := -dx
            end if
            if y = 0 or y = maxy then
                dy := -dy
            end if
        end loop
Details The screen should be in a"graphics" mode. If is not set to "graphics" mode, it will automatically be set to "graphics" mode. See setscreen for details.

See also drawdot, which is used for setting the color of a pixel. See also maxx and maxy, which are used to determine the number of pixels on the screen. See also sound, which causes the computer to make a sound.

See also predefined unit View.


whatrow

whatrow cursor position function

Syntax whatrow : int

Description The whatrow function is used to determine the cursor position's row.

Example This program outputs The current row is 5, the current column is 15.

        locate  ( 5, 10 )
        put "12345"..
        put "The current row is", whatrow
        put "The current column is", whatcol
Details The screen should be in a "screen" or "graphics" mode. whatrow functions properly even if the cursor is invisible.

See also the whatcol function, which is used to set the determine the cursor column. See also the locate, maxrow and maxcol procedure.

See also predefined unit Text.


Window

Description This unit contains the predefined subprograms that handle windows. There are routines to open, close, hide, show and select windows.

All routines in the Window unit are exported qualified (and thus must be prefaced with "Window.").

Details The predefined subprograms of the Window module all use window identifiers to indicate which window to act upon. The default Run window can be specified by using defWindID. For example, the following code causes the main Run window to appear and then blink on and off three times.

        % Output some data to make the Run window appear.
        put "Hello, World!"
        for i : 1 .. 3
            delay (1000)
            Window.Hide (defWinID)
            delay (1000)
            Window.Show (defWinID)
        end for
        put "How are you?"
Entry Points
Open | Opens a new execution window.
Close | Closes an execution window.
Select | Selects an execution window for output.
GetSelect | Returns the currently-selected execution window.
SetActive | Selects and activate (make front-most) an execution window.
GetActive | Gets the current active window.
GetPosition | Get the screen position of an execution window.
SetPosition | Set the screen position of an execution window.
Hide | Hides an execution window.
Show | Shows the current execution window.
Set | Sets the configuration of the execution window.
Update | Updates the onscreen window from the offscreen bitmap.


Window.Close

Window.Close Part of Window module

Syntax Window.Close (windowID : int)

Description The Window.Close procedure closes the window specified by the windowID parameter.

Example The following program opens a window, makes it active and then closes the window after getting a keystroke from the user.

        % Open the window
        var winID : int
        winID := Window.Open ("position:300;300,graphics:200;200")

        % Draw the random ovals in the box
        var x, y, clr : int
        for : 1 .. 20
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            clr := Rand.Int (0, maxcolor)   % Random color
            Draw.FillOval (x, y, 30, 30, clr)
        end for

        var ch : char := getchar            % Wait for input

        Window.Close (winID)            % Close the window
Details If a window is selected (i.e. output is going to that window) when it is closed, the main Run window becomes the selected window.

Status Exported qualified.

This means that you can only call the function by calling Window.Close, not by calling Close.

See also Window.Open and Window.Select.


Window.GetActive

Window.GetActive Part of Window module

Syntax | Window.GetActive : int
Description | The Window.GetActive function returns the window ID of the active window. If the active window is a Turing run window, then Window.GetActive returns defWinID (which is -1) if the window is the default run window, or whatever number was returned from Window.Open for any other run window. If the active window is not a run window, then it returns -5 and sets Error.Last and Error.LastMsg to indicate the fact. An active window is defined as the window that has the input focus. This means that any typing will be sent to the active window. Under most systems an active window is indicated by a change in the appearance of the window.
Status | Exported qualified. This means that you can only call the function by calling Window.GetActive, not by calling GetActive.
See also | Window.SetActive.


Window.GetPosition

Window.GetPosition Part of Window module

Syntax Window.GetPosition (windowID : int, var x, y : int)

Description The Window.GetPosition procedure returns the location of the specified execution window on the screen in the x and y parameters. The x and y parameters specify the lower left corner of the window in screen coordinates. (0, 0) is the lower left corner of the screen.

Example The following program outputs the current position of the run window.

        % Constants for windows
        const titleBarHeight : int := 21
        const windowEdgeSize : int := 13

        % Calculate the actual size of a window
        var windowWidth : int := maxx + windowEdgeSize
        var windowHeight : int := maxy + windowEdgeSize + titleBarHeight

        % Get the screen size
        var screenWidth : int := Config.Display (cdScreenWidth)
        var screenHeight : int := Config.Display (cdScreenHeight)

        % Open the window
        var winID : int := Window.Open ("title:Upper Right")
        Window.SetPosition (winID, screenWidth  windowWidth,                    screenHeight  windowHeight)

        % Return the current position
        var windowXPosition, windowYPosition : int
        Window.GetPosition (winID, windowXPosition, windowYPosition)
        put "Window located at ", windowXPosition, ",", windowYPosition
Status Exported qualified.

This means that you can only call the function by calling Window.GetPosition, not by calling GetPosition.

See also Window.SetPosition to set the current window position and Config.Display to get the size of the screen.


Window.GetSelect

Window.GetSelect Part of Window module

Syntax | Window.GetSelect : int
Description | The Window.GetSelect function returns the window ID of the selected window. If the select window is the main (default) run window, then it returns defWinID (which is -1). A selected window is defined as the window that output will be sent to. It can be invisible. When a program starts execution, the selected window is the main Run window.
Status | Exported qualified. This means that you can only call the function by calling Window.GetSelect, not by calling GetSelect.
See also | Window.Select.


Window.Hide

Window.Hide Part of Window module

Syntax | Window.Hide (windowID : int)
Description | The Window.Hide procedure hides the specified window. This means it disappears from the user's screen. However, it is still possible to select and draw the window while it remains hidden. If the user activates it (using Window.GetActive) it will automatically appear. To make a window appear after it's hidden, you use Window.Show.
Details | When a window is hidden, output to it is faster. It is quite possible for the you to hide a window, do complicated drawing to it and then make it appear in order to have the program execute faster.
Status | Exported qualified. This means that you can only call the function by calling Window.Hide, not by calling Hide.
See also | Window.Select and Window.SetActive.


Window.Open

Window.Open Part of Window module

Syntax Window.Open (setUpString : string) : int

Description The Window.Open function is used to create a window. A window ID is returned if the window is successfully created. If the window is not created then it returns 0. Error.Last and Error.LastMsg can then be used to determine the cause of the failure.

The setUpString parameter is identical to that of View.Set. See View.Set for the list of options available.

When the window is created, it is automatically selected (i.e. all output will be sent to that window unless redirected by a Window.Select command).

Example The following program opens a window, makes it active and then close the window after getting a keystroke from the user.

        % Open the window
        var winID : int
        winID := Window.Open ("position:top;center,graphics:200;200")

        % Draw the random ovals in the box
        var x, y, clr : int
        for : 1 .. 20
            x := Rand.Int (0, maxx)     % Random x
            y := Rand.Int (0, maxy)     % Random y
            clr := Rand.Int (0, maxcolor)   % Random color
            Draw.FillOval (x, y, 30, 30, clr)
        end for

        var ch : char := getchar            % Wait for input

        Window.Close (winID)                % Close the window
Status Exported qualified.

This means that you can only call the function by calling Window.Open, not by calling Open.

See also View.Set for the syntax of startUpString. See also Window.Select and Window.SetActive.


Window.Select

Window.Select Part of Window module

Syntax | Window.Select (windowID : int)
Description | The Window.Select selects the window that output is to be sent to. A selected window is defined as the window that output will be sent to. It can be invisible. When a program starts execution, the selected window is the main Run window.
Status | Exported qualified. This means that you can only call the function by calling Window.Select, not by calling Select.
See also | Window.Select and Window.SetActive.


Window.Set

Window.Set Part of Window module

Syntax Window.Set (windowID : int, setUpString : string)

Description The Window.Set procedure sets the configuration of the window specified by the windowID parameter. See View.Set for a complete list of available options. The setUpString parameter can be any combination options, separated by commas. Here is a selection of the available options.

text:<rows>;<cols> - Sets the output window to text mode and changes the window size to be <rows> rows by <cols> columns in size.

graphics:<xsize>;<ysize> - Sets the output window to graphics mode and changes the window size to be <xsize> pixels across and <ysize> pixels in height.

visible | invisible | popup - Sets the screen to be visible, invisible or popup. A popup window is hidden until output is sent to that window. The main Run window is a popup window. If you never send any output to it, it never appears.

noxor | xor - Sets whether all drawing operations draw using XOR.

nocursor | cursor - Sets whether the cursor is visible or not.

noecho | echo - Sets whether the input from the keyboard is echoed to the screen.

title:<text> - Sets the window title bar to <text>.

position:<x>;<y> - Sets the position of the top left corner of the window to be (<x>,<y>).

offscreenonly | nooffscreenonly - Sets whether output to the window goes to offscreen window alone, or both the onscreen and offscreen window.

Status Exported qualified.

This means that you can only call the function by calling Window.Set, not by calling Set.

See also View.Set for a complete list of the options available with Window.Set. See Window.Open for how to create a new window.


Window.SetActive

Window.SetActive Part of Window module

Syntax | Window.SetActive (windowID : int)
Description | The Window.SetActive procedure activates the window specified by the windowID parameter. An active window is defined as the window that has the input focus. This means that any typing will be sent to the active window. Under most systems an active window is indicated by a change in the appearance of the window.
Details | In general, it is unwise to change the active window. If the user is working on another program at the same time the program is running and the program executes the Window.SetActive procedure, she or he will suddenly be returned to OOT without warning.
Status | Exported qualified. This means that you can only call the function by calling Window.SetActive, not by calling SetActive.
See also | Window.GetActive and Window.Select.


Window.SetPosition

Window.SetPosition Part of Window module

Syntax Window.SetPosition (windowID : int, x, y : int)

Description The Window.SetPosition procedure moves the location of the specified execution window on the screen. x and y specify the lower left corner of the window in screen coordinates. (0, 0) is the lower left corner of the screen.

Example The following program opens four windows, one at each corner of the screen.

        % Constants for windows
        const titleBarHeight : int := 21
        const windowEdgeSize : int := 13

        % Calculate the actual size of a window
        var windowWidth : int := maxx + windowEdgeSize
        var windowHeight : int := maxy + windowEdgeSize + titleBarHeight

        % Get the screen size
        var screenWidth : int := Config.Display (cdScreenWidth)
        var screenHeight : int := Config.Display (cdScreenHeight)

        % Open the window
        var winID1 : int := Window.Open ("title:Upper Right")
        Window.SetPosition (winID1, screenWidth  windowWidth,                   screenHeight  windowHeight)

        var winID2 : int := Window.Open ("title:Upper Left")
        Window.SetPosition (winID2, 0, screenHeight  windowHeight)

        var winID3 : int := Window.Open ("title:Lower Left")
        Window.SetPosition (winID3, 0, 0)

        var winID4 : int := Window.Open ("title:Lower Right")
        Window.SetPosition (winID4, screenWidth  windowWidth, 0)
Status Exported qualified.

This means that you can only call the function by calling Window.SetPosition, not by calling SetPosition.

See also Window.GetPosition to get the current window position and Config.Display to get the size of the screen.


Window.Show

Window.Show Part of Window module

Syntax | Window.Show (windowID : int)
Description | The Window.Show procedure makes the specified window appear if it was invisible. To make a window disappear after it's visible, you use Window.Hide.
Details | When a window is hidden, output to it is faster. It is quite possible for the you to hide a window, do complicated drawing to it and then make it appear in order to have the program execute faster.
Status | Exported qualified. This means that you can only call the function by calling Window.Show, not by calling Show.
See also | Window.Select and Window.SetActive.


Window.Update

Window.Update Part of Window module

Syntax | Window.Update (windowID : int)
Description | The Window.Update procedure updates a specified Run window from an offscreen bitmap. It is used with the command View.Set("offscreenonly") which prevents the Run window from being updated until the Window.Update command is given. This command is identical to the View.Update command except that it updates the specified window. It should be used when doing animation with more than one window.
See also | View.Update for information on flicker-free animation.


write

write file statement

Syntax A writeStatement is:

write : fileNumber [:status ], writeItem {, writeItem}

Description The write statement outputs each of the writeItems to the specified file. These items are output directly using the binary format that they have in the computer. In other words, the items are not in source (ASCII or EBCDIC) format. In the common case, these items will later be input from the file using the read statement. By contrast, the get and put statements use source format, which a person can read using a text editor.

Example This example shows how to output a complete employee record using a write statement.

        var employeeRecord :
            record
                name : string ( 30 )
                pay : int
                dept : 0 .. 9
            end record
        var fileNo : int
        open : fileNo, "payroll", write
        …
        write : fileNo, employeeRecord
Details An array, record or union may be read and written as a whole. The fileNumber must specify a file that is open with write capability (or else a program argument file that is implicitly opened).

The optional status is an int variable that is set to implementation-dependent information about the write. If status is returned as zero, the write was successful. If status is not returned as zero, status gives information about the incomplete or failed write (which is not documented here). Programmers often use status when they are writing a record or array to a file and are not sure if there is enough room on the disk to hold the item. If there is not enough room, the write will fail part way through, but the program can continue and diagnose the problem by inspecting status.

A writeItem is:

        reference [ : requestedSize [ : actualSize ] ]
Each writeItem is a variable or constant, to be written in internal form. The optional requestedSize is an integer expression giving the number of bytes of data to be written. The requestedSize should be less than or equal to the size of the item's internal form in memory (if it is not, a warning message is issued). If no requestedSize is given, the size of the item in memory is used. The optional actualSize is set to the number of bytes actually written.

See also write, open, close, seek, tell, get and put statements.


xor

xor exclusive "or" operator

Syntax A xor B

Description When applied to set values, xor (symmetric difference) yields a set which includes element e if and only if e is contained in exactly one of the operands. When applied to non-negative integer values, xor yields a natural number whose bits are the xor of the corresponding bits of the operands. Both operands A and B are evaluated.

Example Status s3 will contain elements that are in s1 or s2 but not both. Here xor is a set operator. See enum and set types for explanations of these types.

        type status : enum (ready, sending, repeating)
        type statusSet : set of status
        var s1, s2, s3 : statusSet
        s1 := statusSet ( status.read, status.sending )
        s2 := statusSet ( status.read, status.repeating )
        …
        s3 := s1 xor s2     % Same as (s1 + s2) - (s1 * s2)
Example Each bit of natural number n3 will be 1 if exactly one of the corresponding bits of n1 and n2 are 1. For example, if n1 = 2#110 (6) and n2 = 2#010 (2), n3 will be set to 2#100 (4). Here xor is an integer operator.

        var n1, n2, n3 : nat
        …
        n3 := n1 xor n2
Details The xor operator is not a short circuit operator; in other words, both of its operands are always evaluated. The precedence of xor is the same as that of plus (+).

See also set. See also explicitIntegerConstant which describes values such as 2#110.


Turing Language Elements

  • #if - used for conditional compilation
  • addressint - type
  • all - all members of a set
  • and - operator
  • anyclass - the ancestor of all classes
  • array - type
  • assert - statement
  • assignability - of expression to variable
  • assignment - statement
  • begin - statement
  • bind - declaration
  • body - declaration
  • boolean - true-false type
  • break - debugger pause statement
  • case - selection statement
  • catenation (+) - joining together strings
  • char - type
  • char(n) - type
  • checked - compiler directive
  • class - declaration
  • close - file statement
  • collection - declaration
  • comment - remark statement
  • comparisonOperator
  • condition - declaration
  • const - constant declaration
  • constantReference - use of a constant
  • declaration - create a variable
  • deferred - subprogram declaration
  • div - integer truncating division operator
  • enum - enumerated type
  • enumeratedValue - enumerated value
  • equivalence - of types
  • exit - statement
  • explicitCharConstant - character literal
  • explicitConstant - literal
  • explicitIntegerConstant - integer literal
  • explicitRealConstant - real literal
  • explicitStringConstant - string literal
  • explicitTrueFalseConstant - boolean literal
  • expn - expression
  • export - list
  • external - declaration
  • false - boolean value (not true)
  • flexible - array initialization
  • for - statement
  • fork - statement
  • forward - subprogram declaration
  • free - statement
  • function - declaration
  • functionCall
  • get - file statement
  • handler - exception handler
  • id - (identifier) name of an item in a program
  • if - statement
  • implement - clause
  • implement by - clause
  • import - list
  • in - member of a set
  • include - source files
  • indexType
  • indirection - operator (@)
  • infix - operator
  • inherit - inheritance clause
  • init - array initialization
  • int - integer type
  • intn - n-byte integer type
  • invariant - assertion
  • loop - statement
  • mod - modulo operator
  • module - declaration
  • monitor - declaration
  • named - type
  • nat - natural number type
  • natn - n-byte natural number type
  • new - statement
  • nil - pointer to a collection
  • not - true/false (boolean) operator
  • opaque - type
  • open - file statement
  • or - operator
  • paramDeclaration - parameter declaration
  • pause - statement
  • pervasive - declaration modifier
  • pointer - type
  • post - assertion
  • pre - assertion
  • precedence - of operators
  • prefix - operator
  • procedure - declaration
  • procedureCall - statement
  • process - declaration
  • program - a (main) program
  • put - statement
  • quit - fail statement
  • read - file statement
  • real - the real number type
  • realn - n-byte real number type
  • record - type
  • register - use machine register
  • rem - remainder operator
  • result - statement
  • return - statement
  • scalar - type
  • seek - (file) statement
  • separator - between tokens in a program
  • set - type
  • setConstructor
  • shl - shift left operator
  • shr - shift right operator
  • signal - wake up a process statement
  • skip - used in get statement
  • skip - used in put statement
  • standardType
  • statement
  • statementsAndDeclarations
  • string - type
  • string - comparison
  • subprogramHeader
  • subprogramType
  • subrangeType
  • substring - of another string
  • tag - statement
  • tell - file statement
  • token - in input
  • true - boolean value (not false)
  • type - declaration
  • typeSpec - type specification
  • unchecked - compiler directive
  • union - type
  • unit - file containing module, monitor, or class
  • unqualified - export
  • var - declaration
  • variableReference - use of a variable
  • wait - block a process statement
  • write - file statement
  • xor - exclusive "or" operator


Basic Predefined Subprograms

  • Type Conversion
    • From Integer
      • intreal - integer-to-real function
      • intstr - integer-to-string function
    • From Real
      • ceil - real-to-integer function
      • erealstr - real-to-string function
      • floor - real-to-integer function
      • frealstr - real-to-string function
      • realstr - real-to-string function
      • round - real-to-integer function
    • From Nat
      • natreal - natural number to real function
      • natstr - natural-number-to-string function
    • From String
      • strint - string-to-integer:function
      • strintok - string-to-integer:function
      • strnat - string to natural number function
      • strnatok - string to natural number function
      • strreal - string-to-real function
      • strrealok - string-to-real function
    • To/From ASCII
      • chr - integer-to-character function
      • ord - character-to-integer function
  • Maximum Numbers
    • maxint - maximum integer function
    • maxnat - maximum natural number function
    • minint - minimum integer function
    • minnat - minimum natural number function
  • Math
    • abs - absolute value function
    • arctan - arctangent function (radians)
    • arctand - arctangent function (degrees)
    • cos - cosine function (radians)
    • cosd - cosine function (degrees)
    • exp - exponentiation function
    • ln - natural logarithm function
    • max - maximum function
    • min - minimum function
    • sign - function
    • sin - sine function (radians)
    • sind - sine function (degrees)
    • sqrt - square root function
  • Strings
    • index - find pattern in string function
    • length - of a string function
    • repeat - make copies of string:function
  • Enumerated Types
    • pred - predecessor function
    • succ - successor function
  • Files
    • eof - end-of-file function
  • Arrays
    • lower - bound
    • upper - bound
  • Random Numbers
    • rand - random real number procedure
    • randint - random integer procedure
    • randnext - procedure
    • randomize - procedure
    • randseed - procedure
  • Time
    • clock - millisecs used procedure
    • date - procedure
    • sysclock - millisecs used procedure
    • time - time of day as a string procedure
    • wallclock - seconds since 1/1/1970 procedure
  • Sound
    • play - procedure
    • playdone - function
    • sound - statement
  • System
    • delay - procedure
    • fetcharg - fetch argument function
    • getenv - get environment function
    • getpid - get process id function
    • nargs - number of arguments
    • system - statement
  • Parallel Port
    • parallelget - parallel port function
    • parallelput - parallel port procedure
  • Mouse
    • buttonchoose - switch mouse modes
    • buttonmoved - has a mouse event occurred
    • buttonwait - get a mouse event procedure
    • mousewhere
  • Character Graphics
    • cls - clear screen graphics procedure
    • color - text color graphics procedure
    • colorback - background color procedure
    • colour - text color graphics procedure
    • colourback - background color procedure
    • locate - procedure
    • maxcol - maximum column function
    • maxcolor - graphics function
    • maxcolour - graphics function
    • maxrow - maximum row function
    • setscreen - graphics procedure
    • whatcol - cursor position function
    • whatcolor - text color graphics function
    • whatcolorback - color of background function
    • whatcolour - text color graphics function
    • whatcolourback - color of background function
    • whatrow - cursor position function
  • Pixel Graphics
    • cls - clear screen graphics procedure
    • color - text color graphics procedure
    • colorback - background color procedure
    • colour - text color graphics procedure
    • colourback - background color procedure
    • drawarc - graphics procedure
    • drawbox - graphics procedure
    • drawdot - graphics procedure
    • drawfill - graphics procedure
    • drawfillarc - graphics procedure
    • drawfillbox - graphics procedure
    • drawfillmapleleaf - graphics procedure
    • drawfilloval - graphics procedure
    • drawfillpolygon - graphics procedure
    • drawfillstar - graphics procedure
    • drawline - graphics procedure
    • drawmapleleaf - graphics procedure
    • drawoval - graphics procedure
    • drawpic - graphics procedure
    • drawpolygon - graphics procedure
    • drawstar - graphics procedure
    • locate - procedure
    • locatexy - graphics procedure
    • maxcol - maximum column function
    • maxcolor - graphics function
    • maxcolour - graphics function
    • maxrow - maximum row function
    • maxx - graphics function
    • maxy - graphics function
    • setscreen - graphics procedure
    • sizepic - graphics function
    • takepic - graphics procedure
    • whatcol - cursor position function
    • whatcolor - text color graphics function
    • whatcolorback - color of background function
    • whatcolour - text color graphics function
    • whatcolourback - color of background function
    • whatdotcolor - graphics function
    • whatdotcolour - graphics function
    • whatrow - cursor position function
  • Character Input
    • getch - get character procedure
    • getchar - get character function
    • hasch - has character function
  • Concurrency
    • empty - condition function
    • getpriority - function
    • setpriority - procedure
    • simutime - simulated time function
  • Addresses and Sizes
    • addr - address of a variable
    • sizeof - size of a type
  • Bit Manipulation
    • bits - extraction
  • Classes
    • objectclass - of a pointer
    • self - pointer to current object
  • Type Cheats
    • cheat - type cheating


Predefined Modules

  • Concurrency
    • Concurrency.empty
    • Concurrency.getpriority
    • Concurrency.setpriority
    • Concurrency.simutime
  • Config
    • Config.Display
    • Config.Lang
    • Config.Machine
  • Dir
    • Dir.Change
    • Dir.Close
    • Dir.Create
    • Dir.Current
    • Dir.Delete
    • Dir.Get
    • Dir.GetLong
    • Dir.Open
  • Draw
    • Draw.Arc
    • Draw.Box
    • Draw.Cls
    • Draw.Dot
    • Draw.Fill
    • Draw.FillArc
    • Draw.FillBox
    • Draw.FillMapleLeaf
    • Draw.FillOval
    • Draw.FillPolygon
    • Draw.FillStar
    • Draw.Line
    • Draw.MapleLeaf
    • Draw.Oval
    • Draw.Polygon
    • Draw.Star
    • Draw.Text
  • Error
    • Error.Last
    • Error.LastMsg
    • Error.LastStr
    • Error.Msg
    • Error.Str
    • Error.Trip
  • ErrorNum
  • Exceptions
  • File
    • File.Copy
    • File.Delete
    • File.DiskFree
    • File.Exists
    • File.Rename
    • File.Status
  • Font
    • Font.Draw
    • Font.Free
    • Font.GetName
    • Font.GetSize
    • Font.GetStyle
    • Font.Name
    • Font.New
    • Font.Sizes
    • Font.StartName
    • Font.StartSize
    • Font.Width
  • GUI
    • GUI.AddLine
    • GUI.AddText
    • GUI.Alert
    • GUI.Alert2
    • GUI.Alert3
    • GUI.AlertFull
    • GUI.Choose
    • GUI.ChooseFull
    • GUI.ClearText
    • GUI.CloseWindow
    • GUI.CreateButton
    • GUI.CreateButtonFull
    • GUI.CreateCanvas
    • GUI.CreateCanvasFull
    • GUI.CreateCheckBox
    • GUI.CreateCheckBoxFull
    • GUI.CreateFrame
    • GUI.CreateHorizontalScrollBar
    • GUI.CreateHorizontalScrollBarFull
    • GUI.CreateHorizontalSlider
    • GUI.CreateLabel
    • GUI.CreateLabelFull
    • GUI.CreateLabelledFrame
    • GUI.CreateLine
    • GUI.CreateMenu
    • GUI.CreateMenuItem
    • GUI.CreateMenuItemFull
    • GUI.CreatePicture
    • GUI.CreatePictureButton
    • GUI.CreatePictureButtonFull
    • GUI.CreatePictureRadioButton
    • GUI.CreatePictureRadioButtonFull
    • GUI.CreateRadioButton
    • GUI.CreateRadioButtonFull
    • GUI.CreateTextBox
    • GUI.CreateTextBoxFull
    • GUI.CreateTextField
    • GUI.CreateTextFieldFull
    • GUI.CreateVerticalScrollBar
    • GUI.CreateVerticalScrollBarFull
    • GUI.CreateVerticalSlider
    • GUI.Disable
    • GUI.Dispose
    • GUI.Draw...
    • GUI.Enable
    • GUI.FontDraw
    • GUI.GetCheckBox
    • GUI.GetEventTime
    • GUI.GetEventWidgetID
    • GUI.GetEventWindow
    • GUI.GetHeight
    • GUI.GetMenuBarHeight
    • GUI.GetScrollBarWidth
    • GUI.GetSliderValue
    • GUI.GetText
    • GUI.GetVersion
    • GUI.GetWidth
    • GUI.GetX
    • GUI.GetY
    • GUI.Hide
    • GUI.HideMenuBar
    • GUI.OpenFile
    • GUI.OpenFileFull
    • GUI.Pic...
    • GUI.ProcessEvent
    • GUI.Quit
    • GUI.Refresh
    • GUI.SaveFile
    • GUI.SaveFileFull
    • GUI.SelectRadio
    • GUI.SetActive
    • GUI.SetBackgroundColor
    • GUI.SetBackgroundColour
    • GUI.SetCheckBox
    • GUI.SetDefault
    • GUI.SetDisplayWhenCreated
    • GUI.SetKeyEventHandler
    • GUI.SetLabel
    • GUI.SetMouseEventHandler
    • GUI.SetNullEventHandler
    • GUI.SetPosition
    • GUI.SetPositionAndSize
    • GUI.SetScrollAmount
    • GUI.SetSelection
    • GUI.SetSize
    • GUI.SetSliderMinMax
    • GUI.SetSliderReverse
    • GUI.SetSliderSize
    • GUI.SetSliderValue
    • GUI.SetText
    • GUI.SetXOR
    • GUI.Show
    • GUI.ShowMenuBar
  • Input
    • Input.KeyDown - get keyboard state
    • Input.Pause - pause for keystroke
    • Input.getch
    • Input.getchar
    • Input.hasch
  • Joystick
    • Joystick.GetInfo
  • Keyboard
  • Limits
    • maxint - maximum integer function
    • maxnat - maximum natural number function
    • minint - minimum integer function
    • minnat - minimum natural number function
  • Math
    • abs - absolute value function
    • arctan - arctangent function (radians)
    • arctand - arctangent function (degrees)
    • cos - cosine function (radians)
    • cosd - cosine function (degrees)
    • exp - exponentiation function
    • ln - natural logarithm function
    • max - maximum function
    • min - minimum function
    • sign - function
    • sin - sine function (radians)
    • sind - sine function (degrees)
    • sqrt - square root function
  • Mouse
    • Mouse.ButtonChoose
    • Mouse.ButtonMoved
    • Mouse.ButtonWait
    • Mouse.Where
  • Music
    • Music.Play
    • Music.PlayFile
    • Music.PlayFileStop
    • Music.Sound
    • Music.SoundOff
  • Net
    • Net.BytesAvailable
    • Net.CharAvailable
    • Net.CloseConnection
    • Net.HostAddressFromName
    • Net.HostNameFromAddress
    • Net.LineAvailable
    • Net.LocalAddress
    • Net.LocalName
    • Net.OpenConnection
    • Net.OpenURLConnection
    • Net.TokenAvailable
    • Net.WaitForConnection
  • PC
    • PC.ParallelGet
    • PC.ParallelPut
    • parallelget - parallel port function
    • parallelput - parallel port procedure
  • Pic
    • Pic.Blend
    • Pic.Blur
    • Pic.Draw
    • Pic.DrawFrames
    • Pic.DrawFramesBack
    • Pic.DrawSpecial
    • Pic.DrawSpecialBack
    • Pic.FileNew
    • Pic.FileNewFrames
    • Pic.Flip
    • Pic.Frames
    • Pic.Free
    • Pic.Height
    • Pic.Mirror
    • Pic.New
    • Pic.Rotate
    • Pic.Save
    • Pic.Scale
    • Pic.ScreenLoad
    • Pic.ScreenSave
    • Pic.SetTransparentColor
    • Pic.SetTransparentColour
    • Pic.Width
  • RGB
    • RGB.AddColor
    • RGB.AddColour
    • RGB.GetColor
    • RGB.GetColour
    • RGB.SetColor
    • RGB.SetColour
    • RGB.maxcolor
    • RGB.maxcolour
  • Rand
    • Rand.Int
    • Rand.Next
    • Rand.Real
    • Rand.Reset
    • Rand.Seed
    • Rand.Set
  • Sprite
    • Sprite.Animate
    • Sprite.ChangePic
    • Sprite.Free
    • Sprite.Hide
    • Sprite.New
    • Sprite.SetFrameRate
    • Sprite.SetHeight
    • Sprite.SetPosition
    • Sprite.Show
  • Str
    • index - find pattern in string function
    • length - of a string function
    • repeat - make copies of string:function
  • Stream
    • Stream.Flush
    • Stream.FlushAll
    • Stream.eof
    • eof - end-of-file function
  • Sys
    • Sys.Exec
    • Sys.FetchArg
    • Sys.GetComputerName
    • Sys.GetEnv
    • Sys.GetPid
    • Sys.GetUserName
    • Sys.Nargs
    • getenv - get environment function
    • getpid - get process id function
  • Text
    • Text.Cls
    • Text.Color
    • Text.ColorBack
    • Text.Colour
    • Text.ColourBack
    • Text.Locate
    • Text.LocateXY
    • Text.WhatCol
    • Text.WhatColor
    • Text.WhatColorBack
    • Text.WhatColour
    • Text.WhatColourBack
    • Text.WhatRow
    • Text.maxcol
    • Text.maxrow
  • Time
    • Time.Date
    • Time.DateSec
    • Time.Delay
    • Time.Elapsed
    • Time.ElapsedCPU
    • Time.PartsSec
    • Time.Sec
    • Time.SecDate
    • Time.SecParts
  • TypeConv
    • From Integer
      • intreal - integer-to-real function
      • intstr - integer-to-string function
    • From Nat
      • natreal - natural number to real function
      • natstr - natural-number-to-string function
    • From Real
      • ceil - real-to-integer function
      • erealstr - real-to-string function
      • floor - real-to-integer function
      • frealstr - real-to-string function
      • realstr - real-to-string function
      • round - real-to-integer function
    • From String
      • strint - string-to-integer:function
      • strintok - string-to-integer:function
      • strnat - string to natural number function
      • strnatok - string to natural number function
      • strreal - string-to-real function
      • strrealok - string-to-real function
    • To/From ASCII
      • chr - integer-to-character function
      • ord - character-to-integer function
  • View
    • View.ClipAdd
    • View.ClipOff
    • View.ClipSet
    • View.Set
    • View.Update - flicker-free animation
    • View.WhatDotColor
    • View.WhatDotColour
    • View.maxcolor
    • View.maxcolour
    • View.maxx
    • View.maxy
  • Window
    • Window.Close
    • Window.GetActive
    • Window.GetPosition
    • Window.GetSelect
    • Window.Hide
    • Window.Open
    • Window.Select
    • Window.Set
    • Window.SetActive
    • Window.SetPosition
    • Window.Show
    • Window.Update
  • Miscellaneous Subprograms
    • Addresses and Sizes
      • addr - address of a variable
      • sizeof - size of a type
    • Arrays
      • lower - bound
      • upper - bound
    • Bit Manipulation
      • bits - extraction
    • Classes
      • objectclass - of a pointer
      • self - pointer to current object
    • Enumerated Types
      • pred - predecessor function
      • succ - successor function
    • Type Cheats
      • cheat - type cheating


The GUI Module

Introduction

Since the introduction of the Macintosh, graphical user interfaces (GUI) have been becoming more and more common. Most commercial programs written for either the Macintosh or Microsoft Windows make use of GUI elements to make their program easier to use.

For some time, students have been requesting methods of putting GUI elements such as buttons, check boxes, radio buttons, etc, into their Turing programs. Turing now includes a new set of predefined subprograms that allow students to add numerous GUI elements to their programs quickly and easily. These subprograms allow students to create: buttons, check boxes, radio buttons, sliders, scroll bars, picture buttons, radio picture buttons, text fields, lines, text labels, and frames.

The entire GUI Library is written in Turing and the source is included with the Turing distribution. The GUI library is completely procedure-oriented. This means that it is not necessary to know object-oriented programming or concepts in order to be able to use the library. Advanced students are welcome (in fact, encouraged) to look at the programs as an example of a large project written in Turing. We hope that there will be enterprising students who will be inspired to add new widgets to the library and encourage those who do so to submit them to Holt Software for possible inclusion into the next version of the library.

Here is a window with a few widgets.

Some GUI Widgets (Output of Example.dem)

The GUI library is usable by students who understand the concept of subprograms. In order to use the GUI library, students must write procedures (although they may be as simple as the student desires). We therefore suggest that teachers introduce students to the GUI library in a Grade 11 computer science course.

Note:Turing has not changed. It is not a visual building language. Students wishing to use the GUI library will be writing programs to create and use these GUI element, not spending their time visually building user interfaces (which may be fun, but teaches very little). In keeping with the tradition of Turing, the more the students learn about computer science, the more interesting their programs will be, GUI or no GUI!

Terminology

The term "Widget" means any graphical user interface element. A button, a check box or radio button are all examples of widgets.

The term "Event" means either a keystroke or a mouse button being pressed in a window.

Example Programs

All example programs shown here are located in the [Turing Directory]/Examples/GUI directory. (In other words, start in the same directory as the Turing executable, move to the Examples folder and then the GUI folder.) All the available GUI widgets have example programs to demonstrate their use.

General Principles of the GUI Library

Here are some general instructions for the use of the GUI library. Read this section before looking at the specifics of various routines.
  • All the subprograms for the GUI library are placed in a module called GUI. To call any of the subprograms, preface the name of the subprogram with GUI.. For example, the CreateLabel subprogram would be called using GUI.CreateLabel.
  • In general, most widgets have a Create subprogram. For example, buttons have a CreateButton subprogram, radio buttons have a CreateRadioButton subprogram, and so on. The Create subprogram takes as parameters things such as the location, the size of the GUI element, and the name of a procedure to be called when the widget is clicked. This procedure must be declared before the call to the Create subprogram.
  • For most widgets, there are two forms of the Create subprogram. The Create subprogram and the CreateFull subprogram. The difference between the two is that the CreateFull subprogram allows the user to define more parameters that are otherwise set to default values. For example, the GUI.CreateButton procedure allows the user to specify the x and y location of the button, the width of the button, the text that appears in the button, and the procedure to call when the button is clicked. The GUI.CreateButtonFull routine specifies those and also allows the user to specify the height of the button (otherwise set to a height that will fit the label), a short cut keyboard character that allows the user to "press" the button using a keyboard and a parameter to allow the user to specify if this button is the "default" button (the one "pressed" if the user presses the Enter key).
  • All Create subprograms return an integer. This number is the ID of the widget that has been created. You need to use this ID if you want to do anything to the widget later, such as move it, change its size, hide it, and so on. Most simple programs can safely ignore the widget ID, although they will need to handle the return value from the function.
  • After all the widgets have been created, the program must repeatedly call GUI.ProcessEvent until the function returns true.

    % Now process events until the user aborts the program.
    loop
        exit when GUI.ProcessEvent
    end loop

    GUI.ProcessEvent checks for user input from the mouse or the keyboard and then checks to see if the user has clicked on a widget. If the user has, then it responds appropriately (toggling the check box, pressing the button, etc.) and then if appropriate, calls the procedure the user supplied in the Create subprogram. GUI.ProcessEvent returns true when the GUI.Quit has been called, otherwise it returns false.

  • When a program is finished execution (for example if the user selected "Quit" or "Exit" from the file menu), it should call the GUI.Quit procedure. This will cause the GUI.ProcessEvent loop to exit. The program should have any clean up code placed after the end loop.
Here is a very simple example of a program that puts "Hello" every time a button is pressed.

% The "Hello" program.
import GUI

View.Set ("graphics:200;200") % Shrink the run window

% The procedure called when the button is pushed.
procedure PutHello
    put "Hello"
end PutHello

% Create the button. The number returned is the ID number of the button.
var b : int := GUI.CreateButton (100, 100, 0, "Say Hello", PutHello)

% Now process events until the user aborts the program.
loop
    exit when GUI.ProcessEvent
end loop

Here is the output window after the user has pressed the button twice.

Output of Hello.dem

Active and Passive Widgets

Widgets come in two forms. Active widgets are ones that respond to keystrokes and button clicks. Passive widgets do not respond to anything. Examples of passive widgets are lines, frames, labels, labelled frames and pictures. Passive widgets are generally used to organize the output window.

Here is an example of a small program that show some passive widgets.

% The "Passive" program
% This demonstrates some of the passive widgets such as:
% Lines, Frames, Labelled Frames, Labels and Pictures.
import GUI

% We'll need a picture for our Picture widget.  Most likely
% you would normally have it saved in an external file and
% use Pic.FileNew to read it into a picture.  For the example
% program we'll construct it by hand.
Draw.FillOval (50, 50, 50, 50, blue)
Draw.FillBox (17, 17, 83, 83, brightred)
Draw.FillStar (17, 17, 83, 83, brightgreen)
Draw.FillMapleLeaf (37, 37, 63, 63, brightpurple)
var pic := Pic.New (0, 0, 100, 100)

View.Set ("graphics:310;335")

% The background must be gray for indented and exdented
% items to be visible.
GUI.SetBackgroundColor (gray)

% Now place the widgets.
% Three lines of the different types with labels
var line1 := GUI.CreateLine (70, 10, maxx - 10, 10, GUI.LINE)
var label1 := GUI.CreateLabelFull (60, 10, "Line", 0, 0,
    GUI.RIGHT + GUI.MIDDLE, 0)
var line2 := GUI.CreateLine (70, 30, maxx - 10, 30, GUI.INDENT)
var label2 := GUI.CreateLabelFull (60, 30, "Indent", 0, 0,
    GUI.RIGHT + GUI.MIDDLE, 0)
var line3 := GUI.CreateLine (70, 50, maxx - 10, 50, GUI.EXDENT)
var label3 := GUI.CreateLabelFull (60, 50, "Exdent", 0, 0,
    GUI.RIGHT + GUI.MIDDLE, 0)

% Now place the frames
var frame1 := GUI.CreateFrame (10, 70, 100, 120, GUI.LINE)
var label4 := GUI.CreateLabelFull (10, 70, "Line", 90, 50,
    GUI.CENTER + GUI.MIDDLE, 0)
var frame2 := GUI.CreateFrame (110, 70, 200, 120, GUI.INDENT)
var label5 := GUI.CreateLabelFull (110, 70, "Indent", 90, 50,
    GUI.CENTER + GUI.MIDDLE, 0)
var frame3 := GUI.CreateFrame (210, 70, 300, 120, GUI.EXDENT)
var label6 := GUI.CreateLabelFull (210, 70, "Exdent", 90, 50,
    GUI.CENTER + GUI.MIDDLE, 0)

% Now place the labelled frames
var frame4 := GUI.CreateLabelledFrame (10, 140, 100, 190, GUI.LINE, "Line")
var frame5 := GUI.CreateLabelledFrame (110, 140, 200, 190, GUI.INDENT,
    "Indent")
var frame6 := GUI.CreateLabelledFrame (210, 140, 300, 190, GUI.EXDENT,
    "Exdent")

% Place the picture
var label7 := GUI.CreateLabel (30, 315, "Picture without merge")
var pic1 := GUI.CreatePicture (30, 210, pic, false)

var label8 := GUI.CreateLabel (maxx - 130, 315, "Picture with merge")
var pic2 := GUI.CreatePicture (maxx - 130, 210, pic, true)

% This loop doesn't do much since none of the widgets have any actions.
loop
    exit when GUI.ProcessEvent
end loop

Here is the output window from the program with some labels, a line, a picture, and a labelled frame.

Output of Passive.dem

When an active widget is initialized, usually an action procedure must be specified. This is the name of a procedure that will be called when the widget is selected. For example, in the Hello program, the PutHello procedure was specified as the action procedure of the button. Whenever the button was pressed, the PutHello procedure was called.

Some action procedures have arguments. For example, the action procedure for a slider has a parameter of the current value. This allows the procedure to use the current value without having to call a GUI subprogram to get the current slider value.

Keyboard Shortcuts

Several types of widgets can have "shortcuts". A shortcut is simply a keystroke that has the same effect as clicking on the widget. When you specify a shortcut to a widget in the CreateFull procedure for the widget, you must specify a single character. The easiest way to do this is to use the chr function with the ASCII value of the character to be used as the shortcut. You can also specify control characters using the "^" notation. For example, the character Ctrl+F can be expressed as "^F" in Turing.

The following characters cannot be used as shortcuts because the Turing environment uses them for various purposes (stopping or rerunning programs, and so on.): Ctrl+C, Ctrl+D, Ctrl+Z, F1, F11 and F12.

Background Color

It is common for windows to have a different background color from the standard white. To change the background color of a window, use the GUI.SetBackgroundColor procedure. This procedure takes one parameter, the new background color. It redraws the window in the background color and then redraws all the widgets. It also notifies the widgets about the new background color so that when the widget is erased or moved, the location of the widget is filled with the new background color instead of white.

Note that Microsoft Windows dialog boxes often have a background color of gray. In order to simulate that, you should give the command GUI.SetBackgroundColor (gray) before creating widgets.

Several widgets (Canvas, Frame, Labelled Frame, Text Field and Text Box) can have borders of either type INDENT or EXDENT. These borders give a sort of 3-D appearance to the widget. However, they require that the background be set to gray.

Here is an example of a small program that creates a Canvas with a 3-D appearance and then draws circles in the corner.

% The "Canvas1" program.
% Create a canvas and draw four circles on it.
import GUI

View.Set ("graphics:200;200")

% Necessary for a 3-D look for the canvas
GUI.SetBackgroundColor (gray)

% This procedure is needed as an argument to CreateCanvasFull.
procedure DoNothing (mx, my : int)
end DoNothing

% Create a label for the canvas.  We could use CreateLabelFull for more
% precise alignment.
var label1 := GUI.CreateLabel (70, 182, "Four Circles")

% Create the canvas.  We need to use CreateCanvasFull in order to
% specify the type of border.
var canvas := GUI.CreateCanvasFull (20, 20, 160, 160, GUI.INDENT,
    DoNothing, DoNothing, DoNothing)

% Draw the four ovals.  Notice that they don't extend off the canvas
% and the co-ordinates they use are relative to the canvas, not the window.
const radius := 70 % Half the width - 10
GUI.DrawFillOval (canvas, 0, 0, radius, radius, brightred)
GUI.DrawFillOval (canvas, 160, 0, radius, radius, brightgreen)
GUI.DrawFillOval (canvas, 0, 160, radius, radius, brightblue)
GUI.DrawFillOval (canvas, 160, 160, radius, radius, brightpurple)

Here is the output window.

Output of Canvas1.dem

Widget Sizes

The size that you specify a widget to be is not necessarily the actual size that the widget will appear. In fact for many widgets, you can specify a width and height of 0 for the widget and lets the initializer decide how large the widget should be. Another example is with check boxes, where if you specify the check box to be right justified, the x and y coordinates indicate the lower-right corner instead of the lower-left corner as usual. This means that you may have to do some experimentation to determine where you want the widgets to be placed. Read the page on each subprogram that you use to find out exactly what you are specifying with the x, y, width and height parameters.

If you are trying to align widgets together (for example aligning scroll bars with a canvas), use the GUI.GetX, GUI.GetY, GUI.GetWidth, and GUI.GetHeight functions to determine the size of the object.

Positioning Text Labels (Aligning Labels with Widgets)

It is very common to want to align text labels with widgets on the screen. There are a few tips and tricks to doing so successfully. To align a text label with a widget, it is simply a matter of using the GUI.CreateLabelFull function with the appropriate x, y, width, height and alignment arguments.

If you are left or right aligning a label, then generally you will want the x coordinate to specify the edge to be aligned from and the width parameter should be set to 0. Similarly, if you are top or bottom aligning a label, then the y coordinate should specify the edge to be aligned from and the height parameter should be set to 0.

To align a widget horizontally with a widget, choose GUI.CENTER for the horizontal alignment and the use the x coordinate and width of the widget as the label's x coordinate and width. You can get the x coordinate and width of a widget using GUI.GetX and GUI.GetWidth.

Likewise, to align a widget vertically with a widget, choose GUI.MIDDLE for the vertical alignment and the use the y coordinate and height of the widget as the label's y coordinate and height. You can get the y coordinate and height of a widget using GUI.GetY and GUI.GetHeight.

Here is an example illustrating the placement of a label at the center of each of four sides of a widget called w:

import GUI
View.Set ("graphics:200;50,nobuttonbar")
procedure DoNothing (text : string)
end DoNothing

var w : int := GUI.CreateTextField (50, 15, 100, "", DoNothing)

% These following lines are the important part of the program.
var left := GUI.CreateLabelFull (GUI.GetX (w) - 2, GUI.GetY (w),
    "Left", 0, GUI.GetHeight (w), GUI.RIGHT + GUI.MIDDLE, 0)
var above := GUI.CreateLabelFull (GUI.GetX (w),
    GUI.GetY (w) + GUI.GetHeight (w) + 2, "Above", GUI.GetWidth (w), 0,
    GUI.CENTER + GUI.BOTTOM, 0)
var right := GUI.CreateLabelFull (GUI.GetX (w) + GUI.GetWidth (w) + 2,
    GUI.GetY (w), "Right", 0, GUI.GetHeight (w), GUI.LEFT + GUI.MIDDLE, 0)
var below := GUI.CreateLabelFull (GUI.GetX (w), GUI.GetY (w) - 2,
    "Below", GUI.GetWidth (w), 0, GUI.CENTER + GUI.TOP, 0)

Here's the result. Note that the formula for aligning a label with a widget is the same for any type of widget.

Text Box Aligned with Four Labels

Here's an example illustrating aligning a widget with the top of the window. Notice that the label is center aligned with x of 0 and width of maxx, and top aligned with a y of maxy and a height of 0.

var title := GUI.CreateLabelFull (0, maxy, "Title", maxx, 0, GUI.CENTER + GUI.TOP, 0)

Finally, here's an example illustrating the placement of a label in the center of the screen. Notice that the label is center aligned with x of 0 and width of maxx, and middle aligned with a y of 0 and a height of maxy.

var title := GUI.CreateLabelFull (0, 0, "Title", maxx, maxy, GUI.CENTER + GUI.MIDDLE, 0)

Note that if a label's position or size is changed with GUI.SetPosition, GUI.SetSize or GUI.SetPositionAndSize, it still retains its alignment with respect to its new x, y, width, and height values.

Canvases

The canvas is a rather unique widget. It is essentially a drawing surface that you place in the window. There are calls using a canvas widget that essentially duplicate all the standard Draw module calls, along with calls corresponding to Font.Draw and various Pic module calls.

The difference is that the calls using the Canvas widget use (0, 0) to mean the bottom left corner of the canvas (not the window) and all drawing is clipped to the canvas (meaning that if you accidentally draw off the canvas, the part of the picture outside the bounds of the canvas will not appear). One of the most common bugs is to accidentally use the actual Draw module routines instead of the GUI.Draw routines when drawing in a canvas. If the drawing is goes outside the bounds of the Canvas, you have made this mistake.

Another feature of the Canvas widget is that you can specify a procedures to be called whenever a user clicks in the Canvas widget, drags the mouse with the mouse button down and then lets go of the mouse button. These procedures allow your program to respond to mouse activity taking place in the canvas widget.

Here is a program that uses a Canvas to allow the user to draw and a button to allow the user to erase the drawing.

% The "Draw" program
import GUI

View.Set ("graphics:300;300")

var oldx, oldy : int
var canvas : int % The drawing canvas.
var clear : int % The clear button.

% Called when the user presses the mouse button in the canvas.
% Sets the initial mouse position.
procedure MouseDown (mx, my : int)
    oldx := mx
    oldy := my
end MouseDown

% Called as the user drags the mouse with the button down in the canvas.
% Draws a line from the previous mouse position to the current position.
procedure MouseDrag (mx, my : int)
    GUI.DrawLine (canvas, oldx, oldy, mx, my, colorfg)
    oldx := mx
    oldy := my
end MouseDrag

% Called when the mouse button is released.
procedure DoNothing (mx, my : int)
end DoNothing

% Called when the clear button is pressed.
procedure Clear
    GUI.DrawCls (canvas)
end Clear

% Create the canvas
canvas := GUI.CreateCanvasFull (10, 30, maxx - 20, maxy - 40, 0,
    MouseDown, MouseDrag, DoNothing)

% Create the clear button
clear := GUI.CreateButton (maxx div 2 - 20, 0, 40, "Clear", Clear)

loop
    exit when GUI.ProcessEvent
end loop

Here is the output window after the user has drawn some lines.

Output of Draw.dem

Multiple Windows

Turing allows for multiple run windows. This can be used to add extra functionality to programs, however there are a few issues that must be understood before multiple windows can be successfully used.

Turing uses the concept of selected windows and active windows. A selected window is determined by the program and is changed by Window.Select. The selected window is the window in which all output appears. When a widget is created, it is automatically created in the selected window.

An active window is last window on which the user clicked. The active window is shown by having its title bar highlighted. When a user types, all keystrokes are sent to the active window.

It is entirely possible to have the selected window and the active window be to different windows.

When you call getch, Mouse.ButtonWait, or any other input routine, Turing checks only the selected window. The GUI Library works around this by selecting all the windows that have widgets in them (one at a time, starting with the active window) and checking each for events.

If you are processing an event from one of several windows, make certain that the correct window is selected before you output your results. Note that the widgets automatically select the correct window, so there is no need to change the selected window before making any calls to the GUI module.

If you close a window with widgets in it, use GUI.CloseWindow to close the window. This removes all the widgets in the window before closing it. If you have several windows with widgets and want some windows to be hidden and then shown later, use the GUI.ShowWindow and GUI.HideWindow to show and hide the windows with widgets in them.

The GUI Library Internals

While it is not necessary to know the internals of the GUI Library to use it, we provide this brief overview for those who wish to understand the inner workings of the library.

The GUI Library consists of four parts. The only part visible to the user is the GUI module. This is located in "%oot/lib/GUI", where %oot is the directory in which the OOT executable is located. The GUI module is essentially a series of procedures that provide a front end to the Widget Module and the Widget Class Library.

The Widget Module is a module called WidgetModule that consists of a series of subprograms that cover all the aspects of GUI's that do not pertain to a particular widget. For example, the procedure to change the background color is here, as well as the procedure to process an event. It is located in "%oot/lib/GuiClass/wdgtmod.tu"

The GUI Class Library consists of a series of classes arranged in a hierarchy illustrated in the following figure. Most of the actual Turing code for the GUI Library is located in the Widget Class Library. Each different type of widget has its own class. Widgets that share common behavior have the same parent. For example, both the vertical and horizontal slider have a slider class as a parent. Those classes whose names start with Generic are abstract classes. They should not be instantiated themselves. They are used to define common behavior among their subclasses. The Turing source for the classes can be found in the directory "%oot/lib/GuiClass"

The fourth part is the WidgetGlobals module. This module that consists mostly of global variables used by the GUI Class Library and the Widget module. It is located in "%oot/lib/GuiClass/wdgtglob.tu"

Here is an example of how the GUI module works: when you create a button using GUI.CreateButton, the CreateButton function in the GUI module creates an object of type ButtonClass. (ButtonClass is found in the Widget Class Library discussed further down). It then calls the Initialize procedure of the ButtonClass to initialize the button with the specified parameters. Finally it assigns an ID number to the widget and arranges it in a table for future reference. Here is another example: when you call a procedure like GUI.Show, the Show procedure takes the widget ID, looks up the object that it represents, and then calls the Show procedure of the object.

Students who wish to add new widgets to the GUI library will have to understand the principles of object oriented programming, as they will be adding a new class to the GUI Class Library and then adding new subprograms in the GUI module that will call their new classes. (At the very least, a Create subprogram will be required for the new widget.)

A suggested project would be to create new versions of the ButtonClass, CheckBoxClass and RadioButtonClass classes that are buttons, check boxes and radio buttons with the new Windows 95/NT appearance. They could be called the Button95Class, CheckBox95Class and RadioButton95Class. Properly written, these new classes should inherit from ButtonClass, etc. and contain only those procedures that differ from the base class (presumably the procedures that display the widget).

The GUI Class Library Hierarchy

GUI Module Routines Summary

The routines in the GUI module are divided into several different types. There are the routines to create various widgets, the routines to create menus and menu items, the routines to do general activities (such as processing an event, changing the background color, etc.) and the routines that act on various types of widgets.

Here is the list of the routines that create widgets:

GUI.CreateButton, GUI.CreateButtonFull | Create a button.
GUI.CreateCheckBox, GUI.CreateCheckBoxFull | Create a check box.
GUI.CreateRadioButton, GUI.CreateRadioButtonFull | Create a radio button.
GUI.CreatePictureButton, GUI.CreatePictureButtonFull | Create a picture button.
GUI.CreatePictureRadioButton, GUI.CreatePictureRadioButtonFull | Create a picture radio button.
GUI.CreateHorizontalSlider | Create a horizontal slider.
GUI.CreateVerticalSlider | Create a vertical slider.
GUI.CreateHorizontalScrollBar, GUI.CreateHorizontalScrollBarFull | Create a horizontal scroll bar.
GUI.CreateVerticalScrollBar, GUI.CreateVerticalScrollBarFull | Create a vertical scroll bar.
GUI.CreateCanvas, GUI.CreateCanvasFull | Create a canvas.
GUI.CreateTextField, GUI.CreateTextFieldFull | Create a text field.
GUI.CreateTextBoxFull, GUI.CreateTextBoxFull | Create a text box.
GUI.CreateTextBoxChoice | Create a multi-line selector.
GUI.CreateLine | Create a line.
GUI.CreateFrame | Create a frame.
GUI.CreateLabelledFrame | Create a labelled frame.
GUI.CreateLabel, GUI.CreateLabelFull | Create a label.
GUI.CreatePicture | Create a picture.

Here is the list of routines that create menus and menu items:

GUI.CreateMenu | Create a menu.
GUI.CreateMenuItem, GUI.CreateMenuItemFull | Create a menu item.

Here is the list of general routines:

GUI.ProcessEvent | Process a single keyboard or mouse down event.
GUI.Quit | Tell the program to exit the event loop.
GUI.ResetQuit | Reset the "quit" flag so a program can reenter the event loop.
GUI.Refresh | Redraw all the widgets on the screen.
GUI.SetBackgroundColor | Change the window's background colour.
GUI.SetNullEventHandler | Set the null event handler.
GUI.SetKeyEventHandler | Set the keystroke event handler.
GUI.SetMouseEventHandler | Set the mouse event handler.
GUI.HideMenuBar | Hide the menu bar in the window.
GUI.ShowMenuBar | Show the menu bar in the window.
GUI.GetEventWidgetID | Get the selected widget's ID (used in a widget's action procedure).
GUI.GetEventWindow | Get the window that the event took place in (used in a widget's action procedure).
GUI.GetEventTime | Get the time (in milliseconds) that the event took place (used in a widget's action procedure).
GUI.GetScrollBarWidth | Return the width of a scroll bar.
GUI.GetMenuBarHeight | Return the height of a menu bar.
GUI.GetVersion | Return the current version number of the GUI module.

Here is a list of routines that act on the widgets and the sort of widgets they act on.

GUI.Show | Display the widget. | All
GUI.Hide | Hide the widget. | All
GUI.GetX | Return the x coordinate of the widget's left edge. | All
GUI.GetY | Return the y coordinate of the widget's bottom edge. | All
GUI.GetWidth | Return the widget's actual width. | All
GUI.GetHeight | Return the widget's actual height. | All
GUI.Dispose | Dispose of the widget. | All
GUI.SetPosition | Set the widget's position. | All
GUI.SetSize | Set the widget's size. | All
GUI.SetPositionAndSize | Set the widget's position and size. | All
GUI.Enable | Enable the widget to respond to events. | Active Widgets
GUI.Disable | Disable the widget from responding to events. | Active Widgets
GUI.SetLabel | Set the widget's text label. | Button, Check Box, Radio Button, Label, Labelled Frame
GUI.SetColor | Set the button's color. | Button
GUI.SetDefault | Make the button the default button. | Button
GUI.GetCheckBox | Get whether a check box is filled. | Check Box
GUI.SetCheckBox | Set a check box to be filled or not. | Check Box
GUI.SelectRadio | Select a radio button. | Radio Button, Picture Radio Button
GUI.GetSliderValue | Return the current value of the slider. | Slider, Scroll Bar
GUI.SetSliderValue | Set the value of the slider. | Slider, Scroll Bar
GUI.SetSliderMinMax | Set the slider's minimum and maximum. | Slider, Scroll Bar
GUI.SetSliderSize | Set the slider's length (or height). | Slider, Scroll Bar
GUI.SetSliderReverse | Reverse the direction of the slider. | Slider, Scroll Bar
GUI.SetScrollAmount | Set the scroll bar's thumb size and the scroll amount for arrows/page up and down. | Scroll Bar
DrawArc, DrawBox, DrawCls, DrawDot, DrawFill, DrawFillArc, DrawFillBox, DrawFillMapleLeaf, DrawFillOval, DrawFillPolygon, DrawFillStar, DrawLine, DrawMapleLeaf, DrawOval, DrawPolygon, DrawStar, DrawText | Routines that perform the same function as the Draw module for the Canvas widget. | Canvas
GUI.FontDraw | "Font.Draw" for the Canvas widget. | Canvas
PicDraw, PicNew, PicScreenLoad, PicScreenSave | Routines that perform the same function as the Pic module for the Canvas widget. | Canvas
GUI.SetXOR | Performs View.Set ("xor") for the Canvas Widget. | Canvas
GUI.SetText | Set the text of a text field. | Text Field
GUI.SetEchoChar | Set the character that appears when user enters a keystroke. | Text Field
GUI.SetSelection | Set the selection in the text field. | Text Field
GUI.SetActive | Make the text field the active one (where keystrokes will go and where the cursor blinks). | Text Field
GUI.ClearText | Clear a text box. | Text Box
GUI.AddText | Add text to a text box. | Text Box
GUI.AddLine | Add a line of text to a text box. | Text Box
GUI.SetTopLine | Scrolls text box to make line appear at top. | Text Box
GUI.SetScrollOnAdd | Sets whether text box scrolls when text added. | Text Box

Widgets - Common Routines

All of the procedures in this section can be used with any widget, although some may have no effect (for example GUI.GetX on a menu item is meaningless).

GUI.Show | Displays a widget. Used in conjunction with Hide to hide and show widgets. Hidden widgets cannot get events (i.e. respond to keystrokes or mouse clicks).
GUI.Hide | Hides a widget. Used in conjunction with Show to hide and show widgets. Hidden widgets cannot get events (i.e. respond to keystrokes or mouse clicks). If an active text field (see text field) is hidden, then any keystrokes in the window will be ignored.
GUI.GetX
GUI.GetY		Returns the x (y) coordinate of the left edge of a widget. Note that this may be different from the x coordinate specified in the widget's Create call. For example, if a radio button is created with right justification, the x coordinate in the Create method specifies the right edge.

Here is a small subprogram that should draw a rectangle entirely around a widget (i.e. no part of the widget should stick out).

procedure WidgetRect (widgetID : int)
    const x : int := GUI.GetX (widgetID)
    const y : int := GUI.GetY (widgetID)
    const width : int := GUI.GetWidth (widgetID)
    const height : int := GUI.GetHeight (widgetID)
    Draw.Box (x, y, x + width - 1, y + height - 1, black)
end WidgetRect

GUI.GetWidth
GUI.GetHeight		Returns the actual width (height) of a widget. Note that this may be different from the width specified in the Create call (especially since many widgets allow you to specify 0 for the width and let the GUI module determine the necessary width).
GUI.Dispose | Eliminates a widget. It should be called in order to free up any memory that the widget might have allocated. Note that you cannot use the widget after it has been disposed of. If you wish to temporarily get rid of a widget, consider using the Hide method and then the Show method when you want to use it again.
GUI.SetPosition | Moves a widget to the specified location. If the widget is visible, it is moved immediately to the new location. If the widget is hidden, it will appear at the new location when the Show procedure is called. Note that the location specified in GUI.SetPosition are the same as in the Create method. For example, if you had specified a check box to be right justified in the CreateCheckBoxFull function, then the location in a call to SetPosition would specify the lower-right corner as opposed to the lower-left corner.
GUI.SetSize | Changes the size of a widget. If the widget is visible, its size is changed immediately, otherwise the widget will appear in its new size when the widget is next made visible. Note that the width and height parameters are not necessarily the actual width and height of the widget. For example, the TextField widget ignores the height parameter, calculating the widget's actual height from the height of the text in the TextField.
GUI.SetPositionAndSize | Changes the position and size of the widget simultaneously. It works the same way as the SetPosition and SetSize procedures.

Widgets - Buttons

Output of Buttons.dem

The button widget is used to implement a textual button. When you click on a button, the button's action procedure is called. If a button is given a short cut, then entering the keystroke will cause the action procedure to be called. It will not visibly cause the button to depress.

If a button's width or height is set to zero (or not specified at all), then the button is shaped to fit the text.

A button can be the default button for a window. If that is the case, then the button will be drawn with a ticker border around it and if the user presses ENTER, then the button's action procedure will be called.

When a button is not enabled, the text in the button is grayed out and the button no longer responds to any mouse clicks or keystrokes until the button is enabled again.

GUI.CreateButton | Creates and displays a button. GUI.CreateButton specifies the location, width, text and action procedure of the button.
GUI.CreateButtonFull | Creates and displays a button. GUI.CreateButtonFull also specifies the height, keyboard shortcut and default status of the button.
GUI.Enable GUI.Disable | Enables (disables) a button. Disabled buttons have their text grayed out and cannot get events (i.e. respond to keystrokes or mouse clicks).
GUI.SetLabel | Changes the text of a button.
GUI.SetDefault | Sets the "default status" of a button. If a button is the default button, then it is drawn with a heavy outline and it is activated when the user presses ENTER (RETURN on a Macintosh).

Widgets - Check Boxes

Output of CheckBoxes.dem

The check box widget is used to implement a check box that can be set or unset. When you click on a check box, the status of the check box flips from set to unset and back again and the check box's action procedure is called with the new status as a parameter. If a check box is given a short cut, then entering the keystroke will cause the check box to change status and the action procedure to be called. The new status will be displayed immediately.

A check box's size is not specified during creation. It is determined based on the size of the text. Instead the user specifies the lower-left corner of the check box (or the lower-right if the check box is right justified).

When a check box is not enabled, the label beside the check box is grayed out and the check box no longer responds to any mouse clicks or keystrokes until the check box is enabled again.

GUI.CreateCheckBox | Creates and displays a left aligned (check box to the left of the label) check box. GUI.CreateCheckBox specifies the location, text and action procedure of the check box.
GUI.CreateCheckBoxFull | Creates and displays a check box. GUI.CreateCheckBoxFull also specifies the alignment of the check box (whether the checkbox is the right or left of the text) and the check box's keyboard shortcut.
GUI.Enable GUI.Disable | Enables (disables) a check box. Disabled check boxes have their text grayed out and cannot get events (i.e. respond to keystrokes or mouse clicks).
GUI.SetLabel | Changes the text of a check box.
GUI.GetCheckBox | Returns a check box's status. If the check box is set (has an X in it), GUI.GetCheckBox returns true, otherwise it returns false.
GUI.SetCheckBox | Sets the status of a check box. It calls the check box's action procedure with the new status and redraws the widget with the new status.

Widgets - Radio Buttons

Output of RadioButtons.dem

The radio button widget is used to implement a set of buttons of which one and only one button must be selected at all times. (Think old-style radio station button. Selecting one "deselects" the previously-selected station.) When you click on a radio button, any other radio button that is part of the set is deselected and the radio button's action procedure is called. If a radio button is given a short cut, then entering the keystroke will cause the radio button to be selected (and any other radio button in the group to be de-selected) and the action procedure to be called. The newly-selected or deselected radio buttons will be displayed immediately.

When a radio button is created, the widget ID of another radio button must be supplied. A value of zero for the widget ID indicates that this radio button is part of a new group. The widget ID must be the ID of the last radio button added to the group. Because radio buttons are almost always placed in groups you can specify -1 for the x and y coordinates and the radio button will be placed just below the previous radio button and retain the same alignment. When a group of radio buttons is selected, the first radio button created in the group will be the selected one. You can change this by using the GUI.SelectRadio procedure to select a different one.

A radio button's size is not specified during creation. It is determined based on the size of the text. The user specifies the lower-left corner of the radio button (or the lower-right if the radio button is right justified).

When a radio button is not enabled, the label beside the radio button is grayed out and the radio button no longer responds to any mouse clicks or keystrokes until the radio button is enabled again.

GUI.CreateRadioButton | Creates and displays a left aligned (circle to the left of the label) radio button. GUI.CreateRadioButton specifies the location, text, the radio button to be joined to and the action procedure of the radio button.
GUI.CreateRadioButtonFull | Creates and displays a radio button. GUI.CreateRadioButtonFull also specifies the alignment of the radio button (whether the circle is the right or left of the text) and the radio button's keyboard shortcut.
GUI.Enable GUI.Disable | Enables (disables) a radio button. Disabled radio buttons have their text grayed out and cannot get events (i.e. respond to keystrokes or mouse clicks).
GUI.SetLabel | Changes the text of a radio button.
GUI.SelectRadio | Selects a radio button. The previously-selected radio button is "de-selected". The action procedure of the radio button is called.

Widgets - Picture Buttons

Output of PictureButtons.dem

The picture button widget (hereafter simply called a button) is simply a button with a picture on it instead of text. The picture must be created by the program beforehand using Pic.New or Pic.FileNew. The resulting picture can then be used as a parameter to GUI.CreatePictureButton. In general, pictures should be a maximum of about 30 pixels high and wide, although there is no built in limit in the GUI library.

When you click on a picture button, the picture button's action procedure is called. If a picture button is given a short cut, then entering the keystroke will cause the action procedure to be called. It will not visibly cause the button to depress.

If a button's width or height is set to zero (or not specified at all), then the button is shaped to fit the picture.

When a picture button is not enabled, the picture button is grayed out and the picture button no longer responds to any mouse clicks or keystrokes until the button is enabled again.

GUI.CreatePictureButton | Creates and displays a picture button. The button is automatically sized to fit the picture. If you need to know the precise size of the button, use the GUI.GetWidth and GUI.GetHeight functions. GUI.CreatePictureButton specifies the location, picture id and action procedure of the button.
GUI.CreatePictureButtonFull | Creates and displays a picture button. GUI.CreatePictureButtonFull also specifies the width, height and keyboard shortcut of the button. It also specifies whether the button picture should be merged with the background color or not.
GUI.Enable GUI.Disable | Enables (disables) a picture button. Disabled picture buttons are grayed out and cannot get events (i.e. respond to keystrokes or mouse clicks).

Widgets - Picture Radio Buttons

Output of PictureRadioButtons.dem

The picture radio button widget (hereafter simply called a button) is simply a picture button (see Widget - Picture Button) that has the behavior of a radio button. This means that one and only one picture radio button of a group is selected at any time. A selected picture radio button is displayed as being pressed.

When you click on a picture button, the previously-selected picture radio button will be de-selected and the new picture button's action procedure is called. If a picture button is given a short cut, then entering the keystroke will cause the action procedure to be called and the picture radio button will be drawn selected.

GUI.CreatePictureRadioButton | Creates and displays a picture radio button. The button is automatically sized to fit the picture. If you need to know the precise size of the button, use the GUI.GetWidth and GUI.GetHeight functions. GUI.CreatePictureRadioButton specifies the location, picture id and action procedure of the button as well as the radio picture button to be joined to.
GUI.CreatePictureRadioButtonFull | Creates and displays a picture radio button. GUI.CreatePictureRadioButtonFull also specifies the width, height and keyboard shortcut of the button. It also specifies whether the button picture should be merged with the background color or not.
GUI.Enable GUI.Disable | Enables (disables) a picture radio button. Disabled picture buttons are grayed out and cannot get events (i.e. respond to keystrokes or mouse clicks).

Widgets - Sliders

Output of Sliders.dem

Sliders are the equivalent of a volume control on a stereo. To control a slider, the user simply clicks on the control knob and slides the control left and right (up and down for a vertical slider). Whenever the user slides the control knob, the action procedure of the widget is called with the current value as a parameter.

The range of values that the slider will give is determined by the min and max parameters in the Create call. The left side of the slider (bottom for vertical sliders) represents the minimum value, while the right (top) represents the maximum value.

In some instances, you will want the reverse to be true (right/top is minimum). In that case, call the GUI.SetSliderReverse procedure to flip the values of the slider.

Sliders always have a fixed height (for horizontal sliders) or width (for vertical sliders). The length parameter in the Create call specifies how long the slider should be.

GUI.CreateHorizontalSlider | Creates and displays a horizontal (left-right) slider. GUI.CreateHorizontalSlider specifies the location, length, minimum and maximum values for the slider, the initial value of the slider, and the action procedure of the slider.
GUI.CreateVerticalSlider | Creates and displays a vertical (up-down) slider. GUI.CreateVerticalSlider specifies the location, length, minimum and maximum values for the slider, the initial value of the slider, and the action procedure of the slider.
GUI.Enable GUI.Disable | Enables (disables) a slider. Disabled sliders cannot get events (i.e. respond to mouse clicks).
GUI.GetSliderValue | Returns the current value of a slider.
GUI.SetSliderValue | Sets the value of a slider. It moves the control knob on the slider to the appropriate location and calls the slider's action procedure with the new value.
GUI.SetSliderMinMax | Sets the minimum and maximum values of a slider. It redraws the control knob to take into account the new minimum and maximum. If the current value of the slider is outside the new min/max, then the value is adjusted appropriately.
GUI.SetSliderSize | Changes the length of a slider. Redraws the slider and changes the position of the control knob to take into account the new size of the slider.
GUI.SetSliderReverse | Sets a slider into (or out of, if already into) "reverse mode". Normally, a slider is at its minimum value when the control knob is on the left side (bottom for a vertical slider). This reverses it, so the minimum value is when the slider is at the right side (top for vertical sliders) of the track. Calling this routine a second time reverses it back to normal. This procedure redraws the slider to move the control knob to its new location.

Widgets - Scroll Bars

Output of ScrollBars.dem

Scroll bars are usually used to allow a user to see a piece of a document that cannot be displayed on the screen in its entirety. The picture above shows the scroll bars appearance. To control a scroll bar, there are a few choices: the user can click on the thumb (the box in the scroll bar) and slide it up and down, or the user can click in the scroll bar itself above or below the thumb (in which case the thumb is moved up or down one "page"), or the user can click on the up or down arrows at the ends of the scroll bar (in which case the thumb is moved up one "line"). The programmer defines a page or a line. When the value of the scroll bar changes, the action procedure of the scroll bar is called with the new value as a parameter.

The range of values that the scroll bar will give is determined by the min and max parameters in the Create call. The left side of the scroll bar (bottom for vertical scroll bars) represents the minimum value, while the right (top) represents the maximum value. There is also the "thumb size". This represents the range of values that can be seen at once on the screen.

For example, if you have a window that can display 20 lines of text at once and there are 100 lines of text, you would set min to 1, max to 100, and thumbSize to 20. The value returned by the scroll bar would then be the line number of the first line on the screen to be displayed. When the scroll bar was at its maximum value, it would return 81, since by doing so, lines 81-100 would be displayed.

When a scroll bar is disabled or the scroll bar's thumb size is greater than the difference between the minimum and maximum values (i.e. the item being scrolled fits in the window), the scroll bar is deactivated. The bar is drawn in white rather than gray and the arrows are grayed out. The scroll bar does not respond to mouse clicks.

In some instances, you will want the minimum and maximum values of the scroll bar to be reversed (right/top is minimum). In that case, call the GUI.SetSliderReverse procedure to flip the values of the scroll bar.

Scroll bars always have a fixed height (for horizontal scroll bars) or width (for vertical scroll bars). To get the scroll bar's width, use the GUI.GetScrollBarWidth function. The length parameter in the Create call specifies how long the scroll bar should be.

GUI.CreateHorizontalScrollBar | Creates and displays a horizontal (left-right) scroll bar. GUI.CreateHorizontalScrollBar specifies the location, length, minimum and maximum values for the scroll bar, the initial value of the scroll bar, and the scroll bar's action procedure. By default, the arrow increment (the amount the value is changed when the scrolling arrows are pressed) is set to one. The page up/down increment (the amount the value is changed when the user clicks in the bar to the right or left of the thumb) is set to one quarter the difference between the minimum and the maximum. The "thumb size" is set to zero (see the description of scroll bars for an explanation of the thumb size).
GUI.CreateVerticalScrollBar | Creates and displays a vertical (up-down) scroll bar. GUI.CreateVerticalScrollBar specifies the location, length, minimum and maximum values for the scroll bar, the initial value of the scroll bar, and the scroll bar's action procedure. By default, the arrow increment (the amount the value is changed when the scrolling arrows are pressed) is set to one. The page up/down increment (the amount the value is changed when the user clicks in the bar to the right or left of the thumb) is set to one quarter the difference between the minimum and the maximum. The "thumb size" is set to zero (see the description of scroll bars for an explanation of the thumb size).
GUI.CreateHorizontalScrollBarFull | Creates and displays a horizontal (left-right) scroll bar. GUI.CreateHorizontalScrollBarFull also specifies the arrow increment, page increment, and thumb size for the scroll bar.
GUI.CreateVerticalScrollBarFull | Creates and displays a horizontal (left-right) scroll bar. GUI.CreateVerticalScrollBarFull also specifies the arrow increment, page increment and thumb size for the scroll bar.
GUI.Enable GUI.Disable | Enables (disables) a scroll bar. Disabled scroll bars cannot get events (i.e. respond to mouse clicks).
GUI.GetSliderValue | Returns the current value of a scroll bar.
GUI.SetSliderValue | Sets the value of a scroll bar. It moves the control knob on the scroll bar to the appropriate location and calls the scroll bar's action procedure with the new value.
GUI.SetSliderMinMax | Sets the minimum and maximum values of a scroll bar. It redraws the control knob to take into account the new minimum and maximum. If the current value of the scroll bar is outside the new min/max, then the value is adjusted appropriately.
GUI.SetSliderSize | Changes the length of a scroll bar. Redraws the scroll bar and changes the position of the control knob to take into account the new size of the scroll bar.
GUI.SetSliderReverse | Sets a scroll bar into (or out of, if already into) "reverse mode". Normally, a scroll bar is at its minimum value when the control knob is on the left side (bottom for a vertical scroll bar). This reverses it, so the minimum value is when the scroll bar is at the right side (top for vertical scroll bars) of the track. Calling this routine a second time reverses it back to normal. This procedure redraws the scroll bar to move the control knob to its new location.
GUI.SetScrollAmount | Sets a scroll bar's arrow increment, page increment, and thumb size. Redraws the scroll bar to take into account the new thumb size.

Widgets - Canvases

Output of Canvases.dem

A canvas is a drawing surface for use by the program. It differs from just using the window surface to draw on in that (0, 0) represents the lower-left corner of the canvas and all drawing is clipped to the canvas. (This means that if you accidentally attempt to draw outside of the canvas, it will not actually draw beyond the border of the canvas.)

Canvases have procedures that emulate all the procedures in the Draw module as well as a procedure to emulate Font.Draw, Pic.Draw, Pic.New, Pic.ScreenLoad, and Pic.ScreenSave.

You can get mouse feedback from a canvas. Using the GUI.CreateCanvasFull method, you can specify three routines that are called when the mouse button is depressed while pointing in a canvas. One routine will be called when the user presses the mouse button down in a canvas. Another routine will be called while the user drags the mouse with the mouse button down. This routine is repeatedly called whenever the mouse changes position while the mouse button is down. The last routine is called when the mouse button is released. All three routines take an x and y parameter, which is the location of the mouse with respect to the canvas (i.e. (0, 0) is the lower-left corner of the canvas).

GUI.CreateCanvas | Creates and displays a canvas. GUI.CreateCanvas specifies the location and size of the canvas. The canvas will have a line border around it.
GUI.CreateCanvasFull | Creates and displays a canvas. GUI.CreateCanvasFull also specifies the type of border and three procedures to be called when a mouse is pressed, dragged or released on the canvas.
GUI.Enable GUI.Disable | Enables (disables) a canvas. Disabled canvases cannot get events (i.e. respond to mouse clicks). If no mouse routines were specified (i.e. the canvas was created with GUI.CreateCanvas and not GUI.CreateCanvasFull) this routine essentially does nothing.
GUI.DrawArc GUI.DrawBox GUI.DrawCls GUI.DrawDot GUI.DrawFill GUI.DrawFillArc GUI.DrawFillBox GUI.DrawFillMapleLeaf GUI.DrawFillOval GUI.DrawFillPolygon GUI.DrawFillStar GUI.DrawLine GUI.DrawBox GUI.DrawMapleLeaf GUI.DrawOval GUI.DrawPolygon GUI.DrawStar GUI.DrawText GUI.FontDraw GUI.PicDraw GUI.PicNew GUI.PicScreenLoad GUI.PicScreenSave | All these routines draw to a canvas in the same manner as the similarly named Draw…, Pic… and Font.Draw subprograms. All coordinates are based on the canvas and all drawing is clipped to the canvas drawing surface. If the canvas is in "xor mode", all the drawing will be done with "xor" set. (See View.Set for more information about "xor".)
GUI.SetXOR | Sets the "xor mode" of a canvas. When in "xor mode", all the Draw... procedures of a canvas are treated as if the View.Set ("xor") statement had been executed before the Draw procedure.

Widgets - Text Fields

Output of TextFields.dem

A text field is a box for entering one line of text. When the user presses ENTER, the text field's action procedure is called.

Only one text field is active at a time. The active text field has a blinking cursor (or its selection highlighted). If a keystroke occurs when a window has an active text field in it, the keystroke will be directed to the active text field. You can change which text field is active with the GUI.SetActive procedure or by simply clicking on another text field with the mouse.

When multiple text fields are created in a window, the first text field created is active when the program begins.

The current version of the text field does not support cut and paste or keyboard commands to extend the selection.

Because strings are a maximum of 255 characters, this is the maximum number of characters in a text field.

The TAB character cycles between different text fields in a window. It cycles through the text fields in the order in which they were created. BACK TAB (shift+TAB) cycles through the fields in reverse order.

GUI.CreateTextField | Creates and displays a text field. GUI.CreateTextField specifies the location, width, initial text string, and action procedure of the text field. The height of the text field is determined by the height of the font used by the text field. The text field will have a line border around it.
GUI.CreateTextFieldFull | Creates and displays a text field. GUI.CreateTextFieldFull also specifies the type of border, font for entered text, and kind of input restriction (integer only, etc.)
GUI.Enable GUI.Disable | Enables (disables) a text field. Disabled picture buttons are grayed out and cannot get events (i.e. respond to keystrokes or mouse clicks).
GUI.SetText | Sets the text of a text field. The cursor is set the beginning of the text.
GUI.GetText | Returns the current text of a text field.
GUI.SetSelection | Sets the selection (the selected text) in a text field.
GUI.SetActive | Makes a text field active.

Widgets - Text Boxes

Output of TextBoxes.dem

A text box is a box used for displaying larger quantities of text. It has both vertical and horizontal scroll bars to allow the user to scroll through all the text in the box.
GUI.CreateTextBox | Creates and displays a text box. GUI.CreateTextBox specifies the location and size of the text box. The text box will have a line border around it.
GUI.CreateTextBoxFull | Creates and displays a text box. GUI.CreateTextBoxFull also specifies the type of border and the font for displayed text.
GUI.ClearText | Clears all the text in a text box.
GUI.AddText | Adds text to the current line of the text box. Does not add a newline after the text. Equivalent to put text ... This scrolls the text box (if necessary) so that the added text is now visible. To move the cursor to the end of the text without adding any extra text, call GUI.AddText with "" for the text parameter.
GUI.AddLine | Adds text to the current line of the text box followed by a newline. Equivalent to put text. This scrolls the text box (if necessary) so that the added text is now visible.

Widgets - Lines

Output of Lines.dem

Lines are organizational elements that make the window look better and help organize the GUI elements.
GUI.CreateLine Creates and displays a line. GUI.CreateLine specifies the end points of the line (which must be either vertical or horizontal) and the type of line.

Widgets - Frames

Output of Frames.dem

Frames are organizational elements that make the window look better and help organize the GUI elements. Frames and labelled frames are the only widgets in which other widgets can be placed.
GUI.CreateFrame Creates and displays a frame. GUI.CreateFrame specifies the coordinates of the lower-left and upper-right corner of the frame and the type of border of the frame.

Widgets - Labelled Frames

Output of LabelledFrames.dem

Labelled frames are organizational elements that make the window look better and help organize the GUI elements. Frames and labelled frames are the only widgets in which other widgets can be placed.
GUI.CreateLabelledFrame | Creates and displays a labelled frame. GUI.CreateLabelledFrame specifies the coordinates of the lower-left and upper-right corner of the frame, the type of border of the frame, and the text of the frame's label.
GUI.SetLabel | Changes the text of a labelled frame.

Widgets - Labels

Output of Labels.dem

Labels are organizational elements that make the window look better and help organize the GUI elements. They are simply text placed in a window. To aid in aligning text with various widgets, it is possible to align text in a larger region (as shown in the figure).
GUI.CreateLabel | Creates and displays a label. GUI.CreateLabel specifies the lower-left corner of the text and the text itself. The system font is used to display the label.
GUI.CreateLabelFull | Creates and displays a label. GUI.CreateLabelFull also specifies the width, height, alignment, and font for the label. The width and height are specified for alignment purposes.
GUI.SetLabel | Changes the text of a label.

Widgets - Pictures

Output of Pictures.dem

Pictures are organizational elements that make the window look better and help organize the GUI elements. They are simply a picture placed in a window. The pictures are specified using a picture ID from any of the Pic… subprograms.
GUI.CreatePicture Creates and displays a picture. GUI.CreatePicture specifies the location, picture ID, and whether the picture should be merged with the background.

Widgets - Menus

Output of Menus.dem

Menus are used in most modern interfaces. In order to create a full set of menus, you must create the menu and then create the menu items in that menu. The menus are automatically added to the menu bar of the selected menu.

Menu items are the individual entries of a menu. To create menus for a window, you must create a menu, then create the menu items for that menu, then create the next menu, then the items for that menu, etc. All menu items are automatically added to the last menu and after the last menu item of the currently selected (not active!) window.

When you select an item in a menu, the action procedure of the item is called. The action procedure has no parameters.

As of the v1.0 release of the GUI Library, it is an error to create a menu item without having created a menu first. In future releases it will be possible to create menus and attach and remove them from menu bars when desired.

Menus and menu items can be enabled and disabled. A disabled menu item is grayed out. When the user selects the menu, all items in the menu appear disabled and cannot be selected. A disabled menu item is grayed out when the menu is displayed. The user cannot select the menu item.

Separators in a menu appear as a solid line across the menu. These are created by creating a menu item whose text is three dashes "---".
GUI.CreateMenu | Creates and displays a menu. The menu will be added after the other menus in the menu bar. If there are no previous menus, then a menu bar is automatically created and the menu added. GUI.CreateMenu specifies the text that will appear in the menu bar. It is suggested that the text not have any spaces in it.
GUI.Enable GUI.Disable | Enables (disables) a menu. Disabled menus are grayed out in the menu bar. If selected, all the menu items in the menu bar appear disabled and cannot be selected.
GUI.CreateMenuItem | Creates a menu item. GUI.CreateMenuItem specifies the text of the menu item and the action procedure to be called when the menu item is selected. The menu item will be added to the last menu after the other menu items in the menu. If there are no menus defined, an error results.
GUI.CreateMenuItemFull | Creates a menu item. GUI.CreateMenuItemFull also specifies a shortcut keystroke.
GUI.Enable GUI.Disable | Enables (disables) a menu item. Disabled menu items are grayed out when the menu is displayed and cannot be selected by the user.

Widgets - General Routines

The following procedures are included in the GUI module but do not relate to a specific widget.
GUI.ProcessEventThis function processes a single event (a mouse button press or a keystroke). If the event activates a widget, then the action procedure of the widget is called. To find out which widget was activated and called the action procedure (necessary if several widgets have the same action procedure), you can call GUI.GetEventWidgetID. To get the exact time that the event occurred, you can call GUI.GetEventTime. To get the window in which the event took place, you can call GUI.GetEventWindow.
If a mouse click occurred, but did not activate any widget, then the default mouse event handler is called. By default, this does nothing. However, if you want your program to respond to mouse events that do not affect a widget, call GUI.SetMouseEventHandler to specify your own default mouse event handler.
If a keystroke occurred, but did not activate any widget (i.e. it wasn't a short cut for a widget and there are no text fields in the window) then the default keystroke handler is called. By default, this does nothing. However, if you want your program to respond to keystroke events that do not affect a widget, call GUI.SetKeyEventHandler to specify your own default key event handler.
If no event occurred, then the null event handler is called. By default, this does nothing. However, if you want your program to perform some action repetitively when it is not doing anything else, then call GUI.SetNullEventHandler to specify your own null event handler. The null event handler is often used for such things as updating a clock and making certain that music is playing in the background.
GUI.QuitThis procedure causes GUI.ProcessEvent to return true. If the program is structured properly with a

loop
    exit when GUI.ProcessEvent
end loop

at the end of the program, then the program will exit the loop after finishing the current action procedure. This procedure is usually called from the action procedure of a Quit button or Exit menu item.

GUI.Refresh | This routine redraws all the widgets in the currently-selected window. This is used when some form of drawing may have overwritten the widgets in a window. It is used by the GUI Library to redraw all the widgets when the background color of a window has changed.
GUI.SetBackgroundColor
GUI.SetBackgroundColour		Changes the background color of the currently-selected window. (Both spellings of color are acceptable.) This does not change the value of color 0 in the window. Instead it fills the entire window with the new background color and then redraws all the widgets. The usual background color outside of white is gray.
GUI.SetNullEventHandler | Sets the new null event handler. The specified procedure will be called every time GUI.ProcessEvent is called and there is no keystroke or mouse button pressed.
GUI.SetMouseEventHandler | Sets the new default mouse event handler. The specified procedure will be called every time GUI.ProcessEvent is called and there is a mouse button pressed which is not handled by any widget.
GUI.SetKeyEventHandler | Sets the new default keystroke event handler. The specified procedure will be called every time GUI.ProcessEvent is called and there is a keystroke which is not handled by any widget.
GUI.HideMenuBar | Hides the menu bar in the selected window. No menu items can be selected when the menu bar is hidden. (Menu item shortcuts will be ignored when the menu bar is hidden.)
GUI.ShowMenuBar | Shows the menu bar in the selected window.
GUI.GetEventWidgetID | Returns the widget ID of the widget that was activated by the mouse button press or the keystroke. This function should only be called in an action procedure, as it will return -1 when there is no event that activated a widget being processed.
GUI.GetEventWindow | Returns the window ID of the window in which the event (mouse button or keystroke) took place. This function should only be called in an action procedure or in a default mouse or keystroke event handler, as it will return -1 when there is no event being processed.
GUI.GetEventTime | Returns the time in milliseconds when the event (mouse button or keystroke) took place. This value is the same value that Time.Elapsed returns if called when the event was processed. This function should only be called in an action procedure or in a default mouse or keystroke or null event handler, as it will return -1 when there is no event being processed.
GUI.SetDisplayWhenCreated | Sets whether widgets are automatically displayed when created, or whether GUI.Show must be called first. By default, this is set to true (widgets are displayed when created). However, there may be times when you want to create a widget and then make several additional calls before displaying the widget.
GUI.CloseWindow | Closes a window with widgets in it. This procedure automatically disposes of any widgets in the window and makes certain that the GUI Library recognizes that the window no longer exists. This procedure will call Window.Close, so there is no need for the user to do so.
GUI.ShowWindow | Shows a hidden window with widgets in it. This procedure makes certain that the GUI Library recognizes that the window is visible. This procedure will call Window.Show, so there is no need for the user to do so.
GUI.HideWindow | Hides a visible window with widgets in it. This procedure makes certain that the GUI Library recognizes that the window is no longer visible. This procedure will call Window.Hide, so there is no need for the user to do so.
GUI.GetScrollBarWidth | Returns the width of a scroll bar. Useful when placing a scroll bar widget beneath another object.
GUI.GetMenuBarHeight | Returns the height of the menu bar. Useful when placing widgets to make certain that they do not overlap the menu.
GUI.GetVersion | Returns the current version of the GUI module. Because the GUI module is expected to grow, new versions will probably be made available at Holt Software's web site located at http://www.holtsoft.com/turing. If you wish to use features that do not appear in earlier versions of the library, you can have your program check that the current available version meets the programs needs. GUI.GetVersion returns an integer from 100 - 999 and is read as 1.00 to 9.99.


Predefined Names

Predefined Functions and Procedures

abs | addr | arctan | arctand | anyclass
break | buttonchoose | buttonmoved | buttonwait | ceil
chr | clock | cls | color | colorback
colour | colourback | cos | cosd | date
delay | drawarc | drawbox | drawdot | drawfill
drawfillarc | drawfillbox | drawfillmapleleaf | drawfilloval | drawfillpolygon
drawfillstar | drawline | drawmapleleaf | drawoval | drawpic
drawpolygon | drawstar | empty | eof | erealstr
exp | fetcharg | floor | frealstr | getch
getchar | getenv | getpid | getpriority | hasch
index | intreal | intstr | length | ln
locate | locatexy | lower | max | maxcol
maxcolor | maxcolour | maxint | maxnat | maxrow
maxx | maxy | min | minint | minnat
mousehide | mouseshow | mousewhere | nargs | natreal
natstr | nil | ord | palette | play
playdone | pred | rand | randint | randnext
randomize | randseed | realstr | repeat | round
setpriority | setscreen | sign | simutime | sin
sind | sizeof | sizepic | sound | sqrt
strint | strintok | strnat | strnatok | strreal
strrealok | succ | sysclock | sysexit | system
takepic | time | upper | wallclock | whatcol
whatcolor | whatcolorback | whatcolour | whatcolourback | whatdotcolor
whatdotcolour | whatpalette | whatrow | whattextchar | whattextcolor
whattextcolorback | whattextcolour | whattextcolourback

Predefined Modules

Brush | Button | CheckBox | Comm | Concurrency
Config | Dir | Draw | DropBox | EditBox
Error | ErrorNum | Event | File | Font
GUI | Input | Joytick | Keyboard | Limits
ListBox | Math | Menu | Mouse | Music
Net | Obsolete | PC | Pen | Pic
Print | RadioButton | Rand | RGB | Sound
Sprite | Str | Stream | Student | Sys
Text | Time | TypeConv | Video | View
Window

Predefined OOT Constants

(... means several constants with the prefix, see the module for a complete list)

black | blue | brightblue | brightcyan | brightgreen
brightmagenta | brightpurple | brightred | brightwhite | brown
brushErrorBase | cdMaxNumColors | cdMaxNumColours | cdMaxNumPages | cdScreenHeight
cdScreenWidth | clLanguageVersion | clMaxNumDirStreams | clMaxNumRunTimeArgs | clMaxNumStreams
clRelease | cmFPU | cmOS | cmProcessor | colorbg
colourbg | colorfg | colourfg | configErrorBase | cyan
darkgray | darkgrey | defFontID | defWinID | dirErrorBase | drawErrorBase
e... (ErrorNum) | errWinID | excp... (Exceptions) | fileErrorBase | fontDefaultID
fontErrorBase | fsysErrorBase | generalErrorBase | gray | green
grey | guiErrorBase | joystick1 | joystick2 | lexErrorBase
magenta | mouseErrorBase | musicErrorBase | ootAttr... (File) | ootk... (Keyboard)
penErrorBase | pic... (Pic) | picXor
placeCenterDisplay | placeCentreWindow | printerErrorBase | purple
red | rgbErrorBase | spriteErrorBase | streamErrorBase | textErrorBase
timeErrorBase | unixSignalToException | viewErrorBase | white | windowErrorBase
yellow

Keywords

addressint | all | and | array | asm
assert | begin | bind | bits | body
boolean | break | by | case | char
cheat | checked | class | close | collection
condition | const | decreasing | def | deferred
div | else | elseif | elsif | end
endfor | endif | endloop | enum | exit
export | external | false | fcn | flexible
for | fork | forward | free | function
get | handler | if | implement | import
in | include | inherit | init | int
int1 | int2 | int4 | invariant | label
loop | mod | module | monitor | nat
nat1 | nat2 | nat4 | new | not
objectclass | of | opaque | open | or
packed | pause | pervasive | pointer | post
pre | priority | proc | procedure | process
put | quit | read | real | real4
real8 | record | register | rem | result
return | seek | self | set | shl
shr | signal | skip | string | tag
tell | then | timeout | to | true
type | unchecked | union | unqualified | var
wait | when | write | xor


Operators

Mathematical Operators

Operator | Operation | Result Type
Prefix + | Identity | As Operands
Prefix - | Negative | As Operands
+ | Addition | As Operands
- | Subtraction | As Operands
* | Multiplication | As Operands
/ | Division | As Operands
div | Integer Division | int
mod | Modulo | int
rem | Remainder | int
** | Exponentiation | As Operands
< | Less Than | boolean
> | Greater Than | boolean
= | Equals | boolean
<= | Less Than or Equal | boolean
>= | Greater Than or Equal | boolean
not= | Not Equal | boolean

Boolean Operators

Operator | Operation | Result Type
Prefix not | Negation | boolean
and | And | boolean
or | Or | boolean
xor | Exclusive Or | boolean
=> | Implication | boolean

Set Operators

Operator | Operation | Result Type
+ | Union | set
- | Set Subtraction | set
* | Intersection | set
= | Equality | boolean
not= | Inequality | boolean
<= | Subset | boolean
< | Strict (Proper) Subset | boolean
>= | Superset | boolean
> | Strict (Proper) Superset | boolean

Operators on Members and Sets

Operator | Operation | Result Type
in | Member of Set | boolean
not in | Not Member of Set | boolean
xor | Exclusive Or | set

Bit Manipulation Operators

Operator | Operation | Result Type
shl | Shift left | nat
shr | Shift right | nat
and | Bit-wise And | nat
or | Bit-wise Or | nat
xor | Bit-wise Exclusive Or | nat

Pointer Operators

Operator | Operation | Result Type
^ | Follow pointer | Target type

Type Cheats

Operator | Operation | Result Type
# | Type cheat | nat

Operator Short Forms

These can be used in place of the above notation.
not | ~
not= | ~=
not in | ~in
and | &
or | |

Operator Precedence

Highest precedence operators first.
  1. **, ^, #
  2. prefix + and -
  3. * , / , div , mod , rem , shl , shr
  4. + , -, xor
  5. < , > , = , <= , >= , not= , in , not in
  6. not
  7. and
  8. or
  9. =>


File Statements

File Commands

open | open a file
close | close a file
put | write alphanumeric text to a file
get | read alphanumeric text from a file
write | binary write to a file
read | binary read from a file
seek | move to a specified position in a file
tell | report the current file position
eof | check for end of file

File Command Syntax

open : streamNo, fileName, ioCapability {, ioCapability }
ioCapability is one of get, put, read, write, seek, mod
 | put or write capability will cause any existing file to be truncated to zero length unless the mod capability is also specified.
 | seek capability is needed to use seek or tell commands.

close : streamNo
get : streamNo , getItem { , getItem }
put : streamNo , putItem { , putItem }
read : streamNo [ : fileStatus ] , readItem { , readItem }
write : streamNo[ : fileStatus ] , writeItem {, writeItem }
seek : streamNo , filePosition or seek : streamNo , *
tell : streamNo , filePositionVar
eof ( streamNo ) : boolean (This is a function)

Appending to a Text File

% Open the file for put, but do not erase it
open : streamNo, fileName, put { , get }, mod
% Move the file pointer to the end of the file
seek : streamNo, *


Control Constructs

FOR

for [ decreasing ] variable : startValue .. endValue
 | ... statements ...
 | exit when expn
 | ... statements ...
end for

LOOP

loop
 | ... statements ...
 | exit when expn
 | ... statements ...
end loop

IF

if condition then
 | ... statements ...
 | { elsif condition then
 | ... statements ... }
 | [ else
 | ... statements ... ]
end if

CASE

case expn of
 | ... statements ...
 | { label expn {, expn
 | ... statements ... }
 | [ label :
 | ... statements ... ]
end case

Any number of exit and exit when statements can appear at any place inside for .. end for constructs and loop .. end loop constructs.


Document Title

Key Codes

Ordinal values of keystrokes returned by getch and getchar.

 | 0 | (space) | 32 | @ | 64 | ` | 96
Ctrl-A | 1 | ! | 33 | A | 65 | a | 97
Ctrl-B | 2 | " | 34 | B | 66 | b | 98
Ctrl-C | 3 | # | 35 | C | 67 | c | 99
Ctrl-D | 4 | $ | 36 | D | 68 | d | 100
Ctrl-E | 5 | % | 37 | E | 69 | e | 101
Ctrl-F | 6 | & | 38 | F | 70 | f | 102
Ctrl-G | 7 | ' | 39 | G | 71 | g | 103
Ctrl-H / BS | 8 | ( | 40 | H | 72 | h | 104
Ctrl-I / Tab | 9 | ) | 41 | I | 73 | i | 105
Ctrl-J / Enter | 10 | * | 42 | J | 74 | j | 106
Ctrl-K | 11 | + | 43 | K | 75 | k | 107
Ctrl-L | 12 | , | 44 | L | 76 | l | 108
Ctrl-M | 13 | - | 45 | M | 77 | m | 109
Ctrl-N | 14 | . | 46 | N | 78 | n | 110
Ctrl-O | 15 | / | 47 | O | 79 | o | 111
Ctrl-P | 16 | 0 | 48 | P | 80 | p | 112
Ctrl-Q | 17 | 1 | 49 | Q | 81 | q | 113
Ctrl-R | 18 | 2 | 50 | R | 82 | r | 114
Ctrl-S | 19 | 3 | 51 | S | 83 | s | 115
Ctrl-T | 20 | 4 | 52 | T | 84 | t | 116
Ctrl-U | 21 | 5 | 53 | U | 85 | u | 117
Ctrl-V | 22 | 6 | 54 | V | 86 | v | 118
Ctrl-W | 23 | 7 | 55 | W | 87 | w | 119
Ctrl-X | 24 | 8 | 56 | X | 88 | x | 120
Ctrl-Y | 25 | 9 | 57 | Y | 89 | y | 121
Ctrl-Z | 26 | : | 58 | Z | 90 | z | 122
Ctrl-[ / Esc | 27 | ; | 59 | [ | 91 | { | 123
Ctrl-\ | 28 | < | 60 | \ | 92 | | | 124
Ctrl-] | 29 | = | 61 | ] | 93 | } | 125
Ctrl-^ | 30 | > | 62 | ^ | 94 | ~ | 126
Ctrl-_ | 31 | ? | 63 | _ | 95 | Ctrl-BS | 127
Alt-9 | 128 | Alt-D | 160 | F6 | 192 | Ctrl-F3 | 224
Alt-0 | 129 | Alt-F | 161 | F7 | 193 | Ctrl-F4 | 225
Alt-- | 130 | Alt-G | 162 | F8 | 194 | Ctrl-F5 | 226
Alt-= | 131 | Alt-H | 163 | F9 | 195 | Ctrl-F6 | 227
Ctrl-PgUp | 132 | Alt-J | 164 | F10 | 196 | Ctrl-F7 | 228
F11 | 133 | Alt-K | 165 |  | 197 | Ctrl-F8 | 229
F12 | 134 | Alt-L | 166 |  | 198 | Ctrl-F9 | 230
Shift-F11 | 135 |  | 167 | Home | 199 | Ctrl-F10 | 231
Shift-F12 | 136 |  | 168 | Up Arrow | 200 | Alt-F1 | 232
Ctrl-F11 | 137 |  | 169 | PgUp | 201 | Alt-F2 | 233
Ctrl-F12 | 138 |  | 170 |  | 202 | Alt-F3 | 234
Alt-F11 | 139 |  | 171 | Left Arrow | 203 | Alt-F4 | 235
Alt-F12 | 140 | Alt-Z | 172 |  | 204 | Alt-F5 | 236
Ctrl-Up Arrow | 141 | Alt-X | 173 | Right Arrow | 205 | Alt-F6 | 237
 | 142 | Alt-C | 174 |  | 206 | Alt-F7 | 238
Back Tab | 143 | Alt-V | 175 | End | 207 | Alt-F8 | 239
Alt-Q | 144 | Alt-B | 176 | Down Arrow | 208 | Alt-F9 | 240
Ctrl-Down Arrow | 145 | Alt-N | 177 | PgDn | 209 | Alt-F10 | 241
Ctrl-Insert | 146 | Alt-M | 178 | Insert | 210 |  | 242
Ctrl-Delete | 147 |  | 179 | Delete | 211 | Ctrl-Left Arrow | 243
Alt-T | 148 |  | 180 | Shift-F1 | 212 | Ctrl-Right Arrow | 244
Alt-Y | 149 |  | 181 | Shift-F2 | 213 | Ctrl-End | 245
Alt-U | 150 |  | 182 | Shift-F3 | 214 | Ctrl-PgDn | 246
Alt-I | 151 |  | 183 | Shift-F4 | 215 | Ctrl-Home | 247
Alt-O | 152 |  | 184 | Shift-F5 | 216 | Alt-1 | 248
Alt-P | 153 |  | 185 | Shift-F6 | 217 | Alt-2 | 249
 | 154 |  | 186 | Shift-F7 | 218 | Alt-3 | 250
 | 155 | F1 | 187 | Shift-F8 | 219 | Alt-4 | 251
 | 156 | F2 | 188 | Shift-F9 | 220 | Alt-5 | 252
 | 157 | F3 | 189 | Shift-F10 | 221 | Alt-6 | 253
Alt-A | 158 | F4 | 190 | Ctrl-F1 | 222 | Alt-7 | 254
Alt-S | 159 | F5 | 191 | Ctrl-F2 | 223 | Alt-8 | 225

Ordinal values of characters that are set by Input.KeyDown.

Backspace | 8 | (space) | 32 | @ | 64 | ` | 96
Tab | 9 | ! | 33 | A | 65 | a | 97
Enter | 10 | ! | 34 | B | 66 | b | 98
Escape | 27 | # | 35 | C | 67 | c | 99
 |  | $ | 36 | D | 68 | d | 100
F11 | 133 | % | 37 | E | 69 | e | 101
F12 | 134 | & | 38 | F | 70 | f | 102
Shift | 180 | ' | 39 | G | 71 | g | 103
Control | 181 | ( | 40 | H | 72 | h | 104
Alt | 182 | ) | 41 | I | 73 | i | 105
Keypad 5 | 183 | * | 42 | J | 74 | j | 106
F1 | 187 | + | 43 | K | 75 | k | 107
F2 | 188 | , | 44 | L | 76 | l | 108
F3 | 189 | - | 45 | M | 77 | m | 109
F4 | 190 | . | 46 | N | 78 | n | 110
F5 | 191 | / | 47 | O | 79 | o | 111
F6 | 192 | 0 | 48 | P | 80 | p | 112
F7 | 193 | 1 | 49 | Q | 81 | q | 113
F8 | 194 | 2 | 50 | R | 82 | r | 114
F9 | 195 | 3 | 51 | S | 83 | s | 115
F10 | 196 | 4 | 52 | T | 84 | t | 116
 |  | 5 | 53 | U | 85 | u | 117
Home | 199 | 6 | 54 | V | 86 | v | 118
Up Arrow | 200 | 7 | 55 | W | 87 | w | 119
PgUp | 201 | 8 | 56 | X | 88 | x | 120
Left Arrow | 203 | 9 | 57 | Y | 89 | y | 121
Right Arrow | 205 | : | 58 | Z | 90 | z | 122
End | 207 | ; | 59 | [ | 91 | { | 123
Down Arrow | 208 | < | 60 | \ | 92 | | | 124
PgDn | 209 | = | 61 | ] | 93 | } | 125
Insert | 210 | > | 62 | ^ | 94 | ~ | 126
Delete | 211 | ? | 63 | _ | 95 |


Run Window Character Set

The Turing character set and their ASCII values

chr (8) = backspace
chr (9) = tab
char (10) = newline

You can also get (on most systems), the MS-DOS character set by using the command setscreen ("msdos").
This is the character set after the setscreen ("msdos") command was given.

Click the button to launch the program to display the character set in Turing.


Turing Teacher/Administrator Quick Start Guide

This guide is designed to be the minimal information that you should read if you are teaching courses using Turing 4.0 or are in charge of administering Turing 4.0

This guide provides information on the Turing environment (the editor, the run windows, etc.) It does not provide any information on the Turing programming language itself.

Note, if you have any questions not answered here, please check with the Turing Teacher/Administrator's Complete Guide for more information.

Table of Contents

  1. Making Certain You Have the Lastest Version
  2. Mandatory Administration Issues
  3. Using the Parallel Ports in Turing 4
  4. Student Distribution
  5. Technical Support

1. Making Certain You Have the Lastest Version

Turing 4.0 is updated regularly. To find out what version you are currently running, click the About Turing menu item in the Help menu. To find out the current version of Turing, go to http://www.holtsoft.com/turing/support/#currentversion. This lists the current version of the software.

This page also lists which bugs have been fixed and when new features have been added. The page also contains a section ( http://www.holtsoft.com/turing/support/#turing4patches) where a file can be downloaded that will update most versions of Turing to the latest version.

If you are a teacher or an administrator at a school and require a complete installation file (as opposed to the publically available patch), contact Tom West at (416) 978-8363.

2. Mandatory Administration Issues

Turing 4.0 has been designed to run on either a network or installed on individual stand-alone machines. Running on a network is often preferred because of ease of administration. However, Turing, like any other application will load somewhat faster when it is launched if it is stored locally.

There are only two administration issues that must be addressed to configure Turing properly.

  1. Set the start-in (often called the "working") directory properly.

    It is important that the start-in directory for Turing be set to the student's home directory. This is done by setting the start-in (or working) directory of the shortcut or menu item used to launch Turing to the drive mapped to the student's home directory.

    The shortcut's working directory can be modified by changing it's start-in or working directory property. (To display the Properties dialog box, right click on the shortcut or menu item and select Properties from the pop-up menu.)

    Properties for a Shortcut under Windows 2000

    This requires that you have write access to the shortcut. Note that commercial menu front-ends have their own way of setting the start-in directory of applications.

    If there is no drive mapped to the student's home directory, or this method is not applicable to your system setup, please check with the Turing Teacher/Administrator's Complete Guide for more information.

  2. Set either Beginner or Regular Mode for Students.

    Turing can be set to Beginner mode, in which case only one file is open at a time. Opening up another file closes the first one. When the program is running, the Editor window minimizes. In this way, only one window is usually visible at a time. In this fashion, Beginner mode is similar to the old DOS Turing.

    In Regular mode, any number of files can be opened and each appears in its own editor window.

    In general, we suggest Beginner mode for grade 9 and 10 and Regular mode for all others. If you are using Beginner mode, we suggest that you point out to the students that they can use the Prefences to change to Regular mode when they feel comfortable with the environment.

    To change the mode (or to make any other change to the system preferences), you must open a DOS window, cd to the directory in which the Turing executable (turing.exe) is located and issue the command:

    turing -admin

    This will cause Turing to start in Administrator mode, displaying the following dialog box:

    Administration Mode Notification

    Selecting Preferences from the File menu will display a tabbed dialog box of all the Turing preferences.

    Preferences in Administrator Mode

    Set (or unset) the Beginner Mode preference, click the OK button and quit Turing. Of course, you can change any other preferences that you would like. Any changes that you make here will affect all those using Turing.

3. Using the Parallel Ports in Turing 4

Turing 4.0 supports the parallelput and parallelget commands to allow you to set the pins on the parallel port low and high. If you are running under Windows NT, 2000 or XP, you will need to install a device driver on each machine. Instructions for doing so can be found here. If parallelput and parallelget do not seem to function, you may need to change their BIOS settings. You can get information on how to do that here.

4. Student Distribution of Turing 4.0

The Ontario Ministry license does not include the right to redistribute the software to students. If you wish to give the software to students, a separate license must be obtained directly from Holt Software.

If your school does not have such a license, students can purchase the software for home use by printing and then mailing an order form found http://www.holtsoft.com/studentbuy. This order form can also be used to allow interested students to purchase textbooks.

If your school has purchased a redistribution license (almost 200 schools have done so), then you may redistribute the Turing software to your students. You can either burn copies of the CD to distribute to students or place the Turing installer file onto your school Internet server and give your students the URL.

If you place this file on your school internet server, you must not make any links from your web pages to the software.

This will prevent other users of the web from downloading your software. If you place links from your school's web site, then at some point a web search engine will find the software and post its location to the internet at large, allowing for large scale piracy (and a very overloaded school web server). If there are no links to the software, then only those who have been told the exact URL will be able to download the software.

Note that if you are copying a number of different programs onto a single CD for redistribution, you may rename the Turing installer program to something more descriptive.

Permanent student redistribution licenses can be purchased for $500-$750 for most schools. If you are interested in purchasing a student redistribution license, contact Chris Stephenson at (416) 978-6476 or chris@hsa.on.ca

5. Technical Support

If you have problems, questions or suggestions about the Turing software, contact technical support at:
Telephone: | (416) 978-8363
Toll free: | 1-800-361-8324
Fax: | (416) 978-1509
E-mail: | west@hsa.on.ca


Turing Teacher/Administrator Guide

This is the Turing Teacher/Administrator guide. It contains most of the information that you will need to administer the Turing 4.0 software. It should be read by those who are teaching courses using Turing 4.0 or are in charge of administering Turing 4.0

This guide provides information on the Turing environment (the editor, the run windows, etc.) It does not provide any information on the Turing programming language itself.

Note that there is some overlap with the Turing Teacher/Administrator Quick Start Guide.

Table of Contents

  1. Making Certain You Have the Lastest Version
  2. Mandatory Administration Issues
  3. Changing System Preferences
  4. Turing Preferences
  5. Parallel Port and Turing 4
  6. Missing Features from Turing 4
  7. The Turing Debugger
  8. Student Distribution
  9. Technical Support

1. Making Certain You Have the Lastest Version

Turing 4.0 is updated regularly. To find out what version you are currently running, click the About Turing menu item in the Help menu. To find out the current version of Turing, go to http://www.holtsoft.com/turing/support/#currentversion. This lists the current version of the software.

This page also lists which bugs have been fixed and when new features have been added. The page also contains a section ( http://www.holtsoft.com/turing/support/#turing4patches) where a file can be downloaded that will update most versions of Turing to the latest version.

If you are a teacher or an administrator at a school and require a complete installation file (as opposed to the publically available patch), contact Tom West at (416) 978-8363.

2. Mandatory Administration Issues

Turing 4.0 has been designed to run on either a network or installed on individual stand-alone machines. Running on a network is often preferred because of each of installation, however, Turing will load somewhat faster when it is launched if it is stored locally.

Turing 4.0 has been designed to run on either a network or installed on individual stand-alone machines. Running on a network is often preferred because of ease of administration. However, Turing, like any other application will load somewhat faster when it is launched if it is stored locally.

There are a few administration issues that must be addressed to configure Turing properly.

  1. Set the start-in (often called the "working") directory properly.

    It is important that the start-in directory for Turing be set to the student's home directory. This can be done in a variety of ways, from least to most complicated.

    1. Many schools have the student's home directory mapped to a drive (often H:\). If this is the case, then set the start-in (or working) directory of the shortcut or menu item used to launch Turing to the mapped drive.

      The shortcut's working directory can be modified by changing it's start-in or working directory property. (To display the Properties dialog box, right click on the shortcut or menu item and select Properties from the pop-up menu.)

      Properties for a Shortcut under Windows 2000

      This requires changing the shortcut's properties requires write access to the shortcut. Note that commercial menu front-ends have their own way of setting the start-in directory of applications.

    2. If the "My Documents" folder is mapped to the students home directory, you can set the preferences to make Turing use the "My Documents" folder as the start-in folder. Note that this option is the preferred option for home users, where the "My Documents" folder is the home directory.

      The Use "My Documents" Folder in the Admin Pane

      To change the preference, enter Administrator mode (see Changing System Preferences below) and set the Use "My Documents" Folder checkbox in the Admin pane of the Turing Preferences (see Turing Preferences below).

    3. If each student's home directory is specified differently (i.e. there is no mapping of the home directory to a drive), then you may need to use environment variables to create a useable path. For example, if students files are stored in g:\class108\[Student Name] and there is an environment variables USERNAME that contains the student's name, then the the start-in directory for the shortcut should be set to g:\class108\%USERNAME%.

    4. Occasionally users have reported situations like the previous case, except that Windows seems unable to set the start-in directory properly using environment variables.

      The Startup Directory Text Field in the Admin Pane

      To set the start-in directory, enter Administrator mode (see Changing System Preferences below) and set the Startup Directory text field in the Admin pane of the Turing Preferences appropriately (see Turing Preferences below) including specifying the directory using the environment variables.

  2. Set either Beginner or Regular Mode for Students.

    Turing can be set to Beginner mode, in which case only one file is open at a time. Opening up another file closes the first one. When the program is running, the Editor window minimizes. In this way, only one window is usually visible at a time. In this fashion, Beginner mode is similar to the old DOS Turing.

    In Regular mode, any number of files can be opened and each appears in its own editor window.

    In general, we suggest Beginner mode for grade 9 and 10 and Regular mode for all others. If you are using Beginner mode, we suggest that you point out to the students that they can use the Prefences to change to Regular mode when they feel comfortable with the environment.

    To change the preference, you will need to enter Administrator mode (see Changing System Preferences below) and change the Beginner Mode preference in the General pane appropriately (see Turing Preferences below).

  3. Windows 95 and the Turing Net module

    If you are using Windows 95 (not Windows 98/Me/NT/2000/XP) and you wish to use the Turing Net module in order to write programs that communicate with other computers, then you may need update the Window 95 networking code.

    This can be done by running the program located at:

    [Turing directory]\support\Microsoft\W95ws2setup.exe

    This program from Microsoft patches Windows 95 networking code. It must be run on every computer running Windows 95 unless the machines boot from a server.

  4. Parallel Port Usage If you are intend to use Turing to control devices attached to the parallel port (using the parallelput and parallelget, and are running under Windows NT/XP/2000, you will need to install a device driver. (Windows NT/XP/2000 do not allow direct access to the system hardware.). The device driver can be installed by running the program located at:

    [Turing directory]\support\dlportio_install.exe

    Further information can be found in Parallel Port and Turing 4.

3. Changing System Preferences

Turing uses a two level preference model. There is a central set of preferences that are kept in

[Turing Directory]\Support\Ini\turing_admin.ini

These preferences are the same for all users and are called the System Preferences. A second set of preferences is stored in each student's home directory in a file called turing.ini. These preferences override the central preferences and allow students to individually modify the behaviour of Turing.

When a student modifies the preferences, the turing.ini file in the student's home directory is changed. To change the System preferences (i.e. the contents of the turing_admin.ini file), Turing must be started up with the command line

turing -admin

This can be done by starting up a DOS window, doing a cd to the directory in which turing.exe is stored and then typing turing -admin. The user must have write access to the directory in which the turing_admin.ini file is stored.

When Turing is launched, it will display a message box on start-up indicating that it is in Administrator mode and where the preferences will be stored.

Administration Mode Notification

Selecting Preferences from the File menu will display a tabbed dialog box of all the Turing preferences. If you are in Administrator mode, then an extra tab labeled Admin will appear with extra preferences that can only be set by the Administrator. Note that individual students cannot override the preferences that appear on the Admin pane.

Preferences in Administrator Mode

Once the Preferences have been set, the Administrator can exit Turing.

4. Turing Preferences

This section lists all the preferences available in Turing sorted by the pane

"General" Pane

The "General" Pane

  • Beginner Mode
    When Beginner mode is set, only one file can be can be loaded into the Turing environment at a time. The Editor window is minimized every time the Run window is active and vice-versa. The debugger cannot be displayed or used. If this box is not set, then Turing is in Regular mode and multiple files can be open simultaneously. Beginner mode is recommended for students who are overwhelmed or confused by too many Turing windows (especially students in grades 9 and 10).
  • One Window Mode
    This option is not available in Turing 4.0. It will be used to switch between MDI and SDI modes in a future version of the software.
  • Display Full Pathnames
    The full path name and not just the file name are displayed in the Editor window's title bar and recent files submenu.
  • Save Previous File as ".BAK"
    When a file is saved over top of an older file, the older file is renamed with a .BAK suffix (i.e. test.t to test.bak)
  • Confirm on Quit
    When the user closes the last editor window, Turing displays a dialog box asking whether the user wishes to Quit. On systems where loading is slow (usually over a network), this can stop the users from accidentally quitting Turing.
  • Skip Splash Screen
    When Turing starts up, it normally displays a "Splash" screen with the version number. The Splash screen disappears when the user clicks a button or after 3 seconds. Turning this option off causes the Splash screen not to be displayed.
  • Add ".t" to File Names
    When a Save File dialog box appears and the user specifies a file name without a file suffix, Turing adds ".t". This can be removed by the user.
  • Convert Leading Spaces into Tabs
    When Turing saves a file, it normally converts groups of leading spaces into TAB characters, saving disk space. The number of spaces per tab is specified by the Spaces per Tab text field. If this check box is not selected, then the spaces are not converted.
  • Don't Save Recent Files Menu
    Normally Turing lists the last several files opened. However, if students do not have individual accounts, then this feature may not be useful and can be turned off.
  • Find Uses Selected Text
    By default, Turing uses the Windows behaviour that when a Find command is given and there is selected text, the selected text is copied to the Find dialog box. If you don't like this behaviour, then unsetting this option will stop this behaviour. If it is not set, then an additional menu item is placed in the Search menu that finds the next occurance of the currently selected text.
  • Start in Last Active Directory
    If students are writing large projects in many subdirectories, then this option can be enabled to automatically start Turing in the last directory in which a file was loaded or saved. The Turing preferences file is still stored in the student's home directory.
  • Spaces per Tab
    This specifies the number of spaces that a Tab is converted to and from. When Turing reads a text file into the editor, all tabs are converted on to spaces. If you created the Turing file on an editor where Tabs are a different number of spaces, then change this value appropriately.
  • Indent Size
    When Tab is pressed in the Turing editor, it is converted into spaces. The number in the Indent Size text field determines how many spaces the Tab key is converted to. Note the Spaces per Tab is used when Turing reads/writes files. The Indent Size field is used when Turing responds to the Tab key.
  • File Association
    Microsoft Windows has the ability to associate files with a particular suffix with specific programs. The Turing environment can be associated with the following file suffixes: .t, .tur, .dem, .ti and .tu. To associate these file suffixes with Turing, click the Associate ".t" files with Turing button. To reset the file associations back to what they were before, click the Reset ".t" File Association.

"Editor Window" Pane

The "Editor Window" Pane

  • Editor Font
    You can change the font size and typeface used in the editor window. If you change the typeface, you must choose a monospaced font where bold and non-bold letters are the same size. Many monospaced fonts have different sizes for bold and non-bold letters.
  • Full Screen for Beginner Mode
    If in beginner mode, editor windows are automatically in full screen mode. You can change this behaviour buy unsetting this checkbox.
  • Full Screen for Regular Mode
    Editor windows are normally 25x80 columns (or the size specified by the Editor Window Rows/Columns text fields). If this checkbox is set, editor windows are automatically maximized to fill the screen. This option is suggested for systems with 640x480 screen resolution. Users can change the window size by clicking the full screen/normal window button in the window's title bar.
  • Editor Window Rows/Columns
    These text fields control the size of editor windows when first created.
  • Syntax Coloring
    When selected, parts of Turing programs appear in different colors: comments appear in green, strings in red, keywords in bold face, predefined identifiers in black, and user identifiers in blue.
  • Always Show 'Debugger' Menu
    In the interest of keeping the interface as simple as possible, and because most students do not use the debugging features, Turing does not display the Debugger menu by default. Instead, the user selects Show Debugger Menu from the Run menu. Setting this checkbox causes the Debugger menu to always be displayed.
  • Text Cursor Width
    By default, the cursor (correctly called the caret) is 2 pixels wide, allowing it to be seen easily in the Editor window. However, some users prefer the caret to be 1 pixel wide and some prefer the caret to overlay an entire character (in a similar manner to DOS editors). Legal values are 1 (which represent a 1 pixel thick caret), 2 (which represent a 2 pixel thick caret), and 3 (which represents a text cursor that covers the entire character.

"Run Window" Pane

The "Run Window" Pane

  • Default Run Window Font
    You can change the font size and typeface used in the Turing run window. If you change the typeface, you must choose a monospaced font. Note that changing the size of the run window font may cause odd output in Turing programs that were written assuming a particular character size.
  • Start in Graphics Mode
    This makes the initial run window a graphics window. The user can use graphics without the setscreen ("graphics") command in the program. Output that scrolls off the top of the screen is lost. In text mode, graphics are not allowed, but all text output is kept and can be scrolled, saved, and printed at any time.
  • Full Screen Run Window
    This causes the default run window to occupy the entire screen.
  • Run Window Rows/Columns
    This sets the size of the default run window. Changing the size may cause programs that assume a 25x80 window to malfunction.
  • Use Small Fonts on 640x480 Screen
    A standard 25x80 window does not quite fit on a 640x480 screen with a standard size task bar. As a result, without this option, the default graphics mode run window appears with scroll bars. This option causes Turing to use a slightly smaller font for 640x480 run windows so the entire window fits on the screen. This option may cause odd output in Turing programs that were written assuming a particular character size.

"Printing" Pane

The "Printing" Pane

Note that the options marked with an asterisk (*) can be set in the printing dialog.

  • Printing Font/Printing Header Font
    You can change the font size and typeface used in printing. If you change the typeface, you must choose a monospaced font where bold and non-bold letters are the same size. Many monospaced fonts have different sizes for bold and non-bold letters.
  • Bold Keywords/Italicize Identifiers *
    This allows for "syntax coloring" of printouts. Keywords can be placed in bold and identifiers italicized.
  • Print Page Header
    On some systems, a header page is automatically printed out and there is little reason for a page header. Unsetting this checkbox will cause printouts not to have any header on the printed programs.
  • User Name in Header
    Normally the user name is displayed in the header. However, on some systems the user name is non-descriptive or non-existent. This allows you to disable the printing of the user name on such systems.
  • Two-Up Printing *
    This is a paper saving measure. Text is printed in landscape mode with two "pages" per piece of paper. This means that listings use half the amount of paper. Of course, the font is much smaller.
  • Line Numbers *
    This prints out line numbers in front of each line of the program. This is useful if you are printing out a listing to hand out to the class.
  • Border Around Text
    Some users like to have a thin border printed around the text for ease of determining the margins, etc. Setting this checkbox causes Turing to display a hairline border around program printouts.
  • Margins
    If you need to change the margins on printouts (for example, to facilitate the insertion of program listings into 3-ring binders), then you can do by changing the values in the text fields. Margins are expressed in inches.
  • User Name
    On systems where the user name is non-descriptive or non-existent, the user can enter a name that will appear on the printout allowing it to be identified. If students are choosing inappropriate user names, this preference can be disabled in the Admin tab preference dialog.

"Admin" Pane

The "Admin" Pane

Note, the Admin pane is only available in administrator mode. Students starting Turing will not have access to this dialog box.

  • Startup Directory
    Users will start in the directory listed in this text field. If left blank, Turing will use the working directory of the shortcut used to start Turing. If no working directory for the shortcut is specified, the directory where Turing is installed is used. Environment variables prefixed and suffixed with % signs can be used here (example: g:\students\%username%). Note that in most cases, this text field should be blank.
  • Use "My Documents" folder
    The "My Documents" folder can be used as the startup directory instead of the contents of the Startup Directory text field. This is most commonly used in single user systems.
  • Can Set User Name
    Allows the user to specify the user name to appear on top of printouts. This checkbox can be unset if students are choosing inappropriate user names.
  • Can Enter Regular Mode
    Allows the user to turn off the beginner mode preference. This checkbox can be unset if it is desirable to have all students working in beginner mode.
  • Debugger Available
    This checkbox can be unset in order to stop students getting access to the debugger.
  • Cannot Alter Preferences
    When set, this stops students from accessing the Preferences dialog. It also stops Turing from reading the student's turing.ini file. This can be set when it is important to have a uniform set of preferences on all student machines, or when there is no log-on procedure and students are sharing machines.
  • Prohibit use of 'Sys.Exec'
    When set, the Sys.Exec and system procedures do nothing. This can be set if there is a system security concern about students starting arbitrary programs.
  • No Sound or Music
    When set, the Turing sound and music commands do nothing.
  • Use only Startup Directory and Below
    CAUTION! This option only provides rudimentary security and is to be used only on systems where the operating system cannot provide proper security. This option will not allow students to save or load to any directory other that their startup directory or directories created in the startup directory. This option does not stop students from browsing the names of files in other directories, only from loading or saving files in them.
  • Use Only Allowed Drives
    CAUTION! This option only provides rudimentary security and is to be used only on systems where the operating system cannot provide proper security. This option allows students to load files only from the set of drives specified in the text field. The '*' represents network drives.
  • Forbid Use of Certain Drives
    CAUTION! This option only provides rudimentary security and is to be used only on systems where the operating system cannot provide proper security. This option prevents students from loading files from the set of drives specified in the text field. The '*' represents network drives.

5. Using the Parallel Ports in Turing 4

Under Turing 4.0 and , it is possible to access the IBM PC's parallel port for reading and writing. This is normally done using the parallelput and parallelget commands. (In Turing 4.0, you can use PC.ParallelPut and PC.ParallelGet to access ports other than LPT1.)

Under Windows 95/98 and Me, the operating system allows direct access to the parallel port. Under Windows NT, 2000 and XP, access to the parallel port is restricted by the operating system. In order to access the port, under Windows NT, 2000 and XP, it is necessary to install a device driver on each machine that will be accessing the parallel port. The needed device driver installer is located at:

[Turing directory]\support\dlportio_install.exe

where [Turing directory] is the directory in which Turing was installed. Executing this program will install the device driver in the Windows System directory of the machine upon which it is executed.

Lastly, before accessing the parallel port, check that the parallel port is in normal mode and not in bi-directional, PS/2, EPP or ECP mode. You can determine which mode the parallel port is in using the Device Manager. In the list of devices in the Device Manager window, double click Ports (COM and LPT), and then the LPT (or PRN) port. This displays a property sheet about the parallel port. Take a look at what it says about it. If it is in a non-original mode (i.e. mentions bi-directional, PS/2, EPP or ECP mode), then you will probably need to adjust the systems BIOS settings.

(Under Windows 2000 the Device Manager can be displayed by selecting the System Control Panel from Settings in the Start menu. Select the Hardware tab and then click the Device Manager button.)

If the setting for the parallel port needs to be changed, restart the machine, and press the appropriate key to enter the BIOS Set Up Program (the key varies between machines, but is usually noted on the screen). Often the parallel port settings are found in Advanced Settings of the program. The parallel port should be set to Normal, Standard, AT or Unidirectional mode. (All four names are different descriptions of the same mode.) Once this is done and the new settings are saved, then start the machine into Windows. Once in Windows, select Shut Down and turn the machine completely off. Once the machine is off, wait at least 10 seconds in the powered-off state. Then restart the machine. (While shutting down the machine should not be necessary, we have had several cases where the change only took when the machine had been powered-down and restarted.)

6. Missing Features from Turing 4

Turing 4.0 does not yet incorporate all the features that currently exist in Object Oriented Turing 3.1.1 and are intended for future Turing releases. Over the next few months, new features will be added and updates to Turing will be made available on our web site. The features to be added are:
  • View Variables
  • The Sprite module
If you have immediate need of any of these features, please continue to use the Object Oriented Turing 3.1.1 software. Ontario users can obtain the software through their OESS software representative.

To determine the current release of Turing, check the Turing web site at

http://www.holtsoft.com/turing/support

7. The Turing Debugger

The current version of Turing has a Debugger facilities that allow students to follow execution of a program either pausing after each line of execution or executing slowly while highlighting each line of execution. Because of the confusing nature of the debugger for many students, the default configuration of Turing does not display the debugger menu until the student requests it by selecting the Show Debugger Menu from the Run menu.

Always Show 'Debugger' Menu in the Editor Window Pane

If you wish students to have a more regular exposure to the Debugger, you can set a System preference to cause Turing to always display the Debugger menu. To set the this preference, enter Administrator mode (see Changing System Preferences below) and set the Always Show 'Debugger' Menu checkbox in the Editor Window pane of the Turing Preferences.

8. Student Distribution of Turing 4.0

The Ontario Ministry license does not include the right to redistribute the software to students. If you wish to give the software to students, a separate license must be obtained directly from Holt Software.

If your school does not have such a license, students can purchase the software for home use by printing and then mailing an order form found http://www.holtsoft.com/studentbuy. This order form can also be used to allow interested students to purchase textbooks.

If your school has purchased a redistribution license (almost 200 schools have done so), then you may redistribute the Turing software to your students. You can either burn copies of the CD to distribute to students or place the Turing installer file onto your school Internet server and give your students the URL.

If you place this file on your school internet server, you must not make any links from your web pages to the software.

This will prevent other users of the web from downloading your software. If you place links from your school's web site, then at some point a web search engine will find the software and post its location to the internet at large, allowing for large scale piracy (and a very overloaded school web server). If there are no links to the software, then only those who have been told the exact URL will be able to download the software.

Note that if you are copying a number of different programs onto a single CD for redistribution, you may rename the Turing installer program to something more descriptive.

Permanent student redistribution licenses can be purchased for $500-$750 for most schools. If you are interested in purchasing a student redistribution license, contact Chris Stephenson at (416) 978-6476 or chris@hsa.on.ca

9. Technical Support

If you have problems, questions or suggestions about the Turing software, contact technical support at:
Telephone: | (416) 978-8363
Toll free: | 1-800-361-8324
Fax: | (416) 978-1509
E-mail: | west@hsa.on.ca


Turing Debugger Guide

Introduction

Turing supports a number of tools to enable users to debug their programs and examine program execution. Some of the available tools are:
  • Stepping execution a line at a time.
  • Tracing execution with a set pause between lines of execution
  • Setting breakpoints to pause execution at specified points in the program.
  • Viewing all open resources of a program including files, fonts, pictures, etc.
As of May 2002, the Turing 4.1 software does not contain the following feature:
  • View variables.
This feature will be implemented as time and developer resources permit.

Displaying The Debugger Menu

In order to use any of the debugger commands, you need to have the Debugger menu showing in the Editor window. By default, the Debugger menu is hidden in order to simplify the Turing environment for the majority of students not using the debugger.

There are two ways that the Debugger menu can be displayed. You can select the Show Debugger Menu command in the Run menu.

Show Debugger Menu command in the Run menu

If you are consistenly using the debugger, then you should change the Preferences so that the Debugger menu is always displayed. This can be done by bringing up the Editor Window pane of the Preferences dialog box and setting the Always Show 'Debugger' Menu check box.

Always Show 'Debugger' Menu in the Editor Window Pane

Using The Debugger Menu

Show Debugger Menu command in the Run menu

The Debugger menu gives you access to all the debugging features in Turing 4.0. The following menu options are available:

  • Show Debugger Controls
    This command causes each Editor window to display a second row of controls at the top of the window (called the Debugger controls) that allow the user to step through a program and trace execution of the program. When the Debugger controls are visible, then this menu item changes to Hide Debugger Controls.

    Window with Debugger Controls Visible

  • Show Breakpoints This command causes each Editor window to dislay an area on the left where breakpoints can be placed. A breakpoint is a marker that causes the program to pause when execution reaches the marked line.

    Window with Breakpoint Visible

  • Clear Breakpoints This command quickly eliminates all breakpoints that have been set in any Editor window.
  • Show Allocated Objects This command shows all the files, fonts, pictures, etc that have been opened or created by the program but have not been closed. As the program executes, this window updates every time a resource is allocated or freed.

    Allocated Objects Window

Turing Execution

The rest of this document will use some terms that must be understood properly.
  • Running - A Turing program is running when statements are being continuously executed without human intervention. However, running may be stalled while the program is waiting for keyboard input, executing a delay statement, etc.
  • Paused - A Turing program is paused when execution is temporarily halted. No input is accepted by the program while it is paused. A program can become paused in a variety of ways including:
    • The user pressing the Pause button.
    • The user pressing a Step, Step Over or Step Return button.
    • Execution reaching a breakpoint.
    • Execution reaching the break statement in a program.
    When a Turing program is paused, the line in the source code on which the Turing program was about to execute is highlighted.
    In each case, the program can resume running by clicking the Resume button. The program can also temporarily resume running by the user pressing the Step, Step Over or Step Return button. Once the statement or statements are finished running, the program is paused again.
  • Executing - A program is executing when it is either Running or Paused.
  • Halted - A Turing program is halted when it can no longer executing. It cannot be resumed and must be started from the beginning in order to run it again. A program can be halted by:
    • The user pressing the Stop button.
    • A run-time error.
    • The user closing a Run window.

Stepping a Program

Stepping a program consists of executing a Turing program a line at a time. After each step command, execution pauses, highlighting the next line to be executed. To step a program, the program must not be running. The Debugger controls in the Editor window must be visible. To step the program, the user clicks one of the three buttons in the Debugger Controls:
  • Step - If the program is halted, this executes the very first line of code and then pauses. If the program is paused, it executes the highlighted line of code and then pauses. If it line of code to be executed is a subprogram call, then it enters the subprogram and pauses at the first line of code in the subprogram. If it is at the end of the subprogram, then it leaves the subprogram and pauses at the subprogram call. This command is sometimes called Step Into.
  • Step Over - This executes a single line of code. However, if the program is paused at a subprogram call, then the entire subprogram is executed and execution is paused at the next line after the subprogram call.
  • Step Return - This resumes execution until the execution returns from a subprogram. The next line after the subprogram call. Note that if this command is given in the main program, then execution will continue until the program terminates.

Tracing a Program

Tracing a program is simply executing a program slowly with each line of code in the program being highlighted as it is executed. Tracing allows users to see how control constructs operate. Unlike stepping, with tracing, execution continues until it is paused or halted in some other fashion.

To start a program tracing, the Debugger Controls must be visible. The user then clicks the Trace Execution check box. When the program is next running, each time a statement is executed, the line in the source code will be highlighted. The speed at which the tracing occurs is controlled by the Trace Speed slider found in the Debugger Controls. When the slider is on the left, there is essentially no delay between execution of statements. (Note that execution will still be much slower than not tracing due to the time taken to highlight each executing statement.) When the slider is on the right, each statement will wait for about 5 seconds after executing before the next statement is executed.

Setting Breakpoints

Often only a particular section of code is of interest to the user. Breakpoints provide a mechanism for pausing a program only when execution reaches a specified statement. To set breakpoints, they need to be displayed in the Editor window. This is done with the Show Breakpoints command in the Debugger menu. Once breakpoints are visible, they can be set (and removed) by simply clicking the mouse in the breakpoint area. When the mouse is over the breakpoint area, it turns into a diamond. When the breakpoint is set, a red diamond appears in the breakpoint area. To remove the breakpoint, simply click the red diamond and the breakpoint disappears.

Window with Two Breakpoints Set

When execution reaches a line with a breakpoint on it, the program pauses and the line is highlighted. The program can then be resumed or stepped as desired. Note that it is possible to set a breakpoint on a line that is not executed. If you place a breakpoint on a blank line, it is quite likely that execution will not stop. Likewise, in lines broken over multiple lines, it is best to put the breakpoint on the last line in the statement.

To clear all the breakpoints, select Clear Breakpoints from the Debugger menu.

Viewing Open Files/Pictures/Fonts, etc.

A common error in Turing programs is to neglect to close open files (using the Close statement) or free pictures or fonts (using the Pic.Free or Font.Free procedures). The Allocated Objects window displays all allocated resources until they are freed. This window is displayed by selecting the Show Allocated Objects command from the Debugger menu. The command can be given even after a program has halted. It is a useful command to use when am open, Pic.New or Font.New has failed because of too many open files, pictures or fonts.

The window will also display just how much memory each picture takes up.

Allocated Objects Window

Clicking on the line containing the allocated object will highlight the line in the code where the object was allocated. The headings on each of the columns can be clicked allowing the objects to be sorted either by their ID, or by where in the program they were allocated.


Error.Halt

Error.Halt Part of Error module

Syntax Error.Halt (errorMessage : string)

Description Error.Halt is a procedure that immediately halts execution of the program and shows the specified error message on the line in the program that calls Error.Halt.

This procedure is useful for allowing a quick halt to a program while indicating an error condition.

Example This program halts on the first line with an error message stating "Execution terminated by the program."

        Error.Halt ("Execution terminated by the program.")
Execute

Status Exported qualified.

This means that you can only call the function by calling Error.Halt, not by calling Halt.


Turing Help

What's New in Turing 4.1

  • Turing 4.1 has added support for sprites and special effects. Find out all the details here.

Turing Language

Help for the Turing language is broken down into several parts.
  • Complete alphabetical list
    A complete list of Turing language elements, predefined modules, and predefined subprograms in alphabetical order
  • Listing of Turing language elements
  • Listing of all basic (non-module) predefined subprograms in Turing broken down by topic
  • Listing of all predefined modules and their subprograms broken down by module
  • Appendices
    • Predefined Keywords and Names
    • Turing Operators
    • File Statements
    • Control Constructs
    • Keystroke Codes - The character codes returned by getch and getchar
    • Run Window Character Set

Turing Environment

Help for the Turing environment consists of
  • Turing Teacher/Administrator Getting Started Guide
    The minimal information needed to effectively administer Turing in a classroom situation.
  • Turing Teacher/Administrator Complete Guide
    A guide to all the administrative issues that teachers all likely to face using Turing in a classroom situation.
  • Turing Debugger Guide
    A guide to using the Debugging features in Turing 4.0.


What's New in Turing 4.1

Turing 4.1 introduces a number of new features. This page shows some of these features.

  1. Sprite

    The Turing Sprite module allows users to create animation without having to worry about erasing and drawing the objects on the screen. A sprite is created from a picture, and then commands by the program to move the sprite to the desired location. The program then automatically erases the sprite at the old location (restoring the background) and redraws it at the new location (placing it underneath "higher" sprites, if necessary).

    Here is an example of a program that used sprites. Each triangle is a sprite, and the height of each sprite appears on the sprite. Sprites with a height of -1 or -2 actually behind the background, which in this case is a set if green and blue bars. Note how sprites with a higher depth always appear above a sprite with a lower depth.

    Here is a second example of a sprite being used to animate a figure moving across the screen. In this case, the figure is taken from a multi-frame GIF file and the sprite module is used to make it appear to move.

    The Sprite module is fully documented here.

  2. Special Effects

    Turing supports a veriety of special effects. These are obtained by drawing a picture (obtained using the Pic.New, Pic.FileNew, or the new Pic.FileNewFrames functions). When the picture is drawn, the programmer can specify the transition that should be used to display the new picture. These transitions can includes wipes, slides, a growing image, fade-ins, and so on.

    Here is an example of a program that demonstrates many of these transitions.

    The different transitions are fully documented here.

  3. GIF Image support

    The Pic.FileNew command can now read GIF files (now that the patent has expired in Canada). GIF files can specify a "transparent color", and this is supported by Turing. When a GIF with a transparent color is loaded by Turing, the "transparent color" is added to the color palette (if not already present). If the picture is displayed using the picMerge mode, the "transparent color" will not be displayed. Note that the "transparent color" is a real color. If you use the picCopy mode, this color is displayed.

    Here is an example of a program displaying a GIF with a transparent color. In this case, the transparent color is dark blue.

  4. Multi-frame GIF Image support

    Turing also supports multi-frame GIF images. A GIF program can contain multiple images (this is how animated GIFs work). The Pic.FileNewFrames procedure can read a multi-frame GIF into an array of integers. These can then be displayed one at a time, or all in one call using the Pic.DrawFrames procedure.

    Here is an example of a program that displays a rotating globe found in a multi-frame GIF file using these procedures.

  5. Faster animation

    Turing has been improved to speed up animation when the picMerge mode is used. Speed improvements from 50% to 500% have been reported.

  6. Other graphic routines

    Turing now includes the Pic.Blend function to blend two pictures together and the Pic.Blur function to take an existing picture and make it blurry.