The NewtonScript Programming Language (Alpha Draft 1.0)

Embed Size (px)

Citation preview

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    1/59

    The NewtonScript ProgrammingLanguage

    Alpha Draft 1.0

    July 17, 1993PIE Technical Publications Apple Computer, Inc. 1993

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    2/59

    Draft. Preliminary, Confidential. 1993 Apple Computer, Inc. 6/18/93

    Apple Computer, Inc. 1993, Apple Computer, Inc.All rights reserved.No part of this publication or thesoftware described in it may bereproduced, stored in a retrievalsystem, or transmitted, in any form or

    by any means, mechanical, electronic,photocopying, recording, or otherwise,without prior written permission ofApple Computer, Inc., except in thenormal use of the software or to make a

    backup copy of the software. The sameproprietary and copyright notices must

    be affixed to any permitted copies aswere affixed to the original. Thisexception does not allow copies to bemade for others, whether or not sold,

    but all of the material purchased (withall backup copies) may be sold, given,or loaned to another person. Under thelaw, copying includes translating intoanother language or format. You mayuse the software on any computerowned by you, but extra copies cannot

    be made for this purpose.Printed in the United States of America.The Apple logo is a registeredtrademark of Apple Computer, Inc.Use of the keyboard Apple logo(Option-Shift-K) for commercialpurposes without the prior writtenconsent of Apple may constitutetrademark infringement and unfaircompetition in violation of federal andstate laws.No licenses, express or implied, aregranted with respect to any of thetechnology described in this book.

    Apple retains all intellectual propertyrights associated with the technologydescribed in this book. This book isintended to assist applicationdevelopers to develop applications onlyfor Apple Newton computers.

    Apple Computer, Inc.20525 Mariani AvenueCupertino, CA 95014408-996-1010

    Apple, the Apple logo, APDA,LaserWriter, the light bulb logo,Macintosh, and Newton are trademarksof Apple Computer, Inc., registered inthe United States and other countries.Newton ToolKit and QuickDraw are

    trademarks of Apple Computer, Inc.Simultaneously published in the UnitedStates and Canada.

    LIMITED WARRANTY ON MEDIA AND

    REPLACEMENT

    If you discover physical defects in the

    manual or in the media on which a software

    product is distributed, APDA will replace

    the media or manual at no charge to you

    provided you return the item to be replacedwith proof of purchase to APDA.

    ALL IMPLIED WARRANTIES ON THIS

    MANUAL, INCLUDING IMPLIED

    WARRANTIES OF MERCHANTABILITY

    AND FITNESS FOR A PARTICULAR

    PURPOSE, ARE LIMITED IN DURATION

    TO NINETY (90) DAYS FROM THE DATE

    OF THE ORIGINAL RETAIL PURCHASE

    OF THIS PRODUCT.

    Even though Apple has reviewed this

    manual, APPLE MAKES NO WARRANTY

    OR REPRESENTATION, EITHER EXPRESS

    OR IMPLIED, WITH RESPECT TO THIS

    MANUAL, ITS QUALITY, ACCURACY,

    MERCHANTABILITY, OR FITNESS FOR A

    PARTICULAR PURPOSE. AS A RESULT,THIS MANUAL IS SOLD AS IS, AND

    YOU, THE PURCHASER, ARE ASSUMING

    THE ENTIRE RISK AS TO ITS QUALITY

    AND ACCURACY.

    IN NO EVENT WILL APPLE BE LIABLE

    FOR DIRECT, INDIRECT, SPECIAL,

    INCIDENTAL, OR CONSEQUENTIAL

    DAMAGES RESULTING FROM ANY

    DEFECT OR INACCURACY IN THIS

    MANUAL, even if advised of the possibility

    of such damages.

    THE WARRANTY AND REMEDIES SET

    FORTH ABOVE ARE EXCLUSIVE AND IN

    LIEU OF ALL OTHERS, ORAL OR

    WRITTEN, EXPRESS OR IMPLIED. No

    Apple dealer, agent, or employee isauthorized to make any modification,

    extension, or addition to this warranty.

    Some states do not allow the exclusion or

    limitation of implied warranties or liability

    for incidental or consequential damages, so

    the above limitation or exclusion may not

    apply to you. This warranty gives you

    specific legal rights, and you may also have

    other rights which vary from state to state.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    3/59

    iii

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Contents

    Related Publications vii

    Chapter 1 Data Types, Operators, and Expressions 1-1

    Data Types 1-1Immediate References 1-1Integers 1-1Characters 1-2Booleans 1-2

    Pointer References 1-2Symbols 1-3Strings 1-3Real numbers 1-4Arrays 1-4Frames 1-4

    Operators and Expressions 1-5Assignments 1-5

    Copying NewtonScript values 1-6Creating Frame Slots 1-7

    Arithemetic operators 1-8Relational operators 1-8

    Logical operators 1-9String Concatenators 1-9Exists 1-9

    Accessing Frame Slots 1-10Path Expressions 1-10Accessing Array Elements 1-11

    Precedence and evaluation order 1-11

    Chapter 2 Flow of Control 2-1

    Compound statements 2-1Conditional statements 2-1Iterators 2-2

    Break 2-2For 2-3

    Foreach 2-4Loop 2-6

    While 2-6

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    4/59

    iv

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Repeat 2-6

    Chapter 3 Functions 3-1

    Defining Functions 3-1Return statement 3-1Local statement 3-2Constant statement 3-2

    Parameter Passing 3-2Scope 3-3

    Local variables 3-3Extent of Local Variables 3-4Application-Wide Variables 3-5

    Chapter 4 Object-Oriented NewtonScript Programming 4-1

    Inheritance 4-1Prototype Inheritance 4-1

    Creating prototypes 4-2Prototype inheritance rules 4-2

    Parent Inheritance 4-3Creating parent-child relationships 4-3Parent inheritance rules 4-4

    Combining prototype and parent inheritance 4-4Inheritance rules for setting slot values 4-6

    Interactions between functions and inheritance 4-6An object-oriented example 4-7Methods and messages 4-9Self 4-10Calling a function 4-10

    Appendix A Reserved Words A-1

    Appendix B Special Character Codes B-1

    Appendix C NewtonScript Quick Reference Card C-1

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    5/59

    v

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Figures and Tables

    Chapter 1 Data Types, Operators, and Expressions 1-1

    Table 1-1 Characters with special meanings 1-2

    Table 1-2 Special characters allowed within strings 1-3

    Figure 1-1 Contrasting Assignment Statements in C and NewtonScript 1-6

    Figure 1-2 How NewtonScript Handles Variable Assignments 1-7

    Table 1-3 Operator precedence and evaluation order 1-12

    Chapter 4 Object-Oriented NewtonScript Programming 4-1

    Figure 4-1 Prototype frame 4-2

    Figure 4-2 A prototype chain 4-3

    Figure 4-3 Parent-child relationship 4-4

    Figure 4-4 Prototype and parent inheritance interaction order 4-5

    Figure 4-6 An inheritance structure 4-8

    AAppendix B Special Character Codes B-1

    Table A-1 Character codes sorted by Macintosh character code B-2

    Table A-2 Character codes sorted by Unicode B-5

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    6/59

    vi

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    7/59

    vii

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    PREFACE

    About This Book

    This book, Newton Programmers Guide, is the definitive guide and referencefor anyone writing software for the Newton family of personal digitalassistants.

    Note

    The chapters in this book are at different stages of completion. Some areless complete than others. For all chapters, even the most complete ones,keep in mind that the information is preliminary, subject to change, andmay not consistently reflect the latest technical information available,although every effort is being made to supply you with information thatis as accurate as possible. u

    Related Publications

    The suite of Newton technical documentation includes these other books:

    n A Guide to the Newton Toolkit. This book introduces you to the Newtondevelopment environment and teaches you how to develop Newtonapplications. You should read this book first if you are a new Newtonapplication developer.

    n The NewtonScript Programming Language.. This book describes theNewtonScript programming language. If you are new to Newtondevelopment, you should read this book before the Newton ProgrammersGuide so that you are familiar with the language.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    8/59

    viii

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    PREFACE

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    9/59

    CHAPTER 1

    Data Types 1-1

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Data Types, Operators, andExpressions

    In NewtonScript, every statement in a script evaluates to a value. Therefore, everythingin NewtonScript programming is an expression.

    This chapter discusses the basic components of the language, its data types, its operators,and some of the expressions you can make by combining the two. Many of the conceptshere are common to other programming languages.

    Data Types

    NewtonScript uses 32-bit references for data representation. There are two kinds ofreferences: immediate references, in which the reference contains the data, and pointerreferences, in which the reference contains a pointer to a heap object

    Immediate References

    An immediate reference can represent one of three types of data:

    n integers

    n characters

    n Booleans, TRUE and NIL

    The data is stored in 30 bits; the remaining two bits are flag bits.

    Integers

    Integers have no decimal place. They can be either signed or unsigned and areinterpreted as decimal numbers unless prefixed with 0x (zero and the letter x) to signifya hexadecimal value. Here are some examples of integers:

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    10/59

    CHAPTER 1

    Data Types, Operators, and Expressions

    1-2 Data Types

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    13475 -86 0x56a

    Note that there is a 30 bit limit on the size of integers. Behaviour when that limit isexceeded is undefined.

    Characters

    The character set in Newton is stored as Unicode, in two bytes, to facilitate internationalconversions. By design, the first 128 characters match the first 128 characters of theMacintosh standard character set. You must use Unicode character codes to specifycharacters higher than the first 128 in the character set (that is, special characters.)

    Characters in the standard character set are specified in your code by the dollar sign. Forexample, $a or $7 represent the characters "a" and "7", respectively.

    Special characters like "" must be specified as Unicode (16-bit) characters by using thefour-digit hex character code preceded by $\u. The Unicode equivalent of "" is:$\uF7FF

    See Appendix C, "Special Character Codes" for a list of the special characters and theirUnicode equivalents. In addition to special printed characters there are other charactersthat have special meanings. They are shown in Table 1-1.

    Table 1-1 Characters with special meanings

    Booleans

    Newton defines only two Boolean constants, TRUE and NIL. In conditional statements,anything that is not NIL is considered to be TRUE.

    Pointer References

    A pointer reference represents one of several kinds of heap objects,including:

    n Symbolstags used to identify any kind of value

    n Stringsquoted constants

    n Real numbersimmutable floating point numbers

    n Arraysa numbered collection of references

    Character code Meaning

    $x the character x$\n newline$\t

    tab$\\ backslash$\xx hexadecimal$\uxxxx Unicode; see Appendix C, "Special Character Codes"

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    11/59

    CHAPTER1

    Data Types, Operators, and Expressions

    Data Types 1-3

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    n Framesa collection of named references

    Symbols

    NewtonScript symbols are like identifiers in other computer languages. A symbol is asequence of as many as 254 characters, including letters, trailing numbers, and theunderscore character '_'. A symbol

    n cannot begin with a number

    n can include capital and lower-case letters; (NewtonScript is case insensitive, though itpreserves case)

    n can break the above rules (except the 254 character limit) if the symbol is enclosed invertical bars (|). For instance, |Walter Smith!| is a valid symbol, even though itcontains spaces and special characters

    Symbols normally evaluate to the value of their contents. You can prevent this bypreceding the symbol name with a single quote ('). In this case the symbol evaluates tothe symbol itself.

    Strings

    A string constant is zero or more characters enclosed in double-quotation marks.Examples include

    "pqr" "Now is the time" ""

    You can include characters that are not in the standard character set in strings byinserting the escape code, \u, to toggle on the Unicode hex mode. Follow the \u with thefour-number code specifying the special character. If you need to return to the regular

    character set, add another \u to toggle the Unicode hex mode off; however, you are notrequired to turn toggle the hex mode off. (See Appendix C, "Special Character Codes" fora list of the special characters.)

    For example, you could specify the French phrase, "Garon, le billet, sil vous plat!", byembedding Unicode in the string to specify the special characters. You accomplish this asfollows:"Gar\u00e7\uon, le billet, sil vous pla\u00ee\ut!"

    Other characters you can include in strings are summarized in Table 1-2.

    Table 1-2 Special characters allowed within strings

    Character Meaning

    \n new line\t tab\u toggles Unicode on and off\\ backslash

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    12/59

    CHAPTER 1

    Data Types, Operators, and Expressions

    1-4 Data Types

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Real numbers

    Real numbers must contain a decimal point, which can appear any place within thenumber. Hence they are known as "floating point" real numbers. They are represented

    internally in double precision, that is, in 64 bits. They have 15 digits of precision. Someexamples of real numbers include:-0.587 123.9 3.141592653589

    You can also use exponential notation to represent real numbers. Simply follow the realnumber with an "e" and a signed integer exponent, in the range of -308...+308, as shownin these examples:763.112e4 87.3789e-45 -34.2e6 69.e-5

    Real numbers are stored as binary objects and have the implicit class Real.

    Arrays

    Arrays are numbered lists of zero or more references, called array elements that areseperated by commas, and enclosed in brackets. The syntax of an array is:

    [className1: element1 ,element2 ,elementn, ]

    Here is a simple example of an array:[1,2,3]

    Because this array does not include an explicit class name, NewtonScript assigns it theimplicit class Array. The Array designation simply gives the array a type; it does not giveit any special properties. You can specify a class name for your array by preceding thefirst array element with a class identifier and a trailing colon, as shown here:

    [RandomData: [1,2,3], {check:"121", amount:9.00}, "Last element"]

    Array elements may consist of any mixture of the data types that NewtonScriptsupports. Note that the RandomData array in this example contains another array as itsfirst element, a frame as the second element (this data type is discussed in the sectionFrames,) and a string as the third element.

    NewtonScript numbers the elements in an array by beginning with zero for the firstelement. Therefore, element 0 in the RandomData array is the array [1,2,3].

    Frames

    A frame is the basic data object in a NewtonScript program. A frame, like an array, is alist of references separated by commas. However, the references in frames are namedrather than numbered.

    A frame is enclosed in curly braces and is composed of zero or more slots, which arename: value pairs. The syntax of a frame is:

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    13/59

    CHAPTER1

    Data Types, Operators, and Expressions

    Operators and Expressions 1-5

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    {slotName1:value1 , slotName2:value2 , slotNameN:valueN, }

    The slot name can consist of any valid symbol that refers to any valid NewtonScipt datatype. A frame can consist of any number of slots. Here is a simple example of a frame:{name:"Joe Bob", phone:"4-5678", employee:12345}

    Slots can contain references to objects, including other frames and functions. Here is anexample of a frame containing another frame and a function:{ Jupiter:{size:491, distance:8110,speed:34},

    position: func(foo) speed*foo/3.1416

    }

    You may specify an optional class for a frame. This is stored in a slot that you give thename class. Just as for array classes, the class of a frame gives it a type, not specialproperties.

    You can also specify references to other frames by using the slot names _proto and_parent. These set up hierarchical and prototypical behaviors which you can use to

    construct object-oriented programs. Chapter 3, "Inheritance," describes these conceptsand behaviors.

    Operators and Expressions

    NewtonScript operators include assignment operators, arithmetic operators, logical andrelational operators, messaging operators, array and frame element accessors, andbitwise operators.

    Assignments

    Data type declarations are unnecessary in NewtonScript; assignment statements servethe purpose of initializing variables. A simple assignment statement takes the forma := b;

    The trailing semicolon is an optional statement separator. Essentially, an assignmentstatement looks like this:lvalue := expression

    where lvalue is a variable, array or frame access expression.

    Since all statements have a value, you could also construct the following assignmentstatement:x := if a > b then a else b;

    Here is an example of the assignment of a frame reference to a symbol:myFrame := {name: "", phone: "123-4567"}

    Once the frame has been created you can assign values to slots like this:myFrame.name := "Julia"

    If the frame slot does not already exist it will be created.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    14/59

    CHAPTER 1

    Data Types, Operators, and Expressions

    1-6 Operators and Expressions

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    You can construct arrays and assign values to them in a similar manner. The second lineof this code fragment changes the value 789 to 987.

    myArray := [123, 456, 789, "a string"]

    myArray [2] := 987

    s Note

    If you accidentally write an assignment statement as = rather than :=,your statement becomes a simple relational expression. For example, thestatementx = 5

    returns TRUE or NIL and leaves the value of x unchanged. s

    Copying NewtonScript values

    NewtonScript, unlike C, does not copy the contents of a memory location when it makesan assignment. Instead, since most NewtonScript values are pointer references rather

    than immediate references, NewtonScript merely reuses the reference rather thancopying the actual object. Figure 1-1 shows this difference graphically.

    Figure 1-1 Contrasting Assignment Statements in C and NewtonScript

    You can see how these differences manifest when you compare these code snippetexamples from the C programming language and NewtonScript. In the C example wehave the struct named foo that contains an integer member x. You then make twoinstances of the foo struct named a and b. You assign the integer 1 to the member x in thea structure. You then save the value of the a struct to the b struct and change the value of

    the variable a.x to 2. As you expect, the value of the member b.x is 1 at this point in theexecution of the C code.C:

    struct foo {

    int x;

    };

    Cx=foo;

    NewtonScriptx:=foo;

    foomemory addresscontents2E

    18E3

    contents2Ex

    foomemory addresscontents2E

    18E3

    contents18E3x

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    15/59

    CHAPTER1

    Data Types, Operators, and Expressions

    Operators and Expressions 1-7

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    foo a;

    foo b;

    a.x = 1;

    b = a;

    a.x = 2;

    // at this point b.x = 1

    The equivalent code in NewtonScriptlocal a := {x: 1};

    local b := a;

    a.x := 2;

    // at this point b.x = 2

    gives a different outcome. The first assignment statement essentially creates the slot a.xand stores the integer 1 in it. In memory, NewtonScript creates an address for the slot a.xthat points to a memory location where the integer 1 is stored.

    When the frame a is assigned to the local variable b, NewtonScript copies the addressreferring to the location of frame a, so that they share the identical contents. Both of thevariables, a and b, refer to the same memory location.

    When that memory location is changed for one variable it is automatically changed forboth. See Figure 1-2 for a picture of the process.

    Since the two variables share the same memory reference, the slot b.x is assigned thevalue of 2, by default, when the slot a.x is assigned the value of 2.

    Figure 1-2 How NewtonScript Handles Variable Assignments

    Creating Frame Slots

    To create a new slot in a frame, simply assign a value to it. If the slot does not exist, it iscreated. As shown in the discussion above, the statement

    aFrame:= {x: 1};

    dynamically creates the frame, aFrame, with the slot, aFrame.x, and puts the value 1 intoit.

    a:= {x: 1}; a.x memorycontents

    18E318E3 address1

    b:= a; b.x 18E3

    a.x:= 2; a.x memory

    contents

    18E318E3 address2

    b.x 18E3

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    16/59

    CHAPTER 1

    Data Types, Operators, and Expressions

    1-8 Operators and Expressions

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Note

    The NewtonScript inheritance rules affect the ultimate behavior ofassignment statements in frames. For more information aboutinheritance and setting slot values see "Inheritance rules for setting slotvalues,"in Chapter 4.

    Arithemetic operators

    NewtonScript provides the standard set of binary arithmetic operators. They include, inorder of precedence:* / div mod + -

    See Table 1-3 for a summary of operator precedence.

    Relational operators

    The relational operators are less than (=).

    The equality operators are equal (=) and not equal ().

    The relational and equality operators work the way you would expect them to work onimmediate reference data types. For referenced values, strings, arrays, and frames, thecontents are compared only with the relational operators, =. However, theequality operators actually compares pointers, not contents. For instance, if you type[1,2] = [1,2]

    into the Newton ToolKit listener and press Return, it evaluates to NIL because the twoarrays are not the same object.

    However, if you use the statement,x := [1,2]

    to assign a reference to an array to the symbol x, then assign the same reference to thevariable y, and finally compare their equality using the statements,y := x

    x = y

    NewtonScript returns TRUE. You can see that the assignment statement copied thepointer values rather than the evaluating the pointers and copying the values stored atthe pointer address.

    If you try the same exercise when an immediate value is stored in a variable, the result iswhat you would expect using a language like Pascal. NewtonScript returns the value

    TRUE in response to the following lines of code:a := 1

    b := a

    a = b

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    17/59

    CHAPTER1

    Data Types, Operators, and Expressions

    Operators and Expressions 1-9

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Logical operators

    The logical operators include the three reserved words:not and or

    Like their counterparts, || and &&, in the C programming language, expressionsinvolving the logical operators

    and or

    stop evaluation as soon as the conclusion of the verity of the expression has beendetermined. For instance, if the value of the first half of the AND conditional expressionin the if statement

    if x < length(someArray) AND someArray[x] = 42 then doSomething;

    is NIL, then NewtonScript does not process the second part of the AND conditionalstatement.

    Similarly, the OR statement stops executing as soon as one non-NIL value is determinedsince an OR logical operation only requires one TRUE value to make the wholestatement TRUE.

    String Concatenators

    The two string concatenators, && and &, concatenate strings by creating a new stringfrom the two strings you specify. You can also use these operators to concatenate objectsthat are not strings. For instance, the statement

    "foo" & 17

    returns the string

    "foo17"

    The single & operator also creates copies of two strings you specify and concatenatesthem by tacking one onto the end of the other with no space in between. In contrast, the&& operator concatenates the two strings you specify, by placing a space at the end ofthe copy of the first string and then placing a copy of the second string after the space.

    Exists

    Exists is a special postfix operator that is used to check for the existence of variables orslots. When you apply the exists operator to an identifier, such as a variable, it returnsTRUE if the variable is defined in the current context and NIL otherwise. (See"Scope" inChapter 2 for more informtion about the scope of variables.)

    Here is an example of a simple IfThen structure that uses the exists operator:

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    18/59

    CHAPTER 1

    Data Types, Operators, and Expressions

    1-10 Operators and Expressions

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    if myVar exists then myVar else 0

    When you apply exists to a frame slot access expression (see the following section), existsreturns TRUE if the slot exists in the frame or any of its prototype frames, and NILotherwise. For more information about frames and inheritance, see Chapter 3

    "Inheritance."Here are some examples (IfThen expressions are described below in the sectionCondition Expressions):

    if myFrame.aSlot exists then

    if not hasSlot(myFrame, 'aSlot) then

    print("'aSlot slot is in a prototype of myFrame")

    The built-in function hasSlot provides similar functionality to the exists operator. Thesefunctions differ in the type of inheritance that is used to search for slots. Refer to Chapter4, "Functions," to find out more about built-in NewtonScript functions.

    Accessing Frame Slots

    Slots in a particular frame can be accessed by using a frame identifier followed by a dot.For example, the expression myFrame.name returns the contents of the name slot fromthe frame named myFrame. If the slot does not exist, NewtonScript returns NIL.

    If the slot is not found in the specified frame when you use the dot operator to access aframe slot, prototype inheritance is used to search prototype frames. However, thesearch does NOT continue up to the parent frame and its prototypes. The search usesonly prototype inheritance, not parent inheritance.

    Three built-in functions, GetVar, GetVariable, and GetSlot, provide similar kinds of slotaccess, but with different inheritance behavior. Refer to the Newton Programmers Guidefor details.

    Path Expressions

    Alternatively, you can access frame data by using a path expression, like this:

    myFrame.(expression)

    where the path expression is enclosed in parentheses within a slot access expression.Here, the value of expression is used as the slot name. For example:

    myFrame := {Name: "Joe", Title: "Cat"}

    slotPath := 'TitlemyFrame.(slotPath)

    The value of myFrame.(slotPath) is "Cat".

    In this script, myFrame.(slotPath) evaluates to the Title slot, and the value Cat isreturned. The symbol 'Title represents the path to the slot named Title, of the framemyFrame. Longer path expressions are also allowed:

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    19/59

    CHAPTER1

    Data Types, Operators, and Expressions

    Precedence and evaluation order 1-11

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    > myFrame:={Kind:"Cat",Type:{Hair:"long",Color:"black"}}

    > slotPath := 'Type.color

    > myFrame.(slotPath)

    The value of myFrame.(slotPath) is "black".

    A path expression can also be expressed as an array with the class "pathExpr", whereeach array element is a slot in the path. For example, here is the previous example usingarray syntax for the path expression:

    myFrame:={Kind:"Cat",Type:{Hair:"long",Color:"black"}}

    slotPath := '[pathExpr: Type, color]

    myFrame.(slotPath)

    The value of myFrame.(slotPath) is "black".

    Note this syntax: [pathExpr: Type, color]. This creates an array with the class "pathExpr".

    Accessing Array Elements

    Array elements are accessed with square brackets, for example:

    myArray := [123, 456, "Alice's Restaurant"]

    myArray[2]

    The value of myArray[2] is "Alice's Restaurant".

    This expression returns the contents of the third element in the array myArray. Notethat array indexes begin at zero.

    Like frame slots, array elements can also be accessed using path expressions. The path to

    an array element is simply the array index of the element. Here is an example:

    aframe:={name:"Matt",info:{grade:"B",tests:[87,96,73]}}

    mypath:='[pathExpr: info,tests,1]

    myframe.(mypath)

    The value of myFrame.(mypath) is 96.

    Precedence and evaluation order

    The precedence of operators is a set of ratings that tells the compiler which operator toevaluate first, in case it is not inherently apparent in the ststement. Table 1-3 lists theorder of precedence of all the NewtonScript operators in order from top to bottom. Notethat operators grouped together in the table are of equal precedence.

    Evaluation order is simply the order in which the symbols in a line of code areprocessed. Most operators in NewtonScript are processed and evaluated from left to

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    20/59

    CHAPTER 1

    Data Types, Operators, and Expressions

    1-12 Precedence and evaluation order

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    right. The one notable exception is the assignment statement, which is evaluated fromright to left.

    Table 1-3 Operator precedence and evaluation order

    Operator Action Evaluation Order

    . slot access left-to-right

    ::?

    message sendconditional message send

    left-to-right

    [] array dereferencer left-to-right

    - unary minus left-to-right

    >

    left shiftright shift

    left-to-right

    *

    /divmod

    multiply

    float divisioninteger divisionremainder

    left-to-right

    +-

    addsubtract

    left-to-right

    &

    &&

    concatenate (stringreplicant of exprs)concatenate with 1 spacebetween

    left-to-right

    exists variable & slot existence none

    ==

    less thanless than or equal

    greater thangreater than or equalequalnot equal

    left-to-right

    not logical not left-to-right

    andor

    logical andlogical or

    left-to-right

    := assignment right-to-left

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    21/59

    CHAPTER 2

    2-1

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Flow of Control

    Flow of control in a NewtonScript program is determined by

    n Compound statementsn Conditional statements

    n Iterators

    This chapter discusses the syntax and function of these constructs.

    Compound statements

    The BeginEnd construct is used to group statements. You can use these groupsanywhere the syntax calls for a single expression or statement. For example, you maywant to execute more than one action or expression in the then part of a conditional

    statement. In that case you simply use the Begin and End statements to group thestatements as shown here:

    if x=length(myArray) then

    begin

    result := :read(x);

    print(result)

    end

    The return value of a BeginEnd block is the value of either the last expression in theblock or the value of an executed Return statement. Note that the optional trailingsemi-colon doesnt affect the return value of the last statement.

    Conditional statements

    Conditional expressions have the following syntax:if testExpression then firstStatement

    else alternateStatement

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    22/59

    CHAPTER2

    Flow of Control

    2-2

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    If testExpression evaluates to anything other than NIL, it is considered TRUE.

    As is standard in other programming languages, the statement following thetestExpression is executed if testExpression is not NIL (true) and its value is returned.Note that not all statements return a value. For instance,

    if x > 12 then Print(x);

    returns NIL.

    If you have a test expression that evaluates to NIL, the optional alternate statement ofthe else clause is evaluated. If there is no else statement, NewtonScript returns NIL.

    Iterators

    Like all other NewtonScript expressions, iterative statements also return a value. Theiterators normally return a NIL value unless a Break statement, which can be used to

    stop execution of a loop, is executed. As in other programming languages, loops can benested.

    NewtonScript includes these iterators:

    n For

    n Foreach

    n Loop

    n While

    n Repeat

    s Warning

    Loops are not valid at the top level, that is, outside of a function. Thisshouldt be a problem in actual coding because you wouldnt put a loopat the top level, except when testing or debugging. For more informationabout function specifications see s

    Break

    While not an iterator itself, the Break statement interrupts the execution of any of theiterative structures. You must use the Break statement to stop the simple Loop structure,which has no built-in constructs to stop it. See the section Loop in this chapter to findout more about that structure. The syntax of the Break statement is:

    break expression;

    The Break statement optionally takes an argument that is an expression, which isevaluated and returned as the value of the loop. If you use the Break statement with noexpression, the loop returns the value NIL.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    23/59

    CHAPTER2

    Flow of Control

    2-3

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    For

    You use a For loop to perform an action repeatedly, until a loop counter variable reachesa certain value or a break statement is reached.

    The syntax of a For loop is:

    for counter:= initialExpression to limitExpression

    by incrExpression do statement;

    When a For loop starts, the counter variable is set to the value of the initial expressionvariable. The values of the initial expression and the limit expression variables are setjust once. If you do not specify a value for the incremental expression, NewtonScriptuses a default value of 1. The incremental expression must be an integer. A value of zerois an error.

    After each repetition of the loop, the counter is incremented by the value of theincremental expression.

    If the incrExpression variable is positive, the loop test is

    counter = limitExpression

    If the value of the intial expression is less than the value of the limit expression then thestatement in the loop is executed and the counter variable is incremented by either thedefault value of 1 (if no incremental expression is specified) or by the value of theincremental expression.

    After each repetition of the loop, the counter is incremented by the value of theincremental expression, which of course can be negative, or by the default value of 1.Again, if the incremental expression is zero, an error is generated at runtime.

    Here is an example:

    for x:=1 to 10 by 2 do

    print(x);

    1

    3

    5

    7

    9

    The value of counter is undefined on loop exit. It is an error to change the value ofcounter from within the loop body. If you do so, the loop behavior is undefined.

    As usual, you can use a group of statements enclosed in a BeginEnd block, instead of asingle statement, inside a For loop.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    24/59

    CHAPTER2

    Flow of Control

    2-4

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Foreach

    Looping with Foreach allows you to iterate an action over each element of an array orframe. The syntax of the Foreach loop is as follows:

    foreach slot, element in frameOrArraydo|collect statement;

    This loop executes once for each element in an array or frame. On each iteration, the slotvariable takes the value of the next array index or frame slot name, and the elementvariable takes the value of the next array element or frame slot, beginning with the firstelement in the array or frame. Using both slot and element variables is optional, andwhen you specify just one variable, it is assigned the element value.

    Note that the values of slot and element are undefined on loop exit.

    Here is an example using the Foreach loop to print slot names and values for a frame:

    myFrame := {name:"Carol", office:"San Diego", phone:"123-4567"};

    foreach slot, value in myFrame dobegin

    print(slot);

    print(value)

    end

    The output it returns is:

    name

    "Carol"

    office

    "San Diego"

    phone

    "123-4567"

    Here is an example for an array:

    myArray := ["John", "Mary", "Christine", "Mark"];

    foreach index, value in myArray do

    begin

    print(index);

    print(value)

    end

    0

    "John"

    1

    "Mary"

    2

    "Christine"

    3

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    25/59

    CHAPTER2

    Flow of Control

    2-5

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    "Mark"

    The alternative form of the Foreach loop uses the keyword "collect". In this variation, theresults of the iteration are collected into an array which is returned. For example, thecode snippet

    myFrame := {name:"Carol", office:"San Diego",phone:"123-4567"};

    results := foreach value in myFrame collect value;

    print(results);

    gives you an easy way to collect data and print it out, producing the output:["Carol", "San Diego", "123-4567"]

    Heres an example of some code that collects and prints both the slot names and values:

    results := foreach slot,value in myFrame collect

    [slot,value];

    print(results);

    This example produces this output:

    [[name, "Carol"], [office, "San Diego"], [phone, "123-4567"]]

    s Warning

    Do not add or remove slots to a frame when youre within a loop thatiterates over that frame; the results may be unpredictable! (Though it isnot recommended, you can remove the current slot in an array.) s

    Setting values from within a loop

    If you are setting the value of several slots to a constant string by using a single

    statement in a loop to iterate over the slots, all the slots will contain the same pointer. (SeeCopying NewtonScript values, in Chapter 1 for a discussion of this behavior.) Whenthe value of one slot is changed, all the slots in the group receive the same value.Consider this example:

    a := [f1, f2]

    local f;

    foreach f in a do begin

    SetValue(f, 'text, "")

    end

    The text slot in both frames f1 and f2 will contain a pointer to the same string value,

    which is probably not what you want. If you want to initialize empty strings like this, itsbest to set the value to NIL, not to the empty string. Another solution is to use the Clonefunction to clone the empty string as in the statementSetValue(f, 'text, Clone(""))

    See the NewtonScript Programmers Guide for details.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    26/59

    CHAPTER2

    Flow of Control

    2-6

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Loop

    The syntax of the Loop statement is as follows:

    loop statement;

    This is a simple looping mechanism that simply repeats the statements within the loopuntil a Break statement is encountered. This example prints the value of the variable xuntil it reaches the value of 0 and the break statement is executed.

    x:=4

    loop if x = 0 then break

    else

    begin

    print(x);

    x:=x-1

    end

    4

    3

    2

    1

    While

    The syntax of the While loop is as follows:

    while expression do statement;

    The While loop works by evaluating the test expression first. If the test evaluates tonon-NIL, then the statement after the keyword do executes. This sequence repeats untilthe test expression evaluates to NIL and the loop ends.

    Repeat

    The syntax of the Repeat loop is as follows:

    repeat

    action

    until expression;

    The Repeat loop executes the action specified by the statements inside the loop first andthen evaluates the test expression. If the expression at the end of the loop evaluates toNIL, the statement actions repeat and the test expression is evaluated again, and so onuntil the expression evaluates to non-NIL. At this point the loop ends.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    27/59

    CHAPTER 2

    Defining Functions 3-1

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Functions

    This chapter describes NewtonScript functions.

    Defining Functions

    The general syntax of a NewtonScript function is:

    functionName: func(param1,param2,paramN) statements

    You may specify zero or more parameters in the parameter list of your function. Theparentheses must appear. The body of the function is typically a group of statementsenclosed by the Begin and End keywords, although it could be a single statement.

    A function returns a value, typically the value of the last statement enclosed in aBeginEnd block. This sample function diff returns the value of the difference betweenits two parameters:

    diff: func(n1, n2)

    begin

    if n1 > n2 then return n1 - n2

    else return n2 - n1;

    end

    Return statement

    The Return statement sets a functions return value. The syntax of the return statement is

    return expression;

    The expression is optional. If it appears, the value of the expression is returned as thevalue of the function. If no expression follows the keyword Return, NewtonScriptreturns NIL as the function value.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    28/59

    CHAPTER2

    Functions

    3-2 Parameter Passing

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Local statement

    You define variables that are local to a function by using the Local statement, which hasthe syntax:

    local var1, var2, varN, varName := value;

    If you dont assign an initial value for a local variable, its assigned the default valueNIL. For example, the statement

    local x, y:= 2, z;

    creates three local variables, x, y, and z, and initalizes them to the values of NIL , 2, andNIL, respecitvely.

    Constant statement

    You define constants by using the Constant statement. Like local variables, constantsmay be defined and initialized in one statement. The syntax for a constant is:

    constant name1 ,name2, nameN, constantName := value;

    These sample Constant statements define and initialize constants of various data types.

    constant thisConstant := 32;

    constant thatConstant := "Mike";

    constant anotherOne := _symbol ;

    Parameter Passing

    NewtonScript functions pass parameters using the call-by-value mechanism. If you alterthe value of a parameter, as in the function

    func foo(x) x := 1;

    the change is not permanent and is not detected outside the function. In other words,when an argument is an immediate reference data type, as in this example, the functioncannot affect the argument passed to it.

    If the argument is a pointer reference to a structured data typefor example, if its anarray, frame, or stringthen any changes your function makes to the internal values of

    that argument are persistent.Consider the following code fragments that make persistant changes:

    func foo(x) x[0] := 1; // sets 1st element of array arguments

    func foo(x) x.slot1 := 1; // sets slot1 of frame

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    29/59

    CHAPTER2

    Functions

    Scope 3-3

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Scope

    The part of a program within which a variable can be used is called the scope of thevariable. Normally a variable is available within the function or frame where it isdefined, although a frame variable (slot) can also be inherited from prototype and parentframes. (See Chapter 3, "Object-Oriented NewtonScript Programming," for moreinformation about inheritance.) Variables that are accessible only in a certain parts of aprogram are called local variables.

    Local variables

    You can ensure that a variable is local to a function, and not inherited from the caller orother context (due to dynamic scoping), by using the Local statement to declare it beforeinitializing it. For example:

    myFunc: func (x)

    begin

    local myVar, counter;

    ...

    end

    This example declares the variables myVar and counter as local variables. Each time thefunction is executed, they are created as separate variables, unique to the functionmyFunc.

    Local variables can also be initialized when they are declared, like this:local x:=3, y:=2+2;

    The declaration of the local variable is processed at compile time; the values are assignedat runtime, when the statement is encountered. For example, the statements

    x := 10;

    local x, y := 20;

    result in a value of 10 for x and a value of 20 for y. This works because y has beendeclared as a local variable and initialized to the value NIL at compile time.

    By contrast, the statements

    x := y + 10;

    local x, y := 20;

    result in a runtime error. Because local variables are not initialized until runtime, the firststatement is an attempt to add NIL to 10, which produces an error.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    30/59

    CHAPTER2

    Functions

    3-4 Scope

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Attempting to access the value of an undefined variable results in a runtime error.Attempting to assign a value to an undefined variable creates a local variable of thespecified name.

    When looking up a variable, NewtonScript first searches the local variables, then the

    global variables, and then the inherited variables (through the proto and parent chains,as described in the previous chapter).

    For purposes of scope, BeginEnd blocks do not isolate local variables. For example:

    f := {foo: 10,

    bar: func(x)

    begin

    if foo then Print ("hello") ;

    if x > 0 then

    begin

    local foo;

    foo := 42;

    end;

    return foo;

    end;

    }

    For any value of x, nothing is printed. The variable foo has an initial value of NIL.Although the compiler has created a local variable foo, the variable is not initialized untilthe If statement that assigns it the value 42 executes.

    The return value of

    f:bar( 10 )

    is 42. The return value of

    f:bar( -5 )

    is undefined.

    Extent of Local Variables

    NewtonScript doesnt necessarily free up the storage associated with a data structurewhen control exits the function block. Instead, it waits until a data structure is no longerreferenced anywhere in executing code. Therefore, storage allocated for data structures is

    available until all references to the structures are deleted. Consider this example:

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    31/59

    CHAPTER2

    Functions

    Scope 3-5

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    func () begin

    local myArray := [1,2,3,4];

    return myArray;

    end

    The storage asscociated with myArray isnt freed up when control exits the functionblock. Therefore, if youre allocating large data structures you should make sure not toleave any references to them after youre done using them. If you do, NewtonScript willnot reclaim the associated memory.

    By contrast, consider this buggy C code:

    int* fn (void) {int myArray[] = {1,2,3,4};

    return myArray;

    }

    The problem is that when control exits the function block, the storage for myArray isdeallocated, and pointer returned by the function merely points to some location in thestack.

    Application-Wide Variables

    Unlike local variables, slots that are created in the top-level (highest parent) frame ofyour application are available throughout. (For information on parent inheritance inNewtonScript, see Chapter 3, "Object-Oriented NewtonScript Programming."

    For example:

    myApp := {// Here are the globals

    myErrorBase: 5000,

    appName: "SampleApp"

    player: nil,

    . . .

    }

    Because these slots are defined and initialized at the top level, they are inherited by allchild views of the application.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    32/59

    CHAPTER2

    Functions

    3-6 Scope

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    33/59

    CHAPTER4

    Inheritance 4-1

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Object-Oriented NewtonScriptProgramming

    NewtonScript supports several object-oriented features and concepts through itsinheritance system. NewtonScript uses frames as the basic data structure and inheritanceis set up through the _parent and _proto slots in a frame. Methods are implemented asslots containing functions, and messages can be set using a special message sendingsyntax. This chapter describes parent and prototype inheritance as well as

    n how to set up frames with these relationships

    n the rules associated with parent and prototype inheritance

    n how inheritance affects setting slot values

    n the uses of parent and prototype inheritance

    Inheritance

    There are two kinds of inheritance in NewtonScript: prototype inheritance and parentinheritance.

    Prototype Inheritance

    A frame can have a prototype, which is simply another frame it references in a special

    way. A frame inherits slots from its prototype if it does not contain them in itself. If aframe contains a slot with the same name as a slot in the prototype, it overrides theprototype slot.

    You use inheritance from prototype frames (abbreviated as protos) for

    n object refinementin the Newton system there are many system prototypes you canuse whenever you need them

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    34/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    4-2 Inheritance

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    n persistent storage of data this must be something that does not change

    Creating prototypes

    You create a prototype relationship between frames by using a special slot named: _protowhose value references the frame you want to use as your prototype frame. For example,to use a frame called pageTemplate as a prototype for a frame called myPage, youinclude a _proto slot whose value is a pointer to the pageTemplate frame. This isillustrated in Figure 4-1.

    Figure 4-1 Prototype frame

    Prototype inheritance rules

    If during runtime a function in the frame myPage references the slot named topMargin,as shown in Figure 4-1, the interpreter looks first at the frame myPage. It doesnt find theslot named topMargin so it follows the _proto reference to its prototype frame,pageTemplate, where it finds the slot and gets the value 1. In this case, the frame myPageinherits that slot. However, if a function in the frame myPage, references the slot namedleftMargin, that slot is found in the current frame and evaluates to the value 0.75. In thiscase, the current frame overrides the value of the prototype.

    Note that since frame slots can contain functions as well as simple expressions, functionscan also be inherited and overridden.

    The system obtains values during runtime by following the prototype inheritance rulesfor looking up slot references. NewtonScript looks first in the current frame for a slotname. If the slot is not found, it looks at the prototype frame, and if the slot is still notfound, it looks at that frames prototype frame, and so on, through all the prototypes inthe chain.

    myPage

    {_proto: pageTemplate

    leftMargin: 0.75}

    pageTemplate

    This frame serves as

    a prototype

    {topMargin: 1bottomMargin: 2

    leftMargin: 1.5rightMargin: 1.5}

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    35/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    Inheritance 4-3

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    An example of a prototype chain is shown in Figure 2-2. In this figure, the inheritancechain starts with the current frame, myPage, and follows the arrows to its prototypesframes on the right.

    Figure 4-2 A prototype chain

    Parent InheritanceBesides prototypical relationships between frames, you can set up hierarchicalparent-child relationships.

    Inheritance from parent frames is used for

    n sharing information between objects behavior and data objects, for example

    n creating hierarchies, like the view hierarchy of Newton

    Creating parent-child relationships

    The parent-child link between frames exists by way of a slot named _parent, which exists

    in the child frame. You can set this slot directly in your code or you can use the drawingtools in the Newton Toolkit to create view hierarchies. See Getting Started with theNewton Toolkit for more information about how to do this. Figure 4-3 shows anexample of a parent-child relationship between two frames.

    my age

    _proto :

    .

    .

    }

    page emplate some rame some ther rame

    _proto :

    .

    .

    }

    _proto:

    .

    .

    }

    _proto :

    .

    .

    }

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    36/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    4-4 Inheritance

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Figure 4-3 Parent-child relationship

    Frames that serve as parents can themselves be children of other frames, thereby formingan inheritance chain extending upwards.

    Parent inheritance rules

    When you create parent-child hierarchies between frames, NewtonScript uses aninheritance mechanism that works similarly to prototype inheritance.

    As in prototype inheritance a child frame inherits slots from its parent that it does notitself contain. However, if a child frame contains a slot name that is the same as one in aparent frame, the child slot overrides the parent.

    Combining prototype and parent inheritance

    In practice, most frames have prototypes and parents. When a slot is referenced duringruntime, the parent inheritance mechanism interacts with the prototype inheritancemechanism.

    The rules for inheritance order are really very simple:

    1. NewtonScript looks first in the current frame for a referenced slot. (Unless youspecifically reference a different frame with a dot operator expression likemyDoc.header. In that case, the search begins in the referenced frame, myDoc, and

    myPage

    {_parent: myDoc.

    .}

    myDoc

    {...

    }Parent

    Child

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    37/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    Inheritance 4-5

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    moves forward to include only prototype frames of myDocparent inheritance doesnot apply. For details on using the dot operator to access frame slots see the sectionAccessing Frame Slots.)

    2. If the slot is not found, the prototype chain of the current frame is searched.

    3. If the slot is still not found, the search moves up one level to the parent frame. Theparent and its prototype chain are searched in order. The search then moves upanother level (to the parents parent) and continues in the same way until the slot isfound.

    The numbers in Figure 4-4 indicate the order that frames are searched for a slot referencethat is made from a function in the current frame.

    Figure 4-4 Prototype and parent inheritance interaction order

    Basically, prototype inheritance takes precedence over parent inheritance; all prototypeframes on one level are searched before moving up to search a parent frame and itsprototypes on another level.

    myPage

    _parent: my hap

    _proto : pageTemplate

    leftMargin: 0.75

    }

    pageTemplate

    _proto: section emp

    topMargin: 1

    bottomMargin: 2

    leftMargin: 1.5

    rightMargin: 1.5sides: single

    }

    section emp

    si es: nil

    .

    .

    }

    myChap

    {_parent: myDoc

    _proto: chapTemplate

    sides: double

    chapNum: 2

    }

    chapTemplate

    {chapNum: nil

    header: true.

    }

    my oc

    {_proto: baseDoc

    header: nil

    footer: 2

    }

    docTemplate

    {_proto: docTemplate

    footer: 1

    }

    baseDoc

    {paperSize: standard..

    }

    1

    4

    6

    2

    5

    7 8

    3

    urrent

    Frame

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    38/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    4-6 Interactions between functions and inheritance

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    s Note

    You can use the Inherited keyword when executing a function, to forcean inherited version of the function to be executed rather than theversion in the current frame. This only works with prototypeinheritance. s

    Inheritance rules for setting slot values

    Inheritance rules apply not only when a slot is referenced, but also when its value is set.However, the rules are different for setting a slot.

    The basic difference is that slot values are only changed in parent frames during runtime.They are never changed in prototype frames during runtime. One reason for this is thatprototype frames often exist in ROM and therefore, cannot be changed. (Of course, whenyou are first creating the prototype frames their slots can be set, but not when theapplication is running.)

    When setting a slot, the inheritance search is the same as for slot reference, except thatthe slot is not always set where it is found.

    These are the rules for where a slot is set:

    1. If a slot exists in the current frame, its value is set there.

    2. If the slot exists the prototype chain of the current frame, it is copied into the currentframe and its value is set there.

    3. If the slot exists in the parent of the current frame, its value is set in that parent frame.

    4. If the slot exists in the prototype chain of the parent, it is copied into the parent frameat the same level where it was found, and its value is set in that parent frame.

    Note that if you create the slot from within a function, it is created as a local variable

    within the scope of the function only. If you want to make sure the slot is created as aglobal in the current frame, you must use the special frame specifier Self. Self alwaysrefers to the frame in which execution is occurring.

    If you want to explicitly set the value of a slot in the parent of the current frame, you canuse the expression Self._parent.theSlot to force the slot to be created there.

    Interactions between functions and inheritance

    NewtonScript saves information about the context of a NewtonScript function (unlike

    function pointers that are references to blocks of code in C.)In NewtonScript, a function object is created when the keyword func compiles. Considerthe simple function:

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    39/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    Interactions between functions and inheritance 4-7

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    simpleFunction := func(x) x+y;

    Along with the code, NewtonScript saves information about the frame in which it wasdefined (its lexical environment) and about what frame received the message (itsreceiver environment.) An example of the frame object is shown in Figure 4-5.

    Figure 4-5 Functions in NewtonScript contain information about their lexical and receiverenvironment.

    When the function is called with x as a parameter, NewtonScript looks for the freevariable y, first in the frame where the function is defined. If it doesnt find a value thereit continues looking in the inheritance chain.

    An object-oriented example

    The inheritance structure shown in Figure 2-6 demonstrates some of the essentials ofsending messages.

    Lexicalenvironment

    Receiverenvironment

    Code func (x)x + y

    self

    Defining code block

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    40/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    4-8 Interactions between functions and inheritance

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Figure 4-6 An inheritance structure

    You construct this using the code:

    frame1 := {

    slot1: "slot1 from frame1",

    slot6: 99; };

    frame2 := {

    _parent: frame1,

    slot1: "slot1 from frame2"slot2: "slot2 from frame2",};

    frame3 := {

    slot3: "slot3 from frame3",

    slot5: 42,};

    frame1

    {slot1: "slot1 frame1"

    slot6: 99}

    frame2

    {_parent: frame1

    slot1: "slot1 frame2"

    slot2: "slot2 frame2"

    }

    frame3

    {slot3: "slot3 frame3"

    slot5: 42}

    frame4

    {_parent: frame2

    _proto: frame3

    msg1: func() }

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    41/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    Interactions between functions and inheritance 4-9

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    frame4 := {

    _parent: frame2,

    _proto: frame3,

    msg1: func()

    begin

    //show slot from parent inheritance

    Print(slot1);

    //show slot from proto inheritance

    Print(slot3);

    //show slot from parent inheritance - again -

    //but doesn't work cause

    // self.slot1 only searches proto chain

    Print(self.slot1);

    //show slot from proto inheritance - again

    Print(self.slot3);

    end

    Methods and messages

    Methods in NewtonScript are nothing more than functions defined in a frame slot. As inother object-oriented languages, you can send methods as messages to objects (frames)

    that exist in your code. The syntax you use to send a message is:

    frameExpression : messageName (args)

    Using this syntax, you are actually sending the message, messageName along with anyarguments, to the frame (that is the value of the frame expression) on the left side of thecolon.

    In the example, if you type the command line

    > frame4:msg1()

    you are sending msg1 to frame4. This produces the output:

    "slot1 from frame2"

    "slot3 from frame3"

    NIL

    "slot3 from frame3"

    #2 NIL

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    42/59

    CHAPTER 4

    Object-Oriented NewtonScript Programming

    4-10 Interactions between functions and inheritance

    Alpha Draft, Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Self

    As mentioned earlier, there is a special variable, named Self, that you can use in yourscript code. It always evaluates to the receiver; that is, the last frame which received a

    message. This is almost always the frame in which execution is currently occurring.

    Calling a function

    You rarely call functions using NewtonScript. There is, however, a syntax for calling afunction. It is:

    call functionExpression with (arg)

    Note that another way to call a function is to use the built-in Newton function

    apply(functionExpression,[args])

    The second syntax may actually be preferable to the first, since it allows you todynamically set the arguments.

    It is important to be aware that when you call a function, the system variable is set to theframe in which the function is called.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    43/59

    APPENDIX A

    A-1

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/19/93

    Reserved Words

    The following words are reserved in NewtonScript. You may not use any of these wordsas symbols unless you enclose the word in vertical bars, like this: |self|.

    and

    begin

    break

    by

    call

    collect

    do

    div

    else

    end

    exists

    for

    foreach

    fromfunc

    global

    if

    in

    inherited

    local

    loop

    mod

    not

    onexception

    or

    repeat

    return

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    44/59

    APPENDIX A

    Reserved Words

    A-2

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/19/93

    self

    send

    set

    thento

    try

    until

    while

    with

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    45/59

    APPENDIX B

    B-1

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Special Character Codes

    This appendix contains a character code table that has both Macintosh and Unicode(16-bit) character codes for the high 128 characters in the Newton character set(characters 128 through 254). When specifying character constants or strings that containcharacters from the high 128 characters, you must use unicode character codes. TheMacintosh character codes are provided for convenience if you are used to using them.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    46/59

    APPENDIX B

    Special Character Codes

    B-2

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    Table A-1 Character codes sorted by Macintosh character code

    Mac Unicode Char

    80 00C4

    81 00C5

    82 00C7

    83 00C9

    84 00D1

    85 00D6

    86 00DC

    87 00E1

    88 00E0

    89 00E2

    8A 00E4 8B 00E3

    8C 00E5

    8D 00E7

    8E 00E9

    8F 00E8

    90 00EA

    91 00EB

    92 00ED

    93 00EC

    94 00EE 95 00EF

    96 00F1

    97 00F3

    98 00F2

    99 00F4

    9A 00F6

    9B 00F5

    9C 00FA

    9D 00F9 9E 00FB

    9F 00FC

    A0 2020

    A1 00B0

    A2 00A2

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    47/59

    APPENDIX B

    Special Character Codes

    B-3

    Alpha Draft. Preliminary 1993 Apple Computer, Inc. 7/17/93

    A3 00A3

    A4 00A7

    A5 2022A6 00B6

    A7 00DF

    A8 00AE

    A9 00A9

    AA 2122

    AB 00B4

    AC 00A8

    AD 2260

    AE 00C6 AF 00D8

    B0 221E

    B1 00B1

    B2 2264

    B3 2265

    B4 00A5

    B5 00B5

    B6 2202

    B7 2211

    B8 220F B9 03C0

    BA 222B

    BB 00AA

    BC 00BA

    BD 2126

    BE 00E6

    BF 00F8

    C0 00BF

    C1 00A1

    C2 00AC

    C3 221A

    C4 0192

    C5 2248

    C6 2206

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    48/59

    APPENDIX B

    Special Character Codes

    B-4

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    C7 00AB

    C8 00BB

    C9 2026 CA 00A0

    CB 00C0

    CC 00C3

    CD 00D5

    CE 0152

    CF 0153

    D0 2013

    D1 2014

    D2 201CD3 201D

    D4 2018

    D5 2019

    D6 00F7

    D7 25CA

    D8 00FF

    D9 0178

    DA 2044

    DB 00A4

    DC 2039 DD 203A

    DE FB01 fi

    DF FB02 fl

    E0 2021

    E1 00B7

    E2 201A

    E3 201E

    E4 2030

    E5 00C2

    E6 00CA

    E7 00C1

    E8 00CB

    E9 00C8

    EA 00CD

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    49/59

    APPENDIX B

    Special Character Codes

    B-5

    Alpha Draft. Preliminary 1993 Apple Computer, Inc. 7/17/93

    Table A-2 Character codes sorted by Unicode

    EB 00CE

    EC 00CF

    ED 00CC EE 00D3

    EF 00D4

    F0 F7FF F1 00D2

    F2 00DA

    F3 00DB

    F4 00D9

    F5 0131

    F6 02C6 F7 02DC

    F8 00AF

    F9 02D8

    FA 02D9

    FB 02DA

    FC 00B8

    FD 02DD

    FE 02DB

    FF 02C7

    Mac Unicode Char

    CA 00A0

    C1 00A1

    A2 00A2 A3 00A3

    DB 00A4

    B4 00A5

    A4 00A7

    AC 00A8

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    50/59

    APPENDIX B

    Special Character Codes

    B-6

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    A9 00A9

    BB 00AA

    C7 00AB C2 00AC

    A8 00AE

    F8 00AF

    A1 00B0

    B1 00B1

    AB 00B4

    B5 00B5

    A6 00B6

    E1 00B7 FC 00B8

    BC 00BA

    C8 00BB

    C0 00BF

    CB 00C0

    E7 00C1

    E5 00C2

    CC 00C3

    80 00C4

    81 00C5 AE 00C6

    82 00C7

    E9 00C8

    83 00C9

    E6 00CA

    E8 00CB

    ED 00CC

    EA 00CD

    EB 00CE

    EC 00CF

    84 00D1

    F1 00D2

    EE 00D3

    EF 00D4

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    51/59

    APPENDIX B

    Special Character Codes

    B-7

    Alpha Draft. Preliminary 1993 Apple Computer, Inc. 7/17/93

    CD 00D5

    85 00D6

    AF 00D8 F4 00D9

    F2 00DA

    F3 00DB

    86 00DC

    A7 00DF

    88 00E0

    87 00E1

    89 00E2

    8B 00E3 8A 00E4

    8C 00E5

    BE 00E6

    8D 00E7

    8F 00E8

    8E 00E9

    90 00EA

    91 00EB

    93 00EC

    92 00ED 94 00EE

    95 00EF

    96 00F1

    98 00F2

    97 00F3

    99 00F4

    9B 00F5

    9A 00F6

    D6 00F7

    BF 00F8

    9D 00F9

    9C 00FA

    9E 00FB

    9F 00FC

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    52/59

    APPENDIX B

    Special Character Codes

    B-8

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    D8 00FF

    F5 0131

    CE 0152 CF 0153

    D9 0178

    C4 0192

    F6 02C6

    FF 02C7

    F9 02D8

    FA 02D9

    FB 02DA

    FE 02DB F7 02DC

    FD 02DD

    B9 03C0

    D0 2013

    D1 2014

    D4 2018

    D5 2019

    E2 201A

    D2 201C

    D3 201DE3 201E

    A0 2020

    E0 2021

    A5 2022

    C9 2026

    E4 2030

    DC 2039

    DD 203A

    DA 2044

    AA 2122

    BD 2126

    B6 2202

    C6 2206

    B8 220F

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    53/59

    APPENDIX B

    Special Character Codes

    B-9

    Alpha Draft. Preliminary 1993 Apple Computer, Inc. 7/17/93

    B7 2211

    C3 221A

    B0 221E BA 222B

    C5 2248

    AD 2260

    B2 2264

    B3 2265

    D7 25CA

    F0 F7FF DE FB01 fi

    DF FB02 fl

    Mac Unicode Char

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    54/59

    APPENDIX B

    Special Character Codes

    B-10

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    55/59

    APPENDIX C

    C-1

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

    NewtonScript Quick Reference Card

    The third and fourth pages of this appendix contains a quick reference card for theNewtonScript programming language.

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    56/59

    APPENDIXC

    NewtonScript Quick Reference Card

    C-2

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    57/59

    APPENDIXC

    NewtonScript Quick Reference Card

    C-3

    Alpha Draft. Preliminary 1993 Apple Computer, Inc. 7/17/93

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    58/59

    APPENDIXC

    NewtonScript Quick Reference Card

    C-4

    Alpha Draft. Preliminary. 1993 Apple Computer, Inc. 7/17/93

  • 7/27/2019 The NewtonScript Programming Language (Alpha Draft 1.0)

    59/59

    Index

    A

    Arrays 1-4

    B

    BREAK statement 2-2

    CCharacters 1-2

    special codes 1-3

    F

    FOREACH loop 2-4 to 2-5FOR loop 2-3Frames 1-4

    setting class 1-5Functions

    defining 3-1

    G

    Global variables 3-5

    I

    Inheritance 4-1 to ??Integers 1-1

    L

    N

    Numbers 1-1

    O

    Operators 1-5

    RReal numbers 1-4REPEAT loop 2-6

    S

    Scope 3-3Strings 1-3Symbols 1-3

    special characters in 1-3

    U

    Unicode 1-2

    V

    Variablesglobal 3-5local 3-3

    W

    WHILE loop 2 6