alphabetical list of all turing elements · typespec - type specification unchecked - compiler...
TRANSCRIPT
AlphabeticalListofAllTuringElements
abs-absolutevaluefunctionaddr-addressofavariableaddressint-typeall-allmembersofasetand-operatoranyclass-theancestorofallclassesarctan-arctangentfunction(radians)arctand-arctangentfunction(degrees)array-typeassert-statementassignability-ofexpressiontovariableassignment-statementbegin-statementbind-declarationbits-extractionbody-declarationboolean-true-falsetypebreak-debuggerpausestatementbuttonchoose-switchmousemodesbuttonmoved-hasamouseeventoccurredbuttonwait-getamouseeventprocedurecase-selectionstatementcatenation(+)-joiningtogetherstringsceil-real-to-integerfunctionchar(n)-typechar-typecheat-typecheatingchecked-compilerdirectivechr-integer-to-characterfunctionclass-declarationclock-millisecsusedprocedureclose-filestatement
cls-clearscreengraphicsprocedurecollection-declarationcolor-textcolorgraphicsprocedurecolorback-backgroundcolorprocedurecolour-textcolorgraphicsprocedurecolourback-backgroundcolorprocedurecomment-remarkstatementcomparisonOperatorConcurrencyConcurrency.emptyConcurrency.getpriorityConcurrency.setpriorityConcurrency.simutimecondition-declarationConfigConfig.DisplayConfig.LangConfig.Machineconst-constantdeclarationconstantReference-useofaconstantcos-cosinefunction(radians)cosd-cosinefunction(degrees)date-proceduredeclaration-createavariabledeferred-subprogramdeclarationdelay-procedureDirDir.ChangeDir.CloseDir.CreateDir.CurrentDir.DeleteDir.GetDir.GetLongDir.Opendiv-integertruncatingdivisionoperatorDrawDraw.ArcDraw.Box
Draw.ClsDraw.DotDraw.FillDraw.FillArcDraw.FillBoxDraw.FillMapleLeafDraw.FillOvalDraw.FillPolygonDraw.FillStarDraw.LineDraw.MapleLeafDraw.OvalDraw.PolygonDraw.StarDraw.Textdrawarc-graphicsproceduredrawbox-graphicsproceduredrawdot-graphicsproceduredrawfill-graphicsproceduredrawfillarc-graphicsproceduredrawfillbox-graphicsproceduredrawfillmapleleaf-graphicsproceduredrawfilloval-graphicsproceduredrawfillpolygon-graphicsproceduredrawfillstar-graphicsproceduredrawline-graphicsproceduredrawmapleleaf-graphicsproceduredrawoval-graphicsproceduredrawpic-graphicsproceduredrawpolygon-graphicsproceduredrawstar-graphicsprocedureempty-conditionfunctionenum-enumeratedtypeenumeratedValue-enumeratedvalueeof-end-of-filefunctionequivalence-oftypeserealstr-real-to-stringfunctionErrorError.Last
Error.LastMsgError.LastStrError.MsgError.StrError.TripErrorNumExceptionsexit-statementexp-exponentiationfunctionexplicitCharConstant-characterliteralexplicitConstant-literalexplicitIntegerConstant-integerliteralexplicitRealConstant-realliteralexplicitStringConstant-stringliteralexplicitTrueFalseConstant-booleanliteralexpn-expressionexport-listexternal-declarationfalse-booleanvalue(nottrue)fetcharg-fetchargumentfunctionFileFile.CopyFile.DeleteFile.DiskFreeFile.ExistsFile.RenameFile.Statusflexible-arrayinitializationfloor-real-to-integerfunctionFontFont.DrawFont.FreeFont.GetNameFont.GetSizeFont.GetStyleFont.NameFont.NewFont.SizesFont.StartName
Font.StartSizeFont.Widthfor-statementfork-statementforward-subprogramdeclarationfrealstr-real-to-stringfunctionfree-statementfunction-declarationfunctionCallget-filestatementgetch-getcharacterproceduregetchar-getcharacterfunctiongetenv-getenvironmentfunctiongetpid-getprocessidfunctiongetpriority-functionGUIGUI.AddLineGUI.AddTextGUI.AlertGUI.Alert2GUI.Alert3GUI.AlertFullGUI.ChooseGUI.ChooseFullGUI.ClearTextGUI.CloseWindowGUI.CreateButtonGUI.CreateButtonFullGUI.CreateCanvasGUI.CreateCanvasFullGUI.CreateCheckBoxGUI.CreateCheckBoxFullGUI.CreateFrameGUI.CreateHorizontalScrollBarGUI.CreateHorizontalScrollBarFullGUI.CreateHorizontalSliderGUI.CreateLabelGUI.CreateLabelFullGUI.CreateLabelledFrame
GUI.CreateLineGUI.CreateMenuGUI.CreateMenuItemGUI.CreateMenuItemFullGUI.CreatePictureGUI.CreatePictureButtonGUI.CreatePictureButtonFullGUI.CreatePictureRadioButtonGUI.CreatePictureRadioButtonFullGUI.CreateRadioButtonGUI.CreateRadioButtonFullGUI.CreateTextBoxGUI.CreateTextBoxFullGUI.CreateTextFieldGUI.CreateTextFieldFullGUI.CreateVerticalScrollBarGUI.CreateVerticalScrollBarFullGUI.CreateVerticalSliderGUI.DisableGUI.DisposeGUI.Draw...GUI.EnableGUI.FontDrawGUI.GetCheckBoxGUI.GetEventTimeGUI.GetEventWidgetIDGUI.GetEventWindowGUI.GetHeightGUI.GetMenuBarHeightGUI.GetScrollBarWidthGUI.GetSliderValueGUI.GetTextGUI.GetVersionGUI.GetWidthGUI.GetXGUI.GetYGUI.HideGUI.HideMenuBarGUI.OpenFile
GUI.OpenFileFullGUI.Pic...GUI.ProcessEventGUI.QuitGUI.RefreshGUI.SaveFileGUI.SaveFileFullGUI.SelectRadioGUI.SetActiveGUI.SetBackgroundColorGUI.SetBackgroundColourGUI.SetCheckBoxGUI.SetDefaultGUI.SetDisplayWhenCreatedGUI.SetKeyEventHandlerGUI.SetLabelGUI.SetMouseEventHandlerGUI.SetNullEventHandlerGUI.SetPositionGUI.SetPositionAndSizeGUI.SetScrollAmountGUI.SetSelectionGUI.SetSizeGUI.SetSliderMinMaxGUI.SetSliderReverseGUI.SetSliderSizeGUI.SetSliderValueGUI.SetTextGUI.SetXORGUI.ShowGUI.ShowMenuBarhandler-exceptionhandlerhasch-hascharacterfunctionid-(identifier)nameofaniteminaprogram#if-usedforconditionalcompilationif-statementimplementby-clauseimplement-clauseimport-list
in-memberofasetinclude-sourcefilesindex-findpatterninstringfunctionindexTypeindirection-operator(@)infix-operatorinherit-inheritanceclauseinit-arrayinitializationInputInput.getchInput.getcharInput.haschInput.KeyDown-getkeyboardstateInput.Pause-pauseforkeystrokeint-integertypeintn-n-byteintegertypeintreal-integer-to-realfunctionintstr-integer-to-stringfunctioninvariant-assertionJoystickJoystick.GetInfoKeyboardlength-ofastringfunctionLimitsln-naturallogarithmfunctionlocate-procedurelocatexy-graphicsprocedureloop-statementlower-boundMathmax-maximumfunctionmaxcol-maximumcolumnfunctionmaxcolor-graphicsfunctionmaxcolour-graphicsfunctionmaxint-maximumintegerfunctionmaxnat-maximumnaturalnumberfunctionmaxrow-maximumrowfunctionmaxx-graphicsfunctionmaxy-graphicsfunction
min-minimumfunctionminint-minimumintegerfunctionminnat-minimumnaturalnumberfunctionmod-modulooperatormodule-declarationmonitor-declarationMouseMouse.ButtonChooseMouse.ButtonMovedMouse.ButtonWaitMouse.WheremousewhereMusicMusic.PlayMusic.PlayFileMusic.PlayFileStopMusic.SoundMusic.SoundOffnamed-typenargs-numberofargumentsnat-naturalnumbertypenatn-n-bytenaturalnumbertypenatreal-naturalnumbertorealfunctionnatstr-natural-number-to-stringfunctionNetNet.BytesAvailableNet.CharAvailableNet.CloseConnectionNet.HostAddressFromNameNet.HostNameFromAddressNet.LineAvailableNet.LocalAddressNet.LocalNameNet.OpenConnectionNet.OpenURLConnectionNet.TokenAvailableNet.WaitForConnectionnew-statementnil-pointertoacollection
not-true/false(boolean)operatorobjectclass-ofapointeropaque-typeopen-filestatementor-operatorord-character-to-integerfunctionparallelget-parallelportfunctionparallelput-parallelportprocedureparamDeclaration-parameterdeclarationpause-statementPCPC.ParallelGetPC.ParallelPutpervasive-declarationmodifierPicPic.BlendPic.BlurPic.DrawPic.DrawFramesPic.DrawFramesBackPic.DrawSpecialPic.DrawSpecialBackPic.FileNewPic.FileNewFramesPic.FlipPic.FramesPic.FreePic.HeightPic.MirrorPic.NewPic.RotatePic.SavePic.ScalePic.ScreenLoadPic.ScreenSavePic.SetTransparentColorPic.SetTransparentColourPic.Widthplay-procedure
playdone-functionpointer-typepost-assertionpre-assertionprecedence-ofoperatorspred-predecessorfunctionprefix-operatorprocedure-declarationprocedureCall-statementprocess-declarationprogram-a(main)programput-statementquit-failstatementRandRand.IntRand.NextRand.RealRand.ResetRand.SeedRand.Setrand-randomrealnumberprocedurerandint-randomintegerprocedurerandnext-procedurerandomize-procedurerandseed-procedureread-filestatementreal-therealnumbertyperealn-n-byterealnumbertyperealstr-real-to-stringfunctionrecord-typeregister-usemachineregisterrem-remainderoperatorrepeat-makecopiesofstring:functionresult-statementreturn-statementRGBRGB.AddColorRGB.AddColourRGB.GetColor
RGB.GetColourRGB.maxcolorRGB.maxcolourRGB.SetColorRGB.SetColourround-real-to-integerfunctionscalar-typeseek-(file)statementself-pointertocurrentobjectseparator-betweentokensinaprogramset-typesetConstructorsetpriority-proceduresetscreen-graphicsprocedureshl-shiftleftoperatorshr-shiftrightoperatorsign-functionsignal-wakeupaprocessstatementsimutime-simulatedtimefunctionsin-sinefunction(radians)sind-sinefunction(degrees)sizeof-sizeofatypesizepic-graphicsfunctionskip-usedingetstatementskip-usedinputstatementsound-statementSpriteSprite.AnimateSprite.ChangePicSprite.FreeSprite.HideSprite.NewSprite.SetFrameRateSprite.SetHeightSprite.SetPositionSprite.Showsqrt-squarerootfunctionstandardTypestatement
statementsAndDeclarationsStrStreamStream.eofStream.FlushStream.FlushAllstring-typestring-comparisonstrint-string-to-integer:functionstrintok-string-to-integer:functionstrnat-stringtonaturalnumberfunctionstrnatok-stringtonaturalnumberfunctionstrreal-string-to-realfunctionstrrealok-string-to-realfunctionsubprogramHeadersubprogramTypesubrangeTypesubstring-ofanotherstringsucc-successorfunctionSysSys.ExecSys.FetchArgSys.GetComputerNameSys.GetEnvSys.GetPidSys.GetUserNameSys.Nargssysclock-millisecsusedproceduresystem-statementtag-statementtakepic-graphicsproceduretell-filestatementTextText.ClsText.ColorText.ColorBackText.ColourText.ColourBackText.Locate
Text.LocateXYText.maxcolText.maxrowText.WhatColText.WhatColorText.WhatColorBackText.WhatColourText.WhatColourBackText.WhatRowTimeTime.DateTime.DateSecTime.DelayTime.ElapsedTime.ElapsedCPUTime.PartsSecTime.SecTime.SecDateTime.SecPartstime-timeofdayasastringproceduretoken-ininputtrue-booleanvalue(notfalse)type-declarationTypeConvtypeSpec-typespecificationunchecked-compilerdirectiveunion-typeunit-filecontainingmodule,monitor,orclassunqualified-exportupper-boundvar-declarationvariableReference-useofavariableViewView.ClipAddView.ClipOffView.ClipSetView.maxcolorView.maxcolourView.maxx
View.maxyView.SetView.Update-flicker-freeanimationView.WhatDotColorView.WhatDotColourwait-blockaprocessstatementwallclock-secondssince1/1/1970procedurewhatcol-cursorpositionfunctionwhatcolor-textcolorgraphicsfunctionwhatcolorback-colorofbackgroundfunctionwhatcolour-textcolorgraphicsfunctionwhatcolourback-colorofbackgroundfunctionwhatdotcolor-graphicsfunctionwhatdotcolour-graphicsfunctionwhatrow-cursorpositionfunctionWindowWindow.CloseWindow.GetActiveWindow.GetPositionWindow.GetSelectWindow.HideWindow.OpenWindow.SelectWindow.SetWindow.SetActiveWindow.SetPositionWindow.ShowWindow.Updatewrite-filestatementxor-exclusive"or"operator
abs absolutevaluefunction
Syntax abs(expn)
DescriptionTheabsfunctionisusedtofindtheabsolutevalueofanumber(theexpn).Forexample,abs(-23)is23.
Example
Thisprogramoutputs9.83.
varx:real:=-9.83
putabs(x)%Outputs9.83
Execute
Details
Theabsfunctionacceptsnumbersthatareeitherint'sorreal's.Thetypeoftheresultisthesametypeastheacceptednumber.Theabsfunctionisoftenusedtoseeifonenumberxiswithinagivendistancedofanothernumbery;forexample:
ifabs(x-y)<=dthen…
Seealso predefinedunitMath.
addr addressofavariable
Syntax addr(reference)
Description
Theaddrattributeisusedtofindtheintegeraddressofavariableornonscalarconstant.Thisisimplementation-dependent.Thisaddressmaybeusedinanindirectionoperation@.
Example
Setatobetheaddressofx.
varx:real
vara:addressint:=addr(x)
Details
Thevalueoftheaddressproducedbyaddrisoftypeaddressint,anintegertypewhoserangeisthatoftheunderlyingmemoryaddresses.
Theconceptofanaddressisimplementation-dependent.Forexample,anoptimizingcompilercoulddeterminethatavariabledoesnotrequirespacebecausetheprogramcouldbecomputedwithoutthevariablewithnochangeinoutput.However,inmostimplementations,typeshaveapredictablesizeandvariablesofthattypeoccupythatnumberofbytesinmemory.
Seealso
theindirectionoperator@,cheat,explicitIntegerConstant(howtowritehexadecimalconstants),andpointertype(inparticularuncheckedpointertype).Seealsosizeof,whichreturnsthesizeofavariable.
addressint type
Syntax addressint
Description
Theaddressint(addressinteger)typeisanintegertypewhoserangeofvalueisthesameasthatoftheunderlyingcomputer.Thisrangeis,byitsnature,implementation-dependent.On32-bitarchitectures,itiscommonlythesamerangeasnat4(4-bytenaturalnumber).
Example
Recordrcontainsthreefields,oneofwhichhastypechar(28).Variableaisanintegerwhoserangeofvaluesisthesameastheaddressesoftheunderlyingcomputer.ThisassignsBtotheseventhcharacterofarecordoftyperwhichisassumedtobelocatedatabsoluteaddress
typer:
record
i:int
c28:char(28)
c11:char(11)
endrecord
vara:addressint%Aninteger
…%aisassignedanintegervalue
r@(a).c28(7):='B'%Useindirectionoperator
Details
Althoughaddressintiscalledanintegertype,itiscommonlyequivalenttoanaturaltypesuchasnat4(for32-bitmachines).
Becarefulnottoconfuseaddressintwithpointertypes.InlowlevellanguagessuchasassemblerandC,addressesandpointersarethesame.InTuring,however,apointerisahighlevelconceptthatismoreabstractthanamachineaddress.ATuringpointerisareferencetoanobject,andtherepresentationofthisreferencedependsupontheimplementation.IncurrentTuringimplementations,pointers(whicharebydefaultchecked)arerepresentedasatimestamp(auniquenumber)togetherwithanaddress.Thetimestampisusedtomakesurethatthepointeractuallylocatesanobject.Therearealsouncheckedpointers.Anuncheckedpointer'sinternalrepresentationisamachineaddress.Youcanusetypecheats(adangerousfeature)totranslatebetweenaddressintanduncheckedpointers.Thisismeaningfulincurrent
implementations.
Seealso
theindirectionoperator@,cheat,explicitIntegerConstant(howtowritehexadecimalconstants),andpointertype(inparticularuncheckedpointertype).Seealsoaddr,whichreturnstheaddressofavariable.
all allmembersofaset
Syntax setTypeName(all)
DescriptionGivenasettypenamedS,thesetofallofthepossibleelementsofSiswrittenS(all).
ExampletypesmallSet:setof0..2
varx:smallSet:=smallSet(all)
%Setxcontainselements0,1and2
Seealso settypefordetailsaboutsets.
and operator
Syntax AandB
Description
Theand(boolean)operatoryieldsaresultoftrueif,andonlyif,bothoperandsaretrue.Theandoperatorisashortcircuitoperator.Forexample,ifAisfalseinAandBthenBisnotevaluated.
Examplevarsuccess:boolean:=false
varcontinuing:=true%Thetypeisboolean
…
continuing:=continuingandsuccess
Details
Thecontinuingvariableissettotrueif,andonlyif,bothcontinuingandsuccessaretrue.SinceTuringusesshortcircuitoperators,oncecontinuingisfalse,successwillnotbelookedat.
Theandoperatorcanalsobeappliedtonaturalnumbers.Theresultisthenaturalnumberthatisthebit-wiseandoftheoperands.Seenat(naturalnumber).
Example
Thismasksouttheeverythingbutthelowertwobytesofnumber.
varnumber:nat:=16#ABCD
varmask:nat:=16#FF
putnumberandmask%Outputs205(CD16)
Seealso
boolean(whichdiscussestrue/falsevalues),explicitTrueFalseConstant(whichdiscussesthevaluestrueandfalse),precedenceandexpn(expression).
anyclass theancestorofallclasses
Syntax anyclass
Description
Thereisapredefinedclasscalledanyclass,whichistherootoftheexpansiontree.AllclassesthatdonothaveinheritlistsareconsideredtobeexpansionsofThemainpurposeofanyclassistoallowpointersthatcanlocateobjectsofanyclass.
Example
Hereisthedeclarationofapointerpthatcanlocateanobjectofanyclass.
varp:pointertoanyclass%Shortform:varp:^anyclass
varq:pointertostack%Shortform:varq:^stack
newq%Createastackobject
p:=q%Legalbecausep'sclass
%isanancestorofq'sclass
Assumingstackisaclass,thiscreatesastackobjectandplacesitslocationinThecompilerwillnotallowacalltostack'sexportedsubprogramsusingin:
p->push(14)%ILLEGAL!anyclasshasnooperations
Anassignmentfromptoqislegal,asin:
q:=p%Checksthatplocatesastackobject(ordescendant)
Thisimpliesaruntimechecktomakesurethatplocatesanobjectthatisadescendantofastack).
Hereisawaytocallasubprogramexportedfromstackusingp:
stack(p).push(14)%Checksthatplocatesastackobject
Thischeckstoseethatplocatesastackobject(oradescendant)beforecallingthestackoperationpush.
Details
Itislegaltocreateobjectsoftheclasscalledanyclass,butthisisnotofmuchuse,becausethereisnothingyoucandowiththeseobjects(theyhavenooperations).Itislegaltoassigntheseobjectstootherobjectsofthesameclass(anyclassthisaccomplishesnothing.
Seealso
objectclass,whichtakesaclasspointerandproducestheclassoftheobjectlocatedbythepointer.Thisisusedfortestingtodeterminetheclassoftheobjectlocatedbyapointer.
Seealsoclass.Seealsoexportlist,importlist,inheritlist,implementimplementbylist.
arccos arccosinefunction(radians)
Syntax arccos(r:real):real
DescriptionThearccosfunctionisusedtofindthearccosineofavalue.Theresultisgiveninradians.Forexample,arccos(0.5)isp/3.
Example
Thisprogramprintsoutthearccosineof-1through1inradians.
fori:-4..4
constarg:=i/4
put"Arccosineof",arg,"is",
arccos(arg),"radians"
endfor
Execute
Seealso
thearcsinandarctanfunctionsforcalculatingarcsineandarctangent.
thearccosdfunctionwhichfindsthearccosineofavaluewiththeresultgivenindegrees.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
arccosd arccosinefunction(degrees)
Syntax arccosd(r:real):real
DescriptionThearccosdfunctionisusedtofindthearccosineofananglegivenindegrees.Forexample,arccosd(0.5)is60.
Example
Thisprogramprintsoutthearccosineofvaluesfrom-1to1indegrees.
fori:-4..4
constarg:=i/4
put"Arccosineof",arg,"is",
arccosd(arg),"degrees"
endfor
Execute
Seealso
thearcsindandarctandfunctionsforcalculatingarcsineandarctangent
thearccosfunctionwhichfindsthearccosineofavaluewiththeresultgiveninradians.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
arcsin arcsinefunction(radians)
Syntax arcsin(r:real):real
DescriptionThearcsinfunctionisusedtofindthearcsineofavalue.Theresultisgiveninradians.Forexample,arcsin(0.5)isp/6.
Example
Thisprogramprintsoutthearcsineof-1through1inradians.
fori:-4..4
constarg:=i/4
put"Arcsineof",arg,"is",
arcsin(arg),"radians"
endfor
Execute
Seealso
thearccosandarctanfunctionsforcalculatingarccosineandarctangent.
thearcsindfunctionwhichfindsthearcsineofavaluewiththeresultgivenindegrees.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
arcsind arcsinefunction(degrees)
Syntax arcsind(r:real):real
DescriptionThearcsindfunctionisusedtofindthearcsineofananglegivenindegrees.Forexample,arcsind(0.5)is30.
Example
Thisprogramprintsoutthearcsineofvaluesfrom-1to1indegrees.
fori:-4..4
constarg:=i/4
put"Arcsineof",arg,"is",
arcsind(arg),"degrees"
endfor
Execute
Seealso
thearccosdandarctandfunctionsforcalculatingarccosineandarctangent
thearcsinfunctionwhichfindsthearcsineofavaluewiththeresultgiveninradians.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
arctan arctangentfunction(radians)
Syntax arctan(r:real):real
DescriptionThearctanfunctionisusedtofindthearctangentofavalue.Theresultisgiveninradians.Forexample,arctan(1)isp/4.
Example
Thisprogramprintsoutthearctangentof0through3inradians.
fori:0..12
constarg:=i/4
put"Arctangentof",arg,"is",
arctan(arg),"radians"
endfor
Execute
Seealso
thearcsinandarccosfunctionsforcalculatingarcsineandarccosine
thearctandfunctionwhichfindsthearctangentofavaluewiththeresultgivenindegrees.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
arctand arctangentfunction(degrees)
Syntax arctand(r:real):real
DescriptionThearctandfunctionisusedtofindthearctangentofananglegivenindegrees.Forexample,arctand(0)is0.
Example
Thisprogramprintsoutthearctangentofvaluesfrom0to3indegrees.
fori:0..12
constarg:=i/4
put"Arctangentof",arg,"is",
arctand(arg),"degrees"
endfor
Execute
Seealso
thearcsindandarccosdfunctionsforcalculatingarcsineandarccosine
thearctanfunctionwhichfindsthearctangentofavaluewiththeresultgiveninradians.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
array type
Syntax arrayindexType{,indexType}oftypeSpec
Description
Anarrayconsistsofanumberofelements.ThetypeSpecgivesthetypeoftheseelements.Thereisoneelementforeachiteminthe(combinationsof)range(s)oftheindexType(s).Inthefollowingexample,thearraycalledmarksconsistsof100elements,eachofwhichisaninteger.
Example
varmarks:array1..100ofint
…
varsum:int:=0
fori:1..100%Adduptheelementsofmarks
sum:=sum+marks(i)
endfor
Execute
Details
Intheaboveexample,marks(i)isthei-thelementofthemarksarray.Wecallorsubscriptofmarks.InTuring,asubscriptissurroundedbyparentheses,notbysquarebracketsasisthecaseinthePascalorC-likelanguages.
Example
Thepricesarrayshowshowanarraycanhavemorethanonedimension.Thisarrayhasonedimensionfortheyear(1988,1989or1990)andanotherforthemonth(1..12).Thereare36elementsofthearray,oneforeachmonthofeachyear.
varprice:array1988..1990,1..12ofint
…
varsum:int:=0
foryear:1988..1990%Foreachyear
formonth:1..12%Foreachmonth
sum:=sum+price(year,month)
endfor
endfor
Execute
Details
EachindexTypemustcontainatleastoneitem.Therange1..0,forexample,wouldnotbeallowed.Eachindextypemustbeasubrangeoftheintegers,characters(thetype),orofanenumeratedtype,an(entire)enumeratedtype,thechartype,oranamedtypewhichisoneofthese.
Arrayscanalsobedeclaredintheform
vara:array1..*oftypeSpec:=init(…)
Theupperboundofawillbecomputedfromthecountoftheinitializingvalues.Bothvarandconstarrayscanbedeclaredthisway.Anarrayvariable/constantdeclaredwith"*"asanupperboundmusthaveaninitializinglist.Onlyonedimensionalarraysmaybedeclaredinthisform.
Arrayscanbeassignedasawhole(toarraysofanequivalenttype),buttheycannotbecompared.
Anarraycanbeinitializedinitsdeclarationusinginit.Fordetails,seedeclarations.
Example
Inthisexample,thesizeofthearrayisnotknownuntilruntime.
varhowMany:int
gethowMany
varheight:array1..howManyofreal
…readinalltheelementsofthisarray…
functiontotal(a:array1..*ofreal):real
varsum:real:=0
fori:1..upper(a)
sum:=sum+a(i)
endfor
resultsum
endtotal
put"Sumoftheheightsis",total(height)
Execute
Details
Theendsoftherangeofasubscriptarecalledtheboundsofthearray.Ifthesevaluesarenotknownuntilruntime,thearrayissaidtobedynamic.Intheaboveexample,heightisadynamicarray.Dynamicarrayscanbedeclaredasvariables,asinthecaseforheight.However,dynamicarrayscannotappearinsideothertypessuchasrecords,andcannotbenamedtypes.Dynamicarrayscannotbeassignedandcannotbeinitializedusinginit.
Intheaboveexample,upper(a)returnsthesizeofa.Seealsoupper
Inthedeclarationofanarrayparameter,theupperboundcanbegivenasanasterisk(asisdoneintheaboveexample.Thismeansthattheupperboundistakenfromthatofthecorrespondingactualparameter(fromheightinthisexample).
Youcanhavearraysofothertypes,forexamplearraysofrecord.Ifrecords,thenR(i).fisthewaytoaccesstheffieldofthei-thelementofarray
Details
Arrayscanalsobemaderesizeable.Thisisdoneusingtheflexibledeclarationsyntaxis:
varname:flexiblearrayindexType{,indexType
Theindicesmayhavecompile-timeorrun-timeupperbounds(thelowerboundmustbecompile-time).Theupperboundscanbechangedbyusing:
newname,newUpper1{,newUpper2}
Theexistingarrayentrieswillretaintheirvalues,exceptthatanyindexmadesmallerwillhavethecorrespondingarrayentrieslost.Anyindexmadelargerwillhavethenewarrayentriesuninitialized(ifapplicable).
Additionally,theupperbound(bothinthedeclarationandthenewstatement)canbemadeonelessthanthelowerbound.Thiseffectivelymakesanarraythatcontains0
elements.Itcanlaterbeincreasedinsizewithanothernew.
Inthecurrentimplementation(2002),withamulti-dimensionalarraywithanon-zeronumberoftotalelements,itisarun-timeerrortochangeanybutthefirstdimension(unlessoneofthenewupperboundsisonelessthanthecorrespondinglowerbound,giving0elementsinthearray)asthealgorithmtorearrangetheelementmemorylocationshasnotyetbeenimplemented.
Currently,onlyvariablescanbedeclaredinthisform.Thereisnoflexiblearrayparametertype,althoughaflexiblearraycanbepassedtoanarrayparameterwith“astheupperbound.
Example
Inthisexample,thearrayisresizedtofitthenumberofelementsinthefile.
functiongetLines(fileName:string):int
varf,numLines:int
varline:string
open:f,fileName,get
numLines:=0
loop
exitwheneof(f)
get:f,line:*
numLines+=1
endloop
close:f
resultnumLines
endgetLines
procedurereadFile(varlines:array1..*ofstring
varf:int
varline:string
open:f,fileName,get
fori:1..upper(lines)
get:f,lines(i):*
endfor
close:f
endreadFile
varlines:flexiblearray1..0ofstring
newlines,getLines("text.dat")
readFile(lines,"text.dat")
fori:1..upper(lines)
putlines(i)
endfor
Execute
Seealsoinittoinitializearrays,flexibletodeclareresizablearraysandindexTypeindexofanarray.
assert statement
Syntax asserttrueFalseExpn
Description
Anassertstatementisusedtomakesurethatacertainrequirementismet.ThisrequirementisgivenbythetrueFalseExpn.ThetrueFalseExpnisevaluated.Ifitistrue,alliswellandexecutioncontinues.Ifitisfalse,executionisterminatedwithanappropriatemessage.
ExampleMakesurethatnispositive.
assertn>0
Example
ThisprogramassumesthatthetextFileexistsandcanbeopened,inotherwords,thattheopenwillsetthefileNumbertoapositivestreamnumber.Ifthisisnottrue,theprogrammerwantstheprogramhaltedimmediately.
varfileNumber:int
open:fileNumber,"textFile",read
assertfileNumber>0
Details
InsomeTuringsystems,checkingcanbeturnedoff.Ifcheckingisturnedoff,assertstatementsmaybeignoredandasaresultnevercausetermination.
assignability ofexpressiontovariable
Description
Avalue,suchas24,isassignabletoavariable,suchasi,ifcertainrulesarefollowed.Theserules,givenindetailbelow,arecalledtheassignabilityrules.Theymustbefollowedinassignmentstatementsaswellaswhenpassingvaluestonon-varparameters.
Example
vari:int
i:=24%24isassignabletoi
varwidth:0..319
width:=3*i%3*iisassignabletowidth
vara:array1..25ofstring
a(i):="Ralph"%"Ralph"isassignabletoa(i)
varname:string(20)
name:=a(i)%a(i)isassignabletoname
…
varb:array1..25ofstring
b:=a%Arrayaisassignabletob
typepersonType:
record
age:int
name:string(20)
endrecord
varr,s:personType
…
s:=r%Recordrisassignabletos
Theexpressionontherightof:=mustbeassignabletothevariableontheleft.Anexpressionpassedtoanon-varparametermustbeassignabletothecorrespondingparameter.
Anexpressionisdefinedtobeassignabletoavariableifthetworoottypesareequivalentorifanintegervalueisbeingassignedtoarealvariable(inwhichcasetheintegervalueisautomaticallyconvertedtoreal).Twotypesareconsideredtobeequivalentiftheyareessentiallythesametype(seeequivalenceforthedetaileddefinitionofthisterm).
Details
Inmostcasesaroottypeissimplythetypeitself.Theexceptionsaresubrangesandstrings.Theroottypeofasubrange,suchas0..319,isthetypeofitsbounds(inttypeinthisexample).Theroottypeofastring,suchasthetypestring(9),isthemostgeneralstringtype,namelystring.
Whenasubrangevariable,suchaswidth,isusedasanexpression,forexampleontherightsideofanassignmentstatement,itstypeisconsideredtobetheroottype(integerinthiscase)ratherthanthesubrange.Whenanexpressionisassignedtoasubrangevariablesuchaswidth,thevalue(3*iinthisexample)mustlieinthesubrange.Analogously,anystringvariableusedinanexpressionisconsideredtobeofthemostgeneraltypeofstring.Whenastringvalueisassignedtoastringvariable,itslengthmustnotexceedthevariable'smaximumlength.
Turing'sassignabilityruleappliestocharactersandstringsinthisway.Acharvaluecanbeassigned(orpassedtoannonvarparameter)withautomaticconversiontoachar(1)variableandviceversa.Stringvaluesoflength1canbeassignedtocharvariables.Character,thatischar,valuescanbeassignedtostringvariables,yieldingastringoflength1.Stringvaluesoflengthnareassignablewithautomaticconversiontochar(n)variables.Valuesoftypechar(n)canbeassignedwithautomaticconversiontostringvariables.
Turing'sassignabilityruleappliestopointerstoclassesinthisway.ApointerthatlocatesanobjectcreatedasclassE,canbeassignedtoapointertoclassBonlyifBisanancestorof(orthesameas)E.Forexample,apointertoanobjectthatisastackWithDepthcanbeassignedtoapointertostack,wherestackWithDepthisachildofstack,butnotviceversa.Thepointernilcanbeassignedtoanypointervariable,butthevaluenil(C)canonlybeassignedtoapointertoanancestorofC.
Objectsofclassescanbeassignedtoeachotheronlyifbothwerecreatedasthesameclass.
assignment statement
Syntax
AnassignmentStatementis:
variableReference:=expn
DescriptionAnassignmentstatementcalculatesthevalueoftheexpression(expnassignsthatvaluetothevariable(variableReference).
Example
vari:int
i:=24%Variableibecomes24
vara:array1..25ofstring
a(i):="Ralph"%Thei-thelementofabecomes
…
varb:array1..25ofstring
b:=a%Arraybbecomes(isassigned)arraya
Details
Theexpressionontherightof:=mustbeassignabletothevariableontheleft.Forexample,intheabove,anyintegervalue,suchas24,isassignabletoi,butarealvaluesuchas3.14wouldnotbenotassignabletoi.Entirearrays,recordsandunionscanbeassigned.Forexample,intheabove,arrayaisassignedtoarrayb.Seeassignabilityfortheexactrulesofallowedassignments.
Youcannotassignanewvaluetoaconstant(const).
Thereareshortformsthatallowyoutowriteassignmentstatementsmorecompactly.Forexample,
i:=i+1
canbeshortenedto
i+=1
InTuring,thereareshortformsforcombining+,=and*withassignment.Forexample,i*=2doublesi.
Therearealsoshortformstoallowanybinaryoperatortobecombined
withassignment.Forexample,ishl=2shiftsiby2totheleft.
begin statement
Syntax
AbeginStatementis:
begin statementsAndDeclarations end
Description
Abeginstatementlimitsthescopeofdeclarationsmadewithinittotheconfinesofthebegin/endblock.InTuring,beginisrarelyused,becausedeclarationscanappearwhereverstatementscanappear,andbecauseeverystructuredstatementsuchasifendswithanexplicitend.
Examplebegin
varbigArray:array1..2000ofreal
…bigArraywillexistonlyinsidethisbeginstatement…
end
Details
InPascalprograms,beginstatementsarequitecommonbecausetheyarerequiredforgroupingtwoormorestatements,forexample,togroupthestatementsthatfollowthen.ThisisnotnecessaryinTuringaswhereeveryoucanwriteasinglestatement,youcanalsowriteseveralstatements.
bind declaration
Syntax
AbindDeclarationis:
bind[var]idtovariableReference {,[var]idtovariableReference}
Description
Thebinddeclarationcreatesanewname(ornames)foravariablereference(orreferences).Youareallowedtochangethenameditemonlyifyouspecifyvar.Youcanalsobindtonamednonscalarconstants.
WhilevariableReferenceisbounditdoesnotdisappearinthescope.
Example
Renamethen-thelementofarrayAsoitiscalleditemandthenchangethiselementto15.
bindvaritemtoA(n)
item:=15
Details
Thescopeoftheidentifier(itemabove)beginswiththebinddeclarationandlaststotheendofthesurroundingprogramorstatement(ortotheendofthesurroundingpartofacaseorifstatement).Duringthisscope,achangetoasubscript(nabove)thatoccursinthevariablereferencedoesnotchangetheelementtowhichtheidentifierrefers.
Youarenotallowedtousebindattheoutermostlevelofthemainprogram(exceptnestedinsidestatementssuchasif)orattheoutermostlevelinamodule.
Youcanalsooptionallyusetheregisterkeywordtorequestthatthebindbedoneusingamachineregister.ThesyntaxforbindDeclarationisactually:
bind[var][register]idtovariableReference {,[var][register]idtovariableReference}
Inthecurrent(2002)implementation,programsareruninterpretivelyusingpseudo-codeandtheregisterkeywordisignored.
bits extraction
Syntax bits(expn,subrange)
Description
Thebitsoperatorisusedtoextractasequenceofbitsfromanatural(non-negative)numberexpression.Thebitsarenumberedfromrighttoleftas0,1,2…
Example
Setbits2and1(thirdandsecondfromtheright)inthevariabledtobe01.Wefirstsetbtobethebitstring1100.
typeT12:1..2%Usetospecifybitrange
vard:nat2:=2#1100%Twobytenaturalnumber
%Atthispointbits(d,T12)=2#10
bits(d,T12):=2#01
%Atthispointd=2#1010
Example
Setbit7invariablentobe1.Asaresult,nwillequal2#10000000.
varn:nat1:=0%Aonebytevariablesettozero
bits(n,7):=1%nnowcontainsthepattern10000000
Details
Theformofsubrangemustbeoneof:
(a) typeSpec %Subrangetype (b) compileTimeIntegerExpression
Inform(a)thesubrangetypespecifiesarangefromLtoM(forleastmostsignificant).ThisisalittleconfusingbecausethesubrangeiswrittenMwithLontheleftandMontheright,butinanumber,theleastsignificantbitisontherightandthemostsignificantisontheleft.Thesubrangetypecanbeeitherthenameofatype,forexampleT12,oranexplicitsubrange,forexample3..7.Thevaluesintheexplicitsubrangemustbecompiletimevalues.
Form(b)representstherangen..nwherenisthenon-negativevalueoftheexpression.Inotherwords,bothLandMequaln.Theexpressioncanbeanynon-negativeintegervalueornaturalnumbervalue.
Iftheexpressionexpnisavariablereference,thebitsoperationcanbeassignedto,butcannotbepassedto,avarparameter.Forexample,intheabove,bits(d,T12)hasthevalue2#01assignedtoit.Forthisassignmenttobeallowed,theexpressionexpnmustbeanaturalnumbertype(natnat2ornat4).
Seealso
explicitIntegerConstant(fordescriptionofconstantssuchas16#FFFF)andthefollowingfunctionsthatconvertonetypetoanotherinamachine-independentmanner:ord,chr,intstr,strint,natstr,andstrnat.Seealsoandshl(shiftrightandleft).
body declaration
Syntax
AbodyDeclarationisoneof:
(a) bodyprocedureprocedureId statementsAndDeclarations endprocedureId (b) bodyfunctionfunctionId statementsAndDeclarations endfunctionId (c) bodyprocedureid[(paramDeclaration {,paramDeclaration})] statementsAndDeclarations endid (d) bodyfunctionid[([paramDeclaration{, paramDeclaration}])]:typeSpec statementsAndDeclarations endid
Description
Abodydeclarationisusedtoresolveeitheraforwardsubprogramoradeferredsubprogram.
Youdeclareaprocedureorfunctionforwardwhenyouwanttodefineitsheaderbutnotitsbody.Thisisthecasewhenoneprocedureorfunctioncallsanother,whichinturncallsthefirst.Thissituationiscalledmutualrecursion.Theuseofforwardisnecessaryinthiscasebecauseeveryitemmustbedeclaredbeforeitcanbeused.Theforwarddeclarationmustbefollowedbyabodydeclarationforthesameprocedureorfunction.Fordetails,seeforwarddeclarations.
Whenaprocedureorfunctioninaclassisdeclaredtobedeferred(orsimplyexportedfromtheclass),itcanberesolved
oroverriddenafterwardbygivingitsbodyfurtherdowninthatclassorindescendantclasses.Theoverridingproceduremustusethekeywordbody.Seeclassor"implementby"forexamples.
Details
Youcanspecifytheparameterandreturnvaluesofthesubprograminthebodydeclaration.However,thenamesandtypesoftheparametersandreturnvaluesmustmatchtheinitialdeclarationexactly,orawarningresultsandtheparameterlistandreturnvaluesfromthebodydeclarationareignored.
Example
TheexamplegivenhereispartofacompleteTuringprogramthatincludesanexplanationofforwarddeclarations.
vartoken:string
forwardprocedureexpn(vareValue:real)
importforwardterm,vartoken
…otherdeclarationsappearhere…
bodyprocedureexpn
varnextValue:real
term(eValue)%Evaluatet
loop%Evaluate{+t}
exitwhentokennot="+"
gettoken
term(nextValue)
eValue:=eValue+nextValue
endloop
endexpn
Execute
ThesyntaxofabodyDeclarationpresentedabovehasbeensimplifiedbyomittingtheoptionalresultidentifier,importlist,preandpostconditionandinitclause.Seeprocedureandfunctiondeclarationsfordescriptionsoftheseomissions.
The"function"or"procedure"tokeninthedeclarationisnow
Details optional.Inotherwordsthefollowingcodefragmentislegal
forwardprocedurep
…
bodyp
…
endp
Seealso class,forwardandimplementby
boolean true-falsetype
Syntax boolean
Description
Thebooleantypeisusedforvaluesthatareeithertrueorfalse.Thesetrue-falsevaluescanbecombinedbyvariousoperatorssuchasorandand.
Example
varsuccess:boolean:=false
varcontinuing:=true%Thetypeisboolean
…
success:=mark>=60
continuing:=successandcontinuing
ifcontinuingthen…
Details
ThistypeisnamedaftertheBritishmathematician,GeorgeBoole,whoformulatedlawsoflogic.
Theoperatorsfortrueandfalseareand,or,xor,=>,andnot.Fortwotrue/falsevaluesAandB,theseoperatorsaredefinedasfollows:
AandBistruewhenbotharetrue AorBistruewheneitherorbotharetrue AxorBistruewheneitherbutnotbotharetrue
A=>B(AimpliesB)istruewhenbotharetrueorwhenAisfalse
notAistruewhenAisfalse
Theandoperatorhashigherprecedencethanor,soAorBandCmeansAor(BandC).
Theoperatorsor,andand=>areshortcircuitoperators.Forexample,ifAistrueinAorB,Bisnotevaluated.
Details Thebooleantypecanbeusedasanindextoanarray.
Declarationofanarraywithbooleanindex.
Examplevara:arraybooleanofint
a(false):=10
a(true):=20
Details
Theputandgetsemanticsallowput'sandget'sofbooleanvalues.truevalueswillbeoutputas"true"andfalsevalueswillbeoutputas"false".Theonlylegalinputvaluesare"true"and"false",whicharecasesensitive.
SeealsoexplicitTrueFalseConstant(whichdiscussesthevaluestrueandfalse),precedenceandexpn(expression).
break debuggerpausestatement
Syntax break
Description
Onsystemswithadebugger,theenvironment"pauses"whenexecutionreachesthebreakstatement.While"pausing"isenvironmentspecific,ingeneral,theprogramstopsexecutionuntiltheuserpressesthe"Resume"or"Continue"button.Whilepaused,theprogramvariablescanbeinspected,stacktracesdone,etc.
Examplefori:1..100
puti
break
endfor
buttonchoose switchmousemodes
Syntax buttonchoose(choice:string)
Description
Thebuttonchooseprocedureisusedtochangethemodeofthemouse.InTuring,themousecaneitherbein"single-buttonmode"orin"multi-buttonmode".In"single-buttonmode"themouseistreatedasaonebuttonmouse.Abuttonisconsideredpressedwhenanybuttonispressedandreleasedonlywhenallbuttonshavebeenreleased.
InTuring,themousestartsin"single-buttonmode".
Theparameterchoicecanbeoneof"singlebutton","onebutton"(whichswitchthemouseinto"single-buttonmode")or"multibutton"(whichswitchesthemouseinto"multi-buttonmode").
Example
Aprogramthatdisplaysthestatusofthemouseatthetopleftcornerofthescreen.
buttonchoose("multibutton")
varx,y,button,left,middle,right:int
mousewhere(x,y,button)
left:=buttonmod10%left=0or1
middle:=(button-left)mod100%middle=0or10
right:=button-middle-left%right=0or100
ifleft=1then
put"leftbuttondown"
endif
ifmiddle=10then
put"middlebuttondown"
endif
ifright=100then
put"rightbuttondown"
endif
Execute
Seealso
buttonmovedandbuttonwaittogetmouseeventssavedinaqueue.Seealsomousewheretogetthecurrentstatusofmousebutton(s).
SeealsopredefinedunitMouse.
buttonmoved hasamouseeventoccurred
Syntax buttonmoved(motion:string):boolean
Description
Thebuttonmovedfunctionindicateswhetherthereisamouseeventoftheappropriatetypeonthemousequeue.Eventsareeither"up","down","updown"or"downup"events(althoughthe"downup"and"updown"arethesameevent).
Theparametermotionmustbeoneof"up","down","updown"or"downup".Ifaneventofthetyperequestedisinthequeue,buttonmovedreturnstrue.Iftheeventisnotinthequeue,thenbuttonmovedreturnsfalse.
In"single-buttonmode"(wherethemouseistreatedlikeaone-buttonmouse),a"down"eventoccurswheneverallthebuttonsareupandabuttonispressed.An"up"eventtakesplacewhenthelastbuttonisreleasedsothatnobuttonsremainpressed.
In"multi-buttonmode",a"down"eventoccurswheneveranybuttonispressed,andan"up"eventoccurswheneveranybuttonisreleased.
Example
Thisprogramdrawsrandomcirclesonthescreenuntiltheuserclicksthemousebutton,whereuponisstartsdrawingrandomboxes.Clickingthemousebuttonswitchesbetweenthetwo.
varcircles:boolean:=true
loop
varx,y,radius,clr:int
ifbuttonmoved("down")then
varbuttonnumber,buttonupdown:int
buttonwait("down",x,y,buttonnumber,
circles:=notcircles
endif
randint(x,0,maxx)
randint(y,0,maxy)
randint(radius,0,100)
randint(clr,0,maxcolor)
ifcirclesthen
drawfilloval(x,y,radius,radius,clr)
else
drawfillbox(x,y,x+radius,y+radius
endif
endloop
Execute
Example
Thisisanexampledemonstratinghowtocheckforbothcharacterandmouseinputatthesametime.
varch:string(1)
varx,y,btnnum,btnupdown:int
loop
ifhaschthen
getch(ch)
locate(1,1)
put"Thecharacterenteredisa:",ch
endif
ifbuttonmoved("down")then
buttonwait("down",x,y,btnnum,btnupdown
locate(1,1)
put"Thebuttonwasclickedatposition:",
endif
endloop
Execute
Details
buttonmovedcanbethoughtofasthemouseequivalentofhaschinthattheybothcheckforsomethinginaqueueandbothreturnimmediately.
Seealso
buttonwaittogetmouseeventssavedinthequeue.Seealsobuttonchoosetoswitchbetween"single-buttonmode"and"multi-buttonmode".
SeealsopredefinedunitMouse.
buttonwait getamouseeventprocedure
Syntaxbuttonwait(motion:string, varx,y,buttonnumber,buttonupdown:int)
Description
Thebuttonwaitproceduregetsinformationaboutamouseeventandremovesitfromthequeue.
Theparametermotionmustbeoneof"up","down","updown"or"downup".Ifaneventofthetyperequestedisinthequeue,buttonwaitreturnsinstantly.Ifthereisn'tsuchanevent,buttonwaitwaitsuntilthereisoneandthenreturns(muchlikegetchhandleskeystrokes).
In"single-buttonmode"(wherethemouseistreatedlikeaone-buttonmouse),a"down"eventoccurswheneverallthebuttonsareupandabuttonispressed.An"up"eventtakesplacewhenthelastbuttonisreleasedsothatnobuttonsremainpressed.
In"multi-buttonmode",a"down"eventoccurswheneveranybuttonispressed,andan"up"eventoccurswheneveranybuttonisreleased.
Theparametersxandyaresettothepositionofthemousecursorwhenthebuttonwaspressed.Theparameterbuttonnumberissetto1whenin"single-buttonmode".In"multi-buttonmode",itissetto1iftheleftbuttonwaspressed,2ifthemiddlebuttonwaspressed,and3iftherightbuttonwaspressed.Theparameterbuttonupdownissetto1,ifabuttonwaspressedand0ifabuttonwasreleased.
Example
Thisprogramdrawslines.Itstartsalinewheretheuserpressesdownandcontinuestoupdatethelinewhilethemousebuttonishelddown.Whenthebuttonisreleased,thelineispermanentlydrawandtheusercandrawanotherline.
varx,y,buttonnumber,buttonupdown,buttons:
varnx,ny:int
loop
buttonwait("down",x,y,buttonnumber,buttonupdown
nx:=x
ny:=y
loop
drawline(x,y,nx,ny,0)%Erasepreviousline
exitwhenbuttonmoved("up")
mousewhere(nx,ny,buttons)
drawline(x,y,nx,ny,1)%Drawlinetoposition
endloop
buttonwait("up",nx,ny,buttonnumber,buttonupdown
drawline(x,y,nx,ny,2)%Drawlinetofinalposition
endloop
Execute
Example
Inthepreviousexample,whenthemousemoves,thelineiserasedbydrawingitinwhite.Thiserasesanythingthatthelinewasdrawnontopof,includingpreviouslines.Amorecompleteexampleinvolvingtheclickinganddraggingoffilledrectanglesusingthemouseisavailable.Inthisexample,thebackgroundisfullyrestoredwhentherectangleismovedbyusing"xor".
Example
Thisisanexampledemonstratinghowtocheckforbothcharacterandmouseinputatthesametime.
varch:string(1)
varx,y,btnnum,btnupdown:int
loop
ifhaschthen
getch(ch)
locate(1,1)
put"Thecharacterenteredisa:",ch
endif
ifbuttonmoved("down")then
buttonwait("down",x,y,btnnum,btnupdown
locate(1,1)
put"Thebuttonwasclickedatposition:",
endif
endloop
Execute
Details
buttonwaitcanbethoughtofasthemouseequivalentofgetchinthattheybothreadsomethinginaqueueandbothwaituntiltheygetthethingthey'relookingfor.
Seealso
buttonwaittoseeifanappropriateeventisinthequeue.Seealsobuttonchoosetoswitchbetween"single-buttonmode"and"multi-buttonmode".
SeealsopredefinedunitMouse.
case selectionstatement
Syntax
AcaseStatementis:
caseexpnof
{labelcompileTimeExpn{,compileTimeExpn}:
statementsAndDeclarations} [label: statementsAndDeclarations] endcase
Description
Acasestatementisusedtochooseamongasetofstatements(anddeclarations).Onesetischosenandexecutedandthenexecutioncontinuesjustbeyondendcase.
Theexpression(expn)followingthekeywordcaseisevaluatedandusedtoselectoneofthealternatives(setsofdeclarationsandstatements)forexecution.Theselectedalternativeistheonehavingalabelvalueequalingthecaseexpression.Ifnoneareequalandthereisafinallabelwithnoexpression,thatalternativeisselected.
Example
Outputamessagebasedonvalueofmark.
casemarkof
label9,10:put"Excellent"
label7,8:put"Good"
label6:put"Fair"
label:put"Poor"
endcase
Execute
Example
Outputamessagebasedonvalueofname.
casenameof
label"horse","cow":put"Farmanimal"
label"tiger","lion":put"Jungleanimal"
label"cat","dog":put"Pet"
label:put"Unknownanimal"
endcase
Execute
Details
Thecaseexpressionisrequiredtomatchoneofthelabels.Ifitdoesnot,theremustbeafinallabelwithnoexpression.Labelexpressionsmusthavevaluesknownatcompiletime.Alllabelvaluesmustbedistinct.Thecaseexpressionandthelabelvaluesmusthavethesameequivalenttype,whichmustbeaninteger,char,boolean,anenumtypeorstrings.
Notethatthereisnowaytoexpressarangeofvalues(forexamplefrom5to10)inalabel.Eachindividualvaluemustbeexpressedinthelabel.
catenation(+) joiningtogetherstrings
Syntax
Acatenationis:
stringExpn+stringExpn
DescriptionTwostrings(stringExpns),charorchar(n)valuescanbejoinedtogether(catenated)usingthe+operator.
Example
varlastName,wholeName:string
lastName:="Austere"
wholeName:="Nancy"+""+lastName
%ThethreestringsNancy,ablankandAustere
%catenatedtogethertomakethestring
%"NancyAustere".Thisstringbecomesthe
%valueofwholeName
Details
Thelengthofastringcatenationislimitedto255characters.
Catenationissometimescalledconcatenation.
Catenationcanalsobeappliedtocharandchar(n)values.Seecharandchar(n).Ifeitheroperand,sortins+t,isastringoradynamicchar(n)(lengthnotknownatcompiletime),theresulttypeisstring.Otherwise(whenbothsandtarecharornon-dynamicchar(n))theresulttypeischar(n).
Theresultofcatenationisconsideredtobeacompiletimevalueifbothoperandsarecompiletimevalues.
Ifbothoperandshavethetypecharorchar(n)neitherofwhichisadynamicchar(n),theresultisoftypechar(n),whichisalsoofanondynamictype.Thisallowsthecreationofverylongchar(n)valuesthatcaneffectivelyspanlineboundariesusingcatenationtojoinlines.Ifeitheroperandisadynamictypeorastringtype,thecatenationproducesastring,whoselengthislimitedto255characters.
substrings(forseparatingastringsintoparts),repeat(formaking
Seealso
repeatedcatenations),stringtype,length,andindex(todeterminewhereonestringislocatedinsideanother).
Seealsostring,char,char(n),explicitStringConstant,explicitCharConstant,substringandlength.
ceil real-to-integerfunction
Syntax ceil(r:real):int
Description Returnsthesmallestintegergreaterthanorequaltor.
Details
Theceil(ceiling)functionisusedtoconvertarealnumbertoaninteger.Theresultisthesmallestintegerthatisgreaterthanorequaltor.Inotherwords,theceilfunctionroundsuptothenearestinteger.Forexample,ceil(3)is3,ceil(2.25)is3andceil(-8.43)is-8.
Seealso Seealsothefloorandroundfunctions.
char(n) type
Syntax char(numberOfCharacters)
DescriptionEachvariablewhosetypeisachar(n)containsexactlyncharacters.
Example
Canadianpostalcodescontainsixcharacters,forexample,M4V1Y9.Thisisrepresentedinachar(6)variable:
varpostalCode:char(6):='M4V1Y9'
Explicitconstantsforthechar(n)typeusesinglequotesasin'M4V1Y9',asopposedtoexplicitstringconstantswhichusedoublequotes,asin"Nancy".Asinglecharactersinglequotedcharacter,suchas'A',isconsideredtohavethetypecharinsteadofchar(n),butsincethesetwotypescanbeassignedtoeachotherandcomparedtoeachother,thisfacthaslittleconsequence.
Thetypechar(n)isgenerallymoredifficulttousethanthestringtype,whichisfavoredformostsimpleprograms.Thetypechar(n)hastheadvantagethatitisefficientintermsofbothspaceandtime.Inparticular,itisrepresentedasnbytesinthecomputer'smemory.Bycontrast,thestringtypemustuseextraspace(atrailingzerobyteincurrentimplementations)torepresentthecurrentlengthandallocatesspaceforthemaximumvalueitcanhold.
TheformofnumberOfCharactersisoneof:
(a)expn %Integervalue (b)* %Onlyinsubprogramparameters
Thefirstformdeterminesn.Iftheexpressionisaruntimevalue,thetypeisconsideredtobedynamicchar(n).Thevalueofnmustbeatleast1.Thesecondformisusedonlyforsubprogramparametersandusesthelengthoftheactualparameter.Thistoo,isconsideredtobeadynamicchar(n)type.Dynamicchar(n)
Details
typescanonlybepassedtochar(*)parameters.Dynamicchar(n)typeshavethesamerestrictionsasdynamicarrays.Thisimpliestheycannotbeassignedasawholeandcannotappearinrecordanduniontypes.
Animplementationmayimposealimit,recommendedtobeatleast32767,onthelengthn.
Valuesofthechar(n)typecanbeassignedandtheycanbecomparedforbothequalityandforordering,butonlyiftheyhavethesamelengthandtheyarenotdynamic(i.e.thelengthmustbeknownatcompiletime).
Valuesofthechar(n)typecanbereadandwrittenbygetandputstatements.
Thechar(n)typeisanonscalar,whichimpliesthatitsparametersarealwayspassedbyreference(bymeansofanimplicitpointer).
Asistrueforthechartype,all256possiblevaluesofan8-bitbyteareallowedforeachcharacterinchar(n)type.Thereisnopatternlefttobeusedforthe"initializedvalue",sothereisnouninitializedcheckingforchar(n).
Ingeneral,youcanfreelyintermixthevaluesofthetypeschar,char(n)andstring.Thismeansthatcatenation(+),comparisons,lengthandsubstringscanbeappliedtoanyofthesetypes.Seecatenationandsubstring.Iftwonondynamicchar(n)values(orcharvalues)arecatenated,theresultisachar(n)value.Ifeitheraredynamic,itisastringvalue.Thisimpliesthatverylongchar(n)valuescanbecreatedbycatenatingthemtogether,forexampletoinitializeachar(n)variable.
Acharvaluecanbeassigned(orpassedtoannonvarparameter)withautomaticconversiontoachar(1)variableandviceversa.Stringvaluesoflength1canbeassignedtocharvariables.Character(char)valuescanbeassignedtostringvariables,yieldingastringoflength1.Stringvaluesoflengthnareassignablewithautomaticconversiontochar(n)variables.Valuesoftypechar(n)canbeassignedwithautomaticconversionto
stringvariables.
Whencomparingtwochar(n)values,asins>t,ifbotharenon-dynamicandofthesamelength,theyarecomparedwithoutconvertingtostrings.Ifeitheraredynamic,theyareconvertedtostringsandthencompared.
Seealsothechartypewhichismuchlikechar(1).Seealsothestringtype.
char type
Syntax char
DescriptionEachvariablewhosetypeisacharcontainsasinglecharacter,suchastheletterA,thedigit3orthespecialcharacter&.
Example
Countcharactersuntilaperiodisfound.Charactercisreadusingastatementandiscomparedtotheexplicitcharacterconstant'.'.
varc:char
varcounter:=0
loop
exitwheneof
getc%Readasinglecharacter
exitwhenc='.'%Singlequotesforcharconstant
counter:=counter+1
endloop
putcounter,"charactersbeforetheperiod"
Execute
Example
Countcapitalletters.Thisexampleillustratestheuseofthechartypeasthesubscripttypeforthefrequencyarray,theuseofcharactervariablecasasubscript,andtheuseofdasaforcounterthatrangesacrossthelettersAtoZ.
varfrequency:array'A'..'Z'ofnat
ford:'A'..'Z'
frequency(d):=0
endfor
loop%Tabulateuseofcapitalletters
exitwheneof
varc:char
getc%Readonecharacter
ifc>='A'andc<='Z'then
frequency(c):=frequency(c)+1
endif
endloop
ford:'A'..'Z'%Printfrequencyofcapitalletters
putd,"",frequency(d)
endfor
Execute
Details
Thetypestring(orchar(n))isusedinsteadofcharwhenmorethanonecharacterneedstobestored,suchasthestringofcharactersHenryUnlesstheprogramneedstobequiteefficient,itisusuallyeasiertousethestringtype.Seealsothechar(n)type,whichalwaysstoresexactlyncharacters.
Thechartypediffersfromthestring(1)typeinthefollowingway:charalwaysrepresentsexactlyonecharacter,whilestring(1)canrepresenteitherthenullstringorastringcontainingonecharacter.Thechartypeissimilartothechar(1)typeinthatbothcontainatmostonecharacter.
Thechartypeisanindextypeandcanbeused,forexample,assubscripts,forrangesandcaselabels.Forexample,thisdeclaration
varcharCounts:arraycharofint
createsanarraywhosesubscriptsarecharacters.
Thechartypeisascalartype,whichimpliesthatitsparametersarepassedbyvalue,insteadofbyreference(whichisthecaseforcharandstring).
Valuesofthechartypecanbeassignedandtheycanbecomparedforbothequalityandordering.Explicitcharconstantsarewrittenasacharactersurroundedbysinglequotes,forexample,'A'.Fordetails,
includinghowtowritecontrolcharacters,seeexplicitCharConstant
Characterscanbereadandwrittenbygetandputstatements.
Thereare256charvalues,correspondingtothedistinctpatternsinan8-bitbyte.Thisallowsthepatternseos(internalvalue0)anduninitchar(internalvalue128)tobecharvalues(thesepatternsarenotallowedinthestringtype;seethestringtype).All256patternsareused,sothereisnopatternlefttobethe"uninitializedvalue".Uninitializedcheckingisnotdoneforthechartype.
Theordandchrfunctionsconvertbetweenthecharvaluesandtheircorrespondingnumericrepresentationinabyte.Seeordandchr.
Ingeneral,youcanfreelyintermixthevaluesofthetypeschar,char(n)andstring.Thismeansthatcatenation(+),comparisons,lengthandsubstringscanbeappliedtoanyofthesetypes.Seecharfordetailsaboutconversionsbetweenchar,char(n)andstring.
Seealso
stringandchar(n)forrelatedtypes.SeeordandchrfunctionsforconversionfromandtoASCIIvalues.SeeexplicitCharConstantforinformationonspecialcharacterslikecaret(^)andbackslash(\).
cheat typecheating
Dangerous
Syntax
AtypeCheatisoneof:
(a) cheat(targetType,expn[:sizeSpec]) (b) #expn (c) id:cheattypeSpec
Description
Atypecheatinterpretstherepresentation(bits)ofonetypeasanothertype.Typecheatsaredirty(machine-dependent)andsometimesdangerous(arbitrarycorruption)andshouldbeusedonlybyprogrammerswhoknowtheunderlyingcomputerrepresentationofvalues.
Form(b)isashortformtypecheatinwhichthetargettypeisanaturalnumber.
Form(c)isusedasaparameterinasubprogramdeclaration.ItcauseswhateverispassedintotheparametertobeinterpretedastypeSpec
Example
Thecharacter'B'isassignedtovariablei,whosetypeisconsideredtobechar(althoughitisreallyint1).
vari:int1%Onebyteinteger
cheat(char,i):='B'
Thisassignmentisequivalent(onbyteorientedcomputers)toeitherofthefollowing:
i:=cheat(int1,'B')
i:=ord('B')
TheformoftargetTypemustbeoneof:
(a) [id.]typeId (b) int,int1,int2orint4
Details
(c) nat,nat1,nat2ornat4 (d) boolean (e) char[(numberOfCharacters)] (f) string[(maximumLength)] (g) addressint
Inform(a)thebeginningidentifieridmustbethenameofamodule,monitororclassthatexportsthetypeId.EachofnumberOfCharactersandmaximumLengthmustbecompiletimeintegerexpressions.
IftheexpninatypecheatisavariablereferenceandthesizeSpecisomitted,thetypecheatisconsideredtobeavariablewhosetypeistargetType.Thisallows,forexample,thetypecheattobeassignedto,asin:
cheat(char,i):='B'
Iftheexpnisavaluethatisnotavariablereference,orifsizeSpecispresent,thetypecheatisanexpressionvaluewhosetypeistargetType
ThesizeSpecisacompiletimeintegerexpressiongivingthesizeoftheexpn'svalue.Itcanbespecifiedonlyforintegerornaturalnumbervalues(whereitmustbe1,2or4)orrealvalues(whereitmustbe4or8).
Atypecheatiscarriedoutintwosteps.ThefirststepconvertsthevalueifnecessarytothesizegivenbysizeSpec.Thesecondstep,whichinvolvesnogeneratedcode,interpretsthevalueasthetargettype.
Theprefixoperator#isashortformforaclassoftypecheats.Itinterpretsitsargumentasanaturalnumber.Ingeneral,#expnisthesameascheat(natn,expn)wherenisdeterminedasfollows.Iftheexpnisavariableorexpressionofsize1,2or4,nisthesizeoftheitem,otherwisenis4.
Example
Setthesecondcharacterofdsoithasthenumericrepresentation24.Ingeneral,ifcisacharacter,then#c=ord(c).Notethat#ccanhaveanumbervalueassignedtoit,butord(c)cannot.
vard:char(3)
#d(2):=24%Sameasd(2):=chr(24)
Example
Thenotation16#FFFFmeansFFFFinbase16,whichis32767inbase10andis161'sinarowinbase2.Thissamepatternisthetwo'scomplementrepresentationofthevalue-1ina2-byteinteger.
vari:int2
#i:=16#FFFF%Equivalenttoi:=-1
Example
ThefollowingexampleprintsoutastringlocatedataddressintmyAddr
procedurePrintString(str:cheatstring)
putstr
endPrintString
varmyAddr:addressint
...%AssignedavaluetomyAddr
PrintString(myAddr)%myAddrwillbetreatedasastring
Details
Animplementationmayprohibitcertaintypecheats.Memoryalignmentrequirementsmayrendersometypecheatsunfeasible.ItisdangeroustoconsideravaluetohaveatargetTypelargerthanthevalue'stype.Animplementationmayprohibitcertaintypecheatsonregisterscalaritems.
Seealso
explicitIntegerConstant(fordescriptionofconstantssuchas16#FFFF)andthefollowingfunctionsthatconvertonetypetoanotherinamachine-independentmanner:ord,chr,intstr,strint,natstr,andstrnat.
checked compilerdirective
Description
Uncheckedmeansthatcertainruntimetests,whichtakeplacebydefault,canbeeliminated,usuallytomaketheprogrammoreefficientattheriskofunreliability.Thekeywordchecked,usedasastatement,requeststhatthedisablingofchecking,previouslyrequestedbythekeywordunchecked,bere-enabled.Seeuncheckedfordetailsandanexample.
chr integer-to-characterfunction
Syntax chr(i:int):char
Description
Thechrfunctionisusedtoconvertanintegertoacharacter.Thecharacteristhei-thcharacteroftheASCIIsequenceofcharacters(exceptontheIBMmainframe,whichusestheEBCDICsequence.)Forexample,chr(65)is"A".
Theordfunctionistheinverseofchr,soforanycharacterc,:
chr(ord(c))=c.
Execute
Details
Therearetwosetsofcharactersrepresentingvalues128-255:theANSIvalues(thedefaultvaluesforWindows),andtheMS-DOSOEMcharacterset,whichcontainsvariouslinedrawingcharacters.TousetheMS-DOScharacterset,youmustusethesetscreen("msdos")command.
Example
Anotherexampleisavailablethatdisplaystheentirecharactersset,boththeregularANSIcharactersetandtheMS_DOSOEMcharacterset.
Seealso ord,intstrandstrintfunctions.
class declaration
Pointerpisusedtolocateindividualobjectsoftheclass.Thenewstatementcreatesoneoftheseobjects.Thestatement
p->push("Harvey")
isashortformfor:
stackClass(p).push("Harvey")
ThisinsertsthestringHarveyintothestackobjectlocatedbyp.
Syntax
AclassDeclarationis:
[monitor] classid [inheritinheritItem] [implementimplementItem] [implementbyimplementByItem] [import[var]importItem{,[var]importItem [export[howExport]id{,[howExport]id}] statementsAndDeclarations endid
Description
Aclassdeclarationdefinesatemplateforapackageofvariables,constants,types,subprograms,etc.Thenameoftheclass(id)isgivenintwoplaces,justafterjustafterend.Itemsdeclaredinsidetheclasscanbeaccessedoutsideoftheclassonlyiftheyareexported.Itemsfromoutsidetheclassthataretobeusedintheclass,needtobeimported(unlesstheyarepredefinedorpervasive).Instances(objects)ofaclassarecreatedusingthenewstatement.Eachobjectisessentiallyamodulelocatedbyapointer.
Thisclassisatemplateforcreatingobjects,eachofwhichisastackofstrings.(Seethemoduledescriptionforthecorrespondingmodulethatimplementsasinglestackofstrings.)
Example
classstackClass%Templateforcreatingindividualstacks
exportpush,pop
vartop:int:=0
varcontents:array1..100ofstring
procedurepush(s:string)
top:=top+1
contents(top):=s
endpush
procedurepop(vars:string)
s:=contents(top)
top:=top-1
endpop
endstackClass
varp:pointertostackClass%Shortform:var
newstackClass,p%Shortform:newp
p->push("Harvey")
varname:string
p->pop(name)%ThissetsnametobeHarvey
Execute
Thenewstatementisusedtocreateobjectsofaclass.Manyinstancesofaclasscanexistatagiventime,eachlocatedbyapointer.Thefreestatementisusedtodestroyobjectsthatarenolongerofuse.Turingdoesnotsupportgarbagecollection(automaticrecoveryofspacebelongingtoinaccessibleobjects).
Seemodulesforadiscussionofimporting,exportingandrelatedconcepts.Whenanobjectiscreatedbynew,itsinitializationcodeisexecuted.Inthisexample,theobject'stopvariableissetto0.Asistrueinmodules,anexportedsubprogramofanobject'sclasscannotbecalleduntiltheobjectiscompletelyinitialized.
Youarenotallowedtocreatevariablesofaclass,asin:
vars:stack%Notlegal!
Details
Ifthemonitorkeywordispresent(justbeforeclass),theobjectsaremonitors.Thismeansthatonlyoneprocessatatimecanbeactiveintheobject.Seeprocess.
Inheritlistsareusedtospecifyinheritance.Seeinheritlist.Implementandimplement-bylistsprovideaspecialkindofexpansionwhichsupportstheseparationofaninterfacefromitsimplementation.Seeimplementlistandimplement-bycannotcontainbothaninheritandanimplementlist.
Classdeclarationscanbenestedinsidemodulesandmonitorsbutcannotbenestedinsideotherclassesorinsideproceduresorfunctions.Aclassmustnotcontainaasoneofits(outermost)declarations.Areturnstatementcannotbeusedasoneofthe(outermost)statementsinaclass.
Aclasscannotexportvariables(orruntimeconstants)asunqualifiedobjecthasadistinctsetofvariables).
ThesyntaxofaclassDeclarationpresentedabovehasbeensimplifiedbyleavingoutpre,invariantandpostclauses.Thefullsyntaxwhichsupportsprepostisthesameasthatformodules.Theinitializationofclassesisthesameasthatformodules.Seemodule.
Wewillgiveanexampleinwhichasubprograminoneclassoverridesthecorrespondingsubprograminaclassthatisbeinginherited.Theexampleisbasedonaprogramthatimplementsafilesysteminsideanoperatingsystem.Allfileshaveclose,readandwriteoperations.Somefiles,calledDevicefiles,alsohaveanoperationcalledioCtl(input/outputcontrol).Thekindoffiledeterminestheimplementationmethod.Hereistheexpansion(inheritance)hierarchyamongtheclassesoffiles.
TheclasscalledFilegivestheinterfacetoallpossiblekindsoffiles.Theimplementsfilesthataretext(ASCIIcharacters).TheDeviceclassgivestheinterface
Example
toallfilesthathavetheioCtloperationinadditiontoopen,close,readTapeandDiskclassesimplementfilesthatareactuallyphysicaltapesordisks.HereisthedeclarationoftheFileclass:
classFile
exportopen,close,read,write
deferredprocedureopen(…parametersforopen…)
deferredprocedureclose(…parametersforclose…)
deferredprocedureread(…parametersforread…)
deferredprocedurewrite(…parametersforwrite…)
endFile
TheTextFileclassimplementstheFileinterfacebygivingvariablesdeclarationsandprocedurebodiesforASCIIfiles:
classTextFile
inheritFile
varinternalTextFileData:
…internaldatafortextfiles…
bodyprocedureopen
…bodyforopenfortextfiles…
endopen
…bodiesforclose,readandwriteproceduresfortextfiles…
endTextFile
Objectstorepresentindividualtextfilesarecreatedusingthenewstatement:
vartextFilePtr:^TextFile
%Pointerwilllocateatextfileobject
newtextFilePtr%Createatextfileobject
textFilePtr->read(…actualparameters…)%Readtextfile
TheDeviceclassaddstheioCtlproceduretotheFileinterface.
classDevice
inheritFile
exportioCtl
deferredprocedureioCtl(…parametersforioCtl
endDevice
TheDiskclassprovidesdataandprocedurestoimplementafilethatisactuallyadisk(theTapeclassisanalogous):
classDisk
inheritDevice
varinternalDiskFileData:…internaldatafordiskfiles
bodyprocedureopen
…bodyforopen…
endopen
…bodiesforclose,read,writeandioCtlproceduresfordisk…
endDisk
ApointerthatcanlocateanykindofFileobjectisdeclaredthisway:
varfilePtr:^File
Thismaylocate,forexample,aTextFile:
filePtr:=textFilePtr
ThisassignmentisallowedbecausefilePtr'scorrespondingclass(FileoftextFilePtr'scorrespondingclass(TextFile).ItisguaranteedthattheobjectnowlocatedbyfilePtrsupportsaversionofalltheoperationsofaFile(andwrite).
WhenwecallaprocedureintheobjectlocatedbyfilePtr,theactualprocedurecalledwilldependupontheobject:
filePtr->read(…actualparameters…)
Forexample,iffilePtrcurrentlylocatesaDiskfile,thiswillcallthefromtheDiskclass.ThisisanexampleofdynamicbindinginwhichreadtobeusedisselectedatruntimeandthischoiceisbasedontheobjectlocatedbyfilePtr.Thisiscalledpolymorphism,becauseFileobjectscanhavemorethanoneform.
Asanotherexample,considerclassC,whichcontainsheadersandbodiesforfunctionsfandg.Cexportsfunctionsfandg.ThereisalsoaclassD,whichinheritsfromClassDcontainsabodythatoverridesthebodyforg.Dalsocontainsaheaderandbodyforfunctionh.Dexportsfunctionh.
PointerphasbeendeclaredtolocateanobjectofclassC,butatruntimeobjectofclassD.Whenpisusedtocallf,bymeansofp->f,thebodyofappearsinC,isinvoked.Whenpisusedtocallg,bymeansofp->bodyinDisinvoked.Anyattempttouseptocallhisillegalbecause
Example
usedtocallfunctionsthatareexportedfromC.
classC
exportf,g
proceduref
put"C'sf"
endf
procedureg
put"C'sg"
endg
endC
classD
inheritC%Inheritfandg
bodyprocedureg%OverridesginC
put"***D'sg***"
endg
procedureh
put"***D'sh***"
endh
endD
varp:pointertoC%pcanpointtoanydescendantofC
newD,p%plocatesanobjectofclassD
p->f%Outputs"C'sf"
p->g%Outputs"***D'sg***"
p->h%Causeserror"'h'isnotinexportlistof'C'"
Execute
Seealso
module,monitorandunit.Seealsoimportlist,exportlist,implementimplementbylist,andinheritlist.Seealsodeferredsubprogram.Seealsoandobjectclass.
clock millisecsusedprocedure
Syntax clock(varc:int)
Description
Theclockstatementisusedtodeterminetheamountoftimesinceaprogram(process)startedrunning.Variablecisassignedthenumberofmillisecondssincetheprogramstartedrunning.
Example
Thisprogramtellsyouhowmuchtimeithasused.
vartimeRunning:int
clock(timeRunning)
put"Thisprogramhasrun",timeRunning,"milliseconds"
Execute
DetailsOnAppleMacintoshes,thehardwareresolutionofdurationisinunitsof17milliseconds(1/60-thofasecond).
Seealsodelay,time,sysclock,wallclockanddatestatements.
SeealsopredefinedunitTime.
close filestatement
Syntax
AcloseStatementis:
close:fileNumber
Description
InTuring,filesarereadandwrittenusingafileNumber.Inmostcases,thisnumberisgivenavalueusingtheopenstatement,whichtranslatesafilename,suchas"Master",toafilenumber,suchas5.Whentheprogramisfinishedusingthefile,itdisconnectsfromthefileusingtheclosestatement.
Example
Thisprogramillustrateshowtoopen,readandthencloseafile.
varfileName:string:="Master"%Nameoffile
varfileNo:int%Numberoffile
varinputVariable:string(100)
open:fileNo,fileName,read
…
read:fileNo,inputVariable
…
close:fileNo
Details
InaTuringimplementation,therewillgenerallybealimitonthenumberofcurrentlyopenfiles.Thislimitwilltypicallybearound20.Toavoidexceedingthislimit,aprogramthatusesmanyfilesoneafteranothershouldclosefilesthatarenolongerinuse.
Ifaprogramdoesnotcloseafile,thefilewillbeautomaticallyclosedwhentheprogramfinishes.
Thereisanolderandstillacceptableversionofclosethathasthissyntax:
close(fileNumber:int)
Seealso theopen,get,put,read,write,seekandtellstatements.
cls clearscreengraphicsprocedure
Syntax cls
DescriptionThecls(clearscreen)procedureisusedtoblanktheoutputwindow.Thecursorissettothetopleft(torow1,column1).
Details
Theentireoutputwindowissettothecurrenttextbackgroundcolor(assetbycolorbackorText.ColorBack).
Theoutputwindowmustbein"graphics"mode.Seesetscreenfordetails.
Seealso SeealsopredefinedunitText.
collection declaration
Syntax
AcollectionDeclarationisoneof:
(a) varid{,id}:collectionoftypeSpec (b) varid{,id}:collectionofforwardtypeId
Description
Acollectiondeclarationcreatesanewcollection(orcollections).Acollectioncanbethoughtofasanarraywhoseelementsaredynamicallycreated(bynew)anddeleted(byfree).Elementsofacollectionarereferredtobythecollection'snamesubscriptedbyapointer.Seealsonew,freeandpointer.
Example
Createacollectionthatwillrepresentabinarytree.
vartree:collectionof
record
name:string(10)
left,right:pointertotree
endrecord
varroot:pointertotree
newtree,root
tree(root).name:="Adam"
Thestatement"newC,p"createsanewelementincollectionCandsetsptopointati.Ifthereisnomorememoryspacefortheelement,though,pissettonil(C),whichisthenullpointerforcollectionC.Thestatement"freeC,p"deletestheelementofCpointedtobypandsetsptonil(C).Ineachcase,pispassedasavarparameterandmustbeavariableofthepointertypeofC.
Thekeywordforward(formbabove)isusedtospecifythatthetypeIdofthecollectionelementswillbegivenlaterinthecollection'sscope.Thelaterdeclarationmustappearatthesamelevel(inthesamelistofdeclarationsandstatements)astheoriginaldeclaration.Thisallowscycliccollections,forexample,whenacollectioncontainspointerstoanothercollection,whichinturncontainspointerstothefirstcollection.Inthiscase,the
Details
typeIdisthenameofthetypethathasnotyetbeendeclared;typeIdcannotbeuseduntilitsdeclarationappears.Acollectionwhoseelementtypeisforwardcanbeusedonlytodeclarepointerstoituntilthetype'sdeclarationisgiven.
Supposepointerqisequaltopointerpandtheelementtheypointtoisdeletedby"freeC,p".Wesayqisadanglingpointerbecauseitseemstolocateanelement,buttheelementnolongerexists.Adanglingpointerisconsideredtobeanuninitializedvalue.Itcannotbeassigned,compared,usedasacollectionsubscript,orpassedtofree.
Collectionscannotbeassigned,compared,passedasparameters,boundto,ornamedbyaconstdeclaration.Collectionsmustnotbedeclaredinprocedures,functions,recordsorunions.
Thesameshortformsforclassescanbealsousedforcollections.Theseincludeomissionofthecollectionnameinnew,freeandniltogetherwiththe^and->notations.Pointerstotypes(seepointer)canalsobeused,whichareoftenmoreconvenienttousethancollections.
ThesyntaxofacollectionDeclarationpresentedabovehasbeensimplifiedbyleavingoutuncheckedcollections.Withthisfeature,acollectionDeclarationisoneof:
(a)varid{,id}:[unchecked]collectionoftypeSpec
(b)varid{,id}:[unchecked]collectionofforwardtypeId
Whenuncheckedisspecified,thecheckingtoverifythatpointersactuallylocateelementsisremoved.Thischeckingisdoneusinga"timestamp"attachedtoeachelementandpointer,andmakingsurethatthesematchwitheachother.Whenuncheckedisspecified,theexecutionisdangerous,butfasterandsmaller,andthepointersbecomesimplymachineaddresses(asinC).
color textcolorgraphicsprocedure
Syntax color(Color:int)
Description
Thecolorprocedureisusedtochangethecurrentlyactivecolor.Thisisthecolorofcharactersthataretobeputonthescreen.Thealternatespellingiscolour.
Example
Thisprogramprintsoutthemessage"Bravo"threetimes,eachinadifferentcolor.
setscreen("graphics")
fori:1..3
color(i)
put"Bravo"
endfor
Execute
Example
Thisprogramprintsoutamessage.Thecolorofeachletterisdifferentfromtheprecedingletter.Forletternumberithecolornumberisimodmaxcolor+1.Thiscyclesrepeatedlythroughalltheavailablecolors.
setscreen("graphics")
constmessage:="HappyNewYear!!"
fori:1..length(message)
color(imodmaxcolor+1)
putmessage(i)..
endfor
Execute
Details
Seemaxcolorforthenumberofcolorsavailableinthevarious"graphics"modes.Thebackgroundcolorthattextappearsuponcanbesetusingthecolorbackprocedure.
Thescreenmustbeina"graphics"modetousethecolorprocedure.Seesetscreenfordetails.
Seealsocolorback,whatcolorandmaxcolor.
SeealsopredefinedunitText.
colorback backgroundcolorprocedure
Syntax colorback(Color:int)
DescriptionThecolorbackprocedureisusedtochangethecoloruponwhichtextappears.Thealternatespellingiscolourback.
Example
Whenthemessage"Greetings"isoutput,thebackgroundsurroundingeachletterwillbeinred.
setscreen("graphics")
colorback(red)
put"Greetings"..
Execute
Details
Whenanewlineisoutput,suchaswhentheputstatementdoesnotcontaina..attheend,therestofthelineisclearedfromcursortotherightedgeoftheoutputwindowinthetextbackgroundcolor.
Example
Thisprogramwillresultintheword"Hello"beingdisplayedinredonagreenbackgroundfollowedbytheword"Again"displayedinredonayellowbackground.Theyellowbackgroundstretchesacrossthewindow.
setscreen("graphics")
color(red)
colorback(green)
put"Hello"..%The".."attheendoflinestopsthenewline
colorback(yellow)
put"Again"%Therestofthelineisclearedinyellow
Execute
Example
Thisprogramdisplaystheletter'X'in16differentcolorson16differentbackgrounds.Notethattheletterisnotvisiblewhenthetextcolorandthebacgroundcolorarethesame
setscreen("graphics")
forrow:0..15
colorback(row)
forcolumn:0..15
color(column)
locate(row,column)
put"X"..
endfor
endfor
Execute
Details
Seemaxcolorforthenumberofbackgroundcolorsavailable.Thecolorinwhichtextappearscanbesetusingthecolorprocedure.
Thescreenmustbeina"graphics"modetousethecolorprocedure.Seesetscreenfordetails.
Seealsocolorandwhatcolorback.
SeealsopredefinedunitText.
comment remarkstatement
Description
Acommentisaremarktothereaderoftheprogram,whichthecomputerignores.ThemostcommonformofcommentinTuringstartswithapercentsign(%)andcontinuestotheendofthecurrentline;thisiscalledanend-of-linecomment.Thereisalsothebracketedcomment,whichbeginswiththe/*andendswith*/andwhichcancontinueacrosslineboundaries.
Example
%Thisisanend-of-linecomment
varx:real%Hereisanotherend-of-linecomment
consts:="Hello"
/*Hereisabracketedcommentthat
lastsfortwolines*/
constpi:=3.14159
DetailsIntheBASIClanguage,commentsarecalledremarksandstartwiththekeywordREM.InPascal,commentsarebracketedby(*and*).
comparisonOperator
Syntax
AcomparisonOperatorisoneof:
(a) < %Lessthan (b) > %Greaterthan (c) = %Equal (d) <= %Lessthanorequal;subset (e) >= %Greaterthanorequal;superset (f) not= %Notequal
Description
Acomparisonoperatorisplacedbetweentwovaluestodeterminetheirequalityorordering.Forexample,7>2istrueandsois"Adam"<"Cathy".Thecomparisonoperatorscanbeappliedtonumbersaswellastoenumeratedtypes.Theycanalsobeappliedtostringstodeterminetheorderingbetweenstrings(seethestringtypefordetails).Arrays,records,unionsandcollectionscannotbecompared.Booleanvalues(trueandfalse)canbecomparedonlyforequality(=andnot=);thesameistrueofpointervalues.Setvaluescanbecomparedusing<=and>=,whicharethesubsetandsupersetoperators.Thenot=operatorcanbewrittenas~=.
Comparisonsamongclassesisalsosupported(seeclass).IfCandDareclasses,C<=DmeansDisadescendantof(inheritsfrom)C.Seeclass.
Seealso
Seealsoinfixoperatorsandprecedenceofoperators.Seealsotheint,real,string,set,booleanandenumtypes.Seealsostringcomparison.
Concurrency
Description
Thisunitcontainsthepredefinedproceduresthatdealwithconcurrency.Itcontainsonepredefinedfunction,althoughconceptuallyitcontainsthreeothersubprograms.
AllroutinesintheConcurrencymoduleareexportedunqualified.(Thismeansyoucancalltheentrypointsdirectly.)
EntryPoints
empty* Returnstrueifnoprocessesarewaitingontheconditionqueue.
getpriority* Returnsthepriorityofthecurrentprocess.setpriority* Setsthepriorityofthecurrentprocess.
simutime Returnsthenumberofsimulatedtimeunitsthathavepassed.
*Partofthelanguage,conceptuallypartoftheConcurrencyunit.
Concurrency.empty PartofConcurrencymodule
Syntax empty(variableReference):boolean
Description
Theemptyfunctionisusedinaconcurrentprogram.ItreturnstrueifthevariableReference,whichmustbeaconditionvariable,hasnoprocesseswaitingforit.Processesjointhequeueofaconditionvariablebyexecutingthewaitstatement,andareawakenedbythesignalstatement.
Status
PartofthelanguageandonlyconceptuallypartoftheConcurrencyunit.
Thismeansthatyoucanonlycallthefunctionbycallingempty,notbycallingConcurrency.empty.
Seealso condition,wait,signal,forkandmonitor.
Concurrency.getpriority PartofConcurrencymodule
Syntax getpriority:nat
Description
Thegetpriorityfunctionreturnsthepriorityofanexecutingprocessinaconcurrentprogram.Asmallervaluemeansafasterspeed.
Status
PartofthelanguageandonlyconceptuallypartoftheConcurrencyunit.
Thismeansthatyoucanonlycallthefunctionbycallinggetpriority,notbycallingConcurrency.getpriority.
Seealso setpriority,forkandmonitor.
Concurrency.setpriority PartofConcurrencymodule
Syntax setpriority(p:nat)
Description
Thesetpriorityprocedureisusedtosetthepriorityofaprocessinaconcurrentprogram.Thisprioritycannotbecountedontoguaranteecriticalaccesstosharedvariables.Asmallervalueofpmeansincreasedspeed.Theargumenttosetprioritymaybelimitedtotherange0to2**15-1.
Status
PartofthelanguageandonlyconceptuallypartoftheConcurrencyunit.
Thismeansthatyoucanonlycallthefunctionbycallingsetpriority,notbycallingConcurrency.setpriority.
Seealso getpriority,forkandmonitor.
Concurrency.simutime PartofConcurrencymodule
Syntax simutime:int
DescriptionThesimutimefunctionreturnsthenumberofsimulatedtimeunitsthathavepassedsinceprogramexecutionbegan.
Details
Simulatedtimeonlypasseswhenallprocessareeitherpausedorwaiting.ThissimulatesthefactthatCPUtimeiseffectivelyinfinitelyfasterthan"pause"time.
Example
Thisprintsoutthesimulatedtimepassingbetweentwoprocesses.Thiswillprintout3,5,6,9,10,12,15,15,18,20,21,...
processp(t:int)
loop
pauset
putsimutime
endloop
endp
forkp(3)
forkp(5)
Execute
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallingsimutimeorbycallingConcurrency.simutime.
condition declaration
Syntax
AconditionDeclarationis:
varid{,id}:[arrayindexType{,indexType}of]
[conditionOption]condition
Description
Aconditionisessentiallyaqueueofsleepingprocesses.Itisusedinaconcurrentprogramtoallowprocessestoblockthemselves(bythewaitstatement)andlatertobeawakened(bythesignalstatement).Aconditionvariable,whichcanoccuronlyinsideamonitor(aspecialkindofmodulethathandlesconcurrency)ormonitorclass,isusedbythewaitandsignalstatementsforputtingprocessestosleepandlaterwakingthemup.
Example
Theprocessesusethismonitortogainexclusiveaccesstoaresource.Aprocesswantingtousetheresourcecallstherequestentrypointandisblockeduntiltheresourceisfree.Whentheprocessisfinishedwiththeresource,itcallsthereleaseentrypoint.Thismonitorisessentiallyabinarysemaphoreinwhichthesemaphore'sPoperationistherequestandtheVistherelease.
monitorresource
exportrequest,release
varavailable:boolean:=true
varnowAvailable:condition
procedurerequest
ifnotavailablethen
waitnowAvailable%Gotosleep
endif
assertavailable
available:=false%Allocateresource
endrequest
procedurerelease
assertnotavailable%Resourceisallocated
available:=true%Freetheresource
signalnowAvailable%Wakeuponeprocess
%Ifanyaresleeping
endrelease
endresource
processworker
loop
…
resource.request%Blockuntilavailable
…useresource…
resource.release
endloop
endworker
forkworker%Activateoneworker
forkworker%Activateanotherworker
Execute
AconditionOptionisoneof:
(a) priority (b) deferred (c) timeout
Thepriorityoptionrequiresthatthecorrespondingwaitstatementsincludepriorities.Options(b)and(c)declaredeferredconditions.Asignaltoadeferredconditioncausesthesignaledprocesstobecomereadytoenterthemonitorwhenthemonitorbecomesinactive.Thesignalingprocesscontinuesrunninginthemonitor.Asignaltoanimmediate(nondeferred)conditioncausesthesignaledprocesstobeginrunninginthemonitorimmediately.Thesignalingprocesswaitstore-enterthemonitorwhenthemonitorbecomesinactive.Allconditionsinadevicemonitormustbedeferred(ortimeout).
Atimeoutoptionmeansthesignalingisdeferredandthatan
Details extraparametertothewaitstatementmustgiveatimeoutinterval.Ifaprocesswaitslongerthanitsinterval,itisautomaticallysignaled.Bewarethattheemptyfunctioncanbenon-repeatablewhenappliedtotimeoutconditions.Forexample,empty(c)maynotbeequaltoempty(c)inasingleexpression.Inthecurrent(1999)versionofTuring,thetimefortimeoutsismeasuredinsimulationtimeratherthanrealtime.Seethepausestatement.
Conditionscannotbenamedastypes,cannotbecontainedinrecords,unionsorcollectionsandcannotbedeclaredinstatements(suchasbeginorloop)orinsubprograms.Theycanonlybedeclaredinmonitorsandmonitorclasses.
Thereisnoguaranteedorderofprogressamongawakeneddeferredprocesses,processessignalingimmediateconditions,andprocessesattemptingtoenteranactivemonitor.
NotethatconditionOptionmustprecedethekeywordcondition.
Seealsowaitandsignal.Seealsomonitorandfork.Seealsoempty.Seealsopause.
Config
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithgettingconfigurationinformationaboutthemachineandenvironmentonwhichtheprogramisbeingrun.Itexistsinordertoallowuserstoobtaininformationaboutthesystemthatmayonlybeavailableatruntime.
AllroutinesintheConfigmoduleareexportedqualified(andthusmustbeprefacedwith"Config.").
EntryPoints
Display Returnsinformationaboutthedisplaycurrentlyattached.
Lang Returnsinformationaboutthelanguageenvironmentthattheprogramiscurrentlyrunningwithin.
Machine Returnsinformationaboutthehardwareonwhichtheprogramisrunning.
Config.Display PartofConfigmodule
Syntax Config.Display(displayCode:int):int
Description
Config.Displayreturnsinformationaboutthedisplay(ordisplays)attachedtothecomputer.TheparameterdisplayCodedetermineswhatsortofinformationispassedback.displayCodehasanumberofpossiblevalues,allsummarizedbyasetofpredefinedconstants.
Atthetimeofthiswriting,thefollowingconstantsweredefined:
cdScreenHeight returntheheightofthescreeninpixels.cdScreenWidth returnthewidthofthescreeninpixels.
cdMaxNumColors returnthemaximumnumberofcolorssupportedbythedisplay.
cdMaxNumColours returnthemaximumnumberofcolorssupportedbythedisplay.
Execute
Example
Thisprogramprintsthescreenwidthandheight.
constwidth:int:=Config.Display(cdScreenWidth
constheight:int:=Config.Display(cdScreenHeight
put"Thescreenwidthis",width,"thescreenheightis",
Details
OntheMacintosh,it'spossibletohavemultipledisplaysattachedtoasinglecomputer.Togetinformationabouttheextradisplays,youcancallConfig.Displaywithanyofthefirstfourconstantsaboveplusone,two,three,etc.Thiswillreturntheheight,widthormaximumnumberofcolorsforthesecond,thirdandbeyonddisplays.
Example
ThisprogramprintsthescreenwidthandheightoftheseconddisplayonaMacintosh.
constwidth:int:=Config.Display(cdScreenWidth
constheight:int:=Config.Display(cdScreenHeight
put"Theseconddisplaysizeis",width,"x",
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingConfig.DisplaycallingDisplay.
Config.Lang PartofConfigmodule
Syntax Config.Lang(langCode:int):int
Description
Config.Langreturnsinformationaboutthelanguageandthelimitationsoftheimplementationthattheprogramiscurrentlyrunning.TheparameterlangCodedetermineswhatsortofinformationispassedback.langCodehasanumberofpossiblevalues,allsummarizedbyasetofpredefinedconstants.
Atthetimeofthiswriting,thefollowingconstantsweredefined:
clRelease returnthecurrentreleasenumberoftheenvironment(e.g.4.02=400).
clLanguageVersion returnthecurrentversionnumberofthelanguage(e.g.1.81=181).
clMaxNumStreams returnthemaximumnumberofI/Ostreams(usedbytheopenandclosestatements)thatcanbeopenedatonce.
clMaxNumDirStreams returnthemaximumnumberofdirectorystreamsthatcanbeopenedatonce.
clMaxNumRunTimeArgs returnthemaximumnumberofrun-timearguments.
Example
Thisprogramprintsthecurrentenvironmentversion.
constversion:int:=Config.Lang(clLanguageVersion
put"Thelanguageversionnumberis",version
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingConfig.LangnotbycallingLang.
Config.Machine PartofConfigmodule
Syntax Config.Machine(machineCode:int):int
Description
Config.Machinereturnsinformationaboutthemachinethattheprogramiscurrentlyrunningon.TheparametermachineCodedetermineswhatsortofinformationispassedback.machineCodehasanumberofpossiblevalues,allsummarizedbyasetofpredefinedconstants.
Atthetimeofthiswriting,thefollowingconstantsweredefined:
cmProcessor returnanencodingoftheprocessornumber.cmFPU return1ifthereisanFPUinstalled,0ifnot.
cmOS returnthecurrentversionnumberoftheoperatingsystem(e.g.6.07=607).
Example
ThisprogramprintswhetherthemachinehasanFPUornot.
ifConfig.Machine(cmFPU)=1then
put"ThemachinehasanFPUinstalled"
else
put"ThemachinedoesnothaveanFPUinstalled"
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingConfig.Machine,notbycallingMachine.
const constantdeclaration
Syntax
AconstantDeclarationis:
constid[:typeSpec]:=initializingValue
DescriptionAconstdeclarationcreatesanameidforavalue.
Example
constc:=3
consts:="Hello"%Thetypeofsisstring
constx:=sin(y)**2
consta:array1..3ofint:=init(1,2,3)
constb:array1..3ofint:=a
constc:array1..2,1..2ofint:=init(1,2,3,4)
%Soc(1,1)=1,c(1,2)=2,c(2,1)=3,c(2,2)=4
Details
Theinitializingvaluecanbeanarbitraryvalueorelsealistofitemsseparatedbycommasinsideinit(…).ThesyntaxofinitializingValueis:
a. expn b. init(initializingValue,initializingValue)
Eachinit(…)correspondstoanarray,recordorunionvaluethatisbeinginitialized.Thesemustbenestedforinitializationofnestedtypes.InthePascallanguage,constantsmusthavevaluesknownatcompiletime;Turinghasnosuchrestriction.
WhenthetypeSpecisomitted,thevariable'stypeistakentobethe(root)typeoftheinitializingexpression,forexample,intorstring.ThetypeSpeccannotbeomittedfordynamicarraysorwhentheinitializingvalueisoftheforminit(…).Thevaluesinsideinit(…)mustbeknownatcompiletime.
Thekeywordpervasivecanbeinsertedjustafterconst.Whenthisisdone,theconstantisvisibleinsideallsubconstructsoftheconstant'sscope.Withoutpervasiveisnotvisibleinsidemodules,monitorsorclassesunlessexplicitlyimported.Pervasiveconstantsneednotbeimported.Youcanabbreviatepervasiveasanasterisk(
Youcanalsooptionallyusetheregisterkeywordtorequestthattheconstantbeplacedinamachineregister.ThesyntaxforconstantDeclarationisactually:
const[pervasive][register]id[:typeSpec]:=
Inthecurrent(2002)implementation,programsareruninterpretivelyusingpseudo-code,whichhasnomachineregisters,andtheregisterkeywordisignored.Seealsoforrestrictionsontheuseofregisterconstants.
constantReference useofaconstant
Syntax
AconstantReferenceis:
constantId{componentSelector}
Description
InaTuringprogram,aconstantisdeclaredandgivenaname(constantId)andthenused.Eachuseiscalledaconstantreference.
Iftheconstantisanarray,recordorunion,itsparts(components)canbeselectedusingsubscriptsandfieldnames(usingcomponentSelectors).TheformofacomponentSelectorisoneof:
(a) (expn{,expn}) (b) .fieldId
Form(a)isusedforsubscripting(indexing)arrays.Thenumberofarraysubscriptsmustbethesameasinthearray'sdeclaration.Form(b)isusedforselectingafieldofarecordorunion.Componentselectorsareusedinthesamemannerasvariablereferences.SeevariableReferencefordetails.SeealsoconstdeclarationandexplicitConstant.
Example
varradius:real
constpi:=3.14159%Constantdeclaration
…
put"Areais:",pi*radius**2
%piisaconstantreference
cos cosinefunction(radians)
Syntax cos(r:real):real
DescriptionThecosfunctionisusedtofindthecosineofananglegiveninradians.Forexample,cos(0)is1.
Example
Thisprogramprintsoutthecosineofp/6,2p/6,3p/6,upto12p/6radians.
constpi:=3.14159
fori:1..12
constangle:=i*pi/6
put"Cosof",angle,"is",cos(angle)
endfor
Execute
Seealso
thesinandtanfunctionsforcalculatingsineandtangent.
thecosdfunctionwhichfindsthecosineofananglegivenindegrees.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
cosd cosinefunction(degrees)
Syntax cosd(r:real):real
DescriptionThecosdfunctionisusedtofindthecosineofananglegivenindegrees.Forexample,cosd(0)is1.
Example
Thisprogramprintsoutthecosineof30,60,90,upto360degrees.
fori:1..12
constangle:=i*30
put"Cosof",angle,"is",cosd(angle)
endfor
Execute
Seealso
thesindandtandfunctionsforcalculatingsineandtangent.
thecosfunctionwhichfindsthecosineofananglegiveninradians.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
date procedure
Syntax date(vard:string)
Description
Thedatestatementisusedtodeterminethecurrentdate.Variabledisassignedastringintheformat"ddmmmyy",wheremmmisthefirst3charactersofthemonth,e.g.,"Apr".Forexample,ifthedateisChristmas2002,dwillbesetto"25Dec02".
Example
Thisprogramgreetsyouandtellsyouthedate.
vartoday:string
date(today)
put"Greetings!!Thedatetodayis",today
Execute
Details
BewarnedthatTuringgetsthedatefromtheoperatingsystem.Ifthedateisisnotcorrectlysetintheoperatingsystem,thenthedateprocedurewillgiveincorrectresults.
Seealsodelay,clock,sysclock,wallclockandtimestatements.
SeealsopredefinedunitTime.
declaration createavariable
Syntax
Adeclarationisoneof:
(a) variableDeclaration (b) constantDeclaration (c) typeDeclaration (d) bindDeclaration (e) procedureDeclaration (f) functionDeclaration (g) moduleDeclaration (h) classDeclaration (i) processDeclaration (j) monitorDeclaration (k) conditionDeclaration
Description
Adeclarationcreatesanewname(ornames)foravariable,constant,type,procedure,function,module,class,process,monitor,orcondition.Thesenamesarecalledidentifiers,whereidistheabbreviationforidentifier.
Example
varwidth:int%Variabledeclaration
constpi:=3.14159%Constantdeclaration
typerange:0..150%Typedeclaration
proceduregreet%Proceduredeclaration
put"Helloworld"
endgreet
Ordinarily,eachnewnamemustbedistinctfromnamesthatarealreadyvisible;thatis,redeclarationisnotallowed.Therearecertainexceptionstothisrule,forexample,namesofparametersandfieldsofrecordscanbethesameasexistingvisiblevariables.Variablesdeclaredinsideasubprogram(aprocedureandfunction)areallowedtobethesameasvariablesglobalto
Details
(outsideof)thesubprogram.
Theeffectofadeclaration(itsscope)laststotheendoftheconstructinwhichthedeclarationoccurs;thiswillbetheendoftheprogram,theendofthesurroundingprocedure,functionormodule,theendofaloop,for,caseorbeginstatement,ortheendofthethen,elsif,orelseclauseofanifstatement,ortheendofthecasestatementalternative.
Anamemustbedeclaredbeforeitcanbeused;thisiscalledtheDBU(DeclarationBeforeUse)rule.Theexceptionstothisruleusethekeywordforward,asinimportlistsandincollectiondeclarations.
Adeclarationcanappearanyplaceastatementcanappear.ThisdiffersfromthePascallanguage,inwhichdeclarationsareallowedonlyatthebeginningoftheprogramoratthebeginningofaprocedureorfunction.Eachdeclarationcanoptionallybefollowedbyasemicolon(;).
Therearecertainrestrictionsontheplacementofdeclarations.Proceduresandfunctionscannotbedeclaredinsideotherproceduresandfunctionsnorinsidestatements(forexample,notinsideanifstatement).Abinddeclarationcannotappearattheouterlevelofeitherthemainprogramoramodule.Aconditiondeclarationcanappearonlyinsideamonitor.Processescannotbedeclaredinsideprocedures,functions,monitorsorclasses.Classescannotbedeclaredinsideclasses.However,modulesandmonitorscanbedeclaredinsideclassesandviceversa.Monitorscanbedeclaredinsidemodules,notviceversa.
deferred subprogramdeclaration
Syntax
AdeferredDeclarationis:
deferredsubprogramHeader
Description
Aprocedureorfunctionisdeclaredtobedeferredwhenyouwanttobeabletooverridethesubprograminanexpansion.Theprocedureorfunctionmustbeinamodule,monitororclass.
Example
Thedisplayprocedureisdeferredinthisclassofstackstoallowvariouswaysofgraphicallydisplayingthestackonthescreen:
classstack
exportpush,pop
…localdeclarations…
…declarationsofthepushandpopprocedures…
deferredproceduredisplay(howbig:int)
endstack
Anexpansiontothestackclasscangiveabodyfordisplay,asin:
classstackWithSimpleDisplay
bodyproceduredisplay%(howbig:int)
…graphicallydisplaythestackonthescreen…
enddisplay
endstackWithSimpleDisplay
Thefollowingcreatesastackthatcanbedisplayedanddisplaysit:
varp:^stackWithSimpleDisplay
newp
…
p->display(25)%Displaythestackonthescreen
Adeferredprocedureisresolvedbygivingitsbody.Thiscanbedoneinthescope(module,monitororclass)containingthedeferreddeclaration(followingthedeferreddeclaration)orinanyexpansionofthatscope.Onlyoneresolutionperscopeisallowed.Unresolvedsubprogramscanbecalled,buttheyimmediatelyabort.
Allexportedsubprogramsareimplicitlydeferredandcanbe
Details overriddeninexpansions.
Duringinitializationofamodule,monitororobjectofaclass,deferredsubprograms(includingexportedsubprograms)cannotbecalled.Thisrestrictionpreventsaccessinganobjectbeforeitisfullyinitialized.
Adeferreddeclarationmustnotappearinthemainprogram.
Seealsomodule,monitorandclass.Seealsoexportlist,importlist,inheritlist,implementlistandimplementbylist.
delay procedure
Syntax delay(duration:int)
DescriptionThedelaystatementisusedtocausetheprogramtopauseforagiventime.Thetimedurationisinmilliseconds.
Example
Thisprogramprintstheintegers1to10withaseconddelaybetweeneach.
fori:1..10
puti
delay(1000)%Pausefor1second
endfor
Execute
Details
OnAppleMacintoshes,thehardwareresolutionofdurationisinunitsof17milliseconds(1/60thofasecond).Forexample,delay(500)willdelaytheprogrambyabouthalfasecond,butmaybeoffbyasmuchas17milliseconds.
Seealsosound,clock,sysclock,wallclock,timeanddatestatements.
SeealsopredefinedunitTime.
Dir
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithdirectories.Youcanusethesesubprogramstolistthecontentsofdirectories,createdirectories,changedirectoriesandreturnthecurrentdirectory.
AllroutinesintheDirmoduleareexportedqualified(andthusmustbeprefacedwith"Dir.").
EntryPoints
Open Opensadirectorystreaminordertogetalistingofthedirectorycontents.
Get Getsthenextfilenameinthedirectorylisting.
GetLong Getsthenextfilenameandotherinformationinthedirectorylisting.
Close Closesthedirectorystream.Create Createsanewdirectory.Delete Deletesadirectory(mustbeempty).Change Changesthecurrentexecutiondirectory.Current Returnsthecurrentexecutiondirectory.Exists Returnswhetheradirectoryexists.
Details
PathnamesinTuringcanbeexpressedusingeitherforwardslashesorbackslashes.Forexample,Dir.Change("d:\\turingfiles\\assignment3")orDir.Change("d:/turingfiles/assignment3")arebothlegal.Notethatbackslashesmustbedoubledinstringliterals.The"."directoryrepresentthecurrentdirectory(asinDir.Open(".")),andthe".."directoryrepresentstheparentdirectory.Forexample,ifthecurrentexecutiondirectoryis"d:/turingfiles/assignment3",thenDir.Change("..")changesthecurrentexecutiondirectoryto"d:/turingfiles".
Seealso
Fileunitformoreexplanationofthedifferentwaysofspecifyingapathnameofafileordirectoryunderthedifferentoperatingsystems.
Dir.Change PartofDirmodule
Syntax Dir.Change(directoryPathName:string)
Description
Dir.ChangechangestheexecutiondirectorytothatspecifiedbytheparameterdirectoryPathName.ThisistheequivalentofdoingacdinUNIX.
UnderMicrosoftWindows,specifyingadriveinthedirectoryPathNameparametercausesthedrivetobecomethedefaultdrive(unliketheDOScdcommand).
Details
IftheDir.Changecallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramchangestothedirectorycalled/usr/westandthenliststhecurrentdirectory.
Dir.Change("/usr/west")
ifError.Last=eNoErrorthen
put"Directorychanged"
else
put"Didnotchangethedirectory."
put"Error:",Error.LastMsg
endif
put"Thecurrentexecutiondirectoryis",Dir.Current
Example
AnexampledemonstratingtheuseofseveraloftheDirsubprogramsisavailable.Inthisexample,adirectoryiscreated,afileiswrittentothedirectory,anattemptismadetodeletethedirectory,thefileisdeleted,andthenthedirectoryisdeleted.
ThisexampledemonstratestheuseofDir.Change,Dir.Current,Dir.Create,andDir.Delete.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDir.Change,notbycallingChange.
Dir.Close PartofDirmodule
Syntax Dir.Close(streamNumber:int)
Description
Dir.Closeispartofaseriesoffoursubprogramsthathelpusersgetdirectorylistings.Dir.CloseisusedtocloseadirectorystreamnumberopenedbyDir.Open.Afterthedirectorystreamnumberisclosed,itcannotbeusedwithDir.GetorDir.GetLong.
Details
IftheDir.Closecallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramprintsalistingofallthefilesinthedirectorydatafiles.
varstreamNumber:int
varfileName:string
streamNumber:=Dir.Open("datafiles")
assertstreamNumber>0
loop
fileName:=Dir.Get(streamNumber)
exitwhenfileName=""
putfileName
endloop
Dir.Close(streamNumber)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDir.Close,notbycallingClose.
Dir.Create PartofDirmodule
Syntax Dir.Create(directoryPathName:string)
Description
Dir.CreateisusedtocreatethedirectoryspecifiedbytheparameterdirectoryPathName.ThisistheequivalentofdoingamkdirinDOSorUNIX.OntheMacintosh,itcreatesafolder.
Details
IftheDir.Createcallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramcreatesthedirectorycalledinformation.
Dir.Create("information")
ifError.Last=eNoErrorthen
put"Directorycreated"
else
put"Didnotcreatethedirectory."
put"Error:",Error.LastMsg
endif
Example
AnexampledemonstratingtheuseofseveraloftheDirsubprogramsisavailable.Inthisexample,adirectoryiscreated,afileiswrittentothedirectory,anattemptismadetodeletethedirectory,thefileisdeleted,andthenthedirectoryisdeleted.
ThisexampledemonstratestheuseofDir.Change,Dir.Current,Dir.Create,andDir.Delete.
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingDir.Create,notbycallingCreate.
Dir.Current PartofDirmodule
Syntax Dir.Current:string
DescriptionDir.Currentreturnsthefullpathnameofthecurrentexecutiondirectory.ThisistheequivalentofdoingapwdinUNIX.
Details
IftheDir.Currentcallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramchangestothedirectorycalled/usr/westandthenliststhecurrentdirectory.
Dir.Change("/usr/west")
ifError.Last=eNoErrorthen
put"Directorychanged"
else
put"Didnotchangethedirectory."
put"Error:",Error.LastMsg
endif
put"Thecurrentexecutiondirectoryis",Dir.Current
Example
AnexampledemonstratingtheuseofseveraloftheDirsubprogramsisavailable.Inthisexample,adirectoryiscreated,afileiswrittentothedirectory,anattemptismadetodeletethedirectory,thefileisdeleted,andthenthedirectoryisdeleted.
ThisexampledemonstratestheuseofDir.Change,Dir.Current,Dir.Create,andDir.Delete.
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingDir.Current,notbycallingCurrent.
Dir.Delete PartofDirmodule
Syntax Dir.Delete(directoryPathName:string)
Description
Dir.DeleteisusedtodeletethedirectoryspecifiedbytheparameterdirectoryPathName.ThisistheequivalentofdoingarmdirinDOSorUNIX.OntheMacintosh,itremovesafolder.
Dir.Deletewillfailifitattemptsdeleteadirectorythathasfilesinit.
Details
IftheDir.Deletecallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramdeletesthedirectorycalledinformation.
Dir.Delete("information")
ifError.Last=eNoErrorthen
put"Directorydelete"
else
put"Didnotdeletethedirectory."
put"Error:",Error.LastMsg
endif
Example
AnexampledemonstratingtheuseofseveraloftheDirsubprogramsisavailable.Inthisexample,adirectoryiscreated,afileiswrittentothedirectory,anattemptismadetodeletethedirectory,thefileisdeleted,andthenthedirectoryisdeleted.
ThisexampledemonstratestheuseofDir.Change,Dir.Current,Dir.Create,andDir.Delete.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDir.Delete,notbycallingDelete.
Dir.Exists PartofDirmodule
Syntax Dir.Exists(directoryPathName:string):boolean
Description
Dir.ExistsreturnstrueifadirectorybythenameofdirectoryPathNameexists.ItwillreturnfalseifdirectoryPathNameisafile.
Details
IftheDir.Existsreturnsfalse,youcanexamineError.LastorError.LastMsgformoreinformation(i.e.whetherthepathfailedorthedirectorywassimplynotfound).
Example
Thefollowingprogramdeterminesifthedirectory"d:/usr/west"exists,andoutputsanerrormessageifitdoesnot.
ifDir.Exists("d:/usr/west")then
put"Directoryexists"
else
put"Directorydoesnotexists:",Error.LastMsg
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDir.Exists,notbycallingExists.
Dir.Get PartofDirmodule
Syntax Dir.Get(streamNumber:int):string
Description
Dir.Getispartofaseriesoffoursubprogramsthathelpusersgetdirectorylistings.Dir.Getisusedtogetthefilenamesinthedirectory.Eachtimethefunctioniscalled,itreturnsthenextfilenameinthedirectory.Thenamesarenotsorted.Whentherearenomorefilenamesinthedirectory,Dir.Getreturnstheemptystring.
Details
IftheDir.Getcallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramprintsalistingofallthefilesinthedirectorydatafiles.
varstreamNumber:int
varfileName:string
streamNumber:=Dir.Open("datafiles")
assertstreamNumber>0
loop
fileName:=Dir.Get(streamNumber)
exitwhenfileName=""
putfileName
endloop
Dir.Close(streamNumber)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDir.Get,
notbycallingGet.
Dir.GetLong PartofDirmodule
SyntaxDir.GetLong(streamNumber:int,varentryName:string varsize,attribute,fileTime:int)
Description
Dir.GetLongispartofaseriesoffoursubprogramsthathelpusersgetdirectorylistings.Dir.GetLongisusedtogetthenamesandassortedinformationofthefilesinthedirectory.Eachtimethefunctioniscalled,itreturnsthenameandinformationofthenextfileinthedirectory.Thenamesarenotsorted.Whentherearenomorefilenamesinthedirectory,Dir.GetLongreturnstheemptystringintheentryNameparameter.
Thesizeparameteristhesizeofthefileinbytes.Theattributeparameterhasitsindividualbitssetasfollows(theindividualbitscanbeextractedusingthebitsoperator):
Bit0attrDirsetto1ifentryisadirectory.
Bit1attrReadsetto1iftheprogramcanreadthefile.
Bit2attrWritesetto1iftheprogramcanwritethefile.
Bit3attrExecutesetto1iftheprogramcanexecutethefile.
Bit4attrHiddensetto1iftheentryifahiddenfile(PC,Mac).
Bit5attrSystemsetto1iftheentryisasystemfile(PConly).
Bit6attrVolumesetto1iftheentryisavolumename(PConly).
Bit7attrArchivesetto1iftheentryhasarchivebitset(PConly).
Theattr...constantsaredefinedintheDirunit.Theycorrespondtothevaluesofattributeifaspecifiedbitisset.Forexample,attrSystemisthevalueoftheattributeparameterifbit5issetto1.Youcanandororconstantstogetcombinationsofspecificfileattributes.
ThefileTimeisthetimeoflastmodificationofthefile.Itisreturnedasthenumberofsecondssince00:00:00GMT1/1/1970.Toconvertthistoa
string,useTime.SecDate
Details
IftheDir.GetLongcallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramprintsalistingofallthefilesinthedirectorydatafiles
varstreamNumber:int
varfileName:string
varsize,attribute,fileTime:int
streamNumber:=Dir.Open("datafiles")
assertstreamNumber>0
loop
Dir.GetLong(streamNumber,fileName,size,attribute,fileTime
exitwhenfileName=""
putfileName,"",Time.SecDate(fileTime)
endloop
Dir.Close(streamNumber)
Example
Thisprogramprintsalistingoftheattributesofallthefilesinthecurrentdirectory.
varstreamNumber:int
varfileName:string
varsize,attribute,fileTime:int
streamNumber:=Dir.Open(Dir.Current)
assertstreamNumber>0
loop
Dir.GetLong(streamNumber,fileName,size,attribute,fileTime
exitwhenfileName=""
putfileName,""..
if(attributeandattrDir)not=0then
put"Directory"..
endif
if(attributeandattrRead)not=0then
put"Readable"..
endif
if(attributeandattrWrite)not=0then
put"Writeable"..
endif
if(attributeandattrExecute)not=0then
put"Executable"..
endif
put""
endloop
Dir.Close(streamNumber)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDir.GetLongbycallingGetLong.
Dir.Open PartofDirmodule
Syntax Dir.Open(directoryPathName:string):int
Description
Dir.Openispartofaseriesoffoursubprogramsthathelpusersgetdirectorylistings.Dir.Openreturnsadirectorystreamnumberifthedirectorycouldbeopened.ThisstreamnumbercanbeusedtogetfilenamesandinformationusingtheDir.GetandDir.GetLongsubprograms.Aftergettingthelisting,theusershouldcallDir.Close.
Details
IftheDir.Opencallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramprintsalistingofallthefilesinthecurrentdirectory.
varstreamNumber:int
varfileName:string
streamNumber:=Dir.Open(Dir.Current)
assertstreamNumber>0
loop
fileName:=Dir.Get(streamNumber)
exitwhenfileName=""
putfileName
endloop
Dir.Close(streamNumber)
Execute
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
Dir.Open,notbycallingOpen.
div integertruncatingdivisionoperator
Syntax div
Description
Thedivoperatordividesonenumberbyanotherandproducestheintegerresult,truncatedinthedirectionofzero.Forexample,7div2produces3and-7div2produces-3.
Example
Inthisexample,eggCountisthetotalnumberofeggs.Thefirstputstatementdetermineshowmanydozeneggsthereare.Thesecondputstatementdetermineshowmanyextraeggstherearebeyondthelastdozen.
vareggCount:int
geteggCount
put"Youhave",eggCountdiv12,"dozeneggs"
put"Youhave",eggCountmod12,"leftover"
Execute
Seealso infixoperators,precedenceofoperatorsandthemodoperator.
Draw
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithdrawingpixelgraphicstothescreen.
AllroutinesintheDrawunitareexportedqualified(andthusmustbeprefacedwith"Draw.").
EntryPoints
Cls Clearsthescreentocolor0.Dot Drawsadot.Line Drawsaline.DashedLine Drawsadashedordottedline.ThickLine Drawsathickline.Box Drawsabox.FillBox Drawsafilledbox.Oval Drawsanoval.FillOval Drawsafilledoval.Arc Drawsanarc.FillArc Drawsafilledarcorawedge.Polygon Drawsapolygon.FillPolygon Drawsafilledpolygon.MapleLeaf Drawsamapleleaf.FillMapleLeaf Drawsafilledmapleleaf.Star Drawsastar.FillStar Drawsafilledstar.Fill Doesafloodfill.Text Drawstextasgraphics
Draw.Arc PartofDrawmodule
SyntaxDraw.Arc(x,y,xRadius,yRadius:int, initialAngle,finalAngle,Color:int)
Description
TheDraw.Arcprocedureisusedtodrawanarcwhosecenterisat(x,y).ThisisjustlikeDraw.Oval,exceptthatyoumustalsogivetwoangles,initialAngleandfinalAngle,whichdeterminewheretostartandstopdrawing.Zerodegreesis"threeo'clock",90degreesis"twelveo'clock",etc.ThehorizontalandverticaldistancesfromthecentertothearcaregivenbyxRadiusandyRadius.
Example
Thisprogramdrawsaquartercirclewhosecenteris(midx,midy)thecenterofthescreen,usingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.
View.Set("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
Draw.Arc(midx,midy,midx,midy,0,90,1)
Execute
DetailsThescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Arc,notbycallingArc.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Box PartofDrawmodule
Syntax Draw.Box(x1,y1,x2,y2,Color:int)
Description
TheDraw.Boxprocedureisusedtodrawaboxonthescreenwithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)usingthespecifiedColor.
Example
Thisprogramdrawsalargebox,reachingtoeachcornerofthescreenusingcolornumber12.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreenand(maxx,maxy)istherighttop.
View.Set("graphics")
Draw.Box(0,0,maxx,maxy,12)
Execute
Details
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Box,notbycallingBox.
View.Set,maxx,maxyandthevariousproceduresintheDraw
Seealso unit.
Draw.Cls PartofDrawmodule
Syntax Draw.Cls
DescriptionTheDraw.Cls(clearscreen)procedureisusedtoblanktheoutputwindowThecursorissettothetopleft(torow1,column1).
Details
TheDraw.Clsproceduresetsallpixelsintheoutputwindowtocolor0.InthiswayitdiffersfromtheclsandText.Clsprocedureswhichsetthescreentothetextbackgroundcolor.
Thescreenmustbein"graphics"mode.SeeView.Setfordetails.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Cls,notbycallingCls.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.DashedLine PartofDrawmodule
Syntax Draw.DashedLine(x1,y1,x2,y2,lineStyle,Color:int)
Description
TheDraw.DashedLineprocedureisusedtodrawadottedordashedlineonthescreenfrom(x1,y1)to(x2,y2)usingthespecifiedColor.
Therearefivepossiblelinestyles:drawSolidDrawsasolidline(sameasDraw.Line)drawDashDrawsadashedlinedrawDotDrawsadottedlinedrawDashDotDrawsalinethatalternatesdashesanddotsdrawDashDotDotDrawsalinethatalternatesdashanddot-dot
Example
ThisprogramdrawsalargeX,reachingtoeachcornerofthescreenintwodifferentcolors.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreen,(maxx,maxy)istherighttop,etc.
View.Set("graphics")
%Drawalineineachofthestyles.
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
DetailsThescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.DashedLine,notbycallingDashedLine.
Seealso View.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Dot PartofDrawmodule
Syntax Draw.Dot(x,y,Color:int)
Description
TheDraw.Dotprocedureisusedtocolorthedot(pixel)atlocation(x,y)usingthespecifiedColor.
Example
Thisprogramrandomlydrawsdotswithrandomcolors.Themaxx,maxyandmaxcolorfunctionsgivethemaximumx,yandcolorvalues.
View.Set("graphics")
varx,y,c:int
loop
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
c:=Rand.Int(0,maxcolor)%Randomcolor
Draw.Dot(x,y,c)
endloop
Execute
DetailsThescreenmustbeina"graphics"mode.Ifthescreenisnotina
"graphics"mode,anerrorwilloccur.SeeView.Setfordetails.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Dot,notbycallingDot.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Fill PartofDrawmodule
Syntax Draw.Fill(x,y:int,fillColor,borderColor:int)
Description
TheDraw.Fillprocedureisusedtocolorinafigurethatisonthescreen.Startingat(x,y),thefigureisfilledwithfillColortoasurroundingborderwhosecolorisborderColor.
Example
Thisprogramdrawsanovalwithxandyradiusof10inthecenterofthescreeninbrightgreen.Thentheovalisfilledwithred.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.
View.Set("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
Draw.Oval(midx,midy,10,10,brightgreen)
Draw.Fill(midx,midy,red,brightgreen)
Execute
Details
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
Draw.Fill,notbycallingFill.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.FillArc
SyntaxDraw.FillArc(x,y,xRadius,yRadius:int, initialAngle,finalAngle,Color:int)
Description
TheDraw.FillArcprocedureisusedtodrawafilledarcwhosecenterisat(x,y).Itthenfillsinthepie-shapedwedgeusingthespecifiedColor.Tooutlineafilledarc,useDraw.FillArcwiththeColorparametersettothefillcolorandthenDraw.ArcwiththeColorparametersettothebordercolor.ForinitialAngleandfinalAngle,whichdeterminetheedgesofthewedge,zerodegreesis"threeo'clock"and90degreesis"twelveo'clock",etc.ThehorizontalandverticaldistancesfromthecentertothearcaregivenbyxRadiusandyRadius.
Example
Thisprogramdrawsafilledsemicircle(actually,anapproximationtoasemicircle)whosecenteris(midx,0)thebottomcenterofthescreen,inbrightred.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.
View.Set("graphics")
constmidx:=maxxdiv2
Draw.FillArc(midx,0,maxy,maxy,0,180,brightred
Execute
Thescreenmustbeina"graphics"mode.SeetheView.Set
Details procedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.FillArc,notbycallingFillArc.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.FillBox
Syntax Draw.FillBox(x1,y1,x2,y2,Color:int)
Description
TheDraw.FillBoxprocedureisusedtodrawafilledboxonthescreenwithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)filledusingthespecifiedColor.Togetaboxoutlinedinadifferentcolor,useDraw.FillBoxwiththeColorparametersettothefillcolorandthencallDraw.BoxwiththeColorparametersettothebordercolor.
Example
Thisprogramwillfillthebottomhalfofthescreenwithcolor1andthenoutlineitincolor2.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreenand(maxx,maxy)istherighttop.
View.Set("graphics")
Draw.FillBox(0,0,maxx,maxydiv2,1)
Draw.Box(0,0,maxx,maxydiv2,2)
Execute
Details
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingDraw.FillBox,notbycallingFillBox.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.FillMapleLeaf
Syntax Draw.FillMapleLeaf(x1,y1,x2,y2,Color:int)
Description
TheDraw.FillMapleLeafprocedureisusedtodrawafilledmapleleafonthescreenboundedbyarectanglewithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)andfilledusingthespecifiedColor.Togetamapleleafoutlinedinadifferentcolor,useDraw.FillMapleLeafwiththeColorparametersettothefillcolorandthencallDraw.MapleLeafwiththeColorparametersettothebordercolor.Ify1isgreaterthany2,thenthemapleleafisdrawnupsidedown.
Example
Thisprogramwilldrawtwomapleleavesbesideeachother.Thefirstwillbeoutlinedinblackandfilledinbrightred.Thesecondmapleleafwillbeupsidedownandbothfilledandoutlinedingreen.
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
TheDraw.FillMapleLeafprocedureisusefulfordrawingthe
Details
Canadianflag.
Thescreenshouldbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.FillMapleLeaf,notbycallingFillMapleLeaf.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.FillOval
Syntax Draw.FillOval(x,y,xRadius,yRadius,Color:int)
Description
TheDraw.FillOvalprocedureisusedtodrawafilledovalwhosecenterisat(x,y).ThehorizontalandverticaldistancesfromthecentertotheovalaregivenbyxRadiusandyRadius.Togetanovaloutlinedinadifferentcolor,useDraw.FillOvalwiththeColorparametersettothefillcolorandthencallDraw.OvalwiththeColorparametersettothebordercolor.
Example
Thisprogramdrawsalargefilledovalthatjusttoucheseachedgeofthescreenusingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thecenteroftheovalisat(midx,midy),whichisthemiddleofthescreen.
View.Set("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
Draw.FillOval(midx,midy,midx,midy,1)
Execute
Details
Ideally,acircleisdrawnwhenxRadius=yRadius.
Thescreenmustbeina"graphics"mode.SeetheView.Set
procedurefordetails.Ifthescreenisnotina"graphics"mode,amerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.FillOval,notbycallingFillOval.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.FillPolygon
Syntax Draw.FillPolygon(x,y:array1..*ofint,n:int,Color:int)
Description
TheDraw.FillPolygonprocedureisusedtodrawafilledpolygonwithnpoints.Thepolygonisdescribedbythepoints(x(1),y(1))to(x(2),y(2))to(x(3),y(3))andsoonto(x(n),y(n)).ThepolygonwillbedrawnandfilledwithColor.
Togetanpolygonoutlinedinadifferentcolor,useDraw.FillPolygonwiththeColorparametersettothefillcolorandthencallDraw.PolygonwiththeColorparametersettothebordercolor.
Example
Thisprogramwillcreateafilledoctagonanddisplayitinbrightblueandthenoutlineitincyan.
View.Set("graphics")
varx:array1..8ofint:=init(100,100,135,185,
220,220,185,135)
vary:array1..8ofint:=init(100,150,185,185,
150,100,65,65)
Draw.FillPolygon(x,y,8,brightblue)
Draw.Polygon(x,y,8,cyan)
Execute
Details
ThePCallowsamaximumof256points.Aswell,Draw.FillPolygoncanfail(duetolackofmemory).Iffailureoccurs,itwilltrytodrawanoutlineofthepolygon.Ifthatalsofails,itwillnotdrawanything.
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,an
errorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.FillPolygon,notbycallingFillPolygon.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.FillStar PartofDrawmodule
Syntax Draw.FillStar(x1,y1,x2,y2,Color:int)
Description
TheDraw.FillStarprocedureisusedtodrawafilledfivepointedstaronthescreenboundedbyarectanglewithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)andfilledusingthespecifiedColor.Togetastaroutlinedinadifferentcolor,useDraw.FillStarwiththeColorparametersettothefillcolorandthencallDraw.StarwiththeColorparametersettothebordercolor.Ify1isgreaterthany2,thenthestarisdrawnupsidedown.
Example
Thisprogramwilldrawtwostarsbesideeachother.Thefirstwillbeoutlinedincolor1andfilledincolor2.Thesecondstarwillbeupsidedownandbothfilledandoutlinedincolor3.
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
TheDraw.FillStarprocedureisusefulfordrawingtheAmericanflag.
Details Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.FillStar,notbycallingFillStar.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Line PartofDrawmodule
Syntax Draw.Line(x1,y1,x2,y2,Color:int)
Description
TheDraw.Lineprocedureisusedtodrawalineonthescreenfrom(x1,y1)to(x2,y2)usingthespecifiedColor.
Example
ThisprogramdrawsalargeX,reachingtoeachcornerofthescreenusingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreen,(maxx,maxy)istherighttop,etc.
View.Set("graphics")
%Firstdrawalinefromtheleftbottomtorighttop
Draw.Line(0,0,maxx,maxy,1)
%Nowdrawalinefromthelefttoptorightbottom
Draw.Line(0,maxy,maxx,0,1)
Execute
Details
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Line,notbycallingLine.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.MapleLeaf PartofDrawmodule
Syntax Draw.MapleLeaf(x1,y1,x2,y2,Color:int)
Description
TheDraw.MapleLeafprocedureisusedtodrawamapleleafonthescreenboundedbyarectangledescribedbythebottomleftandtoprightcornersof(x1,y1)to(x2,y2)usingthespecifiedColor.Ify1isgreaterthany2,thenthemapleleafisdrawnupsidedown.
Example
Thisprogramwilldrawtwomapleleavesbesideeachother.Thefirstwillbeinredandthesecondmapleleafwillbeupsidedownandinyellow.
View.Set("graphics")
Draw.MapleLeaf(0,0,100,100,red)
Draw.MapleLeaf(150,100,250,0,yellow)
Execute
Details
TheDraw.MapleLeafprocedureisusefulfordrawingtheCanadianflag.
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.MapleLeaf,notbycallingMapleLeaf.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Oval PartofDrawmodule
Syntax Draw.Oval(x,y,xRadius,yRadius,Color:int)
Description
TheDraw.Ovalprocedureisusedtodrawanovalwhosecenterisat(x,y).ThehorizontalandverticaldistancesfromthecentertotheovalaregivenbyxRadiusandyRadius.
Example
Thisprogramdrawsalargeovalthatjusttoucheseachedgeofthescreeninmagenta.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thecenteroftheovalisat(midx,midy),whichisthemiddleofthescreen.
View.Set("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
Draw.Oval(midx,midy,midx,midy,magenta)
Execute
Details
Ideally,acircleisdrawnwhenxRadius=yRadius.Infact,theaspectratio(theratioofheighttowidthofpixelsdisplayedonthescreen)oftheIBMPCcompatiblesisnot1.0,sothisdoesnotdrawatruecircle.InCGAgraphicsmodethisratiois5to4.
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,an
errorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Oval,notbycallingOval.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Polygon PartofDrawmodule
Syntax Draw.Polygon(x,y:array1..*ofint,n:int,Color:int)
Description
TheDraw.Polygonprocedureisusedtodrawapolygonwithnpoints.AlineisdrawninColorfromthepoint(x(1),y(1))to(x(2),y(2))to(x(3),y(3))andsoon.Afterdrawingthelineto(x(n),y(n)),alinewillbedrawnbackto(x(1),y(1)),closingthepolygon.TheDraw.Polygonprocedureisequivalentto:
fori:1..n-1
Draw.Line(x(i),y(i),x(i+1),y(i+1),
endfor
Draw.Line(x(n),y(n),x(1),y(1),Color)
Example
Thisprogramwillcreateanoctagonanddisplayitincolor1.
View.Set("graphics")
varx:array1..8ofint:=init(100,100,135,185,
220,220,185,135)
vary:array1..8ofint:=init(100,150,185,185,
150,100,65,65)
Draw.Polygon(x,y,8,brightblue)
Execute
Details
TheIBMPClimitsDraw.Polygontoamaximumof256points.
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
Draw.Polygon,notbycallingPolygon.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Star PartofDrawmodule
Syntax Draw.Star(x1,y1,x2,y2,Color:int)
Description
TheDraw.Starprocedureisusedtodrawastaronthescreenboundedbyarectangledescribedbythebottomleftandtoprightcornersof(x1,y1)to(x2,y2)usingthespecifiedColor.Ify1isgreaterthany2thenthestarisdrawnupsidedown.
Example
Thisprogramwilldrawtwostarsbesideeachother.Thefirststarwillbeincolor1andthesecondstarwillbeupsidedownandincolor2.
View.Set("graphics")
Draw.Star(0,0,100,100,brightred)
Draw.Star(150,100,250,0,brightblue)
Execute
Details
TheDraw.StarprocedureisusefulfordrawingtheAmericanflag.
Thescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.Star,notbycallingStar.
SeealsoView.Set,maxx,maxyandthevariousproceduresintheDrawunit.
Draw.Text PartofDrawmodule
Syntax Draw.Text(txtStr:string,x,y,fontID,Color:int)
Description
Draw.Textisusedtoactuallydrawtextinaspecifiedfont.ThetextStrparametercontainsthestringtobedrawn.Thexandyparamtersarethelocationofthelowerlefthandcornerofthetexttobedisplayed.Theparameteristhenumberofthefontinwhichthetextistobedrawn.Theparameterisusedtospecifythecolorinwhichthetextistoappear.
Notethatthetextthatappearsiscompletelyunrelatedtothetextthatappearsusingput.Draw.Textisagraphicscommandandthusdoesnotuseoraffectthecursorlocation.
ThetextdrawnbytheDraw.Textproceduredoesnoterasethebackground.
Details
IfDraw.TextispassedaninvalidfontID,afatalerroroccurs.IftheDraw.Textcallfailsforother(non-fatal)reasonsthenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgastringwhichcontainsthetextualversionoftheerror.
DetailsDraw.TextisidenticaltoFont.Draw.Itisplacedhereforconsistencywithotherpixelgraphicsdrawingroutines.
Example
Theprogramdrawsaphraseinredsurroundedbyaboxinbrightblue.
varfont:int
font:=Font.New("serif:12")
assertfont1>0
varwidth:int:=Font.Width("Thisisinaseriffont",
varheight,ascent,descent,internalLeading:int
Font.Sizes(font,height,ascent,descent,internalLeading
Draw.Text("Thisisinaseriffont",50,30,font
Draw.Box(50,30+descent,50+width,30+height
Font.Free(font)
Execute
DetailsTousethesamefontasisusedbytheputstatement,usedefFontIDfontnumber.Thisfontdoesnothavetobecreatedorfreedbytheuser,andallowsaprogramtoquicklyplacetextinanylocationonthescreen.
Example
Theprogramdrawstwostringsinthedefaultfont(defFontID).
Draw.Text("DrawingHere",100,120,defFontID,
Draw.Text("andHere",180,90,defFontID,brightgreen
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.TextcallingText.
SeeAlso Fontmoduleformoreinformationaboutselectingthefonttobedisplayed.
Draw.ThickLine PartofDrawmodule
Syntax Draw.ThickLine(x1,y1,x2,y2,lineWidth,Color:int)
Description
TheDraw.ThickLineprocedureisusedtodrawalineonthescreenfrom(to(x2,y2)usingthespecifiedColor.
Example
ThisprogramdrawsalargeX,reachingtoeachcornerofthescreenintwodifferentcolors.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreen,(maxx,maxy)istherighttop,etc.
View.Set("graphics")
%Firstdrawalineof5pixelwidthfromtheleftbottomtorighttop
Draw.ThickLine(0,0,maxx,maxy,5,brightred)
%Nowdrawalineof5pixelwidthfromthelefttoptorightbottom
Draw.ThickLine(0,maxy,maxx,0,5,brightgreen)
Execute
DetailsThescreenmustbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingDraw.ThickLinecallingThickLine.
Seealso View.Set,maxx,maxyandthevariousproceduresintheDrawunit.
drawarc graphicsprocedure
Syntaxdrawarc(x,y,xRadius,yRadius:int, initialAngle,finalAngle,Color:int)
Description
Thedrawarcprocedureisusedtodrawanarcwhosecenterisat(x,y).Thisisjustlikedrawoval,exceptthatyoumustalsogivetwoangles,initialAngleandfinalAngle,whichdeterminewheretostartandstopdrawing.Zerodegreesis"threeo'clock",90degreesis"twelveo'clock",etc.ThehorizontalandverticaldistancesfromthecentertothearcaregivenbyxRadiusandyRadius.
Example
Thisprogramdrawsasemicircle(actually,anapproximationtoasemicircle)whosecenteris(midx,0)thebottomcenterofthescreen,usingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.
setscreen("graphics")
constmidx:=maxxdiv2
drawarc(midx,0,maxy,maxy,0,180,1)
Execute
Details
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,it
willautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawbox graphicsprocedure
Syntax drawbox(x1,y1,x2,y2,Color:int)
Description
Thedrawboxprocedureisusedtodrawaboxonthescreenwithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)usingthespecifiedColor.
Example
Thisprogramdrawsalargebox,reachingtoeachcornerofthescreenusingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreenand(maxx,maxy)istherighttop.
setscreen("graphics")
drawbox(0,0,maxx,maxy,1)
Execute
Details
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawdot graphicsprocedure
Syntax drawdot(x,y,Color:int)
Description
Thedrawdotprocedureisusedtocolorthedot(pixel)atlocation(x,y)usingthespecifiedColor.
Example
Thisprogramrandomlydrawsdotswithrandomcolors.Themaxx,maxyandmaxcolorfunctionsgivethemaximumx,yandcolorvalues.
setscreen("graphics")
varx,y,c:int
loop
randint(x,0,maxx)%Randomx
randint(y,0,maxy)%Randomy
randint(c,0,maxcolor)%Randomcolor
drawdot(x,y,c)
endloop
Execute
Thescreenshouldbeina"graphics"mode.Ifthescreenisnotin
Details a"graphics"mode,itwillautomaticallybesetto"graphics"mode.Seesetscreenfordetails.
Example
Thisprogramdrawsalineofdotsthatbounceoffthe“sides”ofthescreen.Italsodemonstratesthatyoucanuserealcoordinatestostoreposition(x,y),aslongasyouconvertthecoordinatestointvaluesusingroundinthedrawdotcall.
varx,y:real
vardx,dy:real
varclr: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)modmaxcolor
x:=x+dx
y:=y+dy
ifx<=0orx>=maxxthen
dx:=-dx
endif
ify<=0ory>=maxythen
dy:=-dy
endif
endloop
Execute
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfill graphicsprocedure
Syntax drawfill(x,y:int,fillColor,borderColor:int)
Description
Thedrawfillprocedureisusedtocolorinafigurethatisonthescreen.Startingat(x,y),thefigureisfilledwithfillColortoasurroundingborderwhosecolorisborderColor.
Example
Thisprogramdrawsanovalwithxandyradiusof10inthecenterofthescreenusingcolor1.Thentheovalisfilledwithcolor2.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.
setscreen("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
drawoval(midx,midy,10,10,1)
drawfill(midx,midy,2,1)
Execute
Details
ThemeaningoftheColornumberdependsonthecurrentpalette;seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Warning:InTuringforIBMPCcompatibles,drawfillfailstocompletelyfillinsomecomplicatedfiguresthatcontain"islands"withinthemsurroundedbytheborderColor.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfillarc graphicsprocedure
Syntaxdrawfillarc(x,y,xRadius,yRadius:int, initialAngle,finalAngle,Color:int)
Description
Thedrawfillarcprocedureisusedtodrawafilledarcwhosecenterisat(x,y).Itthenfillsinthepie-shapedwedgeusingthespecifiedColor.Tooutlineafilledarc,usedrawfillarcwiththeColorparametersettothefillcolorandthendrawarcwiththeColorparametersettothebordercolor.ForinitialAngleandfinalAngle,whichdeterminetheedgesofthewedge,zerodegreesis"threeo'clock"and90degreesis"twelveo'clock",etc.ThehorizontalandverticaldistancesfromthecentertothearcaregivenbyxRadiusandyRadius.
Example
Thisprogramdrawsafilledsemicircle(actually,anapproximationtoasemicircle)whosecenteris(midx,0),thebottomcenterofthescreen,usingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.
setscreen("graphics")
constmidx:=maxxdiv2
drawfillarc(midx,0,maxy,maxy,0,180,1)
Execute
OnthePC,drawfillarcfillsthepie-shapedwedgebyusinga
Details
"flood"fillandisthussubjecttoalltheconditionsofafloodfill.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfillbox graphicsprocedure
Syntax drawfillbox(x1,y1,x2,y2,Color:int)
Description
Thedrawfillboxprocedureisusedtodrawafilledboxonthescreenwithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)filledusingthespecifiedColor.Togetaboxoutlinedinadifferentcolor,usedrawfillboxwiththeColorparametersettothefillcolorandthencalldrawboxwiththeColorparametersettothebordercolor.
Example
Thisprogramwillfillthebottomhalfofthescreenwithcolor1andthenoutlineitincolor2.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreenand(maxx,maxy)istherighttop.
setscreen("graphics")
drawfillbox(0,0,maxx,maxydiv2,1)
drawbox(0,0,maxx,maxydiv2,2)
Execute
Details
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfillmapleleaf graphicsprocedure
Syntax drawfillmapleleaf(x1,y1,x2,y2,Color:int)
Description
Thedrawfillmapleleafprocedureisusedtodrawafilledmapleleafonthescreenboundedbyarectanglewithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)andfilledusingthespecifiedColor.Togetamapleleafoutlinedinadifferentcolor,usedrawfillmapleleafwiththeColorparametersettothefillcolorandthencalldrawmapleleafwiththeColorparametersettothebordercolor.Ify1isgreaterthany2,thenthemapleleafisdrawnupsidedown.
Example
Thisprogramwilldrawtwomapleleavesbesideeachother.Thefirstwillbeoutlinedincolor1andfilledincolor2.Thesecondmapleleafwillbeupsidedownandbothfilledandoutlinedincolor3.
setscreen("graphics")
drawfillmapleleaf(0,0,100,100,1)
drawmapleleaf(0,0,100,100,2)
drawfillmapleleaf(150,100,250,0,3)
Execute
Thedrawfillmapleleafprocedureisusefulfordrawingthe
Details
Canadianflag.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfilloval graphicsprocedure
Syntax drawfilloval(x,y,xRadius,yRadius,Color:int)
Description
Thedrawfillovalprocedureisusedtodrawafilledovalwhosecenterisat(x,y).ThehorizontalandverticaldistancesfromthecentertotheovalaregivenbyxRadiusandyRadius.Togetanovaloutlinedinadifferentcolor,usedrawfillovalwiththeColorparametersettothefillcolorandthencalldrawovalwiththeColorparametersettothebordercolor.
Example
Thisprogramdrawsalargefilledovalthatjusttoucheseachedgeofthescreenusingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thecenteroftheovalisat(midx,midy),whichisthemiddleofthescreen.
setscreen("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
drawfilloval(midx,midy,midx,midy,1)
Execute
Ideally,acircleisdrawnwhenxRadius=yRadius.Infact,theaspectratio(theratioofheighttowidthofpixelsdisplayedonthescreen)oftheIBMPCcompatiblesisnot1.0,sothisdoesnot
Details
drawatruecircle.InCGAgraphicsmodethisratiois5to4.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfillpolygon graphicsprocedure
Syntax drawfillpolygon(x,y:array1..*ofint,n:int,Color:int)
Description
Thedrawfillpolygonprocedureisusedtodrawafilledpolygonwithnpoints.Thepolygonisdescribedbythepoints(x(1),y(1))to(x(2),y(2))to(x(3),y(3))andsoonto(x(n),y(n)).ThepolygonwillbedrawnandfilledwithColor.
Togetanpolygonoutlinedinadifferentcolor,usedrawfillpolygonwiththeColorparametersettothefillcolorandthencalldrawpolygonwiththeColorparametersettothebordercolor.
Example
Thisprogramwillcreateafilledoctagonanddisplayitincolor1andthenoutlineitincolor3.
setscreen("graphics")
varx:array1..8ofint:=init(100,100,135,185,
220,220,185,135)
vary:array1..8ofint:=init(100,150,185,185,
150,100,65,65)
drawfillpolygon(x,y,8,1)
drawpolygon(x,y,8,3)
Execute
Details
ThePCallowsamaximumof256points.Aswell,drawfillpolygoncanfail(duetolackofmemory).Iffailureoccurs,itwilltrytodrawanoutlineofthepolygon.Ifthatalsofails,itwillnotdrawanything.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawfillstar graphicsprocedure
Syntax drawfillstar(x1,y1,x2,y2,Color:int)
Description
Thedrawfillstarprocedureisusedtodrawafilledfivepointedstaronthescreenboundedbyarectanglewithbottomleftandtoprightcornersof(x1,y1)to(x2,y2)andfilledusingthespecifiedColor.Togetastaroutlinedinadifferentcolor,usedrawfillstarwiththeColorparametersettothefillcolorandthencalldrawstarwiththeColorparametersettothebordercolor.Ify1isgreaterthany2,thenthestarisdrawnupsidedown.
Example
Thisprogramwilldrawtwostarsbesideeachother.Thefirstwillbeoutlinedincolor1andfilledincolor2.Thesecondstarwillbeupsidedownandbothfilledandoutlinedincolor3.
setscreen("graphics")
drawfillstar(0,0,100,100,1)
drawstar(0,0,100,100,2)
drawfillstar(150,100,250,0,3)
Execute
ThedrawfillstarprocedureisusefulfordrawingtheAmericanflag.
DetailsThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawline graphicsprocedure
Syntax drawline(x1,y1,x2,y2,Color:int)
Description
Thedrawlineprocedureisusedtodrawalineonthescreenfrom(x1,y1)to(x2,y2)usingthespecifiedColor.
Example
ThisprogramdrawsalargeX,reachingtoeachcornerofthescreenusingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thepoint(0,0)istheleftbottomofthescreen,(maxx,maxy)istherighttop,etc.
setscreen("graphics")
%Firstdrawalinefromtheleftbottomtorighttop
drawline(0,0,maxx,maxy,1)
%Nowdrawalinefromthelefttoptorightbottom
drawline(0,maxy,maxx,0,1)
Execute
Details
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawmapleleaf graphicsprocedure
Syntax drawmapleleaf(x1,y1,x2,y2,Color:int)
Description
Thedrawmapleleafprocedureisusedtodrawamapleleafonthescreenboundedbyarectangledescribedbythebottomleftandtoprightcornersof(x1,y1)to(x2,y2)usingthespecifiedColor.Ify1isgreaterthany2,thenthemapleleafisdrawnupsidedown.
Example
Thisprogramwilldrawtwomapleleavesbesideeachother.Thefirstwillbeincolor1andthesecondmapleleafwillbeupsidedownandincolor2.
setscreen("graphics")
drawmapleleaf(0,0,100,100,1)
drawmapleleaf(150,100,250,0,2)
Execute
Details
ThedrawmapleleafprocedureisusefulfordrawingtheCanadianflag.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawoval graphicsprocedure
Syntax drawoval(x,y,xRadius,yRadius,Color:int)
Description
Thedrawovalprocedureisusedtodrawanovalwhosecenterisat(x,y).ThehorizontalandverticaldistancesfromthecentertotheovalaregivenbyxRadiusandyRadius.
Example
Thisprogramdrawsalargeovalthatjusttoucheseachedgeofthescreenusingcolornumber1.Themaxxandmaxyfunctionsareusedtodeterminethemaximumxandyvaluesonthescreen.Thecenteroftheovalisat(midx,midy),whichisthemiddleofthescreen.
setscreen("graphics")
constmidx:=maxxdiv2
constmidy:=maxydiv2
drawoval(midx,midy,midx,midy,1)
Execute
Details
Ideally,acircleisdrawnwhenxRadius=yRadius.Infact,theaspectratio(theratioofheighttowidthofpixelsdisplayedonthescreen)oftheIBMPCcompatiblesisnot1.0,sothisdoesnotdrawatruecircle.InCGAgraphicsmodethisratiois5to4.
ThemeaningoftheColornumberdependsonthecurrentpalette.
Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawpic graphicsprocedure
Syntax drawpic(x,y:int,buffer:array1..*ofint,picmode:int)
Description
Thedrawpicprocedureisusedtocopyofarectangularpictureontothescreen.Theleftbottomofthepictureisplacedat(x,y).Inthecommoncase,thebufferwasinitializedbycallingtakepic.Thevaluesofpicmodeare:
0:Copyactualpictureonscreen. 1:CopypicturebyXORingitontothescreen.
XORingapictureontothescreentwiceleavesthescreenasitwas(thisisaconvenientwaytomoveimagesforanimation).XORingapictureontoabackgroundeffectivelysuperimposesthepictureontothebackground.
Details
Seetakepicforanexampleoftheuseofdrawpicandforfurtherinformationaboutbuffersfordrawingpictures.
Thescreenmustbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,anerrorwilloccur.
Details
Thedrawpic,takepic,andsizepicsubprogramshavebeenmadeobsoletebythesubprogramsPic.DrawandPic.NewofthePicmodule.Usersarestronglysuggestedtousethoseroutinesinstead.ThePicmodulealsocontainssubprogramstoloadimagesfromfiles.
Seealso
takepicandsizepic.Seealsosetscreen,maxx,maxyandthevariousdraw…procedures.
SeealsopredefinedunitDrawandPic.
drawpolygon graphicsprocedure
Syntax drawpolygon(x,y:array1..*ofint,n:int,Color:int)
Description
Thedrawpolygonprocedureisusedtodrawapolygonwithnpoints.AlineisdrawninColorfromthepoint(x(1),y(1))to(x(2),y(2))to(x(3),y(3))andsoon.Afterdrawingthelineto(x(n),y(n)),alinewillbedrawnbackto(x(1),y(1)),closingthepolygon.Thedrawpolygonprocedureisequivalentto:
fori:1..n-1
drawline(x(i),y(i),x(i+1),y(i+1),
endfor
drawline(x(n),y(n),x(1),y(1),Color)
Example
Thisprogramwillcreateanoctagonanddisplayitincolor1.
setscreen("graphics")
varx:array1..8ofint:=init(100,100,135,185,
220,220,185,135)
vary:array1..8ofint:=init(100,150,185,185,
150,100,65,65)
drawpolygon(x,y,8,1)
Execute
Details
TheIBMPClimitsdrawpolygontoamaximumof256points.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
drawstar graphicsprocedure
Syntax drawstar(x1,y1,x2,y2,Color:int)
Description
Thedrawstarprocedureisusedtodrawastaronthescreenboundedbyarectangledescribedbythebottomleftandtoprightcornersof(x1,y1)to(x2,y2)usingthespecifiedColor.Ify1isgreaterthany2,thenthestarisdrawnupsidedown.
Example
Thisprogramwilldrawtwostarsbesideeachother.Thefirstwillbeincolor1andthesecondstarwillbeupsidedownandincolor2.
setscreen("graphics")
drawstar(0,0,100,100,1)
drawstar(150,100,250,0,2)
Execute
Details
ThedrawstarprocedureisusefulfordrawingtheAmericanflag.
ThemeaningoftheColornumberdependsonthecurrentpalette.Seethepalettestatement.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,it
willautomaticallybesetto"graphics"mode.
Seealso setscreen,maxx,maxyandthevariousdraw…procedures.
empty conditionfunction
Syntax empty(variableReference):boolean
Description
Theemptyfunctionisusedinaconcurrentprogram.ItreturnstrueifthevariableReference,whichmustbeaconditionvariable,hasnoprocesseswaitingforit.Processesjointhequeueofaconditionvariablebyexecutingthewaitstatement,andareawakenedbythesignalstatement.
Seealsocondition,wait,signal,forkandmonitor.
SeealsopredefinedunitConcurrency.
enum enumeratedtype
Syntax
AnenumeratedTypeis:
enum(id{,id})
Description
Thevaluesofanenumeratedtypearedistinctandincreasing.Theycanbethoughtofasthevalues0,1,2andsoon,butarithmeticisnotallowedwiththesevalues.
Exampletypecolor:enum(red,green,blue)
varc:color:=color.red
vard:color:=succ(c)%dbecomesgreen
Details
Eachvalueofanenumeratedtypeisthenameofthetypefollowedbyadotfollowedbytheelement'sname,forexample,color.red.Enumeratedvaluescanbecomparedforequalityandforordering.Thesuccandpredfunctionscanbeusedtofindthevaluefollowingorprecedingagivenenumeratedvalue.Theordfunctioncanbeusedtofindtheenumerationpositionofavalue,forexample,ord(color.red)is0.
Enumeratedtypescannotbecombinedwithintegersorwithotherenumeratedtypes.
Details
Itisillegaltodeclarean"anonymous"enum.Theonlylegaldeclarationforanenumisinatypedeclaration.Forexample,thefollowingisnowillegal:
vara:arrayenum(red,green,blue)ofint
Giventhatthereisno(easy)wayofgeneratinganenumvaluewithoutitbeinganamedtype,thisshouldnotimpactanybutthemostbizarrecode.
The"put"and"get"statementsemanticshavebeenexpandedtoallowput'sandget'sofenumvalues.Thevaluesprintedandinputaretheelementnamesthemselves,casesensitive.Forexample,
Details for
typecolors:enum(red,green,blue)
varc:colors:=colors.red
putc%outputs"red"(withoutthequotes)
enumeratedValue enumeratedvalue
Syntax
AnenumeratedValueis:
enumeratedTypeId.enumeratedId
Description
Thevaluesofanenumeratedtypearewrittenasthetypename(enumeratedTypeId)followedbyadotfollowedbyoneoftheenumeratedvaluesofthetype(enumeratedId).
Example
Inthisexample,color.redisanenumeratedValue.
typecolor:enum(red,green,blue)
varc:color:=color.red
vard:color:=succ(c)%dbecomesgreen
Details
Theabovedescriptionhasbeensimplifiedbyignoringthepossibilitythattheenumtypecanbeexportedfromamodule.Ifthisisthecase,eachuseofoneoftheenumeratedvaluesoutsideofmoduleMmustbeprecededbythemodulenameandadot,asinM.color.red.
Seealso theenumtypeandexplicitConstant.
eof end-of-filefunction
Syntax eof(streamNumber:int):boolean
Description
Theeof(endoffile)functionisusedtodetermineifthereisanymoreinput.Itreturnstruewhentherearenomorecharacterstoberead.Theparameteranditsparenthesesareomittedwhenreferringtothestandardinput(usuallythisisthekeyboard);otherwisetheparameterspecifiesthenumberofastream.Thestreamnumberhasbeendetermined(inmostcases)byanopenstatement.
Example
Thisprogramreadsandoutputsallthelinesinthefilecalled"info".
varline:string
varfileNumber:int
open:fileNumber,"info",get
loop
exitwheneof(fileNumber)
get:fileNumber,line:*
putline
endloop
Execute
Details
Seealsothedescriptionofthegetstatement,whichgivesmoreexamplesoftheuseofeof.Seealsotheopenandreadstatements.
Whentheinputisfromthekeyboard,theusercansignalend-of-filebytypingcontrol-ZonaPC(orcontrol-DonUNIX).Ifaprogramtestsforeofonthekeyboard,andtheuserhasnottypedcontrol-Z(orcontrol-D)andtheuserhastypednocharacters
beyondthosethathavebeenread,theprogrammustwaituntilthenextcharacteristyped.Oncethischaracteristyped,theprogramknowswhetheritisattheendoftheinput,andreturnsthecorrespondingtrueorfalsevalueforeof.
Example
AnotherexampleisavailablethatillustratesdetectingEOFfromthekeyboard.
equivalence oftypes
Description
Twotypesareequivalenttoeachotheriftheyareessentiallythesametypes(theexactrulesaregivenbelow).Whenavariableispassedtoavarformalparameter,thetypesofthevariableandtheformalparametermustbeequivalentbecausetheyareeffectivelythesamevariable.Whenanexpressionisassignedtoavariable,theirtypesmustbeequivalent,exceptforspecialcases.Forexample,Turingallowsyoutoassignanintegerexpressiontoarealvariable(seeassignabilityfordetails).
Example
varj:int
varb:array1..25ofstring
typepersonType:
record
age:int
name:string(20)
endrecord
procedurep(vari:int,vara:array1..25of
varr:personType)
…bodyofprocedurep,whichmodifieseachofi,
endp
vars:personType
p(j,b,s)%Procedurecalltop
%iandjhavetheequivalenttypeint
%Arraysaandbhaveequivalenttypes
%Recordsrandshaveequivalenttypes
Twotypesaredefinedtobeequivalentiftheyare:
(a) thesamestandardtype(int,real,booleanorstring),(b) subrangeswithequalfirstandlastvalues,
(c) arrayswithequivalentindextypesandequivalentcomponenttypes,(d) stringswithequalmaximumlengths,(e) setswithequivalentbasetypes,or
Details
(f) pointerstothesamecollection;inaddition,
(g) adeclaredtypeidentifierisalsoequivalenttothetypeitnames(andtothetypenamedbythattype,ifthattypeisanamedtype,etc.)
(h) bothchar,(i) bothchar(n)withthesamelength,
(j) bothproceduretypes,withcorrespondingequivalentparametertypesandcorrespondingvarornon-varoftheparameters,
(k) bothfunctiontypes,withcorrespondingequivalentparametertypesandcorrespondingvarornon-varoftheparametersandequivalentresulttypes,
(l) bothpointertypestothesameclassorequivalenttypeandbotharecheckedorunchecked.
Eachseparateinstanceofarecord,unionorenumeratedtype(writtenoutusingoneofthekeywordsrecord,unionorenum)createsadistincttype,equivalenttonoothertype.Bycontrast,separateinstancesofarrays,strings,subrangesandsetsareconsideredequivalentiftheirpartsareequalandequivalent.
OpaquetypeT,exportedfromamodule,monitororclassMasopaque,isaspecialcaseofequivalence.OutsideofMthistypeiswrittenM.T,andisconsideredtobedistinctfromallothertypes.Bycontrast,iftypeUisexportednon-opaque,theusualrulesofequivalenceapply.TheparameterorresulttypeofanexportedprocedureorfunctionoranexportedconstantisconsideredtohavetypeM.ToutsideofMiftheitemisdeclaredusingthetypeidentifierT.OutsideofM,theopaquetypecanbeassigned,butnotcompared.
Itisnotrequiredthatsubprogramtypeshavethesamenamesandparameternamestobeequivalent.Theyalsodonotrequirethesamefactoringofparametersacrosstheirtypes,asini,j:intinsteadofi:int,j:int.
erealstr real-to-stringfunction
Syntaxerealstr(r:real, width,fractionWidth,exponentWidth:int):string
Description
Theerealstrfunctionisusedtoconvertarealnumbertoastring;forexample,erealstr(2.5e1,10,3,2)="b2.500e+01"wherebrepresentsablank.Thestring(includingexponent)isanapproximationtor,paddedontheleftwithblanksasnecessarytoalengthofwidth.
Thewidthmustbeanon-negativeintvalue.Ifthewidthparameterisnotlargeenoughtorepresentthevalueofr,itisimplicitlyincreasedasneeded.
ThefractionWidthparameteristhenon-negativenumberoffractionaldigitstobedisplayed.Thedisplayedvalueisroundedtothenearestdecimalequivalentwiththisaccuracy.Inthecaseofatie,thevalueisroundedtothelargerofthetwovalues.
TheexponentWidthparametermustbenon-negativeandgivethenumberofexponentdigitstobedisplayed.IfexponentWidthisnotlargeenoughtorepresenttheexponent,morespaceisusedasneeded.Thestringreturnedbyerealstrisoftheform:
{blank}[-]digit.{digit}esigndigit{digit}
wheresignisaplusorminussign.Theleftmostdigitisnon-zero,unlessallthedigitsarezeros.
Theerealstrfunctionapproximatestheinverseofstrreal,althoughround-offerrorskeepthesefrombeingexactinverses.
Seealso frealstr,realstr,strreal,intstrandstrintfunctions.
Error
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwitherrorsreturnedfromotherpredefinedsubprograms.
AllroutinesintheErrorunitareexportedqualified(andthusmustbeprefacedwith"Error.").
TheconstantsrepresentingthepossibleerrorsreturnedbythismodulecanbefoundintheErrorNummodule.
EntryPoints
Last Returnsthe(integer)errorcodeproducedbythelastcalltoapredefinedsubprogram.
LastMsg Returnstheerrorstringproducedbythelastcalltoapredefinedsubprogram.
LastStr Returnsthestringversionoftheerrorconstantproducedbythelastcalltoapredefinedsubprogram.
Msg Returnsthestringthatcorrespondstoaspecifiederrorcode.
Str Returnsthestringversionoftheerrorconstantthatcorrespondstoaspecifiederrorcode.
Trip Thiscausesthespecifiederrorcodetobeset.
TripMsg Thiscausesthespecifiederrorcodeanderrormessagetobeset.
Halt Thiscausesexecutiontohaltwiththespecifiederrormessage.
Error.Last PartofErrormodule
Syntax Error.Last:int
Description
Error.Lastisafunctionthatreturnstheerrorcodesetbythelastcalledpredefinedsubprogram.Ifthereisnoerror,thenitreturnseNoError(whichis0).Ifthereisanerror,youcanuseError.LastMsgtoobtainatextualformoftheerrororError.LastStrtoobtainastringversionoftheerrorconstant.
ThefactthatError.LastisnoteNoErrordoesnotnecessarilymeanthatthepreviouspredefinedfunctionfailedorfailedcompletely.Error.Lastalsoreturnsanumberofwarningcodes.Forexample,ifauserspecifiesanumberlargerthanmaxcolorforthecolorparameteroftheDraw.Lineprocedure,thelineisstilldrawn,onlyincolormaxcolor.However,Error.Lastwillreturnacodethatwarnstheuserofthefact.
Example
Thisprogramcreatesthedirectorycalledinformation.Ifthecreationfails,itprintsouttheerrornumberandanerrormessage.
varf:int
open:f,"testdata/information.txt",get
iff<=0then
put"Fileopened"
else
put"Couldnotopenfile."
put"ErrorNumber:",Error.Last
put"ErrorMessage:",Error.LastMsg
put"ErrorConstant:",Error.LastStr
endif
Execute
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingError.Last,notbycallingLast.
Error.LastMsg PartofErrormodule
Syntax Error.LastMsg:string
Description
Error.LastMsgisafunctionthatreturnstheerrormessagesetbythelastcalledpredefinedsubprogram.Ifthereisnoerror,thenitreturnstheemptystring.Ifthereisanerror,youcanuseError.Lasttoobtaintheerrorcode.
ThefactthatError.LastMsgisnot""doesnotnecessarilymeanthatthepreviouspredefinedfunctionfailedorfailedcompletely.Error.LastMsgalsoreturnsanumberofwarningmessages.Forexample,ifauserspecifiesanumberlargerthanmaxcolorforthecolorparameteroftheDraw.Lineprocedure,thelineisstilldrawn,onlyincolormaxcolor.However,Error.LastMsgwillreturnamessagethatindicatesthatthecolorwasoutofrange
Example
Thisprogramcreatesthedirectorycalledinformation.Ifthecreationfails,itprintsouttheerrornumberandanerrormessage.
Dir.Create("testdata/information")
ifError.Last=eNoErrorthen
put"Directorycreated"
else
put"Didnotcreatethedirectory."
put"ErrorNumber:",Error.Last
put"ErrorMessage:",Error.LastMsg
endif
Execute
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
Error.LastMsg,notbycallingLastMsg.
Error.LastStr PartofErrormodule
Syntax Error.LastStr:string
Description
Error.LastStrisafunctionthatreturnsthestringversionoftheerrorcodesetbythelastcalledpredefinedsubprogram(i.e.itwouldreturnthestring"eDrawClrNumTooLarge"forusingacolorgreaterthanmaxcolorinaDrawcommand).Ifthereisnoerrorthenitreturnstheemptystring.Ifthereisanerror,youcanuseError.Lasttoobtaintheactualerrorcode.
ThefactthatError.LastStrisnot""doesnotnecessarilymeanthatthepreviouspredefinedfunctionfailedorfailedcompletely.Error.LastStralsoreturnsanumberoferrorcodesforwarningmessages.Forexample,ifauserspecifiesanumberlargerthanmaxcolorforthecolorparameteroftheDraw.Lineprocedure,thelineisstilldrawn,onlyincolormaxcolor.However,Error.LastStrwillreturnastringversionoftheerrorcodethatindicatesthatthecolorwasoutofrange.
YoucantakealookattheerrorconstantsdefinedbylookingattheunitErrorNumwhichcontainsalldefinederrorcodes.
Example
Thisprogramcreatesthedirectorycalledinformation.Ifthecreationfails,itprintsouttheerrornumberandanerrormessage.
Dir.Create("testdata/information")
ifError.Last=eNoErrorthen
put"Directorycreated"
else
put"Didnotcreatethedirectory."
put"ErrorNumber:",Error.Last
put"ErrorConstant:",Error.LastStr
endif
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingError.LastStr,notbycallingLastStr.
Error.Msg PartofErrormodule
Syntax Error.Msg(errorCode:int):string
Description
Error.Msgisafunctionthatreturnstheerrormessagerelatedtoaspecifiederrorcode.IftheerrorcodeiseNoError,orifthereisnosucherrorcode,itreturnstheemptystring.Ifthereissuchanerror,itreturnsthetextualmessageassociatedwiththaterror.
Example
ThisprogramprintsouttheerrormessageassociatedwitheFsysFileNotFound(“Filenotfound”).
putError.Msg(eFsysFileNotFound)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingError.Msg,notbycallingMsg.
Error.Str PartofErrormodule
Syntax Error.Str(errorCode:int):string
Description
Error.Strisafunctionthatreturnstheerrormessagerelatedtoaspecifiederrorcode.IftheerrorcodeiseNoErrororifthereisnosucherrorcode,itreturnstheemptystring.Ifthereissuchanerror,itreturnsthetextualmessageassociatedwiththaterror.
ExampleThisprogramprintsoutthestring"eFsysFileNotFound".
putError.Str(eFsysFileNotFound)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingError.Str,notbycallingStr.
Error.Trip PartofErrormodule
Syntax Error.Trip(errorCode:int)
Description
Error.TripisaprocedurethatsetstheerrornumberthatisreturnedbyError.LastandError.LastMsg.Itdoesnothalttheprogram.
Errorcodesthatdonotcorrespondtorecognizederrorswillcauseanabortwiththeerrormessage"UnknownError#n"wherenistheerrorpassedin.
YoucanfindalistofconstantsforthelegalerrorcodesinthemoduleErrorNum.AnycalltoError.TripshoulduseaconstantfoundintheErrorNummodule.
Example
Thisprogramsetsanerrorcode.Theprogramoutputs201fortheerrornumberand"Filenotfound"forthemessage.
Error.Trip(eFsysFileNotFound)
put"Errorcode=",Error.Last
put"Errormessage=",Error.LastMsg
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingError.Trip,notbycallingTrip.
ErrorNum
Description
ThisunitcontainsalltheconstantsrepresentingerrorsusedbytheErrormodule.
AllconstantsintheErrorNummoduleareexportedunqualified.(Thismeansyoucanusetheconstantsdirectlywithouthavingtousethequalifier"ErrorNum.".)
Exceptions
Description
ThisunitcontainsalltheconstantscorrespondingtoexceptionnumbersinTuringforuseinbuildingexceptionhandlers.
AllconstantsintheExceptionsmoduleareexportedunqualified.(Thismeansyoucanusetheconstantsdirectlywithouthavingtousethequalifier"Exceptions.".)
exit statement
Syntax
AnexitStatementisoneof:
(a) exitwhentrueFalseExpn (b) exit
Description
Anexitstatementisusedtostoptheexecutionofalooporforstatement.Form(a)isthemostcommon.Here,thetrue/falseexpressionisevaluated.Ifitistrue,theloopisterminatedandexecutionjumpsdownandcontinuesjustbeyondendlooporendfor.Ifitisfalse,theloopkeepsonrepeating.Form(b)alwayscausesthelooptoterminate.Thisformisalmostalwaysusedinsideanotherconditionalstatementsuchasif.
Example
InputnamesuntilfindingJones.
varname:string
loop
getname
exitwhenname="Jones"
endloop
Details
Exitstatementsmustoccuronlyinsidelooporforstatements.Anexittakesyououtoftheclosestsurroundinglooporfor.Theonlyotherwaystoterminatealooporforisbyreturn(inaprocedureorinthemainprogram,inwhichcasetheentireprocedureormainprogramisterminated)orbyresult(inafunction,inwhichcasetheentirefunctionisterminatedandaresultvaluemustbesupplied).
Theform"exitwhentrueFalseExpn"isequivalentto"iftrueFalseExpnthenexitendif".
exp exponentiationfunction
Syntax exp(r:real):real
Description
Theexpfunctionisusedtofindetothepowerr,whereeisthenaturalbaseandristheparametertoexp.Forexample,exp(0)returns1andexp(1)returnsthevalueofe.
Example
Thisprogramprintsouttheexponentialvaluesof1,2,3,…upto100.
fori:1..100
put"Exponentialof",i,"is",exp(i)
endfor
Seealsoln(naturallogarithmfunction).
SeealsopredefinedunitMath.
explicitCharConstant characterliteral
SyntaxAnexplicitCharConstantisasequenceofcharacterssurroundedbysinglequotationmarks,forexample,'Renzo'.
Example
Inthefollowing,theexplicitcharacterconstantsare'H'and'Hi'.
varc:char:='H'
vard:char(2):='Hi'
Details
Anexplicitcharacterconstantmustcontainatleastonecharacter.Ifitcontainsexactlyonecharacter,asin'A',itstypeischar.Ifitcontainstwoormorecharacters(ncharacters),as'Width',itstypeischar(n).Thedifferencebetweenthecharandchar(1)typesisrarelyofsignificance,butdoesmakeadifferenceindeclarationswithoutanexplicittype,forexample:
varc:='H'%Typeischar
vard:='Hi'%Typeischar(2)
vare:="H"%Typeisstring
Thebackslash\isusedinexplicitstringandchar(n)constantstospecifyspecialvalues,forexample,'\T'isthetabcharacter.Similarly,thecarat^isusedtospecifyASCIIcontrolcharacters,forexample,'^H'istheASCIIbackspace.SeeexplicitStringConstantsfordetails.
Explicitcharacterconstantscannotcrosslineboundaries.Torepresentaconstantthatislongerthanaline,breakitintotwoormorestringsonseparatelinesanduse+(catenation)tojointheindividualstrings.Seecatenation.
Anexplicitcharacterconstantmaybelimitedinlengthbytheimplementation.Werecommendthatthislimitationbeatleast32767.
Explicitcharacterconstants,butnotstrings,areallowedtocontainthecharacterinternalvalues0(calledeosforendofstring)and128(calleduninitchar,usedastheuninitializedstringvalue).
explicitConstant literal
Syntax
AnexplicitConstantisoneof:
(a) explicitStringConstant %e.g.:"Helloworld"
(b) explicitIntegerConstant %e.g.:25 (c) explicitRealConstant %e.g.:51.8
(d) explicitTrueFalseConstant%e.g.:true
(e) explicitCharConstant %e.g.:'Hi'
DescriptionAnexplicitConstantgivesitsvaluedirectly.Forexample,thevalueoftheexplicitconstant25istwenty-five.
Example
Inthefollowing,theexplicitconstantsare"Helloworld",3.14159and2.Notethatpiisanamedconstantratherthananexplicitconstant.
put"Helloworld"
vardiameter:real
constpi:=3.14159
diameter:=pi*r**2
varx:=diameter
Details
Insomeprogramminglanguages,explicitconstantsarecalledliteralsorliteralvalues,becausetheyliterally(explicitly)givetheirvalues.
Seealso
explicitStringConstant,explicitIntegerConstant,explicitRealConstant,explicitTrueFalseConstantandexplicitCharConstant.SeealsoenumeratedValue.
explicitIntegerConstant integerliteral
Syntax
AnexplicitIntegerConstantisasequenceofoneormoredecimaldigits(0to9)optionallyprecededbyaplusorminussign.Thisisanalternateformthatspecifiesanumberbase(suchasbase2orbase16).
Example
Inthefollowing,theexplicitintegerconstantsare0,115and5.
varcount:int:=0
constheight:=115
…
count:=height-5
Details
IncurrentimplementationsofTuring,therangeoftheint(integer)typeisfrom-2147483647to2147483647.Inotherwords,themaximumsizeofintegeris2**31-1.Thisistherangethatfitsintofourbytes,withonepatternleftover(thelargestnegative4-bytenumber)torepresenttheuninitializedvalue.Seemaxint.
Valuescanbewritteninbase2or16oranyotherbaseintherange2to36(36becausethereare10digitsand26letters).Thisformbeginswiththebase,suchas16,then#,andthenthevaluewritteninthatbase,forexample,16#Ahasthevalue10.Thelettersa,b,c…representthedigitvalues10,11,12…CapitallettersA,B,C…canbeusedinsteadoflowercase.Herearesomeexamples.
2#1 =1 (Base2) 2#11 =3 (Base2) 16#a =10 (Base16) 16#FF =255 (Base16) 16#FFFF =32767 (Base16) 8#10 =8 (Base8)
Hereisanexampleofusingthese:
constmaxnat1:=16#FF%Largest1-bytenaturalnumber
constmaxint2:=16#7FFF%Largest2-byteinteger
Youshouldbecarefultoavoidconfusionaboutpatternssuchas16#FFFF.Itistemptingtothinkthatthisisthevalue1,becausethebitpattern(2-bytetwo's
complementinternalrepresentation)for1isthesameasthebitpatternfor16#FFFF=32767.However,thevalue(asopposedtotheinternalrepresentation)of1and32767aredifferent.
Seealso
int,maxint(thelargestintegervalue),nat(positivevaluesonly)andbyteintegers).Seealsointstrandnatstrwhichconvertintegerandnaturalnumbervaluestocorrespondingcharacterstringsinanybase,forexampleintstr(4,0,2)="100".
explicitRealConstant realliteral
SyntaxAnexplicitRealConstantconsistsofanoptionalplusorminussign,asignificantdigitspart,andanexponentpart.
Example
Inthefollowing,theexplicitrealconstantsare0.0and2.93e3.
vartemperature:real:=0.0
constspeed:=2.93e3%Valueis2,930.0
Details
Thesignificantdigitspart(orfractionalpart)ofanexplicitrealconstantconsistsofasequenceofoneormoredigits(0to9)optionallycontainingadecimalpoint(aperiod).Thedecimalpointisallowedtofollowthelastdigitasin16.ortoprecedethefirstdigit,asin.25.
TheexponentpartconsistsofthelettereorEfollowedoptionallybyaplusorminussignfollowedbyoneormoredigits.Forexample,in-9.837e-3theexponentpartise-3.Thevalueof-9.837e-3is-9.837times0.001.
Ifthesignificantfigurespartcontainsadecimalpoint,thentheexponentpartisnotrequired.
explicitStringConstant stringliteral
SyntaxAnexplicitStringConstantisasequenceofcharacterssurroundedbyquotationmarks.
Example
Inthefollowing,theexplicitstringconstantsare"Helloworld",""and"273O'ReillyAve.".
varname:string:="Helloworld"
name:=""%Nullstring,containingzerocharacters
varaddress:string:="273O'ReillyAve."
Details
Withinanexplicitstringconstant(andwithinanexplicitcharacterconstant),thebackslash\isusedtorepresentcertainothercharactersasfollows:
\" quotationmarkcharacter \nor\N endoflinecharacter \tor\T tabcharacter \for\F formfeedcharacter \ror\R returncharacter \bor\B backspacecharacter \eor\E escapecharacter \dor\D deletecharacter \\ backslashcharacter
Forexample,put"One\nTwo"willoutputOneononelineandTwoonthenext.Inanexplicitcharacterconstant(whichissurroundedbysinglequotes,asin'John'),thebackslashisnotrequiredbeforeadoublequote",butitisrequiredbeforeasinglequote',asinthesetwoconstants:
'Johnsaid"Hello"toyou' 'Don\'tcry'.
Youcanusethecaret^tospecifyASCIIcontrolcharacters,forexample:
'^H' ASCIIbackspacecharacter
Thecaretspecifiesthatthetopthreebitsofthecharacteraresettozero.Foranycharacterc,thefollowingistrue:
'^c'=chr(ord('c')&2#11111)
Howeverifcisthequestionmark,asin'^?',thebitsarenotturnedoff.
Explicitstringconstantscannotcrosslineboundaries.Torepresentastringthatislongerthanaline,breakitintotwoormorestringsonseparatelinesandusecatenation(+)tojointheindividualstrings.
Anexplicitstringconstantcancontainatmost255characters(thisisinimplementationconstraint).
Stringvaluesarenotallowedtocontaincharacterswiththecodevaluesof0or128;thesecharactervaluesarecalledeos(endofstring)anduninitchar(uninitializedcharacter).Thesearereservedbytheimplementationtomarktheendofastringvalueandtoseeifastringvariablehasbeeninitialized.
explicitTrueFalseConstant booleanliteral
Syntax
AnexplicitTrueFalseConstantisoneof:
(a) true (b) false
Example
Thefollowingdeterminesifstringscontainsaperiod.Aftertheforstatement,foundwillbetrueifthereisaperiodins.
varfound:boolean:=false
fori:1..length(s)
ifs="."then
found:=true
endif
endfor
Details
true/falsevaluesarecalledbooleanvalues.Abooleanvariable,suchasfoundintheaboveexample,canhaveavalueofeithertrueorfalse.
Seealso booleantype.
expn expression
Syntax
Anexpnisoneof:
(a) explicitConstant %e.g.:25
(b) variableReference %e.g.:width
(c) constantReference %e.g.:pi
(d)expninfixOperatorexpn
%e.g.:3+width
(e) prefixOperatorexpn
%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
Anexpression(expn)returnsavalue;inthegeneralcase,thismayinvolveacalculation,suchasaddition,asintheexpression:
3+width
put"Helloworld"%"Helloworld"isanexpn
Example vardiameter:real
constpi:=3.14159%3.14159isanexpn
diameter:=pi*r**2%pi*r**2isanexpn
varx:=diameter%diameterisanexpn
Details
Inthesimplestcase,anexpression(expn)issimplyanexplicitconstantsuchas25or"Helloworld".Avariablebyitselfisconsideredtobeanexpressionwhenitsvalueisused.Thisisthecaseabove,wherethevalueofdiameterisusedtoinitializex.Moregenerally,anexpressioncontainsanoperatorsuchas+andcarriesoutanactualcalculation.Anexpressionmayalsobeasubstring,functioncall,setconstructororenumeratedvalue.Fordetails,seethedescriptionsoftheseitems.
TheTuringinfixoperatorsare:+,-,*,/,div,mod,**,<,>,=,<=,>=,not=,not,and,or,=>,in,notin,shr(shiftright),shl(shiftleft),and(exclusiveor).Fordetails,seeinfixOperator.TheTuringprefixoperatorsare+,-andnot,^(pointerfollowing)and#(seecheat).Fordetailsseeprefixoperator.
Seealsoprecedenceofoperators,aswellastheint,real,stringandbooleantypes.
export list
Syntax
AnexportListis:
export[howExport]id{,[howExport]id}
Description
Anexportlistisusedtospecifythoseitemsdeclaredinamodule,monitororclassthatcanbeusedoutsideofit.Itemsthataredeclaredinsideamodule,monitororclassbutnotexportedcannotbeaccessedoutsideofit.
Example
Inthisexample,theproceduresnamespopandpushareexportedfromthestackmodule.Thesetwoproceduresarecalledfromoutsidethemoduleonthelastandthirdfromlastlinesoftheexample.Noticethatthewordstackandadotmustprecedetheuseofthesenames.Sincetopandcontentswerenotexported,theycanbeaccessedonlyfrominsidethemodule.
modulestack
exportpush,pop
vartop:int:=0
varcontents:array1..100ofstring
procedurepush…endpush
procedurepop…endpop
endstack
stack.push("Harvey")
varname:string
stack.pop(name)%ThissetsnametoHarvey
Procedures,functions,variables,constantsandtypescanbeexported.Modules,monitorsorclassescanotbeexported.Parenthesesareallowedaroundtheitemsinanexportlist,asin:
export(push,pop)
Thefollowingsyntaxspecifiesthateachexportedidentifiercanoptionallybeprecededbythekeywordsvar,unqualified,pervasiveandopaque.Ofthese,onlyopaqueisavailableinTuringproper.
Details
TheformofhowExportis:
{exportMethod}
TheformofexportMethodisoneof:
(a) var (b) unqualified (c) pervasive (d) opaque
Thekeywordvarmeansthattheexportedvariablecanbechangedoutsideoftheexportingmodule,monitororclass.Thiskeywordappliesonlytoexportedvariables.Forexample,ifstringvariablenameisexportedvarfrommoduleM,namecanbechangedfromoutsideofMbyM.name:="Surprise!".
Thekeywordunqualifiedmeansthatreferencestotheexporteditemdonotneedtobeprefixedbythenameoftheexportingitem.Forexample,ifmoduleMexportsprocedurepunqualified,acalltopoutsideofMcanbesimplypinsteadoftheusualM.p.Aclasscannotexportvariablesordynamicconstantsunqualified(becauseeachobjectoftheclasshasitsowncopiesofthese).Theonlythingsaclasscanexportunqualifiedaretypesandcompiletimeconstants.Thekeywordunqualifiedcanbeabbreviatedto~.whichispronouncedas"notdot".
Thekeywordpervasive,whichisonlymeaningfulifunqualifiedisalsopresent,specifiesthattheexporteditemistobevisibleinsubsequentscopes,inotherwordsthatitisnotnecessarytoimportitintointernalmodules,monitorsandclasses.
Thekeywordopaque,whichcanonlyprecedetypenames,specifiesthatoutsidethemodule,monitororclass,thetypeisconsideredtobedistinctfromallothertypes.Thismeans,forexample,thatifthetypeisanarray,itcannotbesubscriptedoutsideofthemodule.Seemoduledeclarationforanexamplethatusesopaquetypes.Inmostcases,classesarepreferabletoopaquetypes.
Exportedsubprogramsareconsideredtobedeferred,meaningthatexpansionsareallowedtooverridethesesubprograms.Seealsodeferredsubprograms.Thesecanbeoverriddenusingthekeywordbodybeforetheresolvingsubprogrambody.
Aclasscannotexportitemsfromitsparentoritparent'sancestors.Allexporteditemmustbedeclaredinthecurrentclass.
Details
Youcanexportallfromamodule,monitororaclass.Thismeansthateverysibmlethatislegaltoexportisexported.Youmayalsoqualifytheall,asinexportopaqueunqualifiedpervasiveallwherethequalifiersareaddedtoeachexportitem(ifitmakessense).
Ifallisspecifiedastheexportitem,nootheritemmaybespecified.Also,andallexportaffectsonlythemodule,monitororclassthatitisgivenin.Anyinheritingorimplementingmodule,monitororclassdoesnotexportallunlesstheyalsospecifyit.
Seealso
unit,module,monitorandclass.Seealsoimportlist,inheritclause,implementclause,implementbyclauseanddeferredsubprogram.
external declaration
Dangerous
Syntax
AnexternalDeclarationisoneof:
(a)external[overrideName]subprogramHeader (b)external[addressSpec]varid[:typeSpec][:=
Description
Anexternaldeclarationisusedtoaccessvariablesorsubprogramsthatarewritteninotherlanguagesorwhichrequirespeciallinkage.Thisfeatureisimplementation-dependentanddangerousandmaycausearbitrarydataorprogramcorruption.FromaninterpretiveenvironmentsuchasTuring,thisprovideslinkagetoitemsthatarepartoftheTuringsystem.ForcompiledversionsofTuring,thelinkagewouldbebymeansofastandard,operatingsystem-specificlinkageeditor.
Details
Inform(a)theoptionaloverrideNamemustbeanexplicitstringconstant,suchas"printf".Ifitisomitted,theexternalnameisthenameinthesubprogramHeaderSeesubprogramHeader.
Thecurrentimplementationdoesnotsupportform(b).Thisformisdocumentedhereincaseafutureversionsupportsit.TheaddressSpecisacompiletimeexpression(itsvaluemustfitintherangeoftheaddressinttype)orisacompiletimestringvalue.IftheaddressSpecisomitted,theidentifieristhenameofanexternalvariable.Thisnamerepresentsanimplementation-dependentmethodoflocatingavariable.AtleastoneoftypeSpecorexpnmustbepresent.
Declaringvariablesatabsoluteaddressesisusefulfordevicemanagementincomputerarchitectureswithmemorymappeddeviceregisters.Externalvariablesdeclaredtobeintornatwillbydefaultbecheckedforinitialization.Toavoidthischeck,declarethemtobeint4ornat4.
Example
PlacevariablettyDataathexadecimallocation9001andassignitthecharacterA.
external16#9001varttyData:char
ttyData:='A'%CharacterAisassignedtohexlocation9001
ExampleAccessanexternalintegervariablenamedERRFLAG.
externalvarERRFLAG:int
ifERRFLAG=0then…
Example
Accessanintegervariablewhichiscalledyinthisprogrambutiscalledexternally.
external"x"vary:int
ExampleDeclaredrawcircletobeaprocedurethatisexternallyknownascircle
external"circle"proceduredrawcircle(x,y,r,
false booleanvalue(nottrue)
Syntax false
DescriptionAboolean(true/false)variablecanbeeithertrueorfalse(seebooleantype).
Example
varfound:boolean:=false
varword:int
fori:1..10
getword
found:=foundorword="gold"
endfor
iffound=truethen
put"Found'gold'inthetenwords"
endif
DetailsThelineiffound=truethencanbesimplifiedtoiffoundthenwithnochangetothemeaningoftheprogram.
fetcharg fetchargumentfunction
Syntax fetcharg(i:int):string
Description
Thefetchargfunctionisusedtoaccessthei-thargumentthathasbeenpassedtoaprogramfromthecommandline.Forexample,iftheprogramisrunfromtheTuringenvironmentusing
:rfile1file2
thenfetcharg(2)willreturn"file2".Ifaprogramcalledprog.xisrununderUNIXusingthiscommand:
prog.xfile1file2
thevalueoffetcharg(2)willsimilarlybe"file2".
Thenargsfunction,whichgivesthenumberofargumentspassedtotheprogram,isusuallyusedtogetherwiththefetchargfunction.Parameteripassedtofetchargmustbeintherange0..nargs.
The0-thargumentisthenameoftherunningprogram.
Example
Thisprogramlistsitsownnameanditsarguments.
put"Thenameofthisprogramis:",fetcharg(0)
fori:1..nargs
put"Argument",i,"is",fetcharg(i)
endfor
Execute
Seealso nargs
File
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithfilemanipulationonawhole-filebasis(asopposedtomanipulatingthedatainthefileusingopenandclose,etc.).Theseroutinesallowyoutorename,copyanddeletefiles,aswellasgetinformationaboutafileandgetthefreespaceondiskavailableforafile.
AllroutinesintheFilemoduleareexportedqualified(andthusmustbeprefacedwith"File.").
EntryPoints
Exists Returnswhetherafileexists.FullPath Returnsthefullabsolutepathnameofafile.Parent Returnstheparentdirectoryofafileordirectory.
Status Getsinformationaboutafilesuchassize,modificationdate,etc.
Copy Copiesafiletoanotherlocation.Rename Renamesafileordirectory.Delete Deletesafile.
DiskFree Getsthefreespaceonthediskuponwhichafileordirectoryresides.
Details
OnthePC,apathnameofafileoradirectorycanuseeithertheforwardslashorbackwardslashtoseparatedirectorynames.Thedrivemustbefollowedbyacolon.Thusthefollowingarelegalpathnames:
x:\students\west\example.t
c:/turing/test.t
/west/binary.t(usesthedefaultdrive).
OntheMacintosh,apathnameofafileordirectorycanusethestandardMacintoshformatofVolumeName:DirectoryName:DirectoryName:FileNameortheUnixformatof/VolumeName/DirectoryName/DirectoryName/FileName.Notethatthenamescanhavespacesinthem.
HSA:Applications:TuringFiles:example.t
/HSA/Applications/TuringFiles/example.t
OnUNIXsystems,thepathnamemustcorrespondtotheUNIXstandardofusingaforwardslashbetweenpartsofthepath.
/export/home/west/turing/example.t
Ingeneral,youcanachievethegreatestportabilitybyusingtheUNIXstandardforuseinpathnames,asallTuringsystemssupportit.
File.Copy PartofFilemodule
Syntax File.Copy(srcPathName,destPathName:string)
Description
File.CopycopiesafilenamedbythesrcPathNameparametertothefilenamedbythedestPathNameparameter.Thecopycanbebetweendifferentdisksorfilesystems.
Details
Thesourcefilenamemustbeanactualfile.Thisprocedurewillnotcopydirectories.
IftheFile.Copycallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Notethatyoucanuseeitherforwardorbackwardslashestoseparatecomponentsinapath.Ifyouusebackwardslashes,youmustdoubletheminastringliteral.(i.e."d:\\west\\example.t")
Example
Thisprogramcopiesthefile"d:\west\example.dat"to"new_example.t".inthecurrentdirectory.
File.Copy("d:/west/example.dat","new_example.t")
ifError.Last=eNoErrorthen
put"Filecopied"
else
put"Didnotcopythefile."
put"Error:",Error.LastMsg
endif
Execute
AnexampleprogramisavailablethatcopiesafiletothecurrentdirectoryusingFile.Copy,displaysitscontentstotherunwindow,andthendeletesthefileusingFile.Delete.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFile.Copy,notbycallingCopy.
File.Delete PartofFilemodule
Syntax File.Delete(filePathName:string)
Description
File.DeleteisusedtodeletethefilespecifiedbytheparameterfilePathName.ThisistheequivalentofdoingadelinDOSorrminUNIX.
Details
IftheFile.Deletecallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramdeletesthefilecalledinformation.
File.Delete("information")
ifError.Last=eNoErrorthen
put"Filedelete"
else
put"Didnotdeletethefile."
put"Error:",Error.LastMsg
endif
Execute
Anexampleprogramisavailablethatcreatesafileinthecurrentdirectory,andthendeletesthefileusingFile.Delete.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFile.Delete,notbycallingFile.
File.DiskFree PartofFilemodule
Syntax File.DiskFree(pathName:string):int
Description
File.DiskFreegetsthenumberofbytesforthediskuponwhichpathNameresides.ThepathNameparametercanspecifyeitherafileoradirectory.Ifitistheemptystring,thenFile.DiskFreereturnsthenumberofbytesoffreediskspaceonthediskuponwhichtheexecutiondirectoryresides.
Details
IftheFile.DiskFreecallfails,thenitreturns-1.AlsoError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Ifthereismorethan2,147,483,647bytesfreeonadisk,theFile.DiskFreefunctionreturns2,147,483,647.
Example
ThisprogramprintsouttheamountofspaceontheA:driveonaPCandintheexecutiondirectory.
varbytesFree:int
bytesFree:=File.DiskFree("A:\\")
ifbytesFree=-1then
put"Can'tgetfreespaceondriveA:."
put"Error:",Error.LastMsg
else
put"Thereare",bytesFree,"bytesfreeondriveA:"
endif
bytesFree:=File.DiskFree(".")
ifbytesFree=-1then
put"Can'tgetfreespaceondefaultdirectory."
put"Error:",Error.LastMsg
else
put"Thereare",bytesFree,"bytesfreeonthedefaultdir"
endif
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFile.DiskFree,notbycallingDiskFree.
File.Exists PartofFilemodule
Syntax File.Exists(pathName:string):boolean
DescriptionFile.ExistsreturnstrueifafilebythenameofpathNameexists.ItwillreturnfalseifpathNameisadirectory.
Details
IftheFile.Existsreturnsfalse,youcanexamineError.LastorError.LastMsgformoreinformation(i.e.whetherthepathfailedorthefilewassimplynotfound).
Example
Thisprogramloopsuntiltheusertypesinapathnamethateitherdoesn'talreadyexistorisallowedtobeoverwritten.
varpathName:string
varchoice:string
loop
put"Enterfilenametowriteresultsto"..
getpathName
ifFile.Exists(pathName)then
put"Overwrite",pathName,"?"..
getchoice
exitwhenchoice="y"
else
exit
endif
endloop
Execute
Anexampleprogramisavailablethatcreatesafileinthecurrentdirectory,testsforitsexistenceusingFile.ExistsanddeletesthefileusingFile.Delete.
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingFile.Exists,notbycallingExists.
File.FullPath PartofFilemodule
Syntax File.FullPath(pathName):string):string
Description
File.FullPathreturnsastringrepresentingthefullabsolutepathnameinTuringformat(forwardslashes)ofthepaththatispassedtothefunction.Thepathnamepassedindoesnothavetodescribeanexistingfileordirectory.
DetailsThefullpathnamewillbeinTuringformatandincludethedrivename(forexample"d:/turing/examples/games/SpaceGame.t")
Example
Thisprogramobtainsapathfromtheuserandthenoutputsafullpathnamebasedonthepath.
varpathName:string
getpathName
put"Fullpath=",File.FullPath(pathName)
Execute
Details
Anotherexampleisavailablethatcheckswhetherafileandallofthedirectoriesinthepathtothefileexist.ThisprogramillustratestheuseofFile.FullPath,File.Parent,File.Exists,andDir.Exists.
Exportedqualified.
StatusThismeansthatyoucanonlycallthefunctionbycallingFile.FullPath,notbycallingFullPath.
File.Parent PartofFilemodule
Syntax File.Parent(pathName:string):string
Description
File.ParentreturnsastringrepresentingtheparentdirectoryinTuringformat(forwardslashes)ofthepathpassedasaparameter.Thepathnamepassedindoesnothavetodescribeanexistingfileordirectory.Attemptingtoobtaintheparentdirectoryofarootdirectory(forexample"c:/")willreturnthesamerootdirectoryandwillsetthevaluereturnedbyError.Lasttoanon-zerovalue.
Example
Thisprogramobtainsapathfromtheuserandthenlistsalltheparentdirectoriesuntilitreachestherootdirectory.
varpathName:string
put"Enterapath:"..
getpathName
loop
pathName:=File.Parent(pathName)
exitwhenError.Lastnot=eNoError
putpathName
endloop
Execute
Details
Anotherexampleisavailablethatcheckswhetherafileandallofthedirectoriesinthepathtothefileexist.ThisprogramillustratestheuseofFile.FullPath,File.Parent,File.Exists,andDir.Exists.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFile.Parent,notbycallingParent.
File.Rename PartofFilemodule
Syntax File.Rename(srcPathName,destName:string)
Description
File.CopyrenamesafileordirectorynamedbythesrcPathNameparametertothedestNameparameter.ThedestNameparametermustbeanameonly.InotherwordsFile.Renamecan'tmoveafilebetweendifferentdirectories.
Details
IftheFile.Renamecallfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Thisprogramrenamesthefile"/usr/west/example"to"testcase"
File.Rename("/usr/west/example","testcase")
ifError.Last=eNoErrorthen
put"Filerenamed"
else
put"Didnotrenamethefile."
put"Error:",Error.LastMsg
endif
Execute
Anexampleprogramisavailablethatcreatesafileinthecurrentdirectory,renamesittoadifferentnameusingFile.Rename,checkstheexistenceofbothfilesusingFile.ExistsandthendeletesthefileusingFile.Delete.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFile.Rename,notbycallingRename.
File.Status PartofFilemodule
Syntax File.Status(pathName:string,varsize,attribute,fileTime:int)
Description
File.Statusisusedtogetassortedinformationaboutafileordirectory.WhenthefunctioniscalledwithaspecifiedpathName,itreturnstheinformationaboutthefileintheotherparameters.
Thesizeparameteristhesizeofthefileinbytes.
TheattributeparameterhasitsindividualbitssetasexactlyastheattributeparameterinDir.GetLongsubprogramdoes.SeeDir.GetLongforthelistofattributeconstants.
ThefileTimeisthetimeoflastmodificationofthefile.Itisreturnedasthenumberofsecondssince00:00:00GMT1/1/1970.Toconvertthistoastring,useTime.SecDate.
Details
IftheFile.Statuscallfails,size,attributeandfileTimeareallsetto1.Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
ThisprogramprintsinformationabouttheNotePad.exeapplicationinWindowsfoundat"c:\windows\notepad.exe".(Noteonsomesystems,thiswillbe"c:\winnt\notepade.exe"
constpathName:string:="c:/windows/notepad.exe"
varsize,attribute,fileTime:int
File.Status(pathName,size,attribute,fileTime
ifError.Last=eNoErrorthen
put"Name:",File.FullPath(pathName)
put"Created:",Time.SecDate(fileTime)
put"Size:",size,"bytes"
put"Attributes:"..
if(attributeandootAttrDir)not=0then
put"Directory"..
else
put""..
endif
if(attributeandootAttrRead)not=0then
put"Readable"..
else
put""..
endif
if(attributeandootAttrWrite)not=0then
put"Writable"..
else
put""..
endif
if(attributeandootAttrExecute)not=0then
put"Executable",skip
else
putskip
endif
else
put"Unabletogetfileinformation"
put"Error:",Error.LastMsg,skip
endif
Execute
Execute
AnotherexampleprogramisavailablethatusesFile.Statustodeterminethestatusofseveralfilesanddirectories.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFile.Status,notbycallingStatus.
flexible arrayinitialization
Syntax flexiblearrayindexType{,indexType}oftypeSpec
Description
Theflexiblekeywordallowsanarraytoberesizedusingnewatalaterpointintime.Theindicesmayhavecompile-timeorrun-timeupperbounds(thelowerboundmustbecompile-time).Theupperboundscanbechangedbyusing:
newname,newUpper1{,newUpper2}
Theexistingarrayentrieswillretaintheirvalues,exceptthatanyindexmadesmallerwillhavethecorrespondingarrayentrieslost.Anyindexmadelargerwillhavethenewarrayentriesuninitialized(ifapplicable).
Additionally,theupperbound(bothinthedeclarationandthenewstatement)canbemadeonelessthanthelowerbound.Thiseffectivelymakesanarraythatcontains0elements.Itcanlaterbeincreasedinsizewithanothernew.
Inthecurrentimplementation(1999),withamulti-dimensionalarraywithanon-zeronumberoftotalelements,itisarun-timeerrortochangeanybutthefirstdimension(unlessoneofthenewupperboundsisonelessthanthecorrespondinglowerbound,giving0elementsinthearray)asthealgorithmtorearrangetheelementmemorylocationshasnotyetbeenimplemented.
Currently,onlyvariablescanbedeclaredinthisform.Thereisnoflexiblearrayparametertype,althoughaflexiblearraycanbepassedtoanarrayparameterwith“*”astheupperbound.
Example Seearrayforanexampleofflexible.
Execute
Seealso arrayandnew.
floor real-to-integerfunction
Syntax floor(r:real):int
Description Returnsthelargestintegerthatislessthanorequaltor.
Details
Thefloorfunctionisusedtoconvertarealnumbertoaninteger.Theresultisthelargestintegerthatislessthanorequaltor.Inotherwords,thefloorfunctionroundsdowntothenearestinteger.Forexample,floor(3)is3,floor(2.75)is2andfloor(-8.43)is-9.
Seealso ceilandroundfunctions.
Font
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithfonts.Usingtheseroutines,youcandisplaytextinaselectedfontname,sizeandstyleonthescreen.Notethatoutputinaparticularfontistreatedasgraphicsoutput.
AllroutinesintheFontmoduleareexportedqualified(andthusmustbeprefacedwith"Font.").
Details
Thereisadefaultfont.YoucandrawinandobtaininformationaboutthedefaultfontbypassingfontDefaultIDtoFont.Draw,Font.WidthandFont.Sizes.Thedefaultfontisthesamefontasisusedbyputintheoutputwindow.
EntryPoints
New Selectsaparticularfontname,sizeandstyleforanewfont.
Free FreesupthefontcreatedbyusingNew.Draw Drawstextinagivenfont.
Width Getsthewidthinpixelsofaparticularpieceoftextinaspecifiedfont.
Sizes Getstheheightandvariousleadingsofaspecifiedfont.
Name Returnsthenameofthespecifiedfont.StartName Preparestolistallavailablefonts,GetName Getsthenextfontname.GetStyle Getsalltheavailablestylesforaspecifiedfont.
StartSize Preparestolistallavailablesizesforaspecifiedfontandstyle.
GetSize Getsthenextfontsize.
Font.Draw PartofFontmodule
Syntax Font.Draw(txtStr:string,x,y,fontID,Color:int)
Description
Font.Drawisusedtoactuallydrawtextinaspecifiedfont.ThetextStrcontainsthestringtobedrawn.Thexandyparametersarethelocationofthelowerlefthandcornerofthetexttobedisplayed.ThefontIDparameteristhenumberofthefontinwhichthetextistobedrawn.TheColorparameterisusedtospecifythecolorinwhichthetextistoappear.
Notethatthetextthatappearsiscompletelyunrelatedtothetextthatappearsusingput.Font.Drawisagraphicscommandandthusdoesnotuseoraffectthecursorlocation.
ThetextdrawnbytheFont.Drawproceduredoesnoterasethebackground.
Details
IfFont.DrawispassedaninvalidfontID,afatalerroroccurs.Ifthefailsforother(non-fatal)reasons,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramprintsoutseveralphrasesinavarietyoffonts.
varfont1,font2,font3,font4:int
font1:=Font.New("serif:12")
assertfont1>0
font2:=Font.New("sansserif:18:bold")
assertfont2>0
font3:=Font.New("mono:9")
assertfont3>0
font4:=Font.New("Palatino:24:bold,italic")
assertfont4>0
Font.Draw("Thisisinaseriffont",50,30,font1,red
Font.Draw("Thisisinasansseriffont",50,80,
Font.Draw("Thisisinamonofont",50,130,font3,colorfg
Font.Draw("ThisisinPalatino(ifavailable)",50,180,
Font.Free(font1)
Font.Free(font2)
Font.Free(font3)
Font.Free(font4)
Execute
DetailsTousethesamefontasisusedbytheputstatement,usedefFontIDnumber.Thisfontdoesnothavetobecreatedorfreedbytheuser,andallowsaprogramtoquicklyplacetextinanylocationonthescreen.
Example
Theprogramdrawstwostringsinthedefaultfont(defFontID).
Font.Draw("DrawingHere",100,120,defFontID,
Font.Draw("andHere",180,90,defFontID,brightgreen
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.DrawDraw.
Font.Free PartofFontmodule
Syntax Font.Free(fontID:int)
Description
Font.Freeisusedtoreleaseafontthatisnolongerneeded.Thereisalimittothenumberoffontsthatmaybedefinedatanyonetime.ByhavingaFont.FreeeveryFont.New,thenumberofsimultaneouslydefinedfontsiskepttoaminimum.
Details
IfFont.FreeispassedaninvalidfontID,afatalerroroccurs.Ifthefailsforother(non-fatal)reasons,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramprintsoutseveralphrasesinavarietyoffonts.
varfont1,font2,font3,font4:int
font1:=Font.New("serif:12")
assertfont1>0
font2:=Font.New("sansserif:18:bold")
assertfont2>0
font3:=Font.New("mono:9")
assertfont3>0
font4:=Font.New("Palatino:24:Bold,Italic")
assertfont4>0
Font.Draw("Thisisinaseriffont",50,30,font1,red
Font.Draw("Thisisinasansseriffont",50,80,
Font.Draw("Thisisinamonofont",50,130,font3,colorfg
Font.Draw("ThisisinPalatino(ifavailable)",50,180,
Font.Free(font1)
Font.Free(font2)
Font.Free(font3)
Font.Free(font4)
Execute
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingFont.FreeFree.
Font.GetName PartofFontmodule
Syntax Font.GetName:string
Description
Font.GetNameisusedtogetthenextfontavailableonthesystem.ByusingFont.StartNameandthencallingFont.GetNamerepeatedly,youcangetthenamesofallthefontsavailabletotheprogram.
Font.StartNamemustbecalledbeforeanycallstoFont.GetName.Afterthat,Font.GetNamereturnsthelistofthefontnames,onepercall.Whentherearenomoresizes,Font.GetNamereturnstheemptystring.
Oncethenameofafontisknown,it'spossibletolisttheavailablestyles(usingFont.GetStyle)andtheavailablesizes(usingFont.StartSizeandFont.GetSize)forthatfont.
Example
Theprogramlistsallthefontsavailableonthesystem.
varfontName:string
Font.StartName
loop
fontName:=Font.GetName
exitwhenfontName=""
putfontName
endloop
Execute
Anotherexampleisavailablethatdisplaysfullinformationaboutthefontsincludingname,styles,andpointsizes.
Example
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.GetName,notbycallingGetName.
Font.GetSize PartofFontmodule
Syntax Font.GetSize:int
Description
Font.GetSizeisusedtogetthenextsizeinthelistofavailablefontsizesforaparticularfontnameandstyle.
Font.StartSizemustbecalledbeforeanycallstoFont.GetSize.Afterthat,Font.GetSizereturnsthelistofsizes,onepercall.Whentherearenomoresizes,Font.GetSizereturns0.
Somefontsare“scalable”.Thismeansthatthecomputercanscalethefontstofitanygivensize.(UnderMicrosoftWindowsandtheAppleMacintosh,TrueTypeandPostScriptfontsarescalablewiththeappropriateutilities.)Inthiscase,Font.GetSizereturns-1.
ExampleSeeFont.StartSizeforaprogramthatlistsallthefonts,stylesandsizesavailableonthesystem.
Example
Anexampleisavailablethatdisplaysfullinformationaboutthefontsincludingname,styles,andpointsizes.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.GetSize,notbycallingGetSize.
Font.GetStyle PartofFontmodule
SyntaxFont.GetStyle(fontName:string,varbold,italic,underline:boolean):string
Description
Font.GetStyleisusedtogetthestylesavailableonthesystemforaspecifiedfont.bold,italicandunderlinearesettotrueifbold,italicorunderlineversionsofthefontareavailable.Oncethestylesavailableforafontareknown,it'spossibletogetthesizesavailableforeachstylebyusingFont.StartSizeandFont.GetSize.
Example
Theprogramlistsallthefontsandtheirstylesavailableonthesystem.
varfontName:string
varbold,italic,underline:boolean
Font.StartName
loop
fontName:=Font.GetName
exitwhenfontName=""
Font.GetStyle(fontName,bold,italic,underline
putfontName:30..
ifboldthen
put"bold"..
endif
ifitalicthen
put"italic"..
endif
ifunderlinethen
put"underline"..
endif
put""
endloop
Execute
Example
Anexampleisavailablethatdisplaysfullinformationaboutthefontsincludingname,styles,andpointsizes.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.GetStyle,notbycallingGetStyle.
Font.Name PartofFontmodule
Syntax Font.Name(fontID:int)fontName:string
Description
Font.Nameisusedtogetthenameofafontthatisbeingused.Thestringthatisreturnedcanbeusedtodeterminewhichfontisactuallybeingusedforthedefaultfonts“serif”,“sansserif”and“mono”.
Example
Theprogramprintsoutthefontsusedfor“serif”,“sansserif”and“mono”.
varserifFont,sansSerifFont,monoFont:int
serifFont:=Font.New("serif:12")
assertserifFont>0
sansSerifFont:=Font.New("sansserif:12")
assertsansSerifFont>0
monoFont:=Font.New("mono:12")
assertmonoFont>0
put"serif=",Font.Name(serifFont)
put"sansserif=",Font.Name(sansSerifFont)
put"mono=",Font.Name(monoFont)
Font.Free(serifFont)
Font.Free(sansSerifFont)
Font.Free(monoFont)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.Name,notbycallingName.
Font.New PartofFontmodule
Syntax Font.New(fontSelectStr:string):int
Description
Font.Newisusedtoobtainafontfordrawing.ThefontSelectStrparameterspecifiesthename,sizeandstyleofthefont.Font.NewreturnsafontidentifierusedbytheFont.Drawproceduretodrawtextintheselectedfont.
TheformatforthefontSelectStrparameteris"Family:Size:Style".Eachelementisseparatedbyacolon.The":Style"isoptional.Ifleftout,thetextappearsinthestandardfaceforthefont.
Familyisthenameofthefont,suchas"Times","Helvetica",etc.Thenamemustmatchanexistingfontonthesystem.Becauseonedoesnotnecessarilyknowwhichfontswillbeavailableandnamesforthesamefontchangebetweendifferentsystems(i.eTimes,Times-Roman,etc.),Turingdefinesthreefamilynamesbemappedascloselyaspossibletofontsthatexistonthesystem.
"serif"isusedforaserifedbodyfont.ThiswillusuallybemappedtoTimes-Roman.
"sansserif"isusedforanon-serifeddisplayfont.ThiswillusuallybemappedtoArial.
"mono"isusedforamonospacedfont.ThiswillusuallybemappedtoCourier.
Sizeisthepointsizeinwhichthetextshouldappear.Ifthenumberislargerorsmallerthancanbecreatedonagivensystem,thesystemwillreturnthefontofthelargestorsmallestsizeavailableandsetError.Last.
UnderTuring,thesizeparametermayalsohavetheformheightxwidthheightandwidtharethepixelheightandwidthdesired.Whatisreturnedisthescaledinordertofitintothewidthandheightrequested.Thefontnamemustbeascaleablefontforthistosucceed.
examplefontID:=Font.New("Ariel:18x12:Italic")
Styleisthefontstyleinwhichthetextshouldappear.Itcanbeoneof"bold","italic"or"underline".Youcanalsohave"bold,italic"andanyothercombination.
Details
IftheFont.Newcallfails,thenitreturns0.AlsoError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnacontainsthetextualversionoftheerror.
ItisquitepossibleforError.Lasttobeset,evenifthecallsucceeds.reportsuccessevenifunabletosuccessfullymatchtherequestedfontwiththeavailableresources.AfontwillbesetthatmatchesascloselyaspossiblerequestedfontandLast.Errorwillbesettoindicatethatsomesubstitutionswererequired.
Example
Theprogramprintsoutseveralphrasesinavarietyoffonts.
varfont1,font2,font3,font4:int
font1:=Font.New("serif:12")
font2:=Font.New("sansserif:18:bold")
font3:=Font.New("mono:9")
font4:=Font.New("Palatino:24:Bold,Italic")
assertfont1>0andfont2>0andfont3>0and
Font.Draw("Thisisinaseriffont",50,30,font1,red
Font.Draw("Thisisinasansseriffont",50,80,
Font.Draw("Thisisinamonofont",50,130,font3,colorfg
Font.Draw("ThisisinPalatino(ifavailable)",50,180,
Font.Free(font1)
Font.Free(font2)
Font.Free(font3)
Font.Free(font4)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.NewNew.
Font.Sizes PartofFontmodule
SyntaxFont.Sizes(fontID:int,varheight,ascent,descent, internalLeading:int)
Description
Font.Sizesisusedtogetthemetricsofaparticularfont.Thevariouspartsofthemetricareillustratedbelow.Notethatyoucancalculatetheexternalleadingbysubtractingtheascentanddescentfromtheheight.
Details
IfFont.SizesispassedaninvalidfontID,afatalerroroccurs.Ifthefailsforother(non-fatal)reasons,themetricsforthedefaultfontwillbereturned.Aswell,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramgetsinformationabout24ptBoldItalicPalatino.
varfontID,height,ascent,descent,internalLeading,
varexternalLeading:int
fontID:=Font.New("Palatino:24:bold,italic")
Font.Sizes(fontID,height,ascent,descent,internalLeading
externalLeading:=heightascentdescent
put"Theheightofthefontis",height,"pixels"
put"Theascentofthefontis",ascent,"pixels"
put"Thedescentofthefontis",descent,"pixels"
put"Theinternalleadingofthefontis",internalLeading
put"Theexternalleadingofthefontis",externalLeading
Font.Free(fontID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.SizesSizes.
Font.StartName PartofFontmodule
Syntax Font.StartName
Description
Font.StartNameisusedtostartthelistingofallthefontsavailableonthesystem.ThisprocedureiscalledbeforemakingcallstoFont.GetNametogetthenameofthefontsavailable.Oncethenameofafontisknown,it'spossibletolisttheavailablestyles(usingFont.GetStyle)andtheavailablesizes(usingFont.StartSizeandFont.GetSize).
Example
Theprogramlistsallthefontsavailableonthesystem.
varfontName:string
Font.StartName
loop
fontName:=Font.GetName
exitwhenfontName=""
putfontName
endloop
Execute
Example
Anotherexampleisavailablethatdisplaysfullinformationaboutthefontsincludingname,styles,andpointsizes.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.StartName,notbycallingStartName.
Font.StartSize PartofFontmodule
Syntax Font.StartSize(fontName,fontStyle:string)
Description
Font.StartSizeisusedtostartalistingofallthesizesforaparticularfontnameandstyle.
ThefontNameparametershouldbeanactualfontname(asopposedtothedefaultnamesof“serif”,etc).YoucangetalistofthefontnamesbyusingtheFont.StartNameFont.GetNamesubprograms.ThefontStyleparametershouldbeinthesameformataswouldappearintheFont.Newprocedure.
Example
Theprogramlistsallthefonts,stylesandsizesavailableonthesystem.
varfontName:string
varbold,italic,underline:boolean
varsize:int
varstyles:arrayboolean,boolean,booleanofstring
init("","underline","italic","italic,underline","bold",
"bold,underline","bold,italic","bold,italic,underline")
Font.StartName
loop
fontName:=Font.GetName
exitwhenfontName=""
Font.GetStyle(fontName,bold,italic,underline
forb:false..bold
fori:false..italic
foru:false..underline
putfontName:30,styles(b,i,
Font.StartSize(fontName,styles
loop
size:=Font.GetSize
exitwhensize=0
ifsize=-1thenput"scalable"..
elseputsize,""..
endif
endloop
put""
endfor
endfor
endfor
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.StartSizeStartSize.
Font.Width PartofFontmodule
Syntax Font.Width(txtStr:string,fontID:int):int
Description
Font.Widthisusedtoobtainthewidthinpixelsthataspecifiedstringwilltaketodrawinaspecifiedfont.ThetextStrparameteristhestring.ThefontIDparameteristhefontinwhichthestringwouldbedrawn.
Details
IfFont.WidthispassedaninvalidfontID,afatalerroroccurs.IftheFont.Widthcallfailsforother(non-fatal)reasons,thewidthforstringinthedefaultfontwillbereturned.Aswell,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramgetsinformationabout24ptBoldPalatino.
consttestString:="TestString"
varwidth,fontID:int
fontID:=Font.New("Palatino:24:Bold")
width:=Font.Width(testString,fontID)
put"Thewidthof\""+testString+"\"is",width
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
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingFont.WidthbycallingWidth.
for statement
Syntax
AforStatementis:
for[decreasing][id]:first..last[byincrement] statementsAndDeclarations endfor
Description
Thestatementsanddeclarationsinaforstatementarerepeatedlyexecuted.Inthefirstiteration,theidentifierisassignedthevalueoffirst.Witheachadditionaliteration,theidentifierincreasesby1(orbyincrement,ifthebyclauseispresent).Theloopstopsexecutingwhenadding1(orincrement)totheidentifierwouldcausetheidentifiertoexceedlast.firstandlastmustbeintegervalues(orelseenumeratedorcharvalues).Ifyouspecifydecreasing,thentheidentifierdecreasesby1(orbyincrement)eachtimethrough.
Incrementmustbeapositiveintegervalue.Whenthebyclauseispresent,theforloopterminatesassoonastheidentifierwouldbecomegreaterthanlast,unlessdecreasingispresent.Ifdecreasingispresent,theloopterminateswhentheidentifierwouldbecomelessthanlast.
Details
Theidentifierischeckedbeforeitisaddedto(orsubtractedfrom).Thismeansthattheloop
fori:1..maxint
willnotcauseanoverflow.
Example
Output1,2,3to10.
fori:1..10
puti
endfor
Output1,3,5,7and9.
Example fori:1..10by2
puti
endfor
Example
Output10,9,8,downto1.
fordecreasingj:10..1
putj
endfor
Example
Output10,6,and2.
fordecreasingj:10..1by4
putj
endfor
Example
Output1.
forj:1..10by20
putj
endfor
Example
Outputnothing.
forj:5..2
putj
endfor
Details
Theforstatementdeclaresthecountingidentifier(aseparatedeclarationshouldnotbegivenforiorj).Thescopeofthisidentifierisrestrictedtotheforstatement.
Iffirstisavaluebeyondlast,therewillbenorepetitions(andnoerrormessage).Thecountingidentifierisalwaysincreased(ordecreased)by1orincrementifthebyclauseispresent.Executinganexitstatementinsideaforstatementcausesajumptojustbeyondendfor.Youarenotallowedtochangethecountingvariable(forexample,youarenotallowedtowritei:=10).
Thecountingidentifiercanbeomitted.Inthiscase,thestatementisjustasbefore,exceptthattheprogramcannotusethevalueof
theidentifier.
Ifdecreasingisnotpresent,first..lastcanbereplacedbythenameofasubrangetype,forexamplebydozen,declaredby:
typedozen:1..12
Procedures,functionsandmodulescannotbedeclaredinsideaforstatement.Justprecedingthestatementsanddeclarations,youareallowedtowritean"invariantclause"oftheform:
invarianttrueFalseExpn
Thisclauseisequivalentto:asserttrueFalseExpn.
fork statement
Dirtyparts
Syntax
AforkStatementis:
forkprocessId[([expn{,expn}])] [:reference[,expn[,reference]]]
Description
Aforkactivates(startstheconcurrentexecutionof)aprocessdeclaration.Iftheprocesshasparameters,aparenthesizedlistofexpressions(expns)mustfollowtheprocess'name(processId).
Example
Thisprograminitiates(forks)twoconcurrentprocesses,oneofwhichrepeatedlyoutputsHiandtheotherHo.TheresultingoutputisanunpredictablesequenceofHi'sandHo's,asgreetingsexecutestwiceconcurrently,oneinstancewithitswordsettoHiandtheotherwithitswordsettoHo.
processgreetings(word:string)
loop
putword
endloop
endgreetings
forkgreetings("Hi")
forkgreetings("Ho")
Seeproceduredeclarationfordetailsaboutparameters.Thefirstoptionalreferenceintheforkstatementmustbeabooleanvariablereference.Theforksetsthistotrueiftheprocessisactuallyactivated.Ifthisfailstooccur(probablybecausestackspacecouldnotbeallocated),thisreferenceissettofalse.Iftheforkfailsbutthisreferenceisomitted,anexceptionoccurs.Seeexceptionhandlers.
Theoptionalexpnspecifiesthenumberofbytesfortheprocess'stack;thisoverridestheoptionallygivenstacksizeintheprocessdeclaration.Thesecondoptionalreferencemustbeavariablereferencewiththetypeaddressint.Seeaddressint.Thisvariableissettoidentifythe
Details processactivation.Thisreferencehastheimplementation-dependentmeaningoflocatingtheprocess'internaldescriptor.
Inthisexplanationoftheforkstatement,wehaveuptothispointignoredthepossibilityofprocessesexportedfrommodules.Iftheprocessisbeingforkedfromoutsideofamodulefromwhichithasbeenexported,thesyntaxoftheforkstatementis:
forkmoduleId.procedureId[(expn{,expn})]…
Inotherwords,themodule'snameandadotmustprecedetheprocess'name.
forward subprogramdeclaration
Syntax
AforwardDeclarationis:
forwardsubprogramHeader [importimportItem{,importItem}]
Description
Aprocedureorfunctionisdeclaredtobeforwardwhenyouwanttodefineitsheaderbutnotitsbody.Thisisthecasewhenoneprocedureorfunctioncallsanother,whichinturncallsthefirst;thissituationiscalledmutualrecursion.Theuseofforwardisnecessaryinthiscase,becauseeveryitemmustbedeclaredbeforeitcanbeused.
Example
Thisexampleprogramevaluatesaninputexpressioneoftheformt}wheretisoftheformp{*p}andpisoftheform(e)oranexplicitrealexpression.Forexample,thevalueof1.5+3.0*(0.5+1.5)haltis7.5.
vartoken:string
forwardprocedureexpn(vareValue:real)
forwardprocedureterm(vartValue:real)
forwardprocedureprimary(varpValue:real)
bodyprocedureexpn
varnextValue:real
term(eValue)%Evaluatet
loop%Evaluate{+t}
exitwhentokennot="+"
gettoken
term(nextValue)
eValue:=eValue+nextValue
endloop
endexpn
bodyprocedureterm
varnextValue:real
primary(tValue)%Evaluatep
loop%Evaluate{*p}
exitwhentokennot="*"
gettoken
primary(nextValue)
tValue:=tValue*nextValue
endloop
endterm
bodyprocedureprimary
iftoken="("then
gettoken
expn(pValue)%Evaluate(e)
asserttoken=")"
else%Evaluate"explicitreal
pValue:=strreal(token)
endif
gettoken
endprimary
gettoken%Startbyreadingfirsttoken
varanswer:real
expn(answer)%Scanandevaluateinputexpression
put"Answeris",answer
Execute
Details
Followingaforwardprocedureorfunctiondeclaration,thebodyoftheproceduremustbegivenatthesamelevel(inthesamesequenceofstatementsanddeclarationsastheforwarddeclaration).Thisistheonlyuseofthekeywordbody.Seealsobody.
Anyprocedureorfunctionthatisdeclaredusingforwardrequiresanimportlist.Inthislist,importedproceduresorfunctionsthathavenotyetappearedmustbelistedasforward.Forexample,theimportlistforexpnisimportforwardterm…Beforeaprocedureorfunctioncanbecalled,beforeitsbodyappears,andbeforeitcanbepassedasaparameter,itsheaderaswellasheadersofproceduresorfunctionsimporteddirectlyorindirectlybyitmusthaveappeared.
Thekeywordforwardisalsousedincollectionandtypedeclarations.
Seealso collectionandtypedeclarations.
frealstr real-to-stringfunction
Syntax frealstr(r:real,width,fractionWidth:int):string
Description
Thefrealstrfunctionisusedtoconvertarealnumbertoastring.Forexample,frealstr(2.5e1,5,1)="b25.0"wherebrepresentsablank.Thestringisanapproximationtor,paddedontheleftwithblanksasnecessarytoalengthofwidth.
ThenumberofdigitsofthefractiontobedisplayedisgivenbyfractionWidth.
Thewidthmustbenon-negative.Ifthewidthparameterisnotlargeenoughtorepresentthevalueofr,itisimplicitlyincreasedasneeded.
ThefractionWidthmustbenon-negative.Thedisplayedvalueisroundedtothenearestdecimalequivalentwiththisaccuracy.Inthecaseofatie,thevalueisroundedtothenextlargervalue.Theresultstringisoftheform:
{blank}[-]{digit}.{digit}
Iftheleftmostdigitiszero,thenitistheonlydigittotheleftofthedecimalpoint.
Thefrealstrfunctionapproximatestheinverseofstrreal,althoughround-offerrorskeepthesefrombeingexactinverses.
Seealso theerealstr,realstr,strreal,intstrandstrintfunctions.
free statement
Syntax
AfreeStatementis:
free[collectionOrClassId,]pointerVariableReference
DescriptionAfreestatementdestroys(deallocates)anelementthathasbeenallocatedbyanewstatement.
Example
Usingacollection,declarealistofrecordsandallocateoneoftheserecords.Thendeallocatetherecord.
varlist:collectionof
record
contents:string(10)
next:pointertolist
%Shortform:next:^list
endrecord
varfirst:pointertolist%Shortform:varnext:^list
newlist,first
%Allocateanelementoflist;placeitslocationinfirst
%Shortform:newfirst
…
freelist,first%Deallocatetheelementoflistlocatedbyfirst
%Shortform:freefirst
Details
Thefreestatementsetsthepointervariabletothenilvalue.Seetheforexamplesofallocatingelementsofclassesandvaluesoftypes.Itthepointerlocatesatype,thecollectionOrClassIdinthefreestatementmustbeomitted.
Animportedclasscanhaveoneofitsobjectsdestroyed(bythefreeonlyiftheclassisimportedvar.
ThecollectionOrClassIdisoptionalinthefreestatement.
Seealsoclassandcollectiondeclarations,thepointertype,thenewstatementvalue.
function declaration
Syntax
AfunctionDeclarationis:
functionid[([paramDeclaration{,paramDeclaration}])]
:typeSpec statementsAndDeclarations endid
Description
Afunctiondeclarationcreates(butdoesnotrun)anewfunction.Thenameofthefunction(id)isgivenintwoplaces,justafterfunctionandjustafterend.
Example
functiondoubleIt(x:real):real
result2.0*x
enddoubleIt
putdoubleIt(5.3)%Thisoutputs10.6
Thesetofparametersdeclaredwiththefunctionarecalledformalparameters.Forexample,inthedoubleItfunction,xisaformalparameter.Afunctioniscalled(invoked)byafunctioncallwhichconsistsofthefunction'snamefollowedbytheparenthesizedlistofactualparameters(ifany).Forexample,doubleIt(5.3)isacallhaving5.3asanactualparameter.Iftherearenoparametersandnoparentheses,thecalldoesnothaveparentheses.Thekeywordfunctioncanbeabbreviatedtofcn.SeealsofunctionCallandprocedureDeclaration.
Eachactualnon-varparametermustbeassignabletothetypeofitscorrespondingformalparameter.Seealsoassignability.
Afunctionmustfinishbyexecutingaresultstatement,whichproducesthefunction'svalue.Intheaboveexample,theresultstatementcomputesandreturnsthevalue2.0*x.
Details
Inprinciple,afunction(1)shouldnotchangeanyvariablesoutsideofitself(globalvariables)or(2)shouldnothavevarparameters.Inotherwords,itshouldhavenosideeffects.Theoriginalimplementationprevented(1)and(2)andtherebypreventedfunctionsideeffects.CurrentimplementationsofTuringdonotenforcethisrestriction.
Theupperboundsofarraysandstringsthatareparametersmaybedeclaredtobeanasterisk(*),meaningtheboundisthatoftheactualparameter.SeeparamDeclarationfordetailsaboutparameters.
Proceduresandfunctionscannotbedeclaredinsideotherproceduresandfunctions.
ThesyntaxofafunctionDeclarationpresentedabovehasbeensimplifiedbyleavingouttheoptionalresultidentifier,importlist,precondition,initclause,postconditionandexceptionhandler.Thefullsyntaxis
function[pervasive]id
[([paramDeclaration{,paramDeclaration}])]
[resultId]:typeSpec
[pretrueFalseExpn]
[initid:=expn{,id:=expn}]
[posttrueFalseExpn]
[exceptionHandler]
statementsAndDeclarations
endid
TheresultIdisthenameoftheresultofthefunctionandcanbeusedonlyinthepostcondition.
Afunctionmustbedeclaredbeforebeingcalled;toallowformutuallyrecursiveproceduresandfunctions,thereareforwarddeclarationswithlaterdeclarationoftheprocedureorfunctionbody.Seeforwardandbodydeclarationsforexplanations.
Youdeclareparameterlessfunctionsusinganemptyparameterlist.Whenthisisdone,acalltothefunctionmustincludeanemptyparameterlist.
Seealso
importlist,precondition,initclause,postconditionandexceptionHandlerforexplanationsoftheseadditionalfeatures.
Seealsopervasive.
functionCall
Syntax
AfunctionCallis:
functionId[([expn{,expn}])]
Description
Afunctioncallisanexpressionthatcalls(invokesoractivates)afunction.Ifthefunctionhasparameters,aparenthesizedlistofexpressions(expns)mustfollowthefunction'sname(functionId).
Example
Thisfunctiontakesastringcontainingablankandreturnsthefirstwordinthestring(allthecharactersuptothefirstblank).
functionfirstWord(str:string):string
fori:1..length(str)
ifstr(i)=""then
resultstr(1..i-1)
endif
endfor
endfirstWord
put"Thefirstwordis:",firstWord("HenryHudson")
%TheoutputisHenry.
Details
Theparameterdeclaredintheheaderofafunction,isaformalparameter,forexample,straboveisaformalparameter.Eachexpressioninthecallisanactualparameter,forexample,sampleaboveisanactualparameter.
Eachactualparameterpassedtoitsnon-varformalparametermustbeassignabletothatparameter(seeassignabilityfordetails).SeealsofunctionDeclarationandprocedureDeclaration.
InthisexplanationoffunctionCall,wehaveuptothispointignoredthepossibilityoffunctionsexportedfrommodules.Ifthefunctionisbeingcalledfromoutsideofamodulefromwhichithasbeenexported,thesyntaxofthefunctionCallis:
moduleId.functionId[(expn{,expn})]
Inotherwords,themoduleormonitornameandadotmustprecede
thefunction'sname.Ifthefunctionisbeingcalledfromoutsideofaclassfromwhichithasbeenexported,thesyntaxofthefunctionCallisoneof:
(a)classId(p).functionId[([expn{,expn
(b)p->functionId[([expn{,expn}])]
Inthesepmustbeapointervaluethatlocatesanobjectintheclass.Form(b)isashortformforform(a).
Seealso class.
get filestatement
Syntax
AgetStatementis:
get[:streamNumber,]getItem{,getItem}
Description
ThegetstatementinputseachofthegetItems.Ordinarily,theoutputcomesfromthekeyboard.However,ifthestreamNumberispresent,theinputcomesfromthefilespecifiedbythestreamnumber(seetheopenstatementfordetails).Also,inputcanberedirectedsoitistakenfromafileratherthanthekeyboard.Checkthedocumentationontheenvironmentforinstructionsondoingso.
ThesyntaxofagetItemisoneof:
(a)variableReference
(b)skip
(c)variableReference:*
(d)variableReference:widthExpn
Theseitemsareusedtosupportthreekindsofinput:
(1)tokenandcharacterorientedinput:supportedbyforms(a)and(b),
(2)lineorientedinput:supportedbyform(c),and
(3)characterorientedinput:supportedbyform(d).
Examplesofthesewillbegiven,followedbydetailedexplanations.
Example
Token-orientedinput.
varname,title:string
varweight:real
getname%IfinputisAlice,itisinput
gettitle%Ifinputis"Alady",Aladyisinput
varweight%Ifinputis9.62,itisinputintoweight
Example
Line-orientedinput.
varquery:string
getquery:*%Entirelineisinputintoquery
Example
Character-orientedinput.
varcode:string
getcode:2%Next2charactersareinputintocode.
Details
Atokenisasequenceofcharacterssurroundedbywhitespace,wherewhitespaceisdefinedasthecharacters:blank,tab,formfeed,newline,andcarriagereturnaswellasend-of-file.Thesequenceofcharactersmakingupthetokenareeitherallnon-whitespaceorelsethetokenmustbeaquotedstring(anexplicitstringconstant).WhenthevariableReferenceinform(a)isastring,integer,real,intn,natn,orrealn.Turingskipswhitespace,readsatokenintothevariableReference,andthenskipswhitespace(stoppingatthebeginningofthenextline).
IfthevariableReferenceisastring,thetokenisassignedtothevariable(ifthetokenisquoted,thequotationmarksarefirstremoved).Seetheexamplesinvolvingnameandtitleabove.IfthevariableReferenceisanintegerorareal,thetokenisconvertedtobenumericbeforebeingassignedtothevariable.Seetheexampleinvolvingweightabove.
Whentheinputiscomingfromthekeyboard,noinputisdoneuntilReturnistyped.Thelinethatisinputmaycontainmorethanonetoken.Anytokensthatarenotinputbyonegetstatementwillremaintobeinputbythenextgetstatement.
Turinghasbeenmodifiedsothattoken-orientedinputnowalsoskipswhitespacefollowingthetoken,butdoesnotskipbeyondthebeginningofthenextline.Thischangeimpliesthatform(b)isusuallynotneeded,asskipwasusedtoskipwhitespaceafterthetoken.
Form(a)supportscharandchar(n).Ifthetypeischar,exactlyonecharacterisread,withnoskippingofwhitespacebeforeorafter.Thischaractermaybe,forexample,ablankoracarriagereturn.Ifthetypeischar(n),exactlyncharactersareread,withnoskippingofwhitespace.
Inputtingcharandchar(n)typesusingform(a).Thestatementgetc:1
Example
isnotlegal,becauselengthspecificationisnotallowedwithcharactervariables.
varc:char
vard:char(3)
getc%Readonecharacter.
getd%Readthreecharacters
Details
Form(a)supportsenumeratedtypes.Ifthetypeisanenumeratedtype,thenthetokenreadinmustbeoneoftheelementsoftheenumeratedtype.
Example
Inputtinganenumeratedtypeusingform(a).Thestatementgetc:1notlegal,becauselengthspecificationisnotallowedwithenumeratedvariables.
typecolors:enum(red,blue,green)
varc:colors
getc%Readoneofred,greenorblue
DetailsForm(a)supportsboolean.Ifthetypeisanbooleantype,thenthetokenreadinmustbeoneof"true"or"false"
Example
Inputtingabooleantypeusingform(a).Thestatementgetc:1isnotlegal,becauselengthspecificationisnotallowedwithbooleanvariable.
vartf:boolean
gettf%Readoneoftrueorfalse
Details
Inform(b)ofgetItem,skipcauseswhitespaceintheinputtobeskippeduntilnon-whitespace(atoken)ortheend-of-fileisreached.Thisisusedwhentheprogramneedstodetermineiftherearemoretokenstobeinput.Todetermineiftherearemoretokenstoberead,theprogramshouldfirstskipoveranypossiblewhitespace(suchasafinalnewlinecharacter)andthentesttoseeifeof(end-of-file)istrue.Thisisillustratedinthisexample:
Usingtoken-orientedinput,inputandthenoutputalltokens.Thisexamplegiveswhatusedtobethestandardwayofreadingtokensuptoendoffile.Withthenewmeaningofform(a)forreadingtokens,the
Example
getskiplinecanbeomitted.Thisomissionispossiblebecausethelinegetwordnowautomaticallyskipswhitespacefollowingtheinputvalue,uptothebeginningofthenextline.
varword:string
loop
getskip%Skipoveranywhitespace
exitwheneof%Aretheremorecharacters?
getword%Inputnexttoken
putword%Outputthetoken
endloop
Intheaboveandthenextexample,iftheinputhasbeenredirectedsothatitisfromafile,eofbecomestrueexactlywhentherearenomorecharacterstoberead.Iftheinputiscomingfromthekeyboard,youcansignaleofbytypingcontrol-Z(onaPC)orcontrol-D(onUNIX).
Details
Inform(c)ofgetItem,thevariableReferenceisfollowedby:*whichimpliesline-orientedinput.Thisformcausestheentireline(ortheremainderofthecurrentline)toberead.Inthiscasethevariablemustbeastring(notanintegerorreal).Thenewlinecharacterattheendofthelineisdiscarded.Itisanerrortotrytoreadanotherlinewhenyouarealreadyattheendofthefile.Thefollowingexampleshowshowtouseline-orientedinputtoreadalllinesintheinput.
Example
Usingline-orientedinput,inputandthenoutputalllines.
varline:string
loop
exitwheneof%Aretheremorecharacters?
getline:*%Readentireline
putline
endloop
Details
Inform(d)ofgetItem,thevariableReferenceisfollowedby
:widthExpn
whichspecifiescharacter-orientedinput.Thisformcausesthespecifiednumber(widthExpn)ofcharacterstobeinput(oralloftheremainingcharactersifnotenoughareleft).Ifnocharactersremain,thenullstringisreadandnowarningisgiven.Inthisform,thenewlinecharacterisactuallyinputintothevariableReference(thisdiffersfrom
line-orientedinputwhichdiscardsnewlinecharacters).Thefollowingexampleshowshowtousecharacter-orientedinputtoreadeachcharacteroftheinput.Form(d)canbeusedwithstringandchar(nvariables,butnotwithchar,intoranyothertype.
Example
Usingcharacter-orientedinput,inputandthenoutputallcharacters.
varch:string(1)
loop
exitwheneof%Aretheremorecharacters?
getch:1%Readonecharacter
putch..%Outputthecharacter,which
%maybeanewlinecharacter
endloop
Example
Usingcharacter-orientedinput,inputtwocharacters.
vard:char(3):='abc'
getd:2%Readtwocharacter(replace'ab')
Seealso readstatement,whichprovidesbinaryfileinput.
getch getcharacterprocedure
Syntax getch(varch:string(1))
Description
Thegetchprocedureisusedtoinputasinglecharacterwithoutwaitingfortheendofaline.Theparameterchissettothenextcharacterinthekeyboardbuffer(theoldestnot-yet-readcharacter).
Example
ThisprogramcontainsaprocedurecalledgetKeywhichcausestheprogramtowaituntilakeyispressed.
setscreen("graphics")
proceduregetKey
varch:string(1)
getch(ch)
endgetKey
fori:1..1000
puti:4,"Pausetillakeyispressed"
getKey
endfor
Details
Thescreenshouldbeina"screen"or"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
OnIBMPC'ssomekeys,suchastheleftarrowkey,insertkey,deletekey,andfunctionkeysdonotproduceordinarycharactervalues.Thesekeystrokesarereturnedbygetchastheir"scancode"with128addedtothem,unlessthescancodealreadyhasavalueof128orgreater.Thisprovidesauniquevalueforeverykeyonthekeyboard.SeeAppendixDforthesecodes.
Seealso
hasch(hascharacter)whichisusedtoseeifacharacterhasbeentypedbutnotyetread.
SeealsopredefinedunitInput.
getchar getcharacterfunction
Syntax getchar:char
Description
Thegetcharfunctionisusedtoinputasinglecharacterwithoutwaitingfortheendofaline.Thenextcharacterinthekeyboardbuffer(theoldestnot-yet-readcharacter)isreturned.
Example
ThisprogramcontainsaprocedurecalledgetKeywhichcausestheprogramtowaituntilakeyispressed.
setscreen("graphics")
proceduregetKey
varch:char
ch:=getchar
endgetKey
fori:1..1000
puti:4,"Pausetillakeyispressed"
getKey
endfor
Details
Thescreenshouldbeina"screen"or"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
OnIBMPC'ssomekeys,suchastheleftarrowkey,insertkey,deletekey,andfunctionkeysdonotproduceordinarycharactervalues.Thesekeystrokesarereturnedbygetcharastheir"scancode"with128addedtoit,unlessthescancodealreadyhasavalueof128orgreater.Thisprovidesauniquevalueforeverykeyonthekeyboard.SeeAppendixDforthesecodes.
Seealso
hasch(hascharacter)whichisusedtoseeifacharacterhasbeentypedbutnotyetread.
SeealsopredefinedunitInput.
getenv getenvironmentfunction
Syntax getenv(symbol:string):string
Description
Thegetenvfunctionisusedtoaccesstheenvironmentstringwhosenameissymbol.Thesestringsaredeterminedbytheshell(commandprocessor)ortheprogramthatcausedyourprogramtorun.Seealsothenargsandfetchargfunctions.
Example
OnaPC,thisretrievestheenvironmentvariableUSERLEVELandprintsextrainstructionsifUSERLEVELhadbeensettoNOVICE.USERLEVELcanbesettoNOVICEwiththecommandSETUSERLEVEL=NOVICEintheautoexec.batfileorinanybatchfile.
constuserLevel:string
userLevel:=getenv("USERLEVEL")
ifuserLevel="NOVICE"then
…%putasetofinstructions
endif
Seealso SeealsopredefinedunitSys.
getpid getprocessidfunction
Syntax getpid:int
Description
ThegetpidfunctionisusedtodeterminetheI.D.(number)thatidentifiesthecurrentoperatingsystemtask(process).Bewarethatthereareprocesses,activatedbytheforkstatement,thatareindependentoftheoperatingsystemstasks.
UnderUNIX,thenumberisused,forexample,forcreatingauniquenameofafile.
Seealsonargs,fetchargandgetenv.
SeealsopredefinedunitSys.
getpriority function
Syntax getpriority:nat
Description
Thegetpriorityfunctionreturnsthepriorityofanexecutingprocessinaconcurrentprogram.Asmallervaluemeansafasterspeed.
Seealsosetpriority,forkandmonitor.
SeealsopredefinedunitConcurrency.
GUI
Description
ThisunitcontainsthepredefinedsubprogramsforcreatingandusingaGUI(GraphicalUserInterface).ElementsoftheGUIincludebuttons,checkboxes,textboxes,scrollbars,menus,etc.
ForageneralintroductiontothetheGUImodule,seeIntroductiontoGraphicalUserInterfaces.
GUI.AddLine PartofGUImodule
Syntax GUI.AddLine(widgetID:int,text:string)
Description
GUI.AddLineaddstextandanewlinetothecurrentlineofthetextboxspecifiedbywidgetID.Itisessentiallyequivalenttoputtextinthetextbox.GUI.AddLinescrollsthetextbox(ifnecessary)sothattheaddedtextisnowvisible.ThewidgetIDparametermustbethewidgetidofatextbox.Thetextparameteristhetexttobeaddedtothetextbox.
Example
Thefollowingcreatesatextboxandputsthenumbersfrom1to25init.
importGUI
varboxID:int:=GUI.CreateTextBox(50,50,200,200)
fori:1..25
GUI.AddLine(boxID,intstr(i))
endfor
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.AddLine,notbycallingAddLine.
Seealso GUI.CreateTextBox.
GUI.AddText PartofGUImodule
Syntax GUI.AddText(widgetID:int,text:string)
Description
GUI.AddTextaddstexttothecurrentlineofthetextboxspecifiedbywidgetID.Itdoesnotaddanewlineafterthetext.Itisessentiallyequivalenttoputtext...inthetextbox.GUI.AddLinescrollsthetextbox(ifnecessary)sothattheaddedtextisnowvisible.ThewidgetIDparametermustbethewidgetidofatextbox.Thetextparameteristhetexttobeaddedtothetextbox.
Details
Toforceatextboxtoscrolltotheendofthetextwithoutaddinganyextratext,callGUI.AddTextwith""(thenullstring)forthetextparameter.
Example
Thefollowingcreatesatextboxandputsthenumbersfrom1to26followedbytheappropriateletterofthealphabetinit.
importGUI
varboxID:int:=GUI.CreateTextBox(50,50,200,200)
fori:1..26
GUI.AddText(boxID,intstr(i))
GUI.AddText(boxID,"")
GUI.AddLine(boxID,chr(64+i))
endfor
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingGUI.AddText,notbycallingAddText.
Seealso GUI.CreateTextBox.
GUI.Alert[2,3,Full] PartofGUImodule
Syntax
Oneoffourprocedures:
GUI.Alert(title,msg:string) GUI.Alert2(title,msg1,msg2:string) GUI.Alert3(title,msg1,msg2,msg3:string) GUI.AlertFull(title:string, msg:array1..*ofstring,button:string)
Description
Displaysadialogboxwiththestringspecifiedbymsginit.ThereisasinglebuttonlabelledOKwhichdismissesthedialogandresumesexecution.ThetitleparameterspecifiesthewindowtitleunderMicrosoftWindows.OntheAppleMacintosh,thereisnotitle,sodonotassumetheuserwillseethetitle.Thedialogboxiscenteredonthescreen.
TheGUI.Alert2andGUI.Alert3proceduresallowtheusertospecifyatwoorthreelinemessagerespectively.TheGUI.AlertFullprocedureallowstheusertospecifyanynumberoflinesoftextinthestringarrayspecifiedbymsgaswellasthetextinthedismissalbutton.Anyemptystringsattheendofthearrayarenotdisplayed.
Note:ThisfunctionisnotavailableinthecurrentversionoftheGUIProcedureLibrary(shippingwithTuring4.0andMacOOT1.5).ItisdocumentedhereforusewithfutureshippingversionofTuring.ItislikelytobeimplementedintheversionofTuringreleasedinSeptember2002.Checkthereleasenotesthatarefoundintheon-linehelptofindoutifthisfunctionisnowavailable.
Thefollowingprogramaskstheuserforthenameofafileputsupanalertdialogboxifitfails.
importGUIin"%oot/lib/GUI"
Example
varfileName:string
varstreamNumber:int
loop
fileName:=GUI.SaveFile("SaveAs")
open:streamNumber,fileName,put
exitwhenstreamNumber>0
GUI.Alert("OpenFailure","\""+fileName+
"\"couldnotbeopened")
endloop
Example
Thefollowingprogramaskstheuserforthenameofafileputsupamorecompletealertdialogboxifitfails.
importGUIin"%oot/lib/GUI"
varfileName:string
varstreamNumber:int
loop
fileName:=GUI.SaveFile("SaveAs")
open:streamNumber,fileName,put
exitwhenstreamNumber>0
GUI.Alert2("OpenFailure",
"\""+fileName+"\"couldnotbeopened.",
"Reason:"+Error.LastMsg)
endloop
Example
Thefollowingprogramfragmentdisplaysanalertwithfourlinesoftextandabuttonthatsays"Abort".
varmessage:array1..10ofstring
fori:1..10
message(i):=""
endfor
…
message(1):="Theprogrammustnowquit"
message(2):="becasueofanunrecoverableerror."
message(3):="AReadErroroccurredwhilereading"
message(4):="file\""+fileName+"\"."
message(5):=Error.LastMsg
GUI.AlertFull("Error",message,"Abort")
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
GUI.Alert,notbycallingAlert.
GUI.Choose[Full] PartofGUImodule
Syntax
Oneoftwoprocedures:
GUI.Choose(title,msg1,msg2,msg3:string, btn1,btn2,btn3:string):int GUI.ChooseFull(title:string, msg:array1..*ofstring, btn1,btn2,btn3:string, defaultBtn:int):int
Description
Displaysadialogboxwithtextandfromonetothreebuttons.Theuserselectsabuttontodismissthedialog.Thenumberofthebuttonpressedisreturnedbythefunction.Thedialogboxiscenteredonthescreen.
Thetitleparameterspecifiesthetitleinthewindowbarofthedialogbox.TheAppleMacintoshdoesnothaveatitlebar,sodonotassumethattheuserwillseethestringinthetitleparameter.Themessageisspecifiedbystringsinandmsg3forGUI.ChooseandthestringarraymessageforGUI.ChooseFulleachcase,emptystringsattheendofthelistofstringsareignored.Theandbtn3parametersspecifythetexttoappearinthebuttons.Ifthetextisanemptystring(""),thebuttonisnotdisplayed.
Thefunctionreturnsthebuttonnumberfromonetothreethatwaschosen.
ThedefaultBtnparameterinGUI.ChooseFullspecifieswhich,ifany,buttonshouldbethedefaultbutton.ThedefaultbuttonisselectediftheuserpressesEnter.Ifthedefaultbuttonis0,thennobuttonishighlightedasthedefaultbutton.
Note:ThisfunctionisnotavailableinthecurrentversionoftheGUIProcedureLibrary(shippingwithTuring4.0andMacOOT1.5).ItisdocumentedhereforusewithfutureshippingversionofTuring.ItislikelytobeimplementedintheversionofTuring.Checkthereleasenotesthatarefoundintheon-linehelptofindoutifthisfunctionisnowavailable.
ThefollowingprogramasksiftheuserwantscoffeeorteaandsetwantsCoffee
Example
appropriately.
importGUIin"%oot/lib/GUI"
varwantsCoffee:boolean
varchoice:int:=GUI.Choose("BeverageChoice",
"Doyouwantcoffeeortea?","","","Coffee","Tea","")
ifchoice=1then
wantsCoffee:=true
else
wantsCoffee:=false
endif
Example
Thefollowingprogramaskstheuserwhethertheywanttosavetheirwork,don'tsavetheirworkorCancel.
importGUIin"%oot/lib/GUI"
%Returnsfalseifcancellingoperation
procedureCheckUnsavedWork:boolean
varmessage:array1..3ofstring
message(1):="Changesto"+fileName+"havenotbeen"
message(2):="saved.Unsavedworkwillbelost.Doyou"
message(3):="wanttosavebeforequitting."
varchoice:int:=GUI.ChooseFull("SaveBeforeQuit",
message,"Save","Don'tSave","Cancel",1)
ifchoice=1then
SaveWork
elsifchoice=3then
returnfalse
endif
returntrue
endCheckUnsavedWork
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.ChoosecallingChoose.
GUI.ClearText PartofGUImodule
Syntax GUI.ClearText(widgetID:int)
DescriptionClearsallthetextinatextboxspecifiedbywidgetID.ThewidgetIDmustbethewidgetidofatextbox.
Example
Theprogramlists25numbersinatextbox.Everytimethebuttonispressed,itclearsthetextboxandprintsthenext25numbers.
importGUI
varboxID,buttonID,start:int
start:=1
procedurePrintTwentyFive
GUI.ClearText(boxID)
fori:start..start+24
GUI.AddLine(boxID,intstr(i))
endfor
start+=25
endPrintTwentyFive
boxID:=GUI.CreateTextBox(50,50,200,200)
buttonID:=GUI.CreateButton(50,5,0,"Next25",
PrintTwentyFive
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.ClearTextbycallingClearText.
Seealso GUI.CreateTextBox.
GUI.CloseWindow PartofGUImodule
Syntax GUI.CloseWindow(window:int)
Description
Closesawindowwithwidgetsinit.ThisprocedureautomaticallydisposesofanywidgetsinthewindowandmakescertainthattheGUILibraryrecognizesthatthewindownolongerexists.ThisprocedurewillcallWindow.Close,sothereisnoneedfortheusertodoso.
Example
Theprogramopensupawindowwithtwobuttons.Ifthebuttonlabelled"CloseandOpen"ispressed,thewindowisclosedandanewwindowwithtwobuttonsisopenedinarandomlocationonthescreen.
importGUI
constscreenWidth:int:=Config.Display(cdScreenWidth
constscreenHeight:int:=Config.Display(cdScreenHeight
consttitleBarHeight:int:=32
constwindowEdgeSize:int:=13
constwindowWidth:int:=150
constwindowHeight:int:=100
varwindowID,windowNumber,closeButton,quitButton
procedureCloseAndOpen
ifwindowIDnot=0then
GUI.CloseWindow(windowID)
endif
windowNumber+=1
varxPos:int:=Rand.Int(0,screenWidth-
windowEdgeSize)
varyPos:int:=Rand.Int(0,screenHeight-
titleBarHeight)
windowID:=Window.Open("title:Window#"+
intstr(windowNumber)+",graphics:"+
intstr(windowWidth)+";"+intstr(windowHeight
",position:"+intstr(xPos)+";"+intstr
closeButton:=GUI.CreateButton(10,60,130,
"CloseAndOpen",CloseAndOpen)
quitButton:=GUI.CreateButton(10,10,130,"Quit",
endCloseAndOpen
CloseAndOpen
loop
exitwhenGUI.ProcessEvent
endloop
GUI.CloseWindow(windowID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CloseWindow,notbycallingCloseWindow.
SeealsoGUI.ShowWindowandGUI.HideWindow,forshowingandhidingwindowswithwidgetsinthem.
GUI.CreateButton[Full] PartofGUImodule
Syntax
GUI.CreateButton(x,y,width:int,text:string,actionProc:procedurex()):int
GUI.CreateButtonFull(x,y,width:int,text:string,actionProc:procedurex(),height:int,shortcut:char,defaultint
Description
Createsabuttonandreturnsthebutton'swidgetID.
Thebuttonwidgetisusedtoimplementatextualbutton.Whenyoubutton,thebutton'sactionprocedureiscalled.Ifabuttonisgivenashortcut,thenenteringthekeystrokewillcausetheactionproceduretobecalled.Itwillnotvisiblycausethebuttontodepress.
TwoButtons
Thexandyparametersspecifythelower-leftcornerofthebutton.Theparameterspecifiesthewidthofthebutton.Ifwidthislessthanthesizenecessarytodisplaythebutton,thebuttonisautomaticallyenlargedtofitthetext.Thetextparameterspecifiesthetexttoappearinthebutton.Theparameteristhenameofaprocedurethatiscalledwhenthebuttonispressed.
ForGUI.CreateButtonFull,theheightparameterspecifiestheheightofthebutton.Ifheightislessthanthesizenecessarytodisplaythebutton,thebuttonisautomaticallyenlargedtofitthetext.Theshortcutparameteristhekeystroketobeusedasthebutton'sshortcut.Thedefaultparameterisabooleanindicating
whetherthebuttonshouldbethedefaultbutton.Ifthereisalreadyadefaultbutton,anddefaultissettotrue,thenthisbuttonbecomesthenewdefaultbutton.
Example
Thefollowingprogramcreatestwobuttons,onewhichdrawsarandomthescreenandonewhichquitstheprogram.
importGUI
procedureDrawRandomCircle
varr:int:=Rand.Int(20,50)
varx:int:=Rand.Int(r,maxx-r)
vary:int:=Rand.Int(r,maxy-r)
varc:int:=Rand.Int(0,maxcolor)
Draw.FillOval(x,y,r,r,c)
%Incasewedrewoverthebuttons,redrawthem.
GUI.Refresh
endDrawRandomCircle
View.Set("graphics:300;200,nobuttonbar")
vardraw:int:=GUI.CreateButtonFull(50,10,0,"DrawCircle",
DrawRandomCircle,0,'^D',true)
varquitBtn:int:=GUI.CreateButton(200,10,0,"Quit",
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
WhenGUI.CreateButtonorGUI.CreateButtonFulliscalled,thenewlycreatedbuttonwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Ifabutton'swidthorheightissettozero(ornotspecifiedatall),thenthebuttonisshapedtofitthetext.
Abuttoncanbethedefaultbuttonforawindow.Thedefaultbuttonwithathickerborderaroundit.IftheuserpressesENTERinawindowwithadefaultbutton,thedefaultbutton'sactionprocedureiscalled.
Whenabuttonisnotenabled,thetextinthebuttonisgrayedoutandthebuttonnolongerrespondstoanymouseclicksorkeystrokesuntilthebuttonisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithabuttonastheparameter:
GUI.Show,GUI.Hide,GUI.Enable,GUI.Disable,GUI.DisposeGUI.GetX,GUI.GetY,GUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize,GUI.SetLabel,GUI.SetDefault
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateButtonnotbycallingCreateButton.
SeealsoGUI.SetLabelforchangingthebutton'stext,GUI.SetDefaultforsettingdefaultbuttoninawindowandGUI.SetColorforsettingthebutton'scolor.
GUI.CreateCanvas[Full] PartofGUImodule
Syntax
GUI.CreateCanvas(x,y,width,height:int):int
GUI.CreateCanvasFull(x,y,width,height:int,border:int,mouseDown:procedurex(mx,my:int),mouseDrag:procedurex(mx,my:int),mouseUp:procedurex(mx,my:int)):int
Description
Createsacanvasandreturnsthecanvas'widgetID.
Acanvasisadrawingsurfaceforusebytheprogram.Itdiffersfromjustusingthewindowsurfacetodrawoninthat(0,0)representsthelower-leftcornerofthecanvasandalldrawingisclippedtothecanvas.(Thismeansthatifyouaccidentlyattempttodrawoutsideofthecanvas,itwillnotactuallydrawbeyondtheborderofthecanvas.)
CanvaseshaveproceduresthatemulatealltheproceduresintheDrawmoduleaswellasaproceduretoemulateFont.Draw,Pic.Draw,Pic.New,Pic.ScreenLoadandPic.ScreenSave.
Youcangetmousefeedbackfromacanvas.UsingtheCreateCanvasFullmethod,youcanspecifythreeroutinesthatarecalledwhenthemousebuttonisdepressedwhilepointinginacanvas.Oneroutinewillbecalledwhentheuserpressesthemousebuttondowninacanvas.Anotherroutinewillbecalledwhiletheuserdragsthemousewiththemousebuttondown.Thisroutineisrepeatedlycalledwheneverthemousechangespositionwhilethemousebuttonisdown.Thelastroutineiscalledwhenthemousebuttonisreleased.Allthreeroutinestakeanandyparameter,whichisthelocationofthemousewithrespecttothecanvas(i.e.(0,0)isthelower-leftcornerofthecanvas).
OutputofCanvases.dem
Thexandyparametersspecifythelower-leftcornerofthecanvas.Thewidthandheightparametersspecifythewidthandheightofthecanvas.
ForGUI.CreateCanvasFull,theborderparameterspecifiesthetypeofborderthatsurroundsthecanvasandisoneof0,GUI.LINE,GUI.INDENTorGUI.EXDENT.Aborderof0isthedefaultandisthesameasGUI.LINE.GUI.INDENTandGUI.EXDENTonlydisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthecanvasappearindentedorrecessed.GUI.EXDENTmakesthecanvasappeartostandoutfromthewindow.
ThemouseDownparameterisaprocedurecalledwhentheuserpressesthemousebuttoninthecanvas.ThemouseDragparameterisaprocedurecalledwhentheuserdragsthemousewhilethemousebuttonisstillpressed.ThemouseUpparameterisaprocedurecalledwhentheuserreleasesthemousebutton.Theparameterstoallthreearethexandylocationofthemousewherethebuttonwaspressed(dragged/released).Thecoordinatesaregivenwithrespecttothecanvas(i.e.(0,0)isthelower-leftcornerofthecanvas).
Example
Thefollowingprogramdraws10randomstarsinthecanvas.
importGUI
varcanvas:int:=GUI.CreateCanvas(10,10,maxx
fori:1..10
varx:int:=Rand.Int(0,maxx-20)
vary:int:=Rand.Int(0,maxy-20)
varc:int:=Rand.Int(0,maxcolor)
GUI.DrawFillOval(canvas,x,y,20,20,c)
endfor
Execute
Details
WhenGUI.CreateCanvasorGUI.CreateCanvasFulliscalled,thenewlycreatedcanvaswillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Theborderofthecanvasisjustoutsidethedrawingsurface,soGUI.GetWidthandGUI.GetHeightwillreturnslightlargervaluesthanwidthandheight.
Whenthecanvasisdisabled,clickingthemouseinthecanvasdoesnotcallanyofthemouseDown,mouseDrag,ormouseUpprocedures.Theappearanceofthecanvasdoesnotchange.
Details
ThefollowingGUIsubprogramscanbecalledwithabuttonasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Enable,GUI.Disable,GUI.DisposeGUI.GetX,GUI.GetY,GUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize,GUI.Draw…,GUI.FontDraw,GUI.Pic…,GUI.SetXOR
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateCanvas,notbycallingCreateCanvas.
SeealsoGUI.Draw…,GUI.FontDraw,GUI.Pic…,andGUI.SetXORfordrawingonacanvas.
GUI.CreateCheckBox[Full] PartofGUImodule
Syntax
GUI.CreateCheckBox(x,y:int,text:string,actionProc:procedurex(filled:boolean)):int
GUI.CreateCheckBoxFull(x,y:int,text:string,actionProc:procedurex(filled:boolean),alignment:int,shortcutint
Description
Createsacheckbox(withaccompanyingtext)andreturnsthecheckbox'swidgetID.
Thecheckboxwidgetisusedtoimplementacheckboxthatcanbesetorunset.Whenyouclickonacheckbox,thestatusofthecheckboxflipsfromsettounsetandbackagainandthecheckbox'sactionprocedureiscalledwiththenewstatusasaparameter.Ifacheckboxisgivenashortcut,thenenteringthekeystrokewillcausethecheckboxtochangestatusandtheactionprocedurebecalled.Thenewstatuswillbedisplayedimmediately.
TwoCheckBoxes
Thexandyparametersspecifythelower-leftcornerofthecheckbox(unlessalignmentissettoGUI.RIGHT,inwhichcasetheyspecifythelower-rightcornerofthecheckbox).Thetextparameterspecifiesthetext(orlabel)besidethecheckbox.TheactionProcparameteristhenameofaprocedurethatiscalledwhenthestatusofthecheckboxchanges.TheactionProcproceduremusthaveonebooleanparameterwhichisthenewstatusofthecheckbox.InGUI.CreateCheckBox,thecheckbox'stextisalwaystotherightoftheactualcheckbox.InGUI.CreateCheckBoxFull,thetextcanbesettotherightorleftofthecheckboxwiththealignmentparameter.
ForGUI.CreateCheckBoxFull,thealignmentparameterspecifiesthepositionofthecheckboxinrelationtothetextaswellasthemeaningofthe
parameters.Thealignmentparameterisoneof0,GUI.LEFT,orGUI.RIGHTalignmentof0isthedefaultandisthesameasGUI.LEFT.GUI.LEFTactualboxinthecheckboxappearstotheleftofthecheckbox'slabeland(specifiesthelower-leftcorner.AnalignmentofGUI.RIGHTmeansthattheactualboxappearstotherightofthecheckbox'slabeland(x,y)specifiesthelower-rightcornerofthecheckbox.Theshortcutparameteristhekeystroketobeusedasthebutton'sshortcut.Thedefaultparameterisabooleanindicatingwhetherthebuttonshouldbethedefaultbutton.Ifthereisalreadyadefaultbutton,anddefaultissettotrue,thenthisbuttonbecomesthenewdefaultbutton.
Acheckbox'ssizeisnotspecifiedduringcreation.Itisdeterminedbasedonthesizeofthetext.Insteadtheuserspecifiesthelower-leftcornerofthecheckbox(orthelower-rightifthecheckboxisrightjustified).
Example
Thefollowingprogramcreatestwobuttons,onewhichdrawsarandomcircleonthescreenandonewhichquitstheprogram
importGUI
procedureDoNothing(status:boolean)
endDoNothing
View.Set("graphics:300;100,nobuttonbar")
varcb1:int:=GUI.CreateCheckBox(10,10,"CheckBox1",
DoNothing)
varcb2:int:=GUI.CreateCheckBoxFull(200,10,"CheckBox2",
DoNothing,GUI.RIGHT,'2')
GUI.SetCheckBox(cb2,true)
varquitBtn:int:=GUI.CreateButton(230,10,0,"Quit",
loop
exitwhenGUI.ProcessEvent
endloop
varcb1Status:boolean:=GUI.GetCheckBox(cb1)
varcb2Status:boolean:=GUI.GetCheckBox(cb2)
ifcb1Statusthen
put"Checkbox1:filled"
else
put"Checkbox1:empty"
endif
ifcb2Statusthen
put"Checkbox2:filled"
else
put"Checkbox2:empty"
endif
Execute
Details
WhenGUI.CreateButtonorGUI.CreateButtonFulliscalled,thenewlycreatedcheckboxwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenacheckboxisnotenabled,thelabelbesidethecheckboxisgrayedoutandthecheckboxnolongerrespondstoanymouseclicksorkeystrokesuntilthecheckboxisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithacheckboxastheparameter:
GUI.Show,GUI.Hide,GUI.Enable,GUI.Disable,GUI.DisposeGUI.GetX,GUI.GetY,GUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize,GUI.SetLabel,GUI.GetCheckBox,GUI.SetCheckBox
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateCheckBoxnotbycallingCreateCheckBox.
SeealsoGUI.SetLabelforchangingthechecbox'stextandGUI.GetCheckBoxGUI.SetCheckBoxforreadingandsettingthecheckbox'sstate.
GUI.CreateFrame PartofGUImodule
Syntax GUI.CreateFrame(x1,y1,x2,y2,kind:int):int
Description
Createsaframeandreturnstheframe'swidgetID.
AframeisaboxdrawnaroundotherGUIwidgetstomakethewindowlookbetterandhelporganizetheGUIelements.
ThreeTypesofFramesWithaLabelinEachFrame
FramesaretheonlyGUIwidgetsthatcanhaveotherwidgetsplacedwithinthem.Framesarepassivewidgets,meaningthattheydonotrespondtobuttonclicksorkeystrokes.
Thex1andy1parametersspecifythelower-leftcorneroftheframeandthex2andy2parametersspecifytheupper-rightcorneroftheframe.Thekindparameterspecifiesthetypeofframe.Thisisoneof0,GUI.LINEGUI.INDENT,orGUI.EXDENT.Akindof0isthedefaultandisthesameasGUI.LINE.
GUI.INDENTandGUI.EXDENTonlydisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthecontentsframeappearindentedorrecessed.GUI.EXDENTmakesthecontentsoftheframeappeartostandoutfromthewindow.
Thefollowingprogramdrawsthreeframesinthewindowanddrawsalabelineachone.
importGUI
View.Set("graphics:250;90,nobuttonbar")
GUI.SetBackgroundColor(gray)
varlineFrame,indentFrame,exdentFrame:int
ExamplevarlineLabel,indentLabel,exdentLabel:int
lineFrame:=GUI.CreateFrame(10,10,80,70,0)
indentFrame:=GUI.CreateFrame(90,10,160,70,
exdentFrame:=GUI.CreateFrame(170,10,240,70,
%Labelthelines.
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
WhenGUI.CreateFrameiscalled,thenewlycreatedframewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Aframewidgetisapassivewidgetandcannotbeenabledordisabled.
Details
ThefollowingGUIsubprogramscanbecalledwithaframeasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSizeGUI.SetPositionAndSize
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateFrame,notbycallingCreateFrame.
GUI.CreateHorizontalScrollBar[Full] PartofGUImodule
Syntax
GUI.CreateHorizontalScrollBar(x,y,size:int,min,max,start:int,actionProc:procedurex(value:int
GUI.CreateHorizontalScrollBarFull(x,y,size:int,min,max,start:int,actionProc:procedurex(value:int),arrowInc,pageInc,thumbSize:int):int
Description
Createsahorizontal(left-right)scrollbarandreturnsthescrollbar'swidgetID.
Ascrollbarisawidgetthatallowsuserstoseeapieceofadocumentthatcannotbedisplayedonthescreeninitsentirety.Thepicturebelowshowsahorizontalscrollbar.Tocontrolascrollbar,thereareafewchoices:theusercanclickonthethumb(theboxinthescrollbar)andslideitleftorright,ortheusercanclickinthescrollbaritselftotheleftorrightofthethumb(inwhichcasethethumbismovedupordownone"page"),ortheusercanclickontheleftorrightarrowsattheendsofthescrollbar(inwhichcasethethumbismovedleftorrightone"arrowincrement").
AHorizontalScrollBar
Theprogrammerdefinesapageoranarrowincrement.Whenthevalueofthescrollbarchanges,theactionprocedureofthescrollbariscalledwiththenewvalueasaparameter.Theactionprocedureshouldthenredrawthecontentsusingthenewvalueofthescrollbar.
TherangeofvaluesthatthescrollbarwillgiveisdeterminedbythemaxparametersintheCreatecall.Theleftsideofthescrollbarrepresentstheminimumvalue,whiletherightrepresentsthemaximumvalue.Thereisalsothe"thumbsize".Thisrepresentstherangeofvaluesthatcanbeseenatonceonthescreen.
Bydefault,thearrowincrement(theamountthevalueischangedwhenthescrollingarrowsarepressed)issettoone.Thepageincrement(theamountthevalueischangedwhentheuserclicksinthebartotherightorleftofthethumb)issettoonequarterthedifferencebetweentheminimumandthemaximum.The"thumbsize"issettozero(seethedescriptionofscrollbarsforanexplanationofthethumbsize).
Thexandyparametersspecifythelower-leftcornerofthescrollbar.Theparameterspecifiesthelengthofthescrollbar(includingthearrows)inpixels.Theminandmaxparametersaretheminimumandmaximumvaluesreturnedbythescrollbar.Thestartparameteristheinitialvalueofthescrollbarandshouldbebetweenminandmaxinclusive.TheactionProcparameternameofaprocedurethatiscalledwhenthevalueofthescrollbarischanged.Theparametertotheactionprocedureisthecurrentvalueofthescrollbar.
Example
Thefollowingprogramcreatesahorizontalscrollbar.Wheneverthescrollbar'svalueischanged,amessageisdisplayedinthewindow.
importGUI
View.Set("graphics:300;60,nobuttonbar")
varscrollBar:int
procedureScrollBarMoved(value:int)
Text.Locate(2,3)
put"HorizontalScrollBar:",value:4
endScrollBarMoved
scrollBar:=GUI.CreateHorizontalScrollBar(10,10,250,
50,150,50,ScrollBarMoved)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
ForGUI.CreateHorizontalScrollBarFull,thearrowIncparameterspecifies
Description
thearrowincrement(theamountthescrollbar'svalueischangedwhenthescrollarrowsarepressed).ThepageIncspecifiesthepageincrement(theamountthescrollbar'svalueischangedwhentheuserclicksinthepageleft/rightsectionofthescrollbar).ThethumbSizeparameterspecifiesthe"thumbsize".(Seethescrollbarexplanationformoredetailonascrollbar's"thumbsize").
Forexample,ifyouhaveawindowthatcandisplay20linesoftextatonceandthereare100linesoftext,youwouldsetminto1,maxto100and20.Thevaluereturnedbythescrollbarwouldthenbethelinenumberofthefirstlineonthescreentobedisplayed.Whenthescrollbarwasatitsmaximumvalue,itwouldreturn81,sincebydoingso,lines81-100wouldbedisplayed.
Example
Hereisanexampleprogramthatscrollsalargepictureoverasmallerwindow.
%The"ScrollPic"program.
importGUI
varh,v:int%Thescrollbars.
varcanvas:int%Thecanvas.
varpic:int%Thepicture.
constwidth:int:=220%Thewidthofthecanvas.
procedureScrollPic(ignore:int)
%Getthecurrentvalueofthescrollbars.
varx:int:=GUI.GetSliderValue(h)
vary:int:=GUI.GetSliderValue(v)
GUI.PicDraw(canvas,pic,-x,-y,picCopy)
endScrollPic
pic:=Pic.FileNew("Forest.jpg")
ifpic<=0then
put"Errorloadingpicture:",Error.LastMsg
return
endif
View.Set("graphics:265;265")
canvas:=GUI.CreateCanvas(15,15+GUI.GetScrollBarWidth
width,width)
%Notetheframeofthecanvasis:
%(14,14+ScrollbarWidth)-(235,235+ScrollbarWidth)
h:=GUI.CreateHorizontalScrollBarFull(14,14,
221,0,Pic.Width(pic),0,ScrollPic,3,100,
v:=GUI.CreateVerticalScrollBarFull(235,
14+GUI.GetScrollBarWidth,221,0,Pic.Height
Pic.Height(pic),ScrollPic,3,100,width)
ScrollPic(0)%Drawthepictureinitially
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
Insomeinstances,youwillwantthetheminimumandmaximumvaluesofthescrollbartobereversed(right/topisminimum).Inthatcase,calltheGUI.SetSliderReverseproceduretoflipthevaluesofthescrollbar.
Scrollbarsalwayshaveafixedheight(forhorizontalscrollbars)orwidth(forverticalscrollbars).Togetascrollbar'swidth,usetheGUI.GetScrollBarWidthfunction.
WhenGUI.CreateHorizontalScrollBarorGUI.CreateHorizontalScrollBarFulliscalled,thenewlycreatedscrollbarwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenascrollbarisnotenabled,thegrayinthebarissettowhiteandthethumbisnotdisplayed.Thescrollbarnolongerrespondstoanymouseclicksuntilthescrollbarisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithascrollbarastheparameter:
GUI.Show,GUI.Hide,GUI.Enable,GUI.Disable,GUI.DisposeGUI.GetX,GUI.GetY,GUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize,GUI.GetSliderValue,GUI.SetSliderValue,GUI.SetSliderMinMaxGUI.SetSliderSize,GUI.SetSliderReverse,GUI.SetScrollAmount
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateHorizontalScrollBar,notbycallingCreateHorizontalScrollBar
Seealso
GUI.GetSliderValueandGUI.SetSliderValueforreadingandsettingthevalueofascrollbar,GUI.SetSliderMinMaxforchangingtheminimumandmaximumvaluesofascrollbar,andGUI.SetScrollAmountforchangingthescrollingincrementsandthumbsizeofascrollbar.SeealsoGUI.SetSliderSizeforsettingthelengthofascrollbarandGUI.SetSliderReverseforreversingthesenseofascrollbar.
GUI.CreateHorizontalSlider PartofGUImodule
Syntax
GUI.CreateHorizontalSlider(x,y,length:int,min,max,start:int,actionProc:procedurex(value:int)):int
Description
Createsahorizontal(left-right)sliderandreturnstheslider'swidgetID.
Asliderisawidgetthatallowstheusertosetacontinuoussetofvalues.Ithasareal-lifeequivalentinthingssuchasastereovolumecontrol.
AHorizontalSlider
Tocontrolaslider,theuserclicksonthesliderboxanddragsitbackandforth.Everytimethevaluechanges,aprocedureiscalledwiththenewvalueasaparameter.
TherangeofvaluesthatthesliderwillgiveisdeterminedbytheminandmaxparametersintheCreatecall.Theleftsideofthesliderrepresentstheminimumvalue,whiletherightrepresentsthemaximumvalue.
Thexandyparametersspecifythelower-leftcorneroftheslidertrack.Thismeansthattheslideractuallyextendsaboveandbelowthispoint(andslightlytotheleftofittotakeintoaccounttheroundedendofthetrack).Thelengthparameterspecifiesthelengthofthetrackinpixels.(YoucanuseGUI.GetX,GetY,GetWidth,andGetHeighttogettheexactdimensionsoftheslider.)Theminandmaxparametersaretheminimumandmaximumvaluesreturnedbytheslider.Thestartparameteristheinitialvalueofthesliderandshouldbebetweenminandmaxinclusive.TheactionProcparameteristhenameofaprocedure
thatiscalledwhenthevalueofthesliderischanged.Theparametertotheactionprocedureisthecurrentvalueoftheslider.
Example
Thefollowingprogramcreatesahorizontalslider.Whenevertheslider'svalueischanged,amessageisdisplayedinthewindow.
importGUI
View.Set("graphics:300;60,nobuttonbar")
varslider:int
procedureSliderMoved(value:int)
Text.Locate(2,3)
put"HorizontalSlider:",value:4
endSliderMoved
slider:=GUI.CreateHorizontalSlider(10,10,250,
50,150,50,SliderMoved)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
Insomeinstances,youwillwantthetheminimumandmaximumvaluesoftheslidertobereversed(rightisminimum).Inthatcase,calltheGUI.SetSliderReverseproceduretoflipthevaluesoftheslider.
Slidersalwayshaveafixedheight(forhorizontalsliders)orwidth(forverticalsliders).
WhenGUI.CreateHorizontalSliderorGUI.CreateHorizontalSliderFulliscalled,thenewlycreatedsliderwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplay
parametersettofalse.
Whenasliderisnotenabled,theappearancedoesnotchange.However,theslidernolongerrespondstoanymouseclicksuntilitisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithasliderasthewidgetIDparameter:
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
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateHorizontalSlider,notbycallingCreateHorizontalSlider.
Seealso
GUI.GetSliderValueandGUI.SetSliderValueforreadingandsettingthevalueofaslider,GUI.SetSliderMinMaxforchangingtheminimumandmaximumvaluesofaslider.SeealsoGUI.SetSliderSizeforsettingthelengthofasliderandGUI.SetSliderReverseforreversingthesenseofaslider.
GUI.CreateLabel[Full] PartofGUImodule
Syntax
GUI.CreateLabel(x,y:int,text:string):int
GUI.CreateLabelFull(x,y:int,text:string,width,height,alignment,fontID:int):int
Description
Createsalabelandreturnsthelabel'swidgetID.
Thelabelwidgetisusedtodisplaytext.Itcanbeusedtodisplaytextinavarietyoffontsandsizes.Labelwidgetscanalsobealignedinavarietyofways.
ThreeLabels
Thexandyparametersspecifythelower-leftcorneroftheareainwhichthetextwillbedrawn.ForGUI.CreateLabel,thisisthelower-leftcornerofthetext.Thetextparameterspecifiesthetextofthelabel.
ForGUI.CreateLabelFull,thewidthandheightparametersspecifytheareainwhichthelabelistoappear.Thisisusedforalignmentpurposes.Seetheprogrambelowforanexampleofaligningthetexttodifferentcornersofthewindow.Thealignmentparameterspecifiesthealignmentofthetextinthetextarea.Thisvalueisthesumofhorizontalalignmentandtheverticalalignment.Thehorizontalalignmentisoneof0,GUI.LEFT,GUI.CENTER,orGUI.RIGHT.Ahorizontalalignmentof0isthedefaultandisthesameasthealignmentofGUI.LEFTverticalalignmentisoneof0,GUI.TOP,GUI.MIDDLE,orGUI.BOTTOMhorizontalalignmentof0isthedefaultandisthesameasthealignmentofGUI.BOTTOM.Thesealignmentsalignthetextinvariouswaysinthetextarea.ThefontIDparameterspecifiesthefontIDofthefonttobeusedinthetextfield.ThefontIDisreceivedfromaFont.Newcall.DonotcallFont.FreeIDuntilthelabelhasbeendisposedofbycallingGUI.Dispose.
ByusingthefondIDparameter,labelscanbehaveanysizeortypeface.
Labelsarepassivewidgets,meaningthattheydonotrespondtobuttonclicksorkeystrokes.
Example
Thefollowingprogramcreatesthreelabels,onewiththedefaultalignment,theothertwoalignedtoappearinthecenterandupper-rightcornerofthewindow.
importGUI
View.Set("graphics:300;100,nobuttonbar")
varlowerLeft:int:=GUI.CreateLabel(0,0,"Lower-Left")
varcenter:int:=GUI.CreateLabelFull(0,0,"Center",
GUI.MIDDLE+GUI.CENTER,0)
varupperRight:int:=GUI.CreateLabelFull(0,0,"Upper-Right",
maxx,maxy,GUI.RIGHT+GUI.TOP,0)
Execute
Details
WhenGUI.CreateLabelorGUI.CreateLabelFulliscalled,thenewlycreatedlabelwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedcalledwiththedisplayparametersettofalse.
Aframewidgetisapassivewidgetandcannotbeenabledordisabled.
Details
ThefollowingGUIsubprogramscanbecalledwithalabelasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSizeGUI.SetPositionAndSize,GUI.GetSliderValue,GUI.SetSliderValueGUI.SetSliderMinMax,GUI.SetLabel
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateLabelbycallingCreateLabel.
Seealso GUI.SetLabelforchangingthelabel'stext.
GUI.CreateLabelledFrame PartofGUImodule
SyntaxGUI.CreateLabelledFrame(x1,y1,x2,y2,kind:int,text:string):int
Description
Createsalabelledframeandreturnstheframe'swidgetID.
AlabelledframeisaboxwithatextlabeldrawnaroundotherGUIwidgetstomakethewindowlookbetterandhelporganizetheGUIelements.
ThreeTypesofLabelledFrames
FramesandlabelledframesaretheonlyGUIwidgetsthatcanhaveotherwidgetsplacedwithinthem.Labelledframesarepassivewidgets,meaningthattheydonotrespondtobuttonclicksorkeystrokes.
Thex1andy1parametersspecifythelower-leftcorneroftheframeandthex2andy2parametersspecifytheupper-rightcorneroftheframe.(Thetextwillextendabovetheframe.)Thekindparameterspecifiesthetypeofframe.Thisisoneof0,GUI.LINE,GUI.INDENTorGUI.EXDENT.AkindthedefaultandisthesameasGUI.LINE.
GUI.INDENTandGUI.EXDENTonlydisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthecontentsframeappearindentedorrecessed.GUI.EXDENTthecontentsoftheframeappeartostandoutfromthewindow.
Example
Thefollowingprogramdrawsthreeframesinthewindow.
importGUI
View.Set("graphics:250;90,nobuttonbar")
GUI.SetBackgroundColor(gray)
varlineFrame,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
WhenGUI.CreateLabelledFrameiscalled,thenewlycreatedlabelledframewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedbeencalledwiththedisplayparametersettofalse.
Alabelledframewidgetisapassivewidgetandcannotbeenabledordisabled.
Details
ThefollowingGUIsubprogramscanbecalledwithalabelledframeasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSizeGUI.SetPositionAndSize,GUI.SetLabel
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateLabelledFrame,notbycallingCreateLabelledFrame
Seealso GUI.SetLabelforchangingtheframe'stext.
GUI.CreateLine PartofGUImodule
Syntax GUI.CreateLine(x1,y1,x2,y2,kind:int):int
Description
Createsalineandreturnstheline'swidgetID.
Linesaregenerallyusedtoseparatepartsofawindow.AlineisusedtomakethewindowlookbetterandhelporganizetheGUIelements.
ThreeTypesofLines
Linesarepassivewidgets,meaningthattheydonotrespondtobuttonclicksorkeystrokes.
Thex1andy1parametersspecifyoneend-pointofthelineandthespecifytheotherendpoint.Thelinemusteitherbehorizontalorvertical(i.e.x1mustequalx2ory1mustequaly2).Thekindparameterspecifiesthetypeofline.Thisisoneof0,GUI.LINE,GUI.INDENTorGUI.EXDENT.Akindof0isthedefaultandisthesameasGUI.LINE.
GUI.INDENTandGUI.EXDENTonlydisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthelineappearindentedorrecessed.GUI.EXDENTmakesthelineappeartostandoutfromthewindow.
Example
Thefollowingprogramdrawsthreelineswiththreelabelsinthewindow.
importGUI
View.Set("graphics:180;100,nobuttonbar")
GUI.SetBackgroundColor(gray)
varline,indentLine,exdentLine:int
varlineLabel,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,
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
WhenGUI.CreateLineiscalled,thenewlycreatedlinewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplay
Alinewidgetisapassivewidgetandcannotbeenabledordisabled.
Details
ThefollowingGUIsubprogramscanbecalledwithalineasthewidgetID
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateLineCreateLine.
GUI.CreateMenu PartofGUImodule
Syntax GUI.CreateMenu(name:string):int
Description
Createsamenuandreturnsthemenu'swidgetID.Themenuwillbeaddedaftertheothermenusinthemenubar.Iftherearenopreviousmenus,thenamenubarisautomaticallycreatedandthemenuadded.
Thenameparameterspecifiesthetextthatappearsinthemenubar.
AMenuWithanItemSelected
Menusareusedinmostmoderninterfaces.Inordertocreateafullsetofmenus,youmustcreatethemenuandthencreatethemenuitemsinthatmenu.Themenusareautomaticallyaddedtothemenubaroftheselectedmenu.
Asofthev1.0releaseoftheGUILibrary,itisanerrortocreateamenuitemwithouthavingcreatedamenufirst.Infuturereleasesitwillbepossibletocreatemenusandattachandremovethemfrommenubarswhendesired.
Thefollowingprogramcreatesaseriesofmenuswithmenuitemsinthem.Itthendisablesthesecondmenu.
importGUIin"%oot/lib/GUI"
View.Set("graphics:250;150,nobuttonbar")
varfirst,second:int%Themenus.
varitem:array1..12ofint%Themenuitems.
varname:array1..12ofstring(20):=
init("Quit","---","A","B","---","C","D",
"DisableBMenuItem","EnableBMenuItem","---",
Example
"DisableSecondMenu","EnableSecondMenu")
procedureMenuSelected
fori:1..12
ifitem(i)=GUI.GetEventWidgetIDthen
Text.Locate(maxrow,1)
putname(i)+"selected"..
endif
endfor
endMenuSelected
procedureDisableB
GUI.Disable(item(4))
endDisableB
procedureEnableB
GUI.Enable(item(4))
endEnableB
procedureDisableFirst
GUI.Disable(first)
endDisableFirst
procedureEnableFirst
GUI.Enable(first)
endEnableFirst
%Createthemenus
first:=GUI.CreateMenu("First")
item(1):=GUI.CreateMenuItem(name(1),GUI.Quit
forcnt:2..7
item(cnt):=GUI.CreateMenuItem(name(cnt),
MenuSelected)
endfor
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
exitwhenGUI.ProcessEvent
endloop
Execute
DetailsWhenamenuisnotenabled,thetextinthemenubarisgrayedoutandclickingonthemenudoesnotcausethemenutoappear.
Details
ThefollowingGUIsubprogramscanbecalledwithamenuasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.Enable,GUI.Disable
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateMenu,notbycallingCreateMenu.
Seealso
GUI.CreateMenuItemforaddingitemstoamenu.SeealsoGUI.ShowMenuBarandGUI.HideMenuBarforshowingandhidingthemenubar.
GUI.CreateMenuItem[Full] PartofGUImodule
Syntax
GUI.CreateMenuItem(name:string,actionProc:procedurex()):int
GUI.CreateMenuItemFull(name:string,actionProc:procedurex(),shortCut:char,addNow:boolean):int
Description
Createsamenuitemandreturnsthemenuitem'swidgetID.
Menuitemsaretheindividualentriesofamenu.Tocreatemenusforawindow,youmustcreateamenu,thencreatethemenuitemsforthatmenu,thencreatethenextmenu,etc.Allmenuitemsareautomaticallyaddedtothelastmenuandafterthelastmenuitemofthecurrentlyselected(notactive!)window.
Themenuitemwillbeaddedtothelastmenuaftertheothermenuitemsinthemenu.Iftherearenomenusdefined,anerrorresults.
Thenameparameterspecifiesthetextthatistoappear.Anameofthreedashes("---")createsaseparatoracrossthemenu.TheactionProcparameterspecifiesthenameofaproceduretobecalledwhenusertheselectsthemenuitemfromthemenu.
ForGUI.CreateMenuItemFull,theshortCutparameterspecifiesthekeystroketobeusedasthemenuitem'sshortcut.Ifnoshortcutisdesired,then'\0'canbeused.TheaddNowparameterhasnoeffectinthecurrentversionoftheGUILibrary.Infutureversions,itwillallowyoutocreatemenuitemsthatcanthenbeaddedtoamenulaterintheprogram.
Examples SeetheexampleforGUI.CreateMenu.
Execute
Details
Whenamenuitemisnotenabled,thetextofthemenuitemisgrayedoutandclickingonthemenuitemdoesnotcausethemenutoappear.
Details
ThefollowingGUIsubprogramscanbecalledwithamenuasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.Enable,GUI.Disable
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateMenuItem,notbycallingCreateMenuItem.
GUI.CreatePicture PartofGUImodule
SyntaxGUI.CreatePicture(x,y,picture:int,mergePic:boolean):int
Description
Createsapictureandreturnsthepicture'swidgetID.
Thepicturewidgetisusedtodisplayapicture.Itcanbeusedtodisplayapictureeithermergedintothebackgroundornot.
Thexandyparametersspecifythelower-leftcornerofthepicture.TheparameterspecifiesthepictureIDofthepicture.ThepictureIDisreceivedfromaPic.NeworPic.FileNewcall.DonotcallPic.FreeforthispictureIDuntilthebuttonhasbeendisposedofbycallingGUI.Dispose.ThemergePicparameterisabooleanthatspecifieswhetheranythingthatwasthebackgroundcolourinthepicture(usuallycolour0)shouldbesettothebackgroundcolourofthewindow.
Apicturewidgetisapassivewidgetandcannotbeenabledordisabled.
TwoPictures
Example
Thefollowingprogramdrawstwopictures,mergedandnotmerged.
importGUI
View.Set("graphics:230;135,nobuttonbar")
%We'llneedtocreateapictureforourPicturewidget.Normally
%anexternalfile(andPic.FileNew)wouldbeused.
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
varpic:int:=Pic.New(0,0,100,100)
varpicture1,picture2:int
varlabel1,label2:int
GUI.SetBackgroundColor(gray)
label1:=GUI.CreateLabel(15,5,"Picture(nomerge)")
picture1:=GUI.CreatePicture(10,25,pic,false
label2:=GUI.CreateLabel(135,5,"Picture(merge)")
picture2:=GUI.CreatePicture(120,25,pic,true
Execute
Details
WhenGUI.CreatePictureiscalled,thenewlycreatedpicturewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththeparametersettofalse.
Apicturewidgetisapassivewidgetandcannotbeenabledordisabled.
Details
ThefollowingGUIsubprogramscanbecalledwithapictureasthe
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreatePicturecallingCreatePicture.
GUI.CreatePictureButton[Full] PartofGUImodule
Syntax
GUI.CreatePictureButton(x,y,picture:int,actionProc:procedurex()):int
GUI.CreatePictureButtonFull(x,y,picture:int,actionProc:procedurex(),width,height:int,shortcut:char,mergePic:boolean):int
Description
Createsapicturebuttonandreturnsthebutton'swidgetID.
Picturebuttonsbehavelikebuttons(seeGUI.CreateButton)exceptthatinsteadoftextonthebutton,apicturespecifiedbytheuserisdisplayedonthebutton.Thepicturebuttonwidgetrespondstomouseclicksandkeystrokesinthesamemannerasaregularbuttonwidget.
ThepicturemustbecreatedbytheprogrambeforehandusingPic.NewPic.FileNew.TheresultingpicturecanthenbeusedasaparametertoGUI.CreatePictureButton.Ingeneral,picturesshouldbeamaximumofabout50pixelshighandwide,althoughthereisnobuilt-inlimitintheGUIlibrary.
Thexandyparametersspecifythelower-leftcornerofthepicturebutton.ThepictureparameterspecifiesthepictureIDofthepicturetobedisplayedonthebutton.(Notethat,ingeneral,thispictureshouldbefairlysmall.)ThepictureIDisreceivedfromaPic.NeworPic.FileNewcall.DonotcallPic.FreepictureIDuntilthebuttonhasbeendisposedofbycallingGUI.DisposeactionProcparameterspecifiesthenameofaprocedurethatiscalledwhenthepicturebuttonispressed.
ForGUI.CreatePictureButtonFull,thewidthandheightparametersspecifythewidthandheightofthebutton.Iftheyaresetto0,thenthepictureradiobuttonisautomaticallysizedtofitthepicture.Ifyouneedtoknowtheprecisesizeofthebutton,usetheGUI.GetWidthandGUI.GetHeightfunctions.Ifwidthheightarelargerthanthepicture,thepictureiscenteredinthebutton.TheshortCutparameteristhekeystroketobeusedasthebutton'sshortcut.ThemergePicparameterspecifieswhetheranythingthatwasthebackgroundcolourinthepicture(usuallycolour0)shouldbesettothebackgroundcolourofthebutton(whichisusuallygray).ThisdefaultstotrueforCreatePictureButton
TwoPictureButtons
Example
Thefollowingprogramdisplaysfivepicturebuttonswhichoutputamessagewhenpressed.
importGUI
View.Set("graphics:100;70")
constsize:int:=25%Thebuttonssize.
constborder:int:=3
varstarButton,mapleButton,starPic,mapleLeafPic
procedureStarPressed
Text.Locate(1,1)
put"StarPressed"
endStarPressed
procedureMaplePressed
Text.Locate(1,1)
put"MaplePressed"
endMaplePressed
%Createthepictures.
%Thestar.
Draw.Star(border,border,border+size,border
Draw.Star(border+1,border+1,border+size
border+size-1,black)
Draw.FillStar(border+2,border+2,border+
border+size-2,brightred)
starPic:=Pic.New(0,0,2*border+size,2*
%Themapleleaf.
Draw.FillBox(border,border,border+size,border+size,white)
Draw.MapleLeaf(border,border,border+size,border
Draw.MapleLeaf(border+1,border+1,border+
border+size-1,black)
Draw.FillMapleLeaf(border+2,border+2,border
border+size-2,brightred)
mapleLeafPic:=Pic.New(0,0,2*border+size
%Createthepicturebuttons.
Draw.Cls
starButton:=GUI.CreatePictureButton(10,10,starPic
mapleButton:=GUI.CreatePictureButton(55,10,
MaplePressed)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
WhenGUI.CreatePictureButtonorGUI.CreatePictureButtonFullthenewlycreatedpicturewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenapicturebuttonisnotenabled,thepicturebuttonisgrayedoutandthepicturebuttonnolongerrespondstoanymouseclicksorkeystrokesuntilthebuttonisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithapicturebuttonasthewidgetIDparameter:
StatusExportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreatePictureButton,notbycallingCreatePictureButton.
GUI.CreatePictureRadioButton[Full] PartofGUImodule
Syntax
GUI.CreatePictureRadioButton(x,y,picture:int,joinID:int,actionProc:procedurex()):int
GUI.CreatePictureRadioButtonFull(x,y:int,picture,joinID:int,actionProc:procedurex(),width,height:shortcut:char,mergePic:boolean):int
Description
Createsapictureradiobuttonandreturnsthebutton'swidgetID.
Pictureradiobuttonsbehavelikepicturebuttons(seeGUI.CreatePictureButton)exceptthattheyhavethe"radio"property.Thatis,oneofthebuttonsintheradiogroupisalwaysselected,andifanotherbuttoninthegroupisselected,thepreviouslyselectedbuttonisunselected.
Acommonexampleisthebuttonsonapaintprogramthatindicatethecurrentshapebeingpainted.Themapleleafbuttoniscurrentlyselected.Ifthestarbuttonisselectedbytheuser,themapleleafbuttonbecomesunselected.Forpicturebuttons,theselectedbuttonappearsdepressed.
FourPictureRadioButtonswiththeMapleLeafSeledcted
Aradiogroupiscreatedbyfirstcreatingasingleradiobutton.Toaddanotherbuttontothegroup,asecondradiobuttoniscreatedspecifyingthefirstradiobuttoninthejoinIDparameter.Subsequentradiobuttonsareadded,eachspecifyingapreviousmemberofthegroupinthejoinIDparameter.
ThepicturemustbecreatedbytheprogrambeforehandusingPic.NewPic.FileNew.TheresultingpicturecanthenbeusedasaparametertoGUI.CreatePictureButton.Ingeneral,picturesshouldbeamaximumofabout50pixelshighandwide,althoughthereisnobuilt-inlimitintheGUIlibrary.
Thexandyparametersspecifythelower-leftcornerofthepictureradiobutton.Iftheseareboth1andjoinIDisnotzero,thenthebuttonwillbeplaceddirectlybelowthepreviouspictureradiobuttoninthegroup.ThepictureparameterspecifiesthepictureIDofthepicturetobedisplayedonthebutton.(Notethat,ingeneral,thispictureshouldbefairlysmall.)ThepictureIDisreceivedfromaPic.NeworPic.FileNewcall.DonotcallPic.FreeforthispictureIDuntilthebuttonhasbeendisposedofbycallingGUI.Dispose.ThejoinIDparameterspecifiesamemberoftheradiogroupthatthiswidgetshouldjoin.Asepecifiesthisradiobuttonisnotamemberofanygroup.TheactionProcparameterspecifiesthenameofaprocedurethatiscalledwhenthepicturebuttonispressed.
ForGUI.CreatePictureRadioButtonFull,thewidthandheightparametersspecifythewidthandheightofthebutton.Iftheyaresetto0,thenthepictureradiobuttonisautomaticallysizedtofitthepicture.Ifyouneedtoknowtheprecisesizeofthebutton,usetheGUI.GetWidthandGUI.GetHeightfunctions.Ifwidthandheightarelargerthanthepicture,thepictureiscenteredinthebutton.TheshortCutparameteristhekeystroketobeusedasthebutton'sshortcut.ThemergePicparameterspecifieswhetheranythingthatwasthebackgroundcolourinthepicture(usuallycolour0)shouldbesettothebackgroundcolourofthebutton(whichisusuallygray).ThisdefaultstotrueforCreatePictureRadioButton.
Thefollowingprogramcreatesanddisplaysforpictureradiobuttons.
importGUI
View.Set("graphics:150;200,nobuttonbar")
constsize:int:=25%Thebuttonssize.
constborder:int:=3
varstarButton,mapleButton,circleButton,squareButton
varstarPic,mapleLeafPic,circlePic,squarePic:
procedureStarPressed
Text.Locate(1,1)
put"StarPressed"
Example
endStarPressed
procedureMaplePressed
Text.Locate(1,1)
put"MaplePressed"
endMaplePressed
procedureCirclePressed
Text.Locate(1,1)
put"CirclePressed"
endCirclePressed
procedureSquarePressed
Text.Locate(1,1)
put"SquarePressed"
endSquarePressed
%Createthepictures.
%Thestar.
Draw.Star(border,border,border+size,border
Draw.Star(border+1,border+1,border+size
border+size-1,black)
Draw.FillStar(border+2,border+2,border+
border+size-2,brightred)
starPic:=Pic.New(0,0,2*border+size,2*
%Themapleleaf.
Draw.FillBox(border,border,border+size,border
Draw.MapleLeaf(border,border,border+size,border
Draw.MapleLeaf(border+1,border+1,border+
border+size-1,black)
Draw.FillMapleLeaf(border+2,border+2,border
border+size-2,brightred)
mapleLeafPic:=Pic.New(0,0,2*border+size
%Thecircle.
constradius:int:=sizediv2
Draw.FillBox(border,border,border+size,border
Draw.Oval(border+radius,border+radius,radius
Draw.Oval(border+radius,border+radius,radius
black)
Draw.FillOval(border+radius,border+radius,
radius-2,brightred)
circlePic:=Pic.New(0,0,2*border+size,2*
%Thesquare.
Draw.FillBox(border,border,border+size,border
Draw.Box(border,border,border+size,border+
Draw.Box(border+1,border+1,border+size-1,
border+size-1,black)
Draw.FillBox(border+2,border+2,border+size
border+size-2,brightred)
squarePic:=Pic.New(0,0,2*border+size,2*
%Createthepicturebuttons.
Draw.Cls
starButton:=GUI.CreatePictureRadioButton(10,maxy80,
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
exitwhenGUI.ProcessEvent
endloop
Execute
Details
WhenGUI.CreatePictureRadioButtonorGUI.CreatePictureRadioButtonFulliscalled,thenewlycreatedpicturewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenapictureradiobuttonisnotenabled,thepictureradiobuttonisgrayedoutandthepicturebuttonnolongerrespondstoanymouseclicksorkeystrokesuntilthebuttonisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithapictureradiobuttonasthewidgetIDparameter:
GUI.Show,GUI.Hide,GUI.Enable,GUI.Disable,GUI.DisposeGUI.GetX,GUI.GetY,GUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSize,GUI.SelectRadio
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreatePictureRadioButton,notbycallingCreatePictureRadioButton
Seealso
GUI.SelectRadioforselectingapictureradiobuttoninaprogram.SeealsoGUI.CreatePictureButtonandGUI.CreateRadioButtonforinformationonpicturebuttonsandradiobuttons.
GUI.CreateRadioButton[Full] PartofGUImodule
Syntax
GUI.CreateRadioButton(x,y:int,text:string,joinID:int,actionProc:procedurex()):int
GUI.CreateRadioButtonFull(x,y:int,text:string,joinID:int,actionProc:procedurex(),alignment:int,shortCut:char):int
Description
Createsaradiobuttonandreturnstheradiobutton'swidgetID.
Asliderisawidgetthatallowstheusertoselectoneofasetofvalues.Ithasareal-lifeequivalentintheoldcarstereoswhereasinglestationisselectedatatime.Thatis,oneofthebuttonsintheradiogroupisalwaysselected,andifanotherbuttoninthegroupisselected,thepreviouslyselectedbuttonisunselected.
SixRadioButtonsinTwoGroups
Aradiogroupiscreatedbyfirstcreatingasingleradiobutton.Toaddanotherbuttontothegroup,asecondradiobuttoniscreatedspecifyingthefirstradiobuttoninthejoinIDparameter.Subsequentradiobuttonsareadded,eachspecifyingapreviousmemberofthegroupinthejoinIDparameter.
Thexandyparametersspecifythelower-leftcorneroftheradiobutton(unlessalignmentissettoGUI.RIGHT,inwhichcasetheyspecifythelower-rightcorneroftheradiobutton).Iftheseareboth1andjoinIDisnotzero,thenthebuttonwillbeplaceddirectlybelowthepreviousradiobuttoninthegroup.Thetextparameterspecifiesthetext(orlabel)besidetheradiobutton.ThejoinIDparameterspecifiesamemberoftheradiogroupthatthiswidgetshouldjoin.AjoinIDof0sepecifiesthisradiobuttonisnota
memberofanygroup.TheactionProcparameteristhenameofaprocedurethatiscalledwhentheradiobuttonisselected.InGUI.CreateRadioButton,theradiobutton'stextisalwaystotherightoftheactualradiobutton.InGUI.CreateRadioButtonFull,thetextcanbesettotherightorleftoftheradiobuttonwiththealignmentparameter.
ForGUI.CreateRadioButtonFull,thealignmentparameterspecifiesthepositionoftheradiobuttoninrelationtothetextaswellasthemeaningofthexandyparameters.Thealignmentparameterisoneof0,GUI.LEFT,orGUI.RIGHT.Analignmentof0isthedefaultandisthesameasGUI.LEFT.GUI.LEFTmeanstheactualboxinthecheckboxappearstotheleftofthecheckbox'slabeland(x,y)specifythelower-leftcorner.AnalignmentofGUI.RIGHTmeansthattheactualboxappearstotherightoftheradiobutton'slabeland(x,y)specifythelower-rightcorneroftheradiobutton.Theshortcutparameteristhekeystroketobeusedasthebutton'sshortcut.
Aradiobutton'ssizeisnotspecifiedduringcreation.Itisdeterminedbasedonthesizeofthetext.Insteadtheuserspecifiesthelower-leftcorneroftheradiobutton(orthelower-rightiftheradiobuttonisrightjustified).
Thefollowingprogramcreatessixradiobuttonsintwogroups.
importGUI
View.Set("graphics:350;80")
varradio:array1..6ofint%TheradiobuttonIDs.
procedureRadioPressed
Text.Locate(1,1)
put"RadioButton"..
fori:1..6
ifradio(i)=GUI.GetEventWidgetIDthen
puti..
endif
endfor
put"Selected"
endRadioPressed
radio(1):=GUI.CreateRadioButton(15,maxy35,
Example "RadioButton1",0,RadioPressed)
radio(2):=GUI.CreateRadioButton(1,1,"RadioButton2",
radio(1),RadioPressed)
radio(3):=GUI.CreateRadioButton(1,1,"RadioButton3",
radio(2),RadioPressed)
radio(4):=GUI.CreateRadioButtonFull(maxx15,
"RadioButtonA(Shortcut:'a')",0,RadioPressed
GUI.RIGHT,'a')
radio(5):=GUI.CreateRadioButtonFull(1,1,
"RadioButtonB(Shortcut:'b')",radio(4),
GUI.RIGHT,'b')
radio(6):=GUI.CreateRadioButtonFull(1,1,
"RadioButtonC(Shortcut:'c')",radio(5),
GUI.RIGHT,'c')
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
Whenagroupofradiobuttonsisselected,thefirstradiobuttoncreatedinthegroupwillbetheselectedone.YoucanchangethisbyusingtheGUI.SelectRadioproceduretoselectadifferentone.
WhenGUI.CreateRadioButtonorGUI.CreateRadioButtonFulliscalled,thenewlycreatedpicturewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenaradiobuttonisnotenabled,theradiobuttonisgrayedoutandtheradiobuttonnolongerrespondstoanymouseclicksorkeystrokesuntilthebuttonisenabledagain.
ThefollowingGUIsubprogramscanbecalledwitharadiobuttonasthewidgetIDparameter:
Details
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
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateRadioButton,notbycallingCreateRadioButton.
SeealsoGUI.SelectRadioforselectingaradiobuttoninaprogram.SeealsoGUI.SetLabelforchangingtheradiobutton'stext.
GUI.CreateTextBox[Full] PartofGUImodule
Syntax
GUI.CreateTextBox(x,y,width,height:int):int
GUI.CreateTextBoxFull(x,y,width,height:int,border,fontID:int):int
Description
Createsatextboxandreturnsthetextbox'swidgetID.
Atextboxisaboxusedfordisplayingtext.Ithasscrollbarsthatactivatewhentextappearsoutsidetheborderofthetextbox.Theusercannotdirectlyselect,editormodifythetextinthetextbox.
Thexandyparametersspecifythelower-leftcorneroftheareainwhichthetextwillbedrawn.ThewidthandheightparametersspecifythewidthandheightofthetextdrawingareaThetextboxborderisjustoutsidethetextdrawingarea.Becauseofthis,GUI.GetXandGUI.GetYwillreturnavalueslightlysmallerthanxandyandGUI.GetWidthandGUI.GetHeightreturnvaluesslightlylargerthanwidthandheight.
ForGUI.CreateTextBox,theborderaroundthetextboxisalwaysaline.ForGUI.CreateTextBoxFull,thetypeofborderisspecifiedbytheborderparameter.Theborderparameterisoneof0,GUI.LINE,GUI.INDENTGUI.EXDENT.Aborderof0isthedefaultandisthesameasGUI.LINEGUI.INDENTandGUI.EXDENTonlydisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthetextboxappearindentedorrecessed.GUI.EXDENTmakesthetextboxappeartostandoutfromthewindow.ThefontIDparameterspecifiesthefontIDofthefonttobeusedinthetextbox.ThefontIDisreceivedfromaFont.Newcall.DonotcallFont.FreeforthisfontIDuntilthelabelhasbeendisposedofbycallingGUI.Dispose.
ByusingthefondIDparameter,textboxescanhaveanysizeortypeface.
Atextboxdisplayingthecontentsofafile.
Example
Thefollowingprogramdisplaysthecontentsofafileinatextbox.
importGUI
View.Set("graphics:300;300")
constfileNameToBeViewed:string:="TextBxs.DEM"
vartextBox:int%TheTextFieldID.
vartitle:int%Thelabelforthetitle.
varf:int%Thestreamnumberofthefile.
varline:string%Linestobereadfromthefile.
%Openthefile.
open:f,fileNameToBeViewed,get
iff=0then
put"Unabletoopen"+fileNameToBeViewed+":",
return
endif
%Setbackgroundcolortograyforindentedtextbox.
GUI.SetBackgroundColor(gray)
%Createthetitlelabelandtextbox.
title:=GUI.CreateLabelFull(20,280,fileNameToBeViewed
GUI.CENTER,0)
textBox:=GUI.CreateTextBoxFull(10,10,280,265,
GUI.INDENT,0)
%Readthefileandplaceitinthetextbox.
loop
exitwheneof(f)
get:f,line:*
GUI.AddLine(textBox,line)
endloop
close:f%Closethefile.
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
WhenGUI.CreateTextBoxorGUI.CreateTextBoxFulliscalled,thenewlycreatedpicturewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Atextboxwidgetisapassivewidgetandcannotbeenabledordisabled.
Details
ThefollowingGUIsubprogramscanbecalledwithatextboxastheparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSizeGUI.SetPositionAndSize,GUI.AddLine,GUI.AddText,GUI.ClearText,GUI.SetTopLine,GUI.SetScrollOnAdd
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateTextBoxnotbycallingCreateTextBox.
GUI.AddLine,GUI.AddTextforaddingtexttothetextbox.Seealso
Seealso GUI.SetTopLinetosetthetoplineoftextinthetextbox.SeealsoGUI.SetScrollOnAddtosetstopthetextboxfromscrollingwhentexttothetextbox.SeealsoGUI.ClearTextforclearingthetextbox.
GUI.CreateTextBoxChoice PartofGUImodule
SyntaxGUI.CreateTextBoxChoice(x,y,width,height:int,border,fontID:int,actionProc:procedurex(line:int
Description
Createsatextboxthatcanbeusedforselectingindividualitemsandreturnsthetextbox'swidgetID.
Atextboxisaboxusedfordisplayingtext.ByusingGUI.AddLinetheprogramcanthenwaitfortheusertodoubleclickonlinesinthetextbox.highlightswhentheuserclicksthelineonce,andcallstheactionprocedurewhentheuserclicksthehighlightedlineasecondtime.Likeatextbox,thetextboxchoicehasscrollbarsthatactivatewhentextappearsoutsidetheborderofthetextbox.Theusercannotdirectlyeditormodifythetextinthetextboxchoice.
Thexandyparametersspecifythelower-leftcorneroftheareainwhichthetextwillbedrawn.ThewidthandheightparametersspecifythewidthandheightofthetextdrawingareaThetextboxborderisjustoutsidethetextdrawingarea.Becauseofthis,GUI.GetXandGUI.GetYwillreturnavalueslightlysmallerthanGUI.GetWidthandGUI.GetHeightwillreturnvaluesslightlylargerthanheight.
ForGUI.CreateTextBox,theborderaroundthetextboxisalwaysaline.ForGUI.CreateTextBoxFull,thetypeofborderisspecifiedbytheborderborderparameterisoneof0,GUI.LINE,GUI.INDENT,orGUI.EXDENTisthedefaultandisthesameasGUI.LINE.GUI.INDENTandGUI.EXDENTdisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthetextboxappearindentedorrecessed.GUI.EXDENTmakesthetextboxappeartostandoutfromthewindow.ThefontIDparameterspecifiesthefontIDofthefonttobeusedinthetextbox.TheisreceivedfromaFont.Newcall.DonotcallFont.FreeforthisfontIDuntilthelabelhasbeendisposedofbycallingGUI.Dispose.
ByusingthefontIDparameter,textboxescanhaveanysizeortypeface.
Atextboxchoiceafterauserdoubleclickedaline.
Example
Thefollowingprogramdisplaysthecontentsofafileinatextbox.
importGUI
procedureChoseLine(line:int)
location(1,1)
put"Theuserchose",line
endChoseLine
varx:int:=GUI.CreateTextBoxChoice(20,20,200,100,0,0,
GUI.AddLine(x,"ChooseA")
GUI.AddLine(x,"ChooseB")
GUI.AddLine(x,"ChooseC")
GUI.AddLine(x,"ChooseD")
GUI.AddLine(x,"ChooseE")
GUI.AddLine(x,"ChooseF")
GUI.AddLine(x,"ChooseG")
GUI.AddLine(x,"ChooseH")
GUI.AddLine(x,"ChooseI")
GUI.AddLine(x,"ChooseJ")
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
WhenGUI.CreateTextBoxorGUI.CreateTextBoxFulliscalled,thenewlycreatedtextboxchoicewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedbeencalledwiththedisplayparametersettofalse.
Details
ThefollowingGUIsubprogramscanbecalledwithatextboxastheparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetHeight,GUI.SetPosition,GUI.SetSize,GUI.SetPositionAndSizeGUI.AddLine,GUI.AddText,GUI.ClearText,GUI.SetTopLineGUI.SetScrollOnAdd
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateTextBoxChoicenotbycallingCreateTextBoxChoice.
Seealso
GUI.AddLineforaddingtexttothetextbox.SeealsoGUI.SetTopLinelineoftextinthetextbox.SeealsoGUI.SetScrollOnAddtosetstopthetextboxfromscrollingwhentextisaddedtothetextbox.SeealsoGUI.ClearTexttextbox.
GUI.CreateTextField[Full] PartofGUImodule
Syntax
GUI.CreateTextField(x,y,width:int,text:string,actionProc:procedurex(text:string)):int
GUI.CreateTextFieldFull(x,y,width:int,text:string,actionProc:procedurex(text:string),border,fontID,inputKind:int):int
Description
Createsatextfieldandreturnsthetextfield'swidgetID.
Atextfieldisusedtocreatealineoftextthatcanbeeditedbytheuser.Theusercanusethemousetoselectpartofthetextandcanentertextintothetextfield.
Ifoneormoretextfieldsareenabledinawindow,thenoneofthetextfieldswillbeactive.Thismeansthatwhenanykeystrokesareenteredintothewindow,theactivetextfieldwillreceivethekeystrokes.TheactivetextfieldcanbechangedusingtheGUI.SetActiveprocedure.
Thexandyparametersspecifythelower-leftcorneroftheareainwhichthetextwillbedrawn.Thetextfieldborderisjustoutsidethetextdrawingarea.Thewidthparameterspecifiesthewidthofthetextdrawingarea.Theheightofthetextfieldisdeterminedbytheheightofthefontusedbythetextfield.Theborderofthetextfieldisjustoutsidethetextdrawingarea,soGUI.GetWidthwillreturnvaluesslightlylargerthanwidth.TheactionProcparameterspecifiesthenameoftheproceduretobecalledwhentheuserpressesENTER(RETURNonaMacintosh)whenthetextfieldisactive.Theparameteristhecurrenttextinthetextfield.
ForGUI.CreateTextField,theborderaroundthetextfieldisalwaysaline.ForGUI.CreateTextFieldFull,thetypeofborderisspecifiedbytheparameter.Theborderparameterisoneof0,GUI.LINE,GUI.INDENTGUI.EXDENT.Aborderof0isthedefaultandisthesameasGUI.LINEGUI.INDENTandGUI.EXDENTonlydisplayproperlyifthebackgroundcolourhasbeensettograyusingGUI.SetBackgroundColor.GUI.INDENTmakesthetextfieldappearindentedorrecessed.GUI.EXDENTmakesthetextfieldappeartostandoutfromthewindow.ThefontIDparameterspecifiesthe
fontIDofthefonttobeusedinthetextfield.ThefontIDisreceivedfromaFont.Newcall.DonotcallFont.FreeforthisfontIDuntilthelabelhasbeendisposedofbycallingGUI.Dispose.TheinputKindparameterspecifiesthetypeofinputacceptedbythetextfield.Thisisoneof0,GUI.ANY,orGUI.REAL.Aninputtypeof0isthedefaultandisthesameasGUI.ANYGUI.ANYallowsanytypeofinputinthetextfield.GUI.INTEGERpositiveintegerinputinthetextfield.GUI.REALallowsanyrealnumberinputinthetextfield.Notethatusing
GUI.INTEGERorGUI.REALdoesnotguaranteethatthetextfieldstringcanbeconvertedtoanintegerorareal.Thetextcouldbeanullstring,andforGUI.REALcouldbepartofanumbersuchasthestring""or"1.25E"bothofwhichareillegalnumbers.(Tochecktheconversion,usethestrintokstrrealokfunctionsbeforecallingstrintorstrreal.)
TwoTextFields
Example
ThefollowingprogramcreatesatextfieldandechoesitonthescreenwhentheuserpressesENTER.
importGUI
View.Set("graphics:200;100")
varnameTextField,addressTextField:int%TheTextFieldIDs.
procedureNameEntered(text:string)
GUI.SetSelection(addressTextField,0,0)
GUI.SetActive(addressTextField)
endNameEntered
procedureAddressEntered(text:string)
GUI.SetSelection(nameTextField,0,0)
GUI.SetActive(nameTextField)
endAddressEntered
GUI.SetBackgroundColor(gray)
varquitButton:=GUI.CreateButton(52,5,100,"Quit",
nameTextField:=GUI.CreateTextFieldFull(50,70,100,"",
NameEntered,GUI.INDENT,0,0)
addressTextField:=GUI.CreateTextFieldFull(50,40,100,"",
AddressEntered,GUI.INDENT,0,0)
varnameLabel:=GUI.CreateLabelFull(45,70,"Name",0,0,
GUI.RIGHT,0)
varaddressLabel:=GUI.CreateLabelFull(45,40,"Address",0,0,
GUI.RIGHT,0)
loop
exitwhenGUI.ProcessEvent
endloop
GUI.Dispose(quitButton)
colorback(gray)
Text.Locate(maxrow-1,1)
put"Name=",GUI.GetText(nameTextField)
put"Address=",GUI.GetText(addressTextField)..
Execute
Details
Onlyonetextfieldisactiveatatime.Theactivetextfieldhasablinkingcursor(oritsselectionhighlighted).Ifakeystrokeoccurswhenawindowhasanactivetextfieldinit,thekeystrokewillbedirectedtotheactivetextfield.YoucanchangewhichtextfieldisactivewiththeGUI.SetActiveprocedureorbysimplyclickingonanothertextfieldwiththemouse.
Whenmultipletextfieldsarecreatedinawindow,thefirsttextfieldcreatedisactivewhentheprogrambegins.
Thecurrentversionofthetextfielddoesnotsupportcutandpasteorkeyboardcommandstoextendtheselection.
Becausestringsareamaximumof255characters,thisisthemaximumnumberofcharactersinatextfield.
TheTABcharactercyclesbetweendifferenttextfieldsinawindow.Itcyclesthroughthetextfieldsintheorderinwhichtheywerecreated.BACKTAB
(shift+TAB)cyclesthroughthefieldsinreverseorder.
Details
WhenGUI.CreateTextFieldorGUI.CreateTextFieldFulliscalled,thenewlycreatedpicturewillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenatextfieldisnotenabled,thetextfieldcannotbemadeactiveandthetextinthefieldcannotbeedited.
Details
ThefollowingGUIsubprogramscanbecalledwithatextboxastheparameter:
GUI.Show,GUI.Hide,GUI.Dispose,GUI.GetX,GUI.GetYGUI.GetWidth,GUI.GetHeight,GUI.SetPosition,GUI.SetSizeGUI.SetPositionAndSize,GUI.GetText,GUI.SetText,GUI.SetSelection,GUI.SetActive,GUI.SetEchoChar
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateTextField,notbycallingCreateTextField.
Seealso
GUI.GetTextandGUI.SetTextforreadingandsettingthetextinthetextfield.SeealsoGUI.SetEchoCharforsettingthecharacterechoedwhentheuserentersacharacterinatextfield(oftenusedforenteringpasswords).alsoGUI.SetSelectionforsettingtheselectedareaofthetext.SeealsoGUI.SetActiveformakingthetextfieldactive.
GUI.CreateVerticalScrollBar[Full] PartofGUImodule
Syntax
GUI.CreateVerticalScrollBar(x,y,size:int,min,max,start:int,actionProc:procedurex(value:int)):int
GUI.CreateVerticalScrollBarFull(x,y,size:int,min,max,start:int,actionProc:procedurex(value:int),arrowInc,pageInc,thumbSize:int):int
Createsavertical(up-down)scrollbarandreturnsthescrollbar'swidgetID.
Ascrollbarisawidgetthatallowsuserstoseeapieceofadocumentthatcannotbedisplayedonthescreeninitsentirety.Thepicturebelowshowsaverticalscrollbar.Tocontrolascrollbar,thereareafewchoices:theusercanclickonthethumb(theboxinthescrollbar)andslideitupanddown,ortheusercanclickinthescrollbaritselfaboveorbelowthethumb(inwhichcasethethumbismovedupordownone"page"),ortheusercanclickontheupordownarrowsattheendsofthescrollbar(inwhichcasethethumbismovedupordownone"arrowincrement"or"line").
AVerticalScrollBar
DescriptionTheprogrammerdefinesapageoranarrowincrement.Whenthevalueofthescrollbarchanges,theactionprocedureofthescrollbariscalledwiththenewvalueasaparameter.Theactionprocedureshouldthenredrawthecontentsusingthenewvalueofthescrollbar.
TherangeofvaluesthatthescrollbarwillgiveisdeterminedbytheminandmaxparametersintheCreatecall.Theleftsideofthescrollbarrepresentstheminimumvalue,whiletherightrepresentsthemaximumvalue.Thereisalsothe"thumbsize".Thisrepresentstherangeofvaluesthatcanbeseenatonceonthescreen.
Bydefault,thearrowincrement(theamountthevalueischangedwhenthescrollingarrowsarepressed)issettoone.Thepageincrement(theamountthevalueischangedwhentheuserclicksinthebartotherightorleftofthethumb)issettoonequarterthedifferencebetweentheminimumandthemaximum.The"thumbsize"issettozero(seethedescriptionofscrollbarsforanexplanationofthethumbsize).
Thexandyparametersspecifythelower-leftcornerofthescrollbar.Thesizeparameterspecifiesthelengthofthescrollbar(includingthearrows)inpixels.Theminandmaxparametersaretheminimumandmaximumvaliesreturnedbythescrollbar.Thestartparameteristheinitialvalueofthescrollbarandshouldbebetweenminandmaxinclusive.TheactionProcparameteristhenameofaprocedurethatiscalledwhenthevalueofthescrollbarischanged.Theparametertotheactionprocedureisthecurrentvalueofthescrollbar.
Thefollowingprogramcreatesaverticalscrollbar.Wheneverthescrollbar'svalueischanged,amessageisdisplayedinthewindow.
importGUI
View.Set("graphics:125;200,nobuttonbar")
varscrollBar:int
ExampleprocedureScrollBarMoved(value:int)
Text.Locate(9,7)
put"Scroll"
Text.Locate(10,8)
put"Bar"
Text.Locate(11,8)
putvalue:3
endScrollBarMoved
scrollBar:=GUI.CreateVerticalScrollBar(10,10,180,
50,150,50,ScrollBarMoved)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Description
ForGUI.CreateVerticalScrollBarFull,thearrowIncparameterspecifiesthearrowincrement(theamountthescrollbar'svalueischangedwhenthescrollarrowsarepressed).ThepageIncspecifiesthepageincrement(theamountthescrollbar'svalueischangedwhentheuserclicksinthepageleft/rightsectionofthescrollbar).ThethumbSizeparameterspecifiesthe"thumbsize".Seethescrollbarexplanationformoredetailonascrollbar's"thumbsize".
Forexample,ifyouhaveawindowthatcandisplay20linesoftextatonceandthereare100linesoftext,youwouldsetminto1,maxto100andthumbSizeto20.Thevaluereturnedbythescrollbarwouldthenbethelinenumberofthefirstlineonthescreentobedisplayed.Whenthescrollbarwasatitsmaximumvalue,itwouldreturn81,sincebydoingso,lines81-100wouldbedisplayed.
ExampleForanexampleprogramthatscrollsalargepictureoverasmallerwindow,seeGUI.CreateHorizontalScrollBar.
Details
Insomeinstances,youwillwantthetheminimumandmaximumvaluesofthescrollbartobereversed(right/topisminimum).Inthatcase,calltheGUI.SetSliderReverseproceduretoflipthevaluesofthescrollbar.
Scrollbarsalwayshaveafixedheight(forhorizontalscrollbars)orwidth(forverticalscrollbars).Togetthescrollbar'swidth,usetheGUI.GetScrollBarWidthfunction.
WhenGUI.CreateVerticalScrollBarorGUI.CreateVerticalScrollBarFulliscalled,thenewlycreatedscrollbarwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenascrollbarisnotenabled,thegrayinthebarissettowhiteandthethumbisnotdisplayed.Thescrollbarnolongerrespondstoanymouseclicksuntilthescrollbarisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithascrollbarasthewidgetIDparameter:
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
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateVerticalScrollBar,notbycallingCreateVerticalScrollBar.
GUI.GetSliderValueandGUI.SetSliderValueforreadingandsettingthevalueofascrollbar,GUI.SetSliderMinMaxfor
Seealsochangingtheminimumandmaximumvaluesofascrollbar,andGUI.SetScrollAmountforchangingthescrollingincrementsandthumbsizeofascrollbar.SeealsoGUI.SetSliderSizeforsettingthelengthofascrollbarandGUI.SetSliderReverseforreversingthesenseofascrollbar.
GUI.CreateVerticalSlider PartofGUImodule
Syntax
GUI.CreateVerticalSlider(x,y,length:int,min,max,start:int,actionProc:procedurex(value:int)):int
Description
Createsavertical(up-down)sliderandreturnstheslider'swidgetID.
Asliderisawidgetthatallowstheusertosetacontinuoussetofvalues.Ithasareal-lifeequivalentinthingssuchasastereovolumecontrol.
AVerticalSlider
Tocontrolaslider,theuserclicksonthesliderboxanddragsitbackandforth.Everytimethevaluechanges,aprocedureiscalledwiththenewvalueasaparameter.
TherangeofvaluesthatthesliderwillgiveisdeterminedbytheminandmaxparametersintheCreatecall.Theleftsideofthesliderrepresentstheminimumvalue,whiletherightrepresentsthemaximumvalue.
Thexandyparametersspecifythelower-leftcorneroftheslidertrack.Thismeansthattheslideractuallyextendsaboveandbelowthispoint(andslightlytotheleftofittotakeintoaccounttheroundedendofthetrack).Thelengthparameterspecifiesthe
lengthofthetrackinpixels.(YoucanuseGUI.GetX,GetY,GetWidth,andGetHeighttogettheexactdimensionsoftheslider.)Theminandmaxparametersaretheminimumandmaximumvaliesreturnedbytheslider.Thestartparameteristheinitialvalueofthesliderandshouldbebetweenminandmaxinclusive.TheactionProcparameteristhenameofaprocedurethatiscalledwhenthevalueofthesliderischanged.Theparametertotheactionprocedureisthecurrentvalueoftheslider.
Example
Thefollowingprogramcreatesaverticalslider.Whenevertheslider'svalueischanged,amessageisdisplayedinthewindow.
importGUI
View.Set("graphics:125;200,nobuttonbar")
varslider:int
procedureSliderMoved(value:int)
Text.Locate(9,7)
put"Slider"
Text.Locate(10,9)
putvalue:3
endSliderMoved
slider:=GUI.CreateVerticalSlider(20,10,180,
50,150,50,SliderMoved)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Insomeinstances,youwillwantthetheminimumandmaximumvaluesoftheslidertobereversed(rightisminimum).Inthatcase,calltheGUI.SetSliderReverseproceduretoflipthevaluesoftheslider.
Details
Slidersalwayshaveafixedheight(forhorizontalsliders)orwidth(forverticalsliders).
WhenGUI.CreateVerticalSliderorGUI.CreateVerticalSliderFulliscalled,thenewlycreatedsliderwillbedisplayedimmediatelyunlessGUI.DisplayWhenCreatedhasbeencalledwiththedisplayparametersettofalse.
Whenasliderisnotenabled,theappearancedoesnotchange.However,theslidernolongerrespondstoanymouseclicksuntilitisenabledagain.
Details
ThefollowingGUIsubprogramscanbecalledwithasliderasthewidgetIDparameter:
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
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.CreateVerticalSlider,notbycallingCreateVerticalSlider.
Seealso
GUI.GetSliderValueandGUI.SetSliderValueforreadingandsettingthevalueofaslider,GUI.SetSliderMinMaxforchangingtheminimumandmaximumvaluesofaslider.SeealsoGUI.SetSliderSizeforsettingthelengthofasliderandGUI.SetSliderReverseforreversingthesenseofaslider.
GUI.Disable PartofGUImodule
Syntax GUI.Disable(widgetID:int)
Description
DisablesawidgetspecifiedbywidgetID.
UsedinconjunctionwithGUI.Enabletoenableanddisablewidgets.
Disabledwidgetsgenerallyare"grayedout"tovisuallydepicttheirdisabledstatus.
Disabledwidgetsdonotrespondtokeystrokesormouseclicks.
Example
Thethreecolorradiobuttonsareenabledonlywhenthecolorcheckboxisselected.
importGUIin"%oot/lib/GUI"
View.Set("graphics:100;100")
varcolorCheckBox,redRadio,greenRadio,blueRadio
procedureDoNothing
endDoNothing
procedureColorCheckBoxProc(filled:boolean)
iffilledthen
GUI.Enable(redRadio)
GUI.Enable(greenRadio)
GUI.Enable(blueRadio)
else
GUI.Disable(redRadio)
GUI.Disable(greenRadio)
GUI.Disable(blueRadio)
endif
endColorCheckBoxProc
colorCheckBox:=GUI.CreateCheckBox(10,80,
"UseColor",ColorCheckBoxProc)
redRadio:=GUI.CreateRadioButton(33,60,"Red",0,
greenRadio:=GUI.CreateRadioButton(1,1,"Green",
redRadio,DoNothing)
blueRadio:=GUI.CreateRadioButton(1,1,"Blue",
greenRadio,DoNothing)
ColorCheckBoxProc(false)
loop
exitwhenGUI.ProcessEvent
endloop
Details
Thefollowingtypesofwidgetscanbeenabledordisabled:
Buttons,CheckBoxes,RadioButtons,PictureButtons,
PictureRadioButtons,HorizontalScrollBars,HorizontalSliders,Canvases,TextFields,VerticalScrollBars,VerticalSliders
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheprocedurebycallingGUI.DisablenotbycallingDisable.
Seealso GUI.Enable.
GUI.Dispose PartofGUImodule
Syntax GUI.Dispose(widgetID:int)
Description
EliminatesthewidgetspecifiedbywidgetID.
Ifthewidgetisvisible,itisimmediatelymadeinvisiblebeforebeingdeleted.Itshouldbecalledinordertofreeupanymemorythatthewidgetmighthaveallocated.Notethatyoucannotusethewidgetafterithasbeendisposedof.Ifyouwishtotemporarilygetridofawidget,considerusingtheHidemethodandthentheShowmethodwhenyouwanttouseitagain.
Example
ThefollowingprogramwaitsfortheQuitbuttontobepressed.Whenitis,theQuitbuttonisdeletedandamessageisdisplayedinthecenterofthescreen.
importGUIin"%oot/lib/GUI"
View.Set("graphics:150;100")
varbutton,message:int
button:=GUI.CreateButton(20,40,0,"Quit",GUI.Quit
loop
exitwhenGUI.ProcessEvent
endloop
GUI.Dispose(button)
message:=GUI.CreateLabelFull(0,0,"Done",maxx
GUI.CENTER+GUI.MIDDLE,0)
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheprocedurebycallingGUI.Dispose,notbycallingDispose.
GUI.Draw... PartofGUImodule
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:array1..*ofint,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:array1..*ofint,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
PerformsaDraw…commandtothecanvasspecifiedbywidgetID.
Alloftheseroutinesareessentiallythesameasthesimilarly-namedproceduresintheDrawmodule.Allcoordinatesarebasedonthecanvasandalldrawingisclippedtothecanvasdrawingsurface.Ifthecanvasisin"xormode",allthedrawingwillbedonewith"xor"set.(SeeView.Setformoreinformationabout"xor".)
ThewidgetIDmustspecifyacanvaswidget.
Example SeeGUI.CreateCanvasforanexampleofGUI.DrawFillOval.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.Draw…,notbycallingDraw….
Seealso GUI.CreateCanvas.
GUI.Enable PartofGUImodule
Syntax GUI.Enable(widgetID:int)
Description
EnablesadisabledwidgetspecifiedbywidgetID.
UsedinconjunctionwithGUI.Disabletoenableanddisablewidgets.
Disabledwidgetsgenerallyare"grayedout"tovisuallydepicttheirdisabledstatus.
Disabledwidgetsdonotrespondtokeystrokesormouseclicks.
ExampleSeeGUI.DisableforanexampleofGUI.Enable.
Details
Thefollowingtypesofwidgetscanbeenabledordisabled:
Buttons,CheckBoxes,RadioButtons,PictureButtons,
PictureRadioButtons,HorizontalScrollBars,HorizontalSliders,Canvases,TextFields,VerticalScrollBars,VerticalSliders
StatusExportedqualified.
ThismeansthatyoucanonlycalltheprocedurebycallingGUI.Enable,notbycallingEnable.
SeealsoGUI.Disable.
GUI.FontDraw PartofGUImodule
SyntaxGUI.FontDraw(widgetID:int,textStr:string,x,y,fontID,Color:int)
Description
PerformsaFont.DrawcommandtothecanvasspecifiedbywidgetID.
ThisroutineisessentiallythesameastheFont.DrawprocedureintheFontmodule.Allcoordinatesarebasedonthecanvasandalldrawingisclippedtothecanvasdrawingsurface.Ifthecanvasisin"xormode",allthedrawingwillbedonewith"xor"set.(SeeView.Setformoreinformationabout"xor".)
ThewidgetIDmustspecifyacanvaswidget.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheprocedurebycallingGUI.FontDraw,notbycallingFontDraw.
Seealso GUI.CreateCanvas.
GUI.GetCheckBox PartofGUImodule
Syntax GUI.GetCheckBox(widgetID:int):boolean
Description
ReturnsthestatusofthecheckboxspecifiedbywidgetID.Ifthecheckboxisset(hasanXinit),GetCheckBoxreturnstrue,otherwiseitreturnsfalse.
ExampleSeeGUI.CreateCheckBoxforanexampleofGUI.GetCheckBox.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetCheckBox,notbycallingGetCheckBox.
Seealso GUI.CreateCheckBox.
GUI.GetEventTime PartofGUImodule
Syntax GUI.GetEventTime:int
Description
Returnsthetimeinmillisecondswhentheevent(mousebuttonorkeystroke)tookplace.ThisvalueisthesamevalueasTime.Elapsedreturnsifcalledwhentheeventwasprocessed.Thisfunctionshouldonlybecalledinanactionproceduredefaultmouse,keystroke,ornulleventhandler,asitwillreturn1whenthereisnoeventbeingprocessed.
Thiseventcanbeusedasatimerforvariousfunctionssuchasdeterminingwhetherasingleclickoradoubleclickofthemousebuttontookplaceorfortimingkeyboardinput.
Example
Thefollowingprogramtimestheintervalbetweentwobuttonpresses.
importGUIin"%oot/lib/GUI"
View.Set("graphics:300;100")
varstartTime,startButton,finishButton:int
procedureStart
startTime:=GUI.GetEventTime
endStart
procedureFinish
Text.Locate(1,1)
put"Thetimebetweenbuttonpressedis",
GUI.GetEventTimestartTime,"msecs"
GUI.Quit
endFinish
startButton:=GUI.CreateButton(10,10,110,"ClickFirst",
finishButton:=GUI.CreateButton(180,10,110,"ClickSecond",
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetEventTimebycallingGetEventTime.
Seealso GUI.ProcessEvent.
GUI.GetEventWidgetID PartofGUImodule
Syntax GUI.GetEventWidgetID:int
Description
ReturnsthewidgetIDofthewidgetthatwasactivatedbythemousebuttonpressorthekeystroke.Thisfunctionshouldonlybecalledinanactionprocedure,asitwillreturn1whenthereisnoeventthatactivatedawidgetbeingprocessed.
Thisfunctionisusedwhenaseveralbuttonsusethesameactionproceduretodeterminewhichbuttonwaspressed.
Example
Thefollowingprogramprintsamessagestatingwhichbuttonwasselected.
importGUIin"%oot/lib/GUI"
View.Set("graphics:150;210")
varbuttonNames:array1..5ofstring:=init
"Blue","Yellow","Purple")
varbuttons:array1..5ofint
procedureButtonPush
fori:1..5
ifGUI.GetEventWidgetID=buttons(i)then
Text.Locate(1,1)
putbuttonNames(i),"selected"
endif
endfor
endButtonPush
fori:1..5
buttons(i):=GUI.CreateButton(10,21040*
buttonNames(i),ButtonPush)
endfor
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetEventWidgetID,notbycallingGetEventWidgetID.
Seealso GUI.ProcessEvent.
GUI.GetEventWindow PartofGUImodule
Syntax GUI.GetEventWindow:int
Description
ReturnsthewindowIDofthewindowinwhichtheevent(mousebuttonorkeystroke)tookplace.Thisfunctionshouldonlybecalledinanactionprocedureorinadefaultmouseorkeystrokeeventhandler,asitwillreturn1whenthereisnoeventbeingprocessed.
Thisfunctioniscommonlyusedwhenseveralwindowssharethesamelayout.Thesamebuttonsineachwindowpointtothesameactionproceduresdeterminewhichbuttonwasactuallypressed,thefunctioniscalledtogetthewindow.
Example
Thefollowingprogramcreatesfourwindowsinarow,eachwithabuttonthat,whenpressed,causesastartobedrawninthatwindow.
importGUIin"%oot/lib/GUI"
procedureDrawStar
varwindowID:int:=GUI.GetEventWindow
Window.Select(windowID)
Draw.FillStar(25,40,175,190,Rand.Int(10,15))
endDrawStar
fori:0..3
varwindow:int:=Window.Open("graphics:200;200")
%Placewindowabovetaskbar,acrossfrompreviousone.
Window.SetPosition(window,220*i,27)
varbutton:int:=GUI.CreateButton(5,5,190,"DrawStar",
DrawStar)
endfor
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetEventWindow,notbycallingGetEventWindow.
Seealso GUI.ProcessEvent.
GUI.GetHeight PartofGUImodule
Syntax GUI.GetHeight(widgetID:int):int
Description
Returnstheactualheightofawidget.NotethatthismaybedifferentfromtheheightspecifiedintheCreatecall(especiallysincemanywidgetsdonotspecifyaheight.TheGUImoduledeterminestheactualheight).
ThisfunctionisusedinconjunctionwithGUI.GetX,GUI.GetYandGUI.GetWidthtodeterminetheboundsofawidget.Theentirewidgetshouldalwaysfitinthebox(GUI.GetX,GUI.GetY)-(GUI.GetX+GUI.GetWidth1,GUI.GetY+GUI.GetHeight1)
Thepositionandsizeofawidgetisknownonlyafterithasbeendrawntothescreen.Attemptingtogetthelocationordimesionsofthewidgetmaycauseanuninitializedvariableerror.
Example
ThefollowingproceduredrawsaredboxaroundthewidgetspecifiedbywidgetID.
importGUIin"%oot/lib/GUI"
procedureBoxWidget(widgetID:int)
varx,y,width,height:int
x:=GUI.GetX(widgetID)
y:=GUI.GetY(widgetID)
width:=GUI.GetWidth(widgetID)
height:=GUI.GetHeight(widgetID)
Draw.Box(x1,x1,x+width,y+height,
Draw.Box(x2,x2,x+width+1,y+height
endBoxWidget
vartitle:int:=GUI.CreateLabel(20,20,"FrameThis!")
BoxWidget(title)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetHeight,notbycallingGetHeight.
Seealso GUI.GetX,GUI.GetY,andGUI.GetWidth.
GUI.GetMenuBarHeight PartofGUImodule
Syntax GUI.GetMenuBarHeight:int
Description
Returnstheheightofthemenubar.Usefulwhendrawingorplacingwidgetstomakecertainthattheydon'toverlapthemenubar.
Example
Thefollowingprogramdrawsaredboxinthewindowjustbelowethemenubar.
importGUIin"%oot/lib/GUI"
varmenu:int:=GUI.CreateMenu("File")
varitem:int:=GUI.CreateMenuItem("Quit",GUI.Quit
Draw.FillBox(0,0,maxx,maxyGUI.GetMenuBarHeight
brightred)
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetMenuBarHeight,notbycallingGetMenuBarHeight.
Seealso GUI.CreateMenu.
GUI.GetScrollBarWidth PartofGUImodule
Syntax GUI.GetScrollBarWidth:int
DescriptionReturnsthewidthofascrollbar.Usefulwhenplacingascrollbarwidgetbeneathorbesideanotherwidgetorobject.
Example
SeetheScrollPicprograminGUI.CreateHorizontalScrollBarFullforanexampleofGUI.GetScrollBarWidth.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetScrollBarWidth,notbycallingGetScrollBarWidth.
SeealsoGUI.CreateHorizontalScrollBarandGUI.CreateVerticalScrollBar.
GUI.GetSliderValue PartofGUImodule
Syntax GUI.GetSliderValue(widgetID:int):int
Description
ReturnsthecurrentvalueofasliderorscrollbarspecifiedbywidgetID.ThewidgetIDmustspecifyeitherscrollbaroraslider(horizontalorvertical).
Example
SeetheScrollPicprograminGUI.CreateHorizontalScrollBarFullforanexampleofGUI.GetSliderValue.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetSliderValue,notbycallingGetSliderValue.
Seealso
GUI.SetSliderValueforsettingasliderorscrollbar'svalue.SeealsoGUI.CreateHorizontalScrollBar,GUI.CreateVerticalScrollBar,GUI.CreateHorizontalSlider,andGUI.CreateVerticalSlider.
GUI.GetText PartofGUImodule
Syntax GUI.GetText(widgetID:int):string
DescriptionReturnsthecurrenttextofatextfieldspecifiedbywidgetID.ThewidgetIDmustspecifyatextfieldwidget.
Example SeeGUI.CreateTextFieldforanexampleofGUI.GetText.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetText,notbycallingGetText.
SeealsoGUI.SetTextforsettingthetextinatextfield.SeealsoGUI.CreateTextField.
GUI.GetVersion PartofGUImodule
Syntax GUI.GetVersion:int
Description
ReturnsthecurrentversionoftheGUIProcedureLibrary.BecausetheGUIProcedureLibraryisexpectedtogrow,newversionswillprobablybemadeavailableatourwebsitehttp://www.holtsoft.com/turing.Ifyouwishtousefeaturesthatdonotappearinearlierversionsofthelibrary,youcanhaveyourprogramcheckthatthecurrentavailableversionmeetstheprogramsneeds.GUI.GetVersionreturnsanintegerfrom100-999andisreadas1.00to9.99.
Example
ThefollowingprogramfragmentimmediatelyexitsifOOTdoesnotsupportversion1.1oftheGUIProcedureLibrary
importGUIin"%oot/lib/GUI"
ifGUI.GetVersion<110then
put"Youmustupdatetoatleastversion1.1ofthe"
put"GUIProcedureLibrarytousethisprogram."
return
endif
DetailsInversion1.00(shippedwithMacOOT1.5),GUI.GetVersiondidnotexist.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetVersion,notbycallingGetVersion.
GUI.GetWidth PartofGUImodule
Syntax GUI.GetWidth(widgetID:int):int
Description
Returnstheactualwidthofawidget.NotethatthismaybedifferentfromthewidthspecifiedintheCreatecall(especiallysincesomewidgetsdonotspecifyawidth.TheGUImoduledeterminestheactualwidth).
ThisfunctionisusedinconjunctionwithGUI.GetX,GUI.GetYandGUI.GetHeighttodeterminetheboundsofawidget.Theentirewidgetshouldalwaysfitinthebox(GUI.GetX,GUI.GetY)-(GUI.GetX+GUI.GetWidth1,GUI.GetY+GUI.GetHeight1)
Thepositionandsizeofawidgetisknownonlyafterithasbeendrawntothescreen.Attemptingtogetthelocationordimesionsofthewidgetmaycauseanuninitializedvariableerror.
Example
ThefollowingproceduredrawsaredboxaroundthewidgetspecifiedbywidgetID.
importGUIin"%oot/lib/GUI"
procedureBoxWidget(widgetID:int)
varx,y,width,height:int
x:=GUI.GetX(widgetID)
y:=GUI.GetY(widgetID)
width:=GUI.GetWidth(widgetID)
height:=GUI.GetHeight(widgetID)
Draw.Box(x1,x1,x+width,y+height,
Draw.Box(x2,x2,x+width+1,y+height
endBoxWidget
vartitle:int:=GUI.CreateLabel(20,20,"FrameThis!")
BoxWidget(title)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetWidth,notbycallingGetWidth.
Seealso GUI.GetX,GUI.GetY,andGUI.GetHeight.
GUI.Get{X,Y} PartofGUImodule
SyntaxGUI.GetX(widgetID:int):int
GUI.GetY(widgetID:int):int
Description
Returnsthexcoordinateoftheleftedgeofawidget.Notethatthismaybedifferentfromthexcoordinatespecifiedinthewidget'sCreatecall.Forexample,ifaradiobuttoniscreatedwithrightjustification,thexcoordinateintheCreatemethodspecifiestherightedgewhileGUI.GetXwillreturnthexcoordinateoftheleftedge.
ThisfunctionisusedinconjunctionwithGUI.GetWidthandGUI.GetHeighttodeterminetheboundsofawidget.Theentirewidgetshouldalwaysfitinthebox(GUI.GetX,GUI.GetY)-(GUI.GetX+GUI.GetWidth-1,GUI.GetY+GUI.GetHeight-1)
Thepositionandsizeofawidgetisknownonlyafterithasbeendrawntothescreen.Attemptingtogetthelocationordimesionsofthewidgetmaycauseanuninitializedvariableerror.
Example
ThefollowingproceduredrawsaredboxaroundthewidgetspecifiedbywidgetID.
importGUIin"%oot/lib/GUI"
procedureBoxWidget(widgetID:int)
varx,y,width,height:int
x:=GUI.GetX(widgetID)
y:=GUI.GetY(widgetID)
width:=GUI.GetWidth(widgetID)
height:=GUI.GetHeight(widgetID)
Draw.Box(x1,x1,x+width,y+height,
Draw.Box(x2,x2,x+width+1,y+height
endBoxWidget
vartitle:int:=GUI.CreateLabel(20,20,"FrameThis!")
BoxWidget(title)
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingGUI.GetX,notbycallingGetX.
Seealso GUI.GetHeightandGUI.GetWidth.
GUI.Hide PartofGUImodule
Syntax GUI.Hide(widgetID:int)
Description
HidesawidgetspecifiedbywidgetID.UsedinconjunctionwithShowtohideandshowwidgets.Hiddenwidgetscannotgetevents(i.e.respondtokeystrokesormouseclicks).Ifanactivetextfield(seetextfield)ishidden,thenanykeystrokesinthewindowwillbeignored.
Inmostcaseswhereawidgetistoappear,thendisappear,thenappearagain,itisadvisedtocreatethewidgetonceandhideituntilitistoappear,whereuponGUI.Showiscalled.Whentheuserisfinishedwiththewidget,thewidgetishiddenusingGUI.Hide.Thissavestheoverheadofcreatinganddisposingofthesamewidgetseveraltimes.
Example SeeGUI.SetDisplayWhenCreatedforanexampleofGUI.Hide.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.Hide,notbycallingHide.
Seealso GUI.Show.
GUI.HideMenuBar PartofGUImodule
Syntax GUI.HideMenuBar
Description
Hidesthemenubarintheselectedwindow.Nomenuitemscanbeselectedwhenthemenubarishidden.(Menuitemshortcutsareignoredwhilethemenubarishidden.)
ExampleSeeGUI.SetMouseEventHandlerforanexampleofGUI.HideMenuBar.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.HideMenuBar,notbycallingHideMenuBar.
Seealso GUI.ShowMenuBar.SeealsoGUI.CreateMenu.
GUI.HideWindow PartofGUImodule
Syntax GUI.HideWindow(window:int)
Description
Hidesawindowwithwidgetsinit.ThisproceduremakescertainthattheGUILibraryrecognizesthatthewindownolongervisible.ThisprocedurewillcallWindow.Hide,sothereisnoneedfortheusertodoso.
Example
Theprogramopensupawindowwithtwobuttons.Ifthebuttonlabelled"CloseandOpen"ispressed,thewindowisclosedandanewwindowwithtwobuttonsisopenedinarandomlocationonthescreen.
importGUI
varwindowA,windowB:int
varbuttonA,buttonB,buttonQuit:int
varbackToMainA,backToMainB:int
procedureShowWindowA
GUI.HideWindow(defWinID)
GUI.ShowWindow(windowA)
endShowWindowA
procedureShowWindowB
GUI.HideWindow(defWinID)
GUI.ShowWindow(windowB)
endShowWindowB
procedureShowMain
GUI.HideWindow(Window.GetActive)
GUI.ShowWindow(defWinID)
endShowMain
View.Set("graphics:280;100,nobuttonbar")
%Placethebuttonsinthemainwindow
buttonA:=GUI.CreateButton(10,10,0,"ShowWindowA",
buttonB:=GUI.CreateButton(150,10,0,"ShowWindowB",
buttonQuit:=GUI.CreateButton(100,60,0,"Quit",
windowA:=Window.Open("title:WindowA,graphics:150;100,position:bottom;left")
backToMainA:=GUI.CreateButton(20,20,0,"BacktoMain",
Window.Hide(windowA)
windowB:=Window.Open("title:WindowB,graphics:150;100,position:bottom;right")
backToMainB:=GUI.CreateButton(20,20,0,"BacktoMain",
Window.Hide(windowB)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.HideWindowbycallingHideWindow.
SeealsoGUI.ShowWindowforshowingawindowwithwidgetsinit.SeealsoGUI.CloseWindowforclosingawindowwithwidgetsinit.
GUI.OpenFile PartofGUImodule
Syntax GUI.OpenFile(title:string):string
Description
Displaysan"OpenFile"dialogboxtoobtainthenameofanalreadyexistingfile.Thecaption(awindowtitleunderMSWindows,astringinaMacintoshdialogbox)isspecifiedbythetitleparameter.Thefunctionusesadialogboxspecifictotheoperatingsystemtheprogramisbeingrunon.
Iftheuserdidnotchooseafile(i.e.hittheCancelbuttoninthedialog),thefunctionreturns""(theemptystring).
Note:ThisfunctionisnotavailableinthecurrentversionoftheGUIProcedureLibrary(shippingwithTuring4.0andMacOOT1.5).ItisdocumentedhereforusewithfutureshippingversionofTuring.ItislikelytobeimplementedintheversionofTuringreleasedinSeptember2002.Checkthereleasenotesthatarefoundintheon-linehelptofindoutifthisfunctionisnowavailable.
Example
Thefollowingprogramaskstheuserforthenameofafileandthenechoesthecontentsofit.
importGUIin"%oot/lib/GUI"
varfileName,line:string
varstreamNumber:int
fileName:=GUI.OpenFile("ChooseaTextFile")
open:streamNumber,fileName,get
assertstreamNumber>0
loop
exitwheneof(streamNumber)
get:streamNumber,line:*
putline
endloop
close:streamNumber
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingGUI.OpenFile,notbycallingOpenFile.
GUI.OpenFileFull PartofGUImodule
SyntaxGUI.OpenFileFull(title,filter:string,startDir:string):string
Description
Displaysan"OpenFile"dialogboxtoobtainthenameofanalreadyexistingfile.Thecaption(awindowtitleunderMSWindows,astringinaMacintoshdialogbox)isspecifiedbythetitleparameter.Thelistoffilesshownisspecifiedbythefilterparameter.Theinitialdirectorytobedisplayedisspecifiedbytheparameter.Thefunctionusesadialogboxspecifictotheoperatingsystemtheprogramisbeingrunon.
Thefilterparameterisafilenamesuffixthatshouldbedisplayed.Multiplesuffixescanbespecifiedbyseparatingthemwithcommas.Iftheuserspecifiestheemptystringforfilter,thenallthefilesinthedirectoryaredisplayed.IfthestartDirparameterisempty,orifitspecifiesanon-existentdirectory,thenthecurrentdirectoryisdisplayedinthe"OpenFile"dialogbox.
Iftheuserdidnotchooseafile(i.e.hittheCancelbuttoninthedialog),thefunctionreturns""(theemptystring).
Note:ThisfunctionisnotavailableinthecurrentversionoftheGUIProcedureLibrary(shippingwithTuring4.0andMacOOT1.5).ItisdocumentedhereforusewithfutureshippingversionofTuring.ItislikelytobeimplementedintheversionofTuringreleasedinSeptember2002.Checkthereleasenotesthatarefoundintheon-linehelptofindoutifthisfunctionisnowavailable.
Example
Thefollowingprogramaskstheusertoselectafileendingin".txt".TheinitialdirectoryistherootdirectoryoftheCdrive.
importGUIin"%oot/lib/GUI"
varfileName:string
fileName:=GUI.OpenFileFull("ChooseaTextFile","txt","C:\\")
DetailsIfasuffixisplacedinsinglequotes,itwillbeignoredonallbuttheAppleMacintosh,whereitwillspecifyaMacintoshfiletype.
Theexamplemakesthedialogboxdisplayallfilesendingin".txt"or".text"on
ExampleallsystemsbuttheMacintosh.OntheAppleMacintosh,onlyfilesoffiletype'TEXT'willbedisplayed.
fileName:=GUI.OpenFileFull("Open","txt,text,'TEXT'","")
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.OpenFileFullbycallingOpenFileFull.
GUI.Pic... PartofGUImodule
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
PerformsaPic…commandtothecanvasspecifiedbywidgetID.
Alloftheseroutinesareessentiallythesameasthesimilarly-namedproceduresinthePicmodule.Allcoordinatesarebasedonthecanvasandalldrawingisclippedtothecanvasdrawingsurface.
Example
SeetheScrollPicprograminGUI.CreateHorizontalScrollBarFullforanexampleofGUI.PicDraw.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.Pic…,notbycallingPic….
Seealso GUI.CreateCanvas.
GUI.ProcessEvent PartofGUImodule
Syntax GUI.ProcessEvent:boolean
Description
Thisfunctionprocessesasingleevent(amousebuttonpressorakeystroke).Iftheeventactivatesawidget,thentheactionprocedureofthewidgetiscalled.
ThefunctionreturnsfalseuntilGUI.Quitiscalled.Itthenreturnstrue
Inorderforthewidgetstofunctiononceplaced,theGUI.ProcessEventmustbecalledcontinually.WithoutacalltoGUI.ProcessEvent,thewidgetswillappear,butwillnotreacttomouseclicksorkeystrokes.
AlmostallprogramsinvolvingtheGUIProcedureLibraryhavethefollowingcodefragmentintheprogram.Thiscodefragmentisoftencalledtheeventloop
loop
exitwhenGUI.ProcessEvent
endloop
ThelooprunscontinuouslyuntilGUI.Quitiscalled,whereuponGUI.ProcessEventwillreturntrueandtheloopwillexit.Therestoftheprogramisreachedthroughtheactionproceduresthatarecalledwhentheuserinteractswithvariouswidgets.
Details
Itisusuallydesirabletoallowtheusersomewayofquittingtheprogramwithouthavingtoabortit.ThiscanbedonemostsimplybyaddingaQuitbuttonandplacingitinanappropriatelocation.
Example
Hereisprogramthatdoesnothingbutwaitfortheusertopressthequitbutton.
importGUIin"%oot/lib/GUI"
varquitButton:int:=GUI.CreateButton(10,10,0,"Quit",
loop
exitwhenGUI.ProcessEvent
endloop
Tofindoutwhichwidgetwasactivatedandcalledtheactionprocedureifseveralwidgetshavethesameactionprocedure),youcancallGUI.GetEventWidgetID.Togettheexacttimethattheeventoccurred,youcan
Details
callGUI.GetEventTime.Togetthewindowinwhichtheeventtookplace,youcancallGUI.GetEventWindow.
Ifamouseclickoccured,butdidnotactivateanywidget,thenthedefaultmouseeventhandleriscalled.Bydefault,thisdoesnothing.However,ifyouwantyourprogramtorespondtomouseeventsthatdonotaffectawidget,callGUI.SetMouseEventHandlertospecifyyourowndefaultmouseeventhandler.
Ifakeystrokeoccurred,butdidnotactivateanywidget(i.e.itwasn'tashortcutforawidgetandtherearenotextfieldsinthewindow)thenthedefaultkeystrokehandleriscalled.Bydefault,thisdoesnothing.However,ifyouwantyourprogramtorespondtokeystrokeeventsthatdonotaffectawidget,callGUI.SetKeyEventHandlertospecifyyourowndefaultkeyeventhandler.
Ifnoeventoccurred,thenthenulleventhandleriscalled.Bydefault,thisdoesnothing.However,ifyouwantyourprogramtoperformsomeactionrepetetivelywhenitisnotdoinganythingelse,thencallGUI.SetNullEventHandleryourownnulleventhandler.Thenulleventhandlerisoftenusedforsuchthingsasupdatingaclockandmakingcertainthatmusicisplayinginthebackground.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.PProcessEventnotbycallingProcessEvent.
Seealso
GUI.GetEventWidgetID,GUI.GetEventTime,andGUI.GetEventWindowobtaininginformationaboutaneventinanactionprocedure.SeealsoGUI.SetMouseEventHandler,GUI.SetKeyEventHandlerandGUI.SetNullEventHandlerforhandlingmouse,keyboardandnulleventsintheeventloop.SeealsoGUI.Quitforinformationonexittingtheevent
GUI.Quit PartofGUImodule
Syntax GUI.Quit
Description
ThisprocedurecausesGUI.ProcessEventtoreturntrue.Iftheprogramisstructuredproperlywitha
loop
exitwhenGUI.ProcessEvent
endloop
attheendoftheprogram,thentheprogramwillexittheloopaftercurrentactionprocedure.ThisprocedureisusuallycalledfromtheprocedureofaQuitbuttonorExitmenuitem.
Example
Hereisprogramthatdoesnothingbutwaitfortheusertopressthequitbuttonortypetheletter'Q','q','X',or'x'.
importGUI
procedureKeyHandler(ch:char)
ifch='Q'orch='q'orch='X'orch='x'
GUI.Quit
endif
endKeyHandler
varquitButton:int:=GUI.CreateButton(10,10,0,"Quit",
GUI.SetKeyEventHandler(KeyHandler)
loop
exitwhenGUI.ProcessEvent
endloop
put"Done!"
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.QuitcallingQuit.
SeealsoGUI.ProcessEvent.SeealsoGUI.ResetQuitforresettingthe"quit"flag,sothatasecondeventloopcanbeusedinthesameprogram.
GUI.Refresh PartofGUImodule
Syntax GUI.Refresh
Description
Thisroutineredrawsallthewidgetsinthecurrently-selectedwindow.Thisisusedwhensomeformofdrawingmayhaveoverwrittenthewidgetsinawindow.
Itisoftenusedwhenthereissomepossibilitythatthewidgetsmayhavebeendrawnover.Forexample,aprogramthatplacesbuttonsontopofabackgroundimageshouldcallGUI.Refreshwhentheimageischanged.
DetailsGUI.RefreshisusedbytheGUILibrarytoredrawallthewidgetswhenthebackgroundcolourofawindowhaschanged.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.Refresh,notbycallingRefresh.
GUI.ResetQuit PartofGUImodule
Syntax GUI.ResetQuit
Description
TheGUI.ResetQuitprocedureresetsthe"quitting"flagthatissetbytheTheGUI.ResetQuitcanbeusedwheneveryouwanttohaveaprogramthatexitsmainprocessingloop,doessomework,andthenreenterstheprocessingloop.
WithoutGUI.ResetQuit,theprogramwillexitthesecondloopimmediatelybecauseGUI.ProcessEventwillreturntrue.
Thisprogramallowstheusertoselectthecolorthatstarsaretobedrawnin.pressesthebutton,theprogramexitsthefirsteventloopanddrawsthestars.anotherbuttonandenteringasecondeventloop,itcallsGUI.ResetQuit
importGUI
varradio:array1..4ofint
varbutton:int
varstarColor:int:=red
%Actionproceduresfortheradiobuttons
procedureRed
starColor:=brightred
endRed
procedureGreen
starColor:=brightgreen
endGreen
procedureBlue
starColor:=brightblue
endBlue
procedureCyan
starColor:=brightcyan
endCyan
%Createtheradiobuttons
radio(1):=GUI.CreateRadioButton(15,maxy-35,"Red",0,
radio(2):=GUI.CreateRadioButton(-1,-1,"Green",
radio(3):=GUI.CreateRadioButton(-1,-1,"Blue",
radio(4):=GUI.CreateRadioButton(-1,-1,"Cyan",
%Createthepushbutton
Example button:=GUI.CreateButton(100,maxy-70,0,"DrawStars",
%Processeventsuntilthe"DrawStars"buttonispressed
loop
exitwhenGUI.ProcessEvent
endloop
%Disposeofalltheradiobuttonsandthepushbutton
fori:1..4
GUI.Dispose(radio(i))
endfor
GUI.Dispose(button)
%Drawabunchofstars-Nomorehandlingofeventsorwidgets
fori:1..100
varx:int:=Rand.Int(0,maxx-20)
vary:int:=Rand.Int(0,maxy-20)
Draw.FillStar(x,y,x+20,y+20,starColor)
endfor
%Createanewbutton
button:=GUI.CreateButton(300,10,0,"Quit",
%Resetthequitflag.Withoutthisstatement,theloopfollowingwould
%exitimmediatelybecausethequitflagwassetinthepreviousloop
GUI.ResetQuit
%Processeventsuntilthe"Quit"buttonispressed
loop
exitwhenGUI.ProcessEvent
endloop
%Closethewindow
GUI.CloseWindow(defWinID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.ResetQuitResetQuit.
GUI.SaveFile PartofGUImodule
Syntax GUI.SaveFile(title:string):string
Description
Displaysan"SaveFile"dialogboxtoobtainthenameofafile.Thecaption(awindowtitleunderMSWindows,astringinaMacintoshdialogbox)isspecifiedbythetitleparameter.Thefunctionusesadialogboxspecifictotheoperatingsystemtheprogramisbeingrunon.
Iftheuserdidnotchooseafile(i.e.hittheCancelbuttoninthedialog),thefunctionreturns""(theemptystring).
Note:ThisfunctionisnotavailableinthecurrentversionoftheGUIProcedureLibrary(shippingwithTuring4.0andMacOOT1.5).ItisdocumentedhereforusewithfutureshippingversionofTuring.Checkthereleasenotesthatarefoundintheon-linehelptofindoutifthisfunctionisnowavailable.
Example
Thefollowingprogramaskstheuserforthenameofafileandthenwritesthenumbers1to10init.
importGUIin"%oot/lib/GUI"
varfileName:string
varstreamNumber:int
fileName:=GUI.SaveFile("ChooseaTextFile")
open:streamNumber,fileName,put
assertstreamNumber>0
fori:1..10
put:streamNumber,i
endloop
close:streamNumber
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SaveFile,notbycallingSaveFile.
GUI.SaveFileFull PartofGUImodule
SyntaxGUI.SaveFileFull(title,filter:string,startDir:string):string
Description
Displaysan"SaveFile"dialogboxtoobtainthenameofanalreadyexistingfile.Thecaption(awindowtitleunderMSWindows,astringinaMacintoshdialogbox)isspecifiedbythetitleparameter.Thelistoffilesshownisspecifiedbythefilterparameter.TheinitialdirectorytobedisplayedisspecifiedbythestartDirparameter.Thefunctionusesadialogboxspecifictotheoperatingsystemtheprogramisbeingrunon.
Thefilterparameterisafilenamesuffixthatshouldbedisplayed.Multiplesuffixescanbespecifiedbyseparatingthemwithcommas.Iftheuserspecifiestheemptystringforfilter,thenallthefilesinthedirectoryaredisplayed.IfthestartDirparameterisempty,orifitspecifiesanon-existentdirectory,thenthecurrentdirectoryisdisplayedinthe"OpenFile"dialogbox.
Iftheuserdidnotchooseafile(i.e.hittheCancelbuttoninthedialog),thefunctionreturns""(theemptystring).
Note:ThisfunctionisnotavailableinthecurrentversionoftheGUIProcedureLibrary(shippingwithTuring4.0andMacOOT1.5).ItisdocumentedhereforusewithfutureshippingversionofTuring.Checkthereleasenotesthatarefoundintheon-linehelptofindoutifthisfunctionisnowavailable.
Example
Thefollowingprogramsegmentaskstheuserforthenameofafileendingin".txt".TheinitialdirectoryistherootdirectoryoftheCdrive.
varfileName:string:=GUI.SaveFileFull("ChooseaTextFile",
"txt","C:\\")
DetailsIfasuffixisplacedinsinglequotes,itwillbeignoredonallbuttheAppleMacintosh,whereitwillspecifyaMacintoshfiletype.
Example
Thefollowingprogramsegmentaskstheuserforthenameofafile.Itdisplaysfilesoftype'TEXT'.Theinitialdirectoryisthe"TuringPrograms"directoryonthe"MacintoshHD"volume.
varfileName:string:=GUI.SaveFileFull("ChooseaTextFile",
"'TEXT'","MacintoshHD:TuringPrograms")
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SaveFileFull,notbycallingSaveFileFull.
GUI.SelectRadio PartofGUImodule
Syntax GUI.SelectRadio(widgetID:int)
DescriptionSelectsaradiobuttonspecifiedbywidgetID.Thepreviously-selectedradiobuttonis"de-selected".Theactionprocedureoftheradiobuttoniscalled.
Example
Thefollowingprogramcreatessizradiobuttons.Selectingoneofthebuttonscausethebottomtworadiobuttonstobecomeselected.
importGUIin"%oot/lib/GUI"
View.Set("graphics:350;110")
varradio:array1..6ofint%TheradiobuttonIDs.
procedureRadioPressed
Text.Locate(1,1)
fori:1..6
ifradio(i)=GUI.GetEventWidgetIDthen
put"RadioButton",i,"Selected"
endif
endfor
endRadioPressed
procedureSelect
GUI.SelectRadio(radio(3))
GUI.SelectRadio(radio(6))
endSelect
radio(1):=GUI.CreateRadioButton(15,maxy35,
"RadioButton1",0,RadioPressed)
radio(2):=GUI.CreateRadioButton(1,1,"RadioButton2",
radio(1),RadioPressed)
radio(3):=GUI.CreateRadioButton(1,1,"RadioButton3",
radio(2),RadioPressed)
radio(4):=GUI.CreateRadioButtonFull(maxx15,
"RadioButton4",0,RadioPressed,GUI.RIGHT
radio(5):=GUI.CreateRadioButtonFull(1,1,"RadioButton5",
radio(4),RadioPressed,GUI.RIGHT,GUI.NONE
radio(6):=GUI.CreateRadioButtonFull(1,1,"RadioButton6",
radio(5),RadioPressed,GUI.RIGHT,GUI.NONE
varselectButton:int:=GUI.CreateButton(15,10,100,
"SelectBottomButtons",Select)
varquitButton:int:=GUI.CreateButton(maxx15100,10,100,
"Quit",GUI.Quit)loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.SelectRadio,notbycallingSelectRadio.
Seealso GUI.CreateRadioButtonandGUI.CreatePictureRadioButton.
GUI.SetActive PartofGUImodule
Syntax GUI.SetActive(widgetID:int)
Description
MakesatextfieldspecifiedbywidgetIDactive.Ifthetextfieldisnotinanactivewindow,thenthetextfieldwillbecomeactivewhenthewindowdoes.Ifanothertextfieldwasactiveinthewindow,itisdeactivated.
Example SeeGUI.CreateTextFieldforanexampleofGUI.SetActive.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.SetActive,notbycallingSetActive.
Seealso GUI.CreateTextField.
GUI.SetBackgroundColor PartofGUImodule
Syntax GUI.SetBackgroundColor(Color:int)
Description
Changesthebackgroundcolourofthecurrently-selectedwindowtothecolorspecifiedbyColor.Thisdoesnotchangethevalueofcolor0inthewindow.Insteaditfillstheentirewindowwiththenewbackgroundcolorandthenredrawsallthewidgets.
Forindentedandextendeditems,thebackgroundcolorisassumedtobesettogray.
ThealternatespellingisGUI.SetBackgroundColour
ExampleSeeGUI.CreateFrameforanexampleofGUI.SetBackgroundColour.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.SetBackgroundColor,notbycallingSetBackgroundColor.
GUI.SetCheckBox PartofGUImodule
Syntax GUI.SetCheckBox(widgetID:int,status:boolean)
Description
SetsthestatusofacheckboxspecifiedbywidgetID.Ifstatusistrue,thecheckboxisfilled(markedwithan'X').Ifstatusisfalse,thecheckboxissetempty.GUI.SetCheckBoxcallsthecheckbox'sactionprocedurewiththenewstatusandredrawsthewidgetwiththenewstatus.
ExampleSeeGUI.CreateCheckBoxforanexampleofGUI.SetCheckBox.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.SetCheckBox,notbycallingSetCheckBox.
Seealso GUI.CreateCheckBox.
GUI.SetColor PartofGUImodule
Syntax GUI.SetColor(widgetID:int,clrNumber:int)
Description
TheGUI.SetColorprocedureisusedbuttonstochangethecolorofabutton.ThecolorisspecifiedbytheclrNumberparameter.TheedgesofthebuttonareadarkerversionofthecolorspecifiedbyclrNumbergeneralyoushouldusebrightercolorsforbuttons.
Example
Thisprogramdisplaysthreebuttonswithdifferentcolors.
importGUI
procedureDoNothing
endDoNothing
varb1:=GUI.CreateButton(100,100,0,"PushMe",
GUI.SetColor(b1,brightred)
varb2:=GUI.CreateButton(100,140,0,"PushMe",
GUI.SetColor(b2,brightgreen)
varb3:=GUI.CreateButton(100,180,0,"PushMe",
GUI.SetColor(b3,brightblue)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetColornotbycallingSetColor.
GUI.SetDefault PartofGUImodule
Syntax GUI.SetDefault(widgetID:int,default:boolean)
Description
Setsthe"defaultstatus"ofabuttonspecifiedbywidgetID.Ifabuttonisthedefaultbutton,thenitisdrawnwithaheavyoutlineanditisactivatedwhentheuserpressesENTER.
Onlyonebuttoncanbethedefaultbuttonperwindow.Ifabuttonissettobethedefaultbutton,thenthepreviousdefaultbuttonhasits"defaultstatus"removed.
Status
Exportedqualified.
ThismeansthatyoucanonlycalltheproceduresbycallingGUI.SetDefault,notbycallingSetDefault.
Seealso GUI.CreateButton.
GUI.SetDisplayWhenCreated PartofGUImodule
Syntax GUI.SetDisplayWhenCreated(display:boolean)
Description
Bydefault,wheneverawidgetiscreatedwithaGUI.Create…procedure,thewidgetinstantlyappears.Sometimes,thisisnotthedesiredbehaviour.Forexample,ifseveralwidgetsaretooccupythesamelocationwithonlyonebeingdisplayedatatime,thenitisdesirablenottohavethewidgetappearwhenfirstcreated.
Ifawidgetisnotdisplayedwhencreated,thenGUI.Showmustbecalledtomakethewidgetvisible.
Ifthedisplayparameteristrue,thenwidgetsaredisplayedimmediatelyuponcreation.Ifthedisplayparameterissettofalse,thenthewidgetisnotmadevisibleoncreationandGUI.Showmustbecalledtodisplaythewidget.
Example
Thefollowingprogramtogglesthevisiblilityoftheframewhenthebuttonispushed.Theframestartsoutinvisible.
importGUIin"%oot/lib/GUI"
View.Set("graphics:150;100")
varvisible:boolean:=false
varbutton,frame:int
procedureToggle
ifvisiblethen
GUI.Hide(frame)
else
GUI.Show(frame)
endif
visible:=notvisible
endToggle
button:=GUI.CreateButton(25,40,0,"ToggleFrame",
GUI.SetDisplayWhenCreated(false)
frame:=GUI.CreateFrame(10,10,140,90,0)
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetDisplayWhenCreated,notbycallingSetDisplayWhenCreated
GUI.SetEchoChar PartofGUImodule
Syntax GUI.SetEchoChar(widgetID:int,echoChar:char)
Description
TheGUI.SetEchoCharprocedureisusedwithtextfields,especiallywhenusingatextfieldtoinputapassword.WhentheGUI.SetEchoChariscalledwithatextfield,anycharacterenteredintothetextfieldwillappearasthecharacterspecifiedbyinputChar
Thisallowsyoutousethetextfieldtoenterapassword.ThecharactersthattheusertypeswillbeechoedwiththecharacterspecifiedbyinputChar(oftenanasterisk).
Example
Thisprogramdisplaysatextfield.Astheuserenterscharacters,eachcharacterisrepresentedasa'*'.Whentheuserentersreturn,theprogramexitsafterdisplayingtheactualtextenteredintothetextfield.
importGUI
procedureEchoString(s:string)
put"Youentered\"",s,"\""
GUI.Quit
endEchoString
vartf:=GUI.CreateTextField(10,100,100,"",
GUI.SetEchoChar(tf,'*')
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Details
NotethattheechoCharargumenttoGUI.SetEchoCharmustbeacharacter,notastring.Thismeansthecharactershouldbeenclosedinsinglequotemarks('),notdoublequotes(").
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetEchoChar,notbycallingSetEchoChar.
GUI.SetKeyEventHandler PartofGUImodule
SyntaxGUI.SetKeyEventHandler(keyEventHandler:procedurex(ch:char))
Description
Setsthenewdefaultkeystrokeeventhandler.ThekeyEventHandlerthenameofaprocedurethatiscalledeverytimeGUI.ProcessEventthereisakeystrokewhichisnothandledbyanywidget.ThechparameterinthekeyEventHandleristhekeystroketypedbytheuser.
Thisprocedureisoftenusedtoallowformorethanoneshortcutcharacterforagivenbutton.
Example
Thefollowingprogramdrawsastarorquitsdepeningonthebutton.TheDrawStarbuttoncanbeactivatedbyclickingonitortyping'D','d','S','s'orCtrl+S.TheQuitbuttoncanbeactivatebytyping'Q','q'orCtrl+Q.TheDrawStarbuttonisalsothedefaultbutton.ItisactivatedwhenevertheuserpressesENTER.
importGUI
View.Set("graphics:220;200")
procedureDrawStar
Draw.FillStar(25,40,175,190,Rand.Int(10,15))
endDrawStar
procedureKeyHandler(ch:char)
ifch='q'orch='^Q'then
Draw.Cls
GUI.Quit
elsifch='d'orch='^d'orch='S'orch
DrawStar
endif
endKeyHandler
GUI.SetKeyEventHandler(KeyHandler)
varbutton:int:=GUI.CreateButtonFull(5,5,100,"DrawStar",
DrawStar,0,'D',true)
varquitButton:int:=GUI.CreateButtonFull(115,5,100,"Quit",
GUI.Quit,0,'Q',false)
loop
exitwhenGUI.ProcessEvent
endloop
Exportedqualified.
StatusThismeansthatyoucanonlycallthefunctionbycallingGUI.SetKeyEventHandler,notbycallingSetKeyEventHandler.
Seealso GUI.ProcessEvent.
GUI.SetLabel PartofGUImodule
Syntax GUI.SetLabel(widgetID:int,text:string)
Description
ChangesthetextofawidgetspecifiedbywidgetIDtotext.Thisprocedurecanacceptabutton,checkbox,radiobutton,label,oralabelledframewidgetasthewidgetIDparameter.
Inmostcases,ifthetextwillnotfitinthewidget'scurrentsize,thewidgetwillberesizedtofitthetext.Ifthewidgetwasmadelargertofitthetextandthenthetextischanged,thewidgetwillberesizedasappropriatefortheoriginalwidthspecifiedandthenewtext.
Example
Thefollowingprogramchangesthetextinthebuttonwheneverakeystrokeoccurs.Whenthetextischangedbackto"Quit",thebuttonassumesawidthof100again.
importGUIin"%oot/lib/GUI"
View.Set("graphics:220;50")
varshort:boolean:=true
varbutton:int
procedureKeyHandler(ch:char)
ifshortthen
GUI.SetLabel(button,"PressThisButtontoQuit")
else
GUI.SetLabel(button,"Quit")
endif
short:=notshort
endKeyHandler
GUI.SetKeyEventHandler(KeyHandler)
button:=GUI.CreateButton(10,5,100,"Quit",
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetLabel,notbycallingSetLabel.
Seealso
GUI.CreateButton,GUI.CreateCheckBox,GUI.CreateRadioButton,GUI.CreateLabel,andGUI.CreateLabelledFrame.
GUI.SetMouseEventHandler PartofGUImodule
SyntaxGUI.SetMouseEventHandler(mouseEventHandler:procedurex(mx,my:int))
Description
Setsthenewdefaultmouseeventhandler.ThemouseEventHandlerparameteristhenameofaprocedurethatiscalledeverytimeGUI.ProcessEventiscalledandthereisamousebuttondownwhichisnothandledbyanywidget.ThemxandmyparametersinthemouseEventHandlerarethelocationofmousewhenthebuttonwaspressed.
Thisprocedureisusedbyprogramstoallowformouseinputinaprogramthatuseswidgets.
Thisisaprogramthatallowstheusertoplacestarsonthescreen.Themenubarallowstheusertoquittheprogramatanytime.Theusercanalsotoggletheappearanceofthemenubarbypressinganykey.
importGUI
varstarX,starY,starColor:array1..100ofint
varnumStars:int:=0
varmenuVisible:boolean:=true
procedureDrawStar(i:int)
ifmenuVisiblethen
View.ClipSet(0,0,maxx,
maxyGUI.GetMenuBarHeight)
endif
Draw.FillStar(starX(i)20,starY(i)20,
starY(i)+20,starColor(i))View.ClipOff
endDrawStar
procedureRedraw
fori:1..numStars
DrawStar(i)
endfor
Text.Locate(maxrow,1)
put"Pressanykeytotogglemenubar"..
endRedraw
procedureKeyHandler(ch:char)
Example ifmenuVisiblethen
GUI.HideMenuBarelse
GUI.ShowMenuBar
endif
menuVisible:=notmenuVisible
Redraw
endKeyHandler
procedureMouseHandler(x,y:int)
ifnumStars=100then
Text.Locate(maxrow,1)
put"Maximumnumberofstarsexceeded!"..
return
endif
numStars+=1
starX(numStars):=x
starY(numStars):=y
starColor(numStars):=Rand.Int(9,15)
DrawStar(numStars)
endMouseHandler
varmenu:int:=GUI.CreateMenu("File")
varmenuItem:int:=GUI.CreateMenuItemFull("Quit",
GUI.Quit,'^Q',false)
GUI.SetKeyEventHandler(KeyHandler)
GUI.SetMouseEventHandler(MouseHandler)
Redraw
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetMouseEventHandler,notbycallingSetMouseEventHandler.
Seealso GUI.ProcessEvent.
GUI.SetNullEventHandler PartofGUImodule
SyntaxGUI.SetNullEventHandler(nullHandler:procedurex())
Description
Setsthenewnulleventhandler.ThenullHandlerparameteristhenameofaprocedurethatiscalledeverytimeGUI.ProcessEventiscalledandtherearenomousebuttonpressesorkeystrokestobeprocessed.
Thisisusedbyprogramsthatneedtocallsubprogramsoften,butdonotwishtointerrupttheactionofuserwidgets.
Example
ThefollowingprogramhasaQuitbutton.Whennowidgetsarebeingprocessed,aclockinthecornerisupdated.
importGUI
View.Set("graphics:220;50")
varoldTime:string:=""
varbutton:int
procedureNullHandler
varnewTime:string:=Time.Date
newTime:=newTime(11..*)
ifnewTimenot=oldTimethen
Text.Locate(maxrow,maxcol9)
putnewTime..
oldTime:=newTime
endif
endNullHandler
GUI.SetNullEventHandler(NullHandler)
button:=GUI.CreateButton(10,5,100,"Quit",
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetNullEventHandler,notbycallingSetNullEventHandler
Seealso GUI.ProcessEvent.
GUI.SetPosition PartofGUImodule
Syntax GUI.SetPosition(widgetID,x,y:int)
Description
MovesawidgetspecifiedbywidgetIDtothelocation(x,y).Ifthewidgetisvisible,itismovedimmediatelytothenewlocation.Ifthewidgetishidden,itwillappearatthenewlocationwhentheShowprocedureiscalled.NotethatthexandyspecifiedherearethesameasintheCreatemethod.Forexample,ifyouhadspecifiedacheckboxtoberightjustifiedintheCreateCheckBoxFullfunction,then(x,y)inacalltoSetPositionwouldspecifythelower-rightcornerasopposedtothelower-leftcorner.
Example
Thefollowingprogrammovesthebuttoneverytimethebuttonispressed.
importGUIin"%oot/lib/GUI"
varbutton:int
procedureMoveButton
varnewX,newY:int
newX:=Rand.Int(0,maxxGUI.GetWidth(button
newY:=Rand.Int(0,maxyGUI.GetHeight(button
GUI.SetPosition(button,newX,newY)
endMoveButton
button:=GUI.CreateButton(100,100,0,"MoveButton",
MoveButton)
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetPosition,notbycallingSetPosition.
GUI.SetPositionAndSize PartofGUImodule
SyntaxGUI.SetPositionAndSize(widgetID,x,y:int,width,height:int)
Description
ChangesthepositionandsizeofthewidgetspecifiedbywidgetIDsimultaneously.Thex,y,widthandheightparametershavethesamemeaningasintheGUI.Createfunctionforthatwidget.Anywidgetexceptamenuoramenuitemcanberesized,althoughforsomewidgets,thewidthorheightparametermaybeignored.
GUI.SetPositionAndSizeworksthesamewayastheGUI.SetPositionandGUI.SetSizeprocedures.
Example
Thefollowingprogrammovesandresizesthebuttoneverytimethebuttonispressed.
importGUIin"%oot/lib/GUI"
varbutton,minWidth,minHeight:int
procedureMoveButton
varnewX,newY,newWidth,newHeight:int
newWidth:=max(minWidth,Rand.Int(0,200))
newHeight:=max(minHeight,Rand.Int(0,100))
newX:=Rand.Int(0,maxxnewWidth)
newY:=Rand.Int(0,maxynewHeight)
GUI.SetPositionAndSize(button,newX,newY,
newWidth,newHeight)
endMoveButton
button:=GUI.CreateButton(100,100,0,"MoveButton",
MoveButton)
minHeight:=GUI.GetHeight(button)
minWidth:=GUI.GetWidth(button)
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
GUI.SetPositionAndSize,notbycallingSetPositionAndSize.
GUI.SetScrollAmount PartofGUImodule
SyntaxGUI.SetScrollAmount(widgetID:int,arrowInc,pageInc,thumbSize:int)
Description
Setsascrollbar'sarrowincrement,pageincrementandthumbsize.Redrawsthescrollbartotakeintoaccountthenewthumbsize.ThewidgetIDspecifiesthescrollbartobechanged.ThearrowIncparameteristhenewarrowincrement(theamountthescrollbar'svalueischangedwhenthescrollarrowsarepressed).Avalueof1meanstousethepreviously-definedarrowincrementvalue.ThepageIncparameterspecifiesthenewpageincrement(theamountthescrollbar'svalueischangedwhentheuserclicksinthepageup/downsectionofthescrollbar).Avalueof1meanstousethepreviously-definedpageincrementvalue.Thespecifieshenewthumbsize.Seethescrollbarexplanationformoredetailonascrollbar'sthumbsize.Avalueof1meanstousethepreviously-definedthumbsize.
Thefollowingprogramdisplaysanimageinacanvasinawindow.Iftheimageislargerthanthecanvas,scrollbarstothebottomandleftareusedtoallowtheusertoseetheentireimage.Atextfieldallowsuserstoloadadditionalimageswheneverthe"LoadFile"buttonispressed.
%The"ScrollPic2"program.
importGUIin"%oot/lib/GUI"
%Themaximumwidth/heightofthecanvas.
constmaxSize:int:=220
constleftBorder:int:=15%Leftmargin.
constbottomBorder:int:=25%Bottommargin.
varh,v:int%Thescrollbars.
varcanvas:int%Thecanvas.
varpic:int%Thepicture.
varfileNameField:int%Thefilenametextfield.
varerrorLabel:int%Theerrormessagelabel.
varloadButton:int%The"LoadPicture"button.
procedureScrollPic(ignore:int)
%Getthecurrentvalueofthescrollbars.
varx:int:=GUI.GetSliderValue(h)
vary:int:=GUI.GetSliderValue(v)
GUI.PicDraw(canvas,pic,x,y,picCopy)
endScrollPic
procedureLoadFile(fileName:string)
varpicWidth,picHeight,canvasWidth,canvasHeight
varnewPic:int:=Pic.FileNew(fileName)
ifnewPic<=0then
GUI.SetLabel(errorLabel,
Example
"Errorloadingpicture:"+Error.LastMsg
GUI.SetSelection(fileNameField,1,1)
return
else
GUI.SetLabel(errorLabel,"")
pic:=newPic
endif
picWidth:=Pic.GetWidth(pic)
picHeight:=Pic.GetHeight(pic)
canvasWidth:=min(picWidth,maxSize)
canvasHeight:=min(picHeight,maxSize)
%Hidethecanvasandthethreeitems,readjustthem
%andthenshowthem.
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,picWidth1)
GUI.SetSliderMinMax(v,0,picHeight1)
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)
endLoadFile
procedureLoadFileButton
varfileName:string:=GUI.GetText(fileNameField
LoadFile(fileName)
endLoadFileButton
View.Set("graphics:265;295")
%Weplacethecanvasfirstandeverythingelseisplaced
%relativetothecanvas.
canvas:=GUI.CreateCanvas(leftBorder,
bottomBorder+GUI.GetScrollBarWidth,maxSize
GUI.GetY(canvas)GUI.GetScrollBarWidth,
GUI.GetWidth(canvas),0,100,0,ScrollPic,3,100,
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(
GUI.GetY(canvas)+GUI.GetHeight(canvas)+10,150,"",
LoadFile)
loadButton:=GUI.CreateButton(GUI.GetX(fileNameField
GUI.GetWidth(fileNameField)+20,
GUI.GetY(fileNameField),0,"LoadFile",LoadFileButton
errorLabel:=GUI.CreateLabel(GUI.GetX(canvas),5,"")
%Settheinitialpictureandreturnifitisnotfound.
GUI.SetText(fileNameField,"Forest.bmp")
LoadFileButton
ifpic=0then
return
endif
loop
exitwhenGUI.ProcessEvent
endloop
StatusExportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetScrollAmount
Seealso GUI.CreateHorizontalScrollBarandGUI.CreateVerticalScrollBar
GUI.SetScrollOnAdd PartofGUImodule
Syntax GUI.SetScrollOnAdd(widgetID:int,scrollOnAdd:boolean
Description
TheGUI.SetScrollOnAddprocedureallowsyoutospecifywhetheratextboxscrollstothebottomofthetextwhennewtextisadded(thedefaultbehaviour).BycallingthisprocedurewithscrollOnAddsettofalse,thetextboxwillnotscrollunlesstheusermanipulatesthetextbox'sscrollbars.
Example
Thisprogramdisplaysthecontentsofafileinatextbox.Afterthefileisdisplayed,thetoplineinthetextboxwillbethefirstlineinthefile.
importGUI
View.Set("graphics:300;300")
constfileNameToBeViewed:string:="TextBxs.DEM"
vartextBox:int%TheTextFieldID.
vartitle:int%Thelabelforthetitle.
varf:int%Thestreamnumberofthefile.
varline:string%Linestobereadfromthefile.
%Openthefile.
open:f,fileNameToBeViewed,get
iff=0then
put"Unabletoopen"+fileNameToBeViewed+":",
return
endif
%Setbackgroundcolortograyforindentedtextbox.
GUI.SetBackgroundColor(gray)
%Createthetitlelabelandtextbox.
title:=GUI.CreateLabelFull(20,280,fileNameToBeViewed
GUI.CENTER,0)
textBox:=GUI.CreateTextBoxFull(10,10,280,265,
GUI.INDENT,0)
GUI.SetScrollOnAdd(textBox,false)
%Readthefileandplaceitinthetextbox.
loop
exitwheneof(f)
get:f,line:*
GUI.AddLine(textBox,line)
endloop
close:f%Closethefile.
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetScrollOnAdd,notbycallingSetScrollOnAdd.
GUI.SetSelection PartofGUImodule
Syntax GUI.SetSelection(widgetID,fromSel,toSel:int)
Description
SetstheselectedtextinthetextfieldspecifiedbywidgetID.ThevalueofthefromSelandtoSelparametersindicatethecharacterswheretheselectionwillbeginandend.Forexample,ifthetextwas"Hellothere",settingfromSelto2andtoSelto5wouldselect"ell".SettingfromSelandtoSelautomaticallyselectstheentiretext.
ThefromSelparameterspecifiesthestartoftheselection.Thisrangesfrom1(beforethefirstcharacter)tothenumberofcharactersinthetext+1(afterthelastcharacter).Avalueof1forbothfromSelandtoSelselectstheentiretext.
ThetoSelparameterspecifiestheendoftheselection.Thisrangesfrom1(beforethefirstcharacter)tothenumberofcharactersinthetext+1(afterthelastcharacter).Avalueof1forbothfromSelandtoSelselectstheentiretext.
Example
Thefollowingprogramallowstheusertotypeintoatextfield.WhentheuserpressesENTER,itsearchesforanynon-lowercasetextandifitfindsany,selectsittomakeiteasyfortheusertocorrectit.Ifalltheinputislower-casetext,theprogramterminates.
importGUIin"%oot/lib/GUI"
vartextField,lbl:int
procedureCheckInput(s:string)
fori:1..length(s)
if(s(i)<'a'or'z'<s(i))ands(i
GUI.SetSelection(textField,i,i+1)
return
endif
endfor
GUI.Quit
endCheckInput
textField:=GUI.CreateTextField(100,100,200,"",
lbl:=GUI.CreateLabelFull(100+GUI.GetWidth(
100+GUI.GetHeight(textField),
"OnlyAllowsLowerCaseLetters",0,0,
GUI.CENTER+GUI.BOTTOM,0)
loop
exitwhenGUI.ProcessEvent
endloop
GUI.SetLabel(lbl,"ProgramFinished!")
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetSelectionnotbycallingSetSelection.
Seealso GUI.CreateTextField.
GUI.SetSize PartofGUImodule
Syntax GUI.SetSize(widgetID,width,height:int)
Description
ChangesthesizeofthewidgetspecifiedbywidgetID.Ifthewidgetisvisible,itssizeischangedimmediately,otherwisethewidgetwillappearinitsnewsizewhenthewidgetisnextmadevisible.Notethatthewidthandheightparametersarenonecessarilytheactualwidthandheightofthewidget.Forexample,theTextFieldwidgetignorestheheightparameter,calculatingthewidget'sactualheightfromtheheightofthetextintheTextField.
Example
Thefollowingprogramresizesthebuttoneverytimethebuttonispressed.
importGUIin"%oot/lib/GUI"
varbutton:int
procedureResizeButton
varnewWidth,newHeight:int
newWidth:=Rand.Int(0,200)
newHeight:=Rand.Int(0,200)
GUI.SetSize(button,newWidth,newHeight)
endResizeButton
button:=GUI.CreateButton(100,100,0,"ResizeButton",
ResizeButton)
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetSize,notbycallingSetSize.
GUI.SetSliderMinMax PartofGUImodule
Syntax GUI.SetSliderMinMax(widgetID,min,max:int)
Description
SetstheminimumandmaximumvaluesofthesliderorscrollbarspecifiedbywidgetID.Theminparameterspecifiesthenewminimumvalueofthesliderorscrollbar.Themaxparameterspecifiesthenewmaximumvalueofthesliderorscrollbar.Themaxparametermustbegreaterthantheminparameter.
GUI.SetSliderMinMaxredrawsthethumbtotakeintoaccountthenewminimumandmaximum.Ifthecurrentvalueofthesliderisoutsidethenewminimum/maximum,thenthevalueisadjustedappropriately.
ExampleSeeGUI.SetScrollAmountforanexampleofGUI.SetSliderMinMax.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetSliderMinMax,notbycallingSetSliderMinMax.
Seealso
GUI.CreateHorizontalScrollBar,GUI.CreateVerticalScrollBar,GUI.CreateHorizontalSlider,andGUI.CreateVerticalSlider.
GUI.SetSliderReverse PartofGUImodule
Syntax GUI.SetSliderReverse(widgetID:int)
Description
SetsasliderorscrollbarspecifiedbywidgetIDinto(oroutof,ifalreadyinto)"reversemode".Normally,asliderorscrollbarisatitsminimumvaluewhenthethumbisonthelefthandside(bottomforaverticalslider).Thisreversesit,sotheminimumvalueiswhenthethumbisattherighthandside(topforverticalsliders)ofthetrack.Callingthisroutineasecondtimereversesitbacktonormal.Thisprocedureredrawstheslidertomovethethumbtoitsnewlocation.
Example
Thefollowingprogramcreatestwosliders,oneofwhichisreversed.
importGUIin"%oot/lib/GUI"
View.Set("graphics:300;70")
varsBar,sBarLabel,reverseSBar,reverseSBarLabel
procedureSBarMoved(value:int)
GUI.SetLabel(sBarLabel,intstr(value))
endSBarMoved
procedureReverseSBarMoved(value:int)
GUI.SetLabel(reverseSBarLabel,intstr(value
endReverseSBarMoved
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(
GUI.GetWidth(reverseSBar)+10,40,"50")
loop
exitwhenGUI.ProcessEvent
endloop
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
GUI.SetSliderReverse,notbycallingSetSliderReverse.
SeealsoGUI.CreateHorizontalScrollBar,GUI.CreateVerticalScrollBar,GUI.CreateHorizontalSlider,andGUI.CreateVerticalSlider.
GUI.SetSliderSize PartofGUImodule
Syntax GUI.SetSliderSize(widgetID,length:int)
Description
ChangesthelengthofasliderorscrollbarspecifiedbywidgetIDtothevaluespecifiedbythelengthparameter.Redrawsthesliderorscrollbarandchangesthepositionofthethumbtotakeintoaccountthenewsizeofthesliderorscrollbar.
ExampleSeeGUI.SetScrollAmountforanexampleofGUI.SetSliderSize.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetSliderSize,notbycallingSetSliderSize.
Seealso
GUI.CreateHorizontalScrollBar,GUI.CreateVerticalScrollBar,GUI.CreateHorizontalSlider,andGUI.CreateVerticalSlider.
GUI.SetSliderValue PartofGUImodule
Syntax GUI.SetSliderValue(widgetID,value:int)
Description
SetsthevalueofasliderorscrollbarspecifiedbywidgetIDtovalue.Itmovesthethumbonthesliderorscrollbartotheappropriatelocationandcallstheslider'sactionprocedurewiththenewvalue.
ExampleSeeGUI.SetScrollAmountforanexampleofGUI.SetSliderValue.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetSliderValue,notbycallingSetSliderValue.
Seealso
GUI.GetSliderValueforreadingasliderorscrollbar'svalue.SeealsoGUI.CreateHorizontalScrollBar,GUI.CreateVerticalScrollBar,GUI.CreateHorizontalSlider,andGUI.CreateVerticalSlider.
GUI.SetText PartofGUImodule
Syntax GUI.SetText(widgetID:int,text:string)
DescriptionSetsthetextofatextfieldspecifiedbywidgetIDtotext.Theselectionissetto1,1(i.e.thecursorisatthebeginningofthetext).
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetTextbycallingSetText.
Example
ThefollowingprogramconvertsalllowercaseinputinthetextfieldtouppercasewhentheuserpressesENTER.
importGUI
vartextField,lbl:int
procedureCheckInput(s:string)
varnewString:string:=""
fori:1..length(s)
if'a'<=s(i)ands(i)<='z'then
newString+=chr(ord(s(i))32)
else
newString+=s(i)
endif
endfor
GUI.SetText(textField,newString)
GUI.SetSelection(textField,1,1)
endCheckInput
textField:=GUI.CreateTextField(100,100,200,"",
lbl:=GUI.CreateLabelFull(100+GUI.GetWidth(
100+GUI.GetHeight(textField),"ConvertstoUpperCase",
0,0,GUI.CENTER+GUI.BOTTOM,0)
loop
exitwhenGUI.ProcessEvent
endloop
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetTextbycallingSetText.
Seealso GUI.CreateTextField.
GUI.SetTopLine PartofGUImodule
Syntax GUI.SetTopLine(widgetID:int,lineNum:int)
Description
TheGUI.SetTopLineprocedurescrollsthetextinatextboxsoastoplacethelinenumberspecifiedbylineNumatthetopofthetextbox(ifpossible).Thisisoftenusedtoscrollthetextbacktothebeginningofthetextboxbyassigningavalueof1tolineNum.
Example
Thisprogramdisplays100linesoftextinatextbox,thensetsthetextboxtodisplayline50atthetopofthebox.
importGUI
vartextBox:int%TheTextFieldID.
textBox:=GUI.CreateTextBoxFull(10,10,180,275,
GUI.INDENT,0)
GUI.SetBackgroundColor(gray)
%Readthefileandplaceitinthetextbox.
fori:1..100
GUI.AddLine(textBox,intstr(i))
endfor
GUI.SetTopLine(textBox,50)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetTopLine,notbycallingSetTopLine.
GUI.SetXOR PartofGUImodule
Syntax GUI.SetXOR(widgetID:int,xor:boolean)
Description
Setsthe"xormode"ofthecanvasspecifiedbywidgetID.Ifthexorparmeterissettotrue,thecanvasissettoxormode.Wheninxormode,alltheDraw...proceduresofacanvasaretreatedasiftheView.Set("xor")statementhadbeenexecutedbeforetheDrawprocedure.
Example
SeeGUI.SetDisplayWhenCreatedforanexampleofGUI.Show.
importGUIin"%oot/lib/GUI"
View.Set("graphics:400;300")
varcanvas1,label1,canvas2,label2:int
canvas1:=GUI.CreateCanvas(10,20,maxxdiv220,
label1:=GUI.CreateLabelFull(10,2,"XOR",maxx
GUI.CENTER,0)
canvas2:=GUI.CreateCanvas(maxxdiv2+10,20,
maxxdiv220,maxy30)
label2:=GUI.CreateLabelFull(maxxdiv2+10,2,"Normal",
maxxdiv220,0,GUI.CENTER,0)
GUI.SetXOR(canvas1,true)
fori:1..20
varx:int:=Rand.Int(0,maxxdiv220)
vary:int:=Rand.Int(0,maxy20)
varc:int:=Rand.Int(1,15)
GUI.DrawFillStar(canvas1,x20,y20,x+20,
endfor
GUI.SetXOR(canvas2,false)
fori:1..20
varx:int:=Rand.Int(0,maxxdiv220)
vary:int:=Rand.Int(0,maxy20)
varc:int:=Rand.Int(1,15)
GUI.DrawFillStar(canvas2,x20,y20,x+20,
endfor
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.SetXOR,notbycallingSetXOR.
Seealso GUI.CreateCanvas.
GUI.Show PartofGUImodule
Syntax GUI.Show(widgetID:int)
Description
ShowsawidgetspecifiedbywidgetID.UsedinconjunctionwithGUI.Hidetoshowandhidewidgets.Hiddenwidgetscannotgetevents(i.e.respondtokeystrokesormouseclicks).Ifanactivetextfield(seetextfield)ishidden,thenanykeystrokesinthewindowwillbeignored.
Inmostcaseswhereawidgetistoappear,thendisappear,thenappearagain,itisadvisedtocreatethewidgetonceandhideituntilitistoappear,whereuponGUI.Showiscalled.Whentheuserisfinishedwiththewidget,thewidgetishiddenusingGUI.Hide.Thissavestheoverheadofcreatinganddisposingofthesamewidgetseveraltimes.
ExampleSeeGUI.SetDisplayWhenCreatedforanexampleofGUI.Show.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.Show,notbycallingShow.
Seealso GUI.Hide.
GUI.ShowMenuBar PartofGUImodule
Syntax GUI.ShowMenuBar
Description Showsthemenubarintheselectedwindow.
ExampleSeeGUI.SetMouseEventHandlerforanexampleofGUI.HideMenuBar.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.ShowMenuBar,notbycallingShowMenuBar.
Seealso GUI.HideMenuBar.SeealsoGUI.CreateMenu.
GUI.ShowWindow PartofGUImodule
Syntax GUI.ShowWindow(window:int)
Description
Hidesawindowwithwidgetsinit.ThisproceduremakescertainthattheGUILibraryrecognizesthatthewindownolongervisible.ThisprocedurewillcallWindow.Hide,sothereisnoneedfortheusertodoso.
Example
Theprogramopensupawindowwithtwobuttons.Ifthebuttonlabelled"CloseandOpen"ispressed,thewindowisclosedandanewwindowwithtwobuttonsisopenedinarandomlocationonthescreen.
importGUI
varwindowA,windowB:int
varbuttonA,buttonB,buttonQuit:int
varbackToMainA,backToMainB:int
procedureShowWindowA
GUI.HideWindow(defWinID)
GUI.ShowWindow(windowA)
endShowWindowA
procedureShowWindowB
GUI.HideWindow(defWinID)
GUI.ShowWindow(windowB)
endShowWindowB
procedureShowMain
GUI.HideWindow(Window.GetActive)
GUI.ShowWindow(defWinID)
endShowMain
View.Set("graphics:280;100,nobuttonbar")
%Placethebuttonsinthemainwindow
buttonA:=GUI.CreateButton(10,10,0,"ShowWindowA",
buttonB:=GUI.CreateButton(150,10,0,"ShowWindowB",
buttonQuit:=GUI.CreateButton(100,60,0,"Quit",
windowA:=Window.Open("title:WindowA,graphics:150;100,position:bottom;left")
backToMainA:=GUI.CreateButton(20,20,0,"BacktoMain",
Window.Hide(windowA)
windowB:=Window.Open("title:WindowB,graphics:150;100,position:bottom;right")
backToMainB:=GUI.CreateButton(20,20,0,"BacktoMain",
Window.Hide(windowB)
loop
exitwhenGUI.ProcessEvent
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingGUI.ShowWindowbycallingShowWindow.
SeealsoGUI.HideWindowforhidingawindowwithwidgetsinit.SeealsoGUI.CloseWindowforclosingawindowwithwidgetsinit.
handler exceptionhandler
Dirty
Syntax
AexceptionHandleris:
handler(id) statementsAndDeclarations endhandler
Description
Anexceptionhandlerisanoptionalblockofstatementsanddeclarationsinasubprogram(orprocess).Itisactivatedwhentheprogram(orprocess)fails.Thisoccurs,forexamplewhendividingbyzero.
Example
Thisprogramparsestheinputstreamusingastack.Ifthestackoverflows(itstopexceedsitsmaximum),aquitstatementinthepushprocedureabortstheparsingandgivescontroltotheexceptionhandlerintheparseprocedure.TheparseprocedurecallsparseExpnwhichcallspush.Ifpushoverflowsthestack,itexecutesaquitandcontrolispassedtotheexceptionhandlerintheparseprocedure.Theinterruptedprocedures(parseExpnandpush)areterminatedandtheirlocalvariablesaredeleted.
conststackOverflow:=500
constmaxTop:=100
vartop:0..maxTop:=0
varstack:array1..maxTopofint
procedurepush(i:int)
iftop=maxTopthen
quit:stackOverflow
endif
top:=top+1
stack(top):=i
endpush
…
procedureparse
handler(exceptionNumber)
put"Failurenumber",exceptionNumber
caseexceptionNumberof
labelstackOverflow:
put"Stackhasoverflowed!!"
…otherexceptionshandledhere…
label:%Unexpectedfailures
quit>%Passexceptionfurther
endcase
endhandler
parseExpn%Eventuallypushiscalled
endparse
SeethequitstatementforanexplanationofitsquitReason(stackOverflowinthefirstquitstatementabove)anditsguiltyParty(>inthesecondquitstatement,meaningtheexceptionisduetocausesoutsideofthishandler).
Anexceptionhandlercanappearonlyinthebodyofasubprogram(orprocess),justprecedingthedeclarationsandstatements.Theformofaprocedureis:
procedure[pervasive]id
[([paramDeclaration{,paramDeclaration}])]
[import[[var]id{,[var]id}]]
[pretrueFalseExpn]
[initid:=expn{,id:=expn}]
[posttrueFalseExpn]
[exceptionHandler]
statementsAndDeclarations
endid
Exactlythesamedeclarationsandstatementscanappearinahandlerascanappearinthesubprogrambodyfollowingthehandler.Intheabsenceofexceptions,handlershavenoobservableeffect.Aparticularhandlerisactivated(itbecomesreadytohandleanexception)whenitisencounteredduringexecution.Itremainsactiveuntilthesubprogram(orprocess)containingithascompleted,orthehandlerisgivencontrol.Activationofahandlerwhenaprevioushandlerisalreadyactivewillcauseexceptionstobepassedtothenewly-activatedhandler.Inotherwords,handlershaveadynamicscopethatbeginswhentheexceptionhandlerisencounteredandendswhenthesubprogram(orprocess)containingthehandlerhasterminatedorthehandlerisgivencontrol.
Details
Whenahandlerisgivencontrol,itbecomes,ineffect,areplacementforthedeclarationsandstatementsfollowingit.Ifthehandlerisinafunction,itmustterminatewitharesultstatementorwithaquit.Ifthehandlerisinaprocedure(orprocess),thehandlermustterminatewithareturn,aquit,orbyencounteringtheendofthehandler(whichisequivalenttoareturn).
Whenahandlerterminateswitharesultorreturnstatement(orbyreachingtheendofaprocedure'shandler),thesubprogram'spostcondition(ifany)mustbetrue.Aquitstatementdoesnotneedtoestablishthepostcondition.
Programmingwithexceptionhandlerseasilyleadstoincomprehensiblesoftware,duetothedifficultyofkeepingtrackoftheflowofcontrol.Oneofthemostinsidioussituationsiswhenanexceptionoccursinamodule,classormonitorandispropagatedoutsideoftheunit.Thiscanleavethecontaineddatainaninconsistentstate;inthecaseofamonitor,itisleftlockedforever.Toavoidthispossibility,youcanuseahandlerineachexportedsubprogram.Ifanexceptioninaprocessisnothandled,theentireprogramisaborted.Ifanimplementationallocatesdynamicarraysontheheap,anexceptionmaypreventthedeallocationofsuchanarray.
Withoutexceptionhandling,aprogramexecutesaccordingtothelanguagedefinitionorelseisaborted.Ifanexceptionhandlerisactive,insteadofaborting,controlisgiventothehandler.ThequitNumberforasystem-detectedfailureisimplementation-dependent.Thereisafile"%exceptions"whichliststhesenumbers.Theuserprogramcansimulateasystemexceptionbydoingaquitwiththecorrespondingnumber.
Iftheuserturnsoffcheckingexplicitly,thesystemmaynotdetectfailures.Insomecasesthefailuremayyieldincorrectdataorarbitrarybehavior.
Someexceptionsareunpredictableorimplementation-dependent.Forexample,inx:=24divi+24/i,ifiiszero,theexception
couldbeeitheranintegerorarealdivisionbyzero,becausetheorderorevaluationisimplementation-dependent.
hasch hascharacterfunction
Syntax hasch:boolean
DescriptionThehaschprocedureisusedtodetermineifthereisacharacterthathasbeentypedbutnotyetbeenread.
Example
Thisprogramsimulatestherollingofapairofdiceuntiltheuserpressedthekeyboard.
put"Pressanykeytostopthedicerolling"
vardie1,die2:int
varch:string(1)
loop
exitwhenhasch
randint(die1,1,6)
randint(die2,1,6)
locate(1,1)
put"Yourolled",die1+die2
endloop
getch(ch)%Discardthecharacter
Execute
Details
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotin"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Ifthereisthepossibilitythattherearealreadykeystrokesinthekeyboardbuffer,theInput.Flushcommandcanbeusedtoflushthekeyboardbuffer(removeallkeystrokesfromthebuffer)beforeenteringthelooptocheckforinput.
getchandgetchar.
SeealsoSeealsotheInput.Flushcommandforflushingthekeyboardbuffer.
SeealsopredefinedunitInput.
id (identifier)nameofaniteminaprogram
Description
Variables,constants,types,procedures,etc.inTuringprogramsaregivennamessuchasincomeTax,x,andheight.Thesenamesarecalledidentifiers(ids).
Anidentifiermuststartwithaletter(largeorsmall)oranunderscore(_)andcancontainupto50characters,eachofwhichmustbealetter,adigit(0to9)oranunderscore(_).Largeandsmalllettersareconsidereddistinct,sothatAandaaredifferentnames.ThisdiffersfromPascalwherelargeandsmalllettersinnamesareequivalent.
Everycharacterinanameissignificantindistinguishingonenamefromanother.
Byconvention,wordsthatmakeupanidentifierarecapitalized(exceptthefirstone),asinincomeTaxandjustInTime.
AniteminaTuringprogramcannotbegiventhesamenameasakeywordsuchasgetorasareservedwordsuchasindex.SeeAppendixAforalistofkeywordsandreservedwords.Aswell,therearesomeidentifiersthatareusedbytheTuringerrorrecoveryproceduresandarethusunavailableforuseasidentifiers.Specifically,theyare:endif,elseif,endloopandendfor.
#if usedforconditionalcompilation
Syntax
Aconditionalcompilation#ifhastheform:
#ifexpnthen …anysourcetext… {#elsifexpnthen …anysourcetext…} [#else …anysourcetext…] #endif
Description
An#ifconstructsupportscompiletimeselectionofsectionsofsourcetexttomakeupaprogram(orunitofaprogram),inotherwordsconditionalcompilation.Anyarbitrarysourcetext(characters)canbeselected.
Eachoftheselectingexpressions(expns)havetheformofabooleanexpression,withtheuseoftheoperatorsand,orandnot(butnot=>)andparentheses.Theshortforms&and~aresupported.Theoperandsoftheexpressionsmustbepreprocessorflags,whicharesetbyasystem-dependentmechanismnotdescribedhere.Aflagisconsideredtobetrueifitisexplicitlyset.Ifitisnotexplicitlyset,itisconsideredfalse.
Unlikeotherpartsofthelanguage,the#if,#elsif,#elseand#endifconstructsarenotfreeformat.Specifically,theymustbeplacedbythemselvesonasingleline.
Example
Apairofdeclarationsischosenifbothstatsanddebugareset,otherwisetheputstatementisselected.Theselectedpartbecomespartoftheprogramandtheotherpartsareignored.
#ifstatsanddebugthen
varcount:array1..5ofreal
varmessage:string
#else
put"Debuggingmessage"
#endif
if statement
Syntax
AnifStatementis:
iftrueFalseExpnthen statementsAndDeclarations {elsiftrueFalseExpnthen statementsAndDeclarations} [else statementsAndDeclarations] endif
Description
Anifstatementisusedtochooseamongasetofstatements(anddeclarations).Oneset(atmost)ischosenandexecutedandthenexecutioncontinuesjustbeyondendif.
Theexpressions(thetrueFalseExpressions)followingthekeywordifandeachelsifarecheckedoneaftertheotheruntiloneofthemisfoundtobetrue,inwhichcasethestatements(anddeclarations)followingthecorrespondingthenareexecuted.Ifnoneoftheseexpressionsevaluatestotrue,thestatementsfollowingelseareexecuted.Ifnoelseispresentandnoneoftheexpressionsaretrue,nostatementsareexecutedandexecutioncontinuesfollowingtheendif.
Example
Outputamessagebasedonvalueofmark.
ifmark>=50then
put"Youpass"
else
put"Youfail"
endif
OutputA,B,C,DorFdependingonmark.
ifmark>=80then
put"A"
elsifmark>=70then
Exampleput"B"
elsifmark>=60then
put"C"
elsifmark>=50then
put"D"
else
put"F"
endif
Example
Ifxisnegative,changeitssign.
ifx<0then
x:=-x
endif
Example
Ifxislessthanzeroorgreaterthanmaxx,putamessage.
ifx<0orx>maxxthen
put"Outofbounds!"
endif
Example
Ifthebooleanflagistrueandnameis“stop”,putamessageandreturn.
ifflagandname="stop"then
put"Exitingroutine"
return
endif
DetailsSeveralstatementsanddeclarationscanappearafteraparticularthen.
Seealso casestatementsforanotherwaytoselectamongstatements.
implementby clause
Syntax
AnimplementByClauseis:
implementbyimplementByItem
Description
Animplement-byclauseisusedtospecifythatamodule,monitororclassCistobeautomaticallyimplementedbytheimplementByItem.CiscalledtheinterfaceandtheimplementByItem,whichmustcontainanimplementclause,iscalledtheimplementation.Seeimplementclausefordetailsandanexample.
Theimplement-byclausecanonlybeusedinaunit.Seeunitforthedefinitionofaunit.
AnimplementByItemisoneof:
(a) id (b) idinfileName
Thesecondformisusedwhentheimplement-byclauseisforaseparateunitandtheimporteditemisinafilewhosenameisdifferentfromtheitem'sname,asin:
implementbyledgerBodyin"ledgbod.t"
ThefileNamemustbeanexplicitcharacterstring,e.g.,"ledgbod.t".Seealsounit.Parenthesesareallowedaroundtheitemsinanimplement-byclauses,asin:
implementby(ledgerBodyin"ledgbod.t")
implement clause
Syntax
AnimplementClauseis:
implementimplementItem
Description
Animplementclauseisusedtospecifythatthemodule,monitororclasscontainingtheclauseistobetheimplementationofanothermodule,monitororclass.Thisimplementationisaspecialkindofexpansion.Themodule,monitororclasscontainingtheclausegainsaccessto(inherits)allthedeclarationsinsidethetargetitem.Seeinheritclauseforrulesaboutexpansions,whicharealsorulesforimplementations.
Theimplementclausecanonlybeusedinaunit.Seeunitforthedefinitionofaunit.
Example
Hereisastackmodulewhichdefersallofitsexportedsubprograms.Thismoduleisaninterfacebutnotanimplementation.FollowingstackisthestackBodymodulethatimplementsthestackmodule,givingthebodiesforstack'ssubprograms.Anycalltostack'spushorpopprocedures,suchasstack.push("Ed"),willactuallycalltheproceduresgiveninstackBody.
modulestack%Interface
implementbystackBody
%stackBodyhasimplementation
exportpush,pop
deferredprocedurepush(s:string)
deferredprocedurepop(vars:string)
endstack
Nextcomestheexpansionwhichgivesthebodiesforthedeferredprocedurespushandpop.ThestackBodybodyalsoaddsdeclarationsforthetopandcontentsvariables.
modulestackBody%Implementation
implementstack%stackhasinterface
vartop:int:=0
varcontents:array1..100ofstring
bodyprocedurepush%(s:string)
top:=top+1
contents(top):=s
endpush
bodyprocedurepop%(vars:string)
s:=contents(top)
top:=top-1
endpop
endstackBody
Details
Module,monitororclassDcanbeinC'simplement-byclauseif,andonlyif,CisinD'simplementclause.Inotherwords,aninterfacemustapplytoexactlyoneimplementationandviceversa.Amodulecanimplementonlyamodule,amonitoronlyamonitor,andaclassonlyaclass.Classes(butnotmodulesandmonitors)cancontaininheritclauses.Aclasscannotcontainbothaninheritandanimplementclause.
AnimplementItemisoneof:
(a)id
(b)idinfileName
Thesecondformisusedwhentheimplementclauseisforaseparateunitandtheimporteditemisinafilewhosenameisdifferentfromtheitem'sname,asin:
implementledgerin"ledg.t"
ThefileNamemustbeanexplicitcharacterstring,e.g.,"ledg.t".Seealsounit.Parenthesesareallowedaroundtheitemsinimplementclauses,asin:
implement(ledgerin"ledg.t")
Thereisnorestrictiononthedeclarationsthataninterfacemaycontain.Inparticular,aninterface(anymodule,monitororclasscontaininganimplement-byclause),cancontainsubprogrambodiesandvariabledeclarations,exactlyasisthecaseinexpansions.ThisisdifferentfromlanguagessuchasC++inwhichtherearestrictruleslimitingwhatyoucanputinaninterface.
EventhoughDcontainsanimplementclause,Dcanalsocontainanimplement-byclause,whichimpliesfurtherimplementationbyfurtherautomaticexpansion.
SupposeclassDisinclassC'simplement-byclauseandthatpisapointertoclassC:
varp:^C
EventhoughCisimplementedbyD,premainsapointertoclassC.EachcreationofanobjectofclassCactuallycreatesanobjectoftypeD,forexample:
newp%CreatesobjectofclassD
ClassD,whichimplementsC,couldalsohaveanimplement-byclause,whichcausesitsimplementationtobeautomaticallycreatedandsoon.IfanotherclassEinheritsC,thisexpansiondoesnotincludeD.
IfthenewstatementcontainsanexplicitclassnameEthatisadescendantofC(butnotactuallyC),asin
newE,p
theobjectoftheexplicitclassiscreated.IfEhasanimplement-byclause,theexpansioniscreated.
Seealsounit,module,monitorandclass.Seealsoimplementbyclause,inheritclause,exportlist,andimportlist.Seealsodeferredsubprograms.
import list
Syntax
AnimportListis:
import[howImport]importItem {,[howImport]importItem}
Description
Animportlistisusedtospecifythoseitemsthataprocedure,function,module,monitor,oraclassusesfromoutsideofitself.Notethatafunctionorprocedureisnotallowedtohaveanimportlistandthusautomaticallyimportswhicheverfunctionsorproceduresareusedbythefunctionorprocedure.Thecompilerdeterminesthelistautomaticallybylookingtoseewhatitemsareactuallyused.
Example
Inthisexample,thetypeTisimportedintothestackmoduleandusedasthetypethatcanbepushedontoorpoppedoffthestack.Sincenootheritemsareimported,theonlyidentifiersfromoutsideofstackthatcanbeusedinitmustbepredefined,suchassqrt,ordeclaredtobepervasive.
typeT:string
…
modulestack
importT
exportpush,pop
vartop:int:=0
varcontents:array1..100ofT
procedurepush…endpush
procedurepop…endpop
endstack
TheimportItemisoneof:
(a)id (b)idinfileName
ThesecondformisusedinOOTwhenthelististheimportlistforaseparateunit(orthemainprogram),andtheimporteditem
Details
isinafilewhosenameisdifferentfromtheitem'sname,forexample:
importledgerin"newledg.t"
ThefileNamemustbeanexplicitcharacterstring.Seealsounit.
Parenthesesareallowedaroundtheitemsinanimportlists,asin:
import(ledgerin"newledg.t")
Therearevariouswaystoimportitems,asdeterminedbyhowImport.TheformofhowImportisoneof:
(a)var (b)const (c)forward
CommonlythehowImportisomitted,whichmeansthedefaultaccessfortheitemisthesameaccessastheitemhas.Inotherwords,aread-writeitemthatisimportedwithoutahowImportisimportedread-write.Aread-onlysymbolthatisimportedwithoutahowImportisimportedread-only.
IftheimportItemisforward,theimportlistispartofaforwardprocedureorfunctiondeclarationandtheimporteditemisitselfnecessarilyaprocedureorfunction.Seeforwarddeclarationsfordetailsandanexample.
Iftheimportlistofamodule,monitororclassisomitted,theimplementationassumesthatthelistisimport(),meaningthatnoitemsareimported.Forexample,amodulemustexplicitlyimportanyglobalidentifiersthatarenotpredefinedorpervasive.
Circular(recursive)importsarenotallowed.Forexample,ifunitAimportsBthenBcannotimportA.However,circularusageofseparatelycompiledunitsispossiblebyseparatingtheunitsintointerfacesandbodiesandhavingthebodiesimporttheinterfaces.Forexample,ifCistheparentclassofD,DcanimportC,butnotviceversa.
Inanexpansion(orimplementation),theimportlistoftheexpansionaugmentstheimportlistoftheparent.
Anoverridingsubprogram(inanexpansion)ignorestheimportlistofthetargetsubprogramandusesitsownimportlist.
Turinginitializesmodulesandmonitorsinorderofimportation.Initializationbeginswiththemainprogram,whichfirstinitializesitsimportsintheordergiveninitsimportlist,andtheninitializesitself.
Seealsounit,module,monitorandclass.Seealsoexportlist,inheritclause,implementclauseandimplementbyclause.
in memberofaset
Syntax in
Description Theinoperatordeterminesifanelementisinaset.
ExampletyperankSet:setof0..10
varrankings:rankSet:=rankSet(0)%Theset
…
if5inrankingsthen…%Is5intherankingsset?
Description
Thenotinoperatorisexactlytheoppositeofin.Forexample,7notinrankingsmeansthesameasnot(7inrankings).
Theelementisrequiredtobeintheset'sindextype.Intheaboveexamplethisissatisfiedbecauseelement5isintheindextype0..10.
Thekeywordinisalsousedinlistssuchasimportlists.Seeimportlist.
Seealso thesettype,infixoperators,andprecedenceofoperators.
include sourcefiles
Syntax
AnincludeConstructis:
includefileName
Description
AnincludeisusedtocopypartsoffilessothattheybecomepartoftheTuringprogram.Thiscopyingistemporary,thatis,nofilesarechanged.Thefilenamemustbeanexplicitstringconstantsuchas"stdstuff".
Example
OnIBMPCcompatiblecomputers,therearearrowkeysthatproducecharactervaluessuchas200and208.Letussupposethatafilecalledarrowscontainsdefinitionsofthesevalues:
constupArrow:=200
constdownArrow:=208
constrightArrow:=205
constleftArrow:=203
Thesedefinitionscanbeincludedinanyprograminthefollowingmanner:
include"arrows"
…
varch:string(1)
getch(ch)%Readonecharacter
caseord(ch)of
labelupArrow:
…handleuparrow…
labeldownArrow:
…handledownarrow…
labelrightArrow:
…handlerightarrow…
labelleftArrow:
…handleleftarrow…
label:
…handleanyotherkey…
endcase
Anincludefilecanitselfcontainincludeconstructs.Thiscancontinuetoanylevel,althoughacircularpatternofincludes
Detailswouldbeamistake,asitwouldleadtoaninfinitelylongprogram.
Itiscommontosaveprocedures,functionsandmodulesinseparatefiles.Thefilesarecollectedtogetherusinginclude.
Details
Ifthefilenameintheincludestatementstartswitha"%",thenTuringsearchesthesystemdirectoryforthefile.Seetheeditorreferencefortheenvironmenttoseehowtosetthesystemdirectory.Thismethodcanbeusedtoallowthesystemadministratortoeasilysupplyasetofroutinesinafiletoalargenumberofusersbyplacingitinoneeasy-to-findlocation.
Example
Ifthesystemdirectoryissetto"C:\TURING",thentheline
include"%sorting.t"
willincludethefile"C:\TURING\SORTING.T"intheprogram.
Details
UnderOOT,thereareseveralsystemdirectoriesavailable.The"%oot"directoryisthedirectorywherealltheOOTsystemfilesarelocated.The"%home"directoryistheuser'shomedirectory.
Example
Iftheootdirectoryissetto"/usr/local/lib/oot"thentheline
include"%oot/teacher/sorting.t"
willincludethefile"/usr/local/lib/oot/teacher/sorting.t"intheprogram.
index findpatterninstringfunction
Syntax index(s,patt:string):int
DescriptionTheindexfunctionisusedtofindthepositionofpattwithinstrings.Forexample,index("chair","air")is3.
Example
Thisprogramoutputs2,because"ill"isasubstringof"willing",startingatthesecondcharacterof"willing".
varword:string:="willing"
putindex(word,"ill")
Details
Ifthepattern(patt)doesnotappearinthestring(s),indexreturns0(zero).Forexample,hereisanifstatementthatcheckstoseeifstringscontainsablank:
ifindex(s,"")not=0then…
Theindexissometimesusedtoefficientlydetermineifacharacterisoneofagivensetofcharacters.Forexample,hereisanifstatementthatcheckstoseeifch,whichisdeclaredusingvarch:string(1),isadigit:
ifindex("0123456789",ch)not=0then…
Ifastringcontainsmorethatoneoccurrenceofthepattern,theleftmostlocationisreturned.Forexample,index("pingpong","ng")returns3.
Ifpattisthenullstring,theresultis1.
indexType
Syntax
AnindexTypeisoneof:
(a) subrangeType (b) enumeratedType
(c) namedType %Whichisasubrangeorenumeratedtype
(d) char (e) boolean
Description
Anindextypedefinesarangeofvaluesthatcanbeusedasanarraysubscript,asacaseselector,asaselector(tag)forauniontype,orasthebasetypeofasettype.
Example varz:array1..9ofreal%0..9isanindextype
typesmallSet:setof0..2%0..2isanindextype
indirection operator(@)
Dangerous
Syntax targetType@(expn)
Description
Theindirectionoperator@isusedtoaccessvaluesthatlieatabsolutemachineaddressesinthecomputer'smemory.Thisisdangerousandimplementation-dependentandcancausearbitrarycorruptionofdataandprograms.
Example
Copythebytevalueatmemorylocation246intobandthensetthatmemorybytetozero.
varb:nat1%Onebytenaturalnumber
b:=nat1@(246)
nat1@(246):=0
Details
TheformoftargetTypemustbeoneof:
(a)[id.]typeId
(b)int,int1,int2orint4
(c)nat,nat1,nat2ornat4
(d)boolean
(e)char[(numberOfCharacters)]
(f)string[(maximumLength)]
(g)addressint
Inform(a)thebeginningidentifieridmustbethenameofamodule,monitororclassthatexportsthetypeId.EachofnumberOfCharactersandmaximumLengthmustbecompiletimeintegerexpressions.Thesearethesametargettypesasintypecheats.
Theindirectionoperator@takesanintegerasanaddress.Thisvaluemustfitintherangeofaddressint.Seeaddressint.Seealsopointertypesandthe^operator(whichaccessesobjectslocatedbypointers).
Seealsocheat.SeealsoexplicitIntegerConstant(whichexplainshowtowritehexadecimalconstants,whichareoftenusedforaddresses).
infix operator
Syntax
AninfixOperatorisoneof:
(a) + %Integerandrealaddition;setunion;
%stringcatenation
(b) - %Integerandrealsubtraction;setdifference
(c) * %Integerandrealmultiplication;setintersection
(d) / %Realdivision
(e) div %Truncatingintegerdivision
(f) mod %Modulo (g) rem %Remainder
(h) ** %Integerandrealexponentiation
(i) < %Lessthan (j) > %Greaterthan (k) = %Equal
(l) <= %Lessthanorequal;subset
(m) >= %Greaterthanorequal;superset
(n) not= %Notequal
(o) and %And(booleanconjunction)
(p) or %Or(booleandisjunction)
(q) => %Booleanimplication (r) in %Memberofset (s) notin %Notmemberofset (t) shr %Shiftright (u) shl %Shiftleft (v) xor %ExclusiveOR
Aninfixoperatorisplacedbetweentwovaluesoroperandstoproduceathirdvalue.Forexample,theresultof5+7is12.Insomecasesthemeaningoftheoperatorisdeterminedbyitsoperands.Forexample,in"pine"+"apple",the+operatormeansstringcatenationwhilein5+7itmeansintegeraddition.Therearealsoprefixoperators(-,+andnot),whichareplacedinfrontofasinglevalue.Seeprefixoperator.
Inexpressionswithseveraloperators,suchas3+4*5,theprecedencerulesdeterminetheorderinwhichtheoperationisdone(seeprecedenceforalistingoftheserules).Inthisexample,themultiplicationisdonebeforetheaddition,sotheexpressionisequivalentto3+(4*5).
Thenumerical(integerorreal)operatorsare+,-,*,/,div,mod,and**.Alloftheseexceptdivproducearealresultwhenatleastoneoftheiroperandsisreal.Ifbothoperandsareintegers,theresultisanintegerexceptinthecaseofrealdivision(/)whichalwaysproducesarealresultregardlessoftheoperands.
Thedivoperatorislikerealdivision(/),exceptthatitalwaysproducesanintegerresult,truncatinganyfractiontoproducethenearestintegerinthedirectionofzero.
Themodoperatoristhemoduloandtheremoperatoristheremainder.Thesignoftheresultofmodoperatoristhesameasthesignofthesecondoperand.TheremoperatoroperateslikethemodoperatorinTuring(andinmostotherlanguages).It
Descriptionproducestheremainder,whichisthedifferencebetweenrealdivision(/)andintegerdivision(div).Whenbothoperandsarepositive,thisisthemodulo.Forexample,14mod10is4.Ifoneoftheoperandsisnegative,anegativeanswermayresult,forexample,7mod2is1.Seealsotheintandrealtypes.
Thecomparisonoperators(<,>,=,<=,>=,not=)canbeappliedtonumbersaswellastoenumeratedtypes.Theycanalsobeappliedtostringstodeterminetheorderingbetweenstrings(seestringtypefordetails).Arrays,records,unionsandcollectionscannotbecompared.Booleanvalues(trueandfalse)canbecomparedonlyforequality(=andnot=);thesameappliestopointervalues.Setvaluescanbecomparedusing<=and>=,whicharethesubsetandsupersetoperators.Thenot=operatorcanbewrittenas~=.
Stringsaremanipulatedusingcatenation(+)aswellassubstringexpressions(seesubstring)andtheindexfunction(seeindex).Seealsothestringtype.
Theoperatorstocombinetrue/falsevaluesareand,or,and=>(implication),aswellasequality(=andnot=).Seealsothebooleantype.
Thesetoperatorsareunion(+),intersection(*),setdifference(-),subset(<=),superset(>=),andmembership(inandnotin).Seealsothesettype.
Theshr(shiftright),shl(shiftleft)andxor(exclusiveOR)operatorsacceptandproducenaturalnumbers.Seeshr,shl,andxor.
inherit inheritanceclause
Syntax
AninheritClauseis:
inheritinheritItem
Description
Aninheritclausespecifiesthattheclasscontainingtheclauseistobeanexpansionofanotherclass.Thisexpansioniscalledinheritance.Theclasscontainingtheclausegainsaccessto(inherits)allthedeclarationsinsidethetargetitem.Expansionsareusedtoaddnewdeclarationsandexportsandtosupportpolymorphism(overridingsubprograms).
Example
Hereisanexampleofastackclass.Followingit,weshowanotherclass,calledstackWithDepth,thatinheritsstackbyaddingafunctioncalleddepth.
classstack
exportpush,pop
vartop:int:=0
varcontents:array1..100ofstring
procedurepush(s:string)
top:=top+1
contents(top):=s
endpush
procedurepop(vars:string)
s:=contents(top)
top:=top-1
endpop
endstack
Nextcomesanexpansion,whichinheritstheinternaldeclarationsofthestackclassandaddsthedepthfunction.
classstackWithDepth
inheritstack
exportdepth
functiondepth:int
resulttop
endpush
endstackWithDepth
Details
ObjectsoftheinheritedclassstackWithDeptharelikeobjectsoftheparentclassstack,exceptthereisanadditionalexportedfunctionnameddepth
AninheritItemisoneof:
(a)id (b)idinfileName
Thesecondformisusedwhentheinheritclauseisforaseparateunittheimporteditemisinafilewhosenameisdifferentfromtheitem'sname,forexample:
inheritledgerin"newledg.t"
ThefileNamemustbeanexplicitcharacterstring,e.g.,"newledg.t".Parenthesesareallowedaroundtheiteminaninheritclause,asin:
inherit(ledgerin"newledg.t")
Thereisaspecialformofinheritclause,calledanimplementclauseisusedtoseparateaninterfacefromanimplementation.Modulesandmonitors,aswellasclasses,usetheseclauses.Seeimplementclauseandimplementbyclause.
IfclassDinheritsclassC,wesaythatCistheparentandDisthechildClassBissaidtobeanancestorofclassD(andDisthedescendantifBandDarethesameclass,orifBistheparentofD,orifBistheparentoftheparentofD,etc.Wewritethisasfollows:
B<=D%BisanancestorofD
IfBisanancestorofDbutnotthesameasD,wesayBisastrictancestorofD.Wewritethisas:
B<D%BisastrictancestorofD
WealsousethenotationsD>=B,D>BandD=Bwiththeobviousmeanings.Allofthesenotationscanbeusedinaprogram.Theirmainuseisinconjunctionwithobjectclass,whichdeterminestheclassofanobjectlocatedbyapointer.Forexample,ifpisdeclaredtobeapointertoawecanwritethefollowingtoseeifpcurrentlylocatesanobjectwiththe
depthoperation:
%Doestheobjectlocatedbyphavethedepthoperation
ifstackWithDepth<=objectclass(p)then
ApointerthatlocatesanobjectcreatedasclassEcanbeassignedtoapointertoclassB,onlyifBisanancestorofE.Forexample,apointertoanobjectthatisastackWithDepthcanbeassignedtoapointertostacknotviceversa.Thepointernilcanbeassignedtoanypointervariable,butthevaluenil(C)canonlybeassignedtoapointertoanancestorofC.
Anobject(locatedbyapointer)canbeassignedtoanotherobjectonlyiftheywerecreatedasobjectsofthesameclass.However,assignmentofobjectsthataremonitorsorthatcontaindynamicarraysorcollectionsisnotallowed.
Circular(recursive)inheritsarenotallowed.Forexample,ifunitBAthenAcannotinheritB.Onlyoneitemisallowedinaninheritclause;inotherwords,Turingsupportssingleinheritancebutnotmultipleinheritance.
Seeimplementclauseforaspecialkindofexpansionthatseparatesamodule,monitororclass'interfacefromitsimplementation.Seeclassanexampleofpolymorphism,inwhichaninheritingclassoverridessubprogramsofitsparentclass.
Theinitializationofamodule,amonitororanobjectisimmediatelyprecededbytheinitializationoftheitemthatitinheritsorimplements(ifany).Correspondingly,iftheitemhasanimplementbyclause,theimplementationisinitializedimmediatelyaftertheinitializationofthecurrentitem.
WithinaclassC,withancestorB,youcanforceacalltoexportedsubprogrampusingtheformC.p(orB.p).ThiscallsthesubprogramdeclaredinC(orinBinthecaseofB.p),regardlessoftheactualclassoftheobjectandanyoverridingofp.ThisissimilartothenotationCtheC++language.ThisnotationcanonlybeusedinsideclassC.
Seealso
unit,module,monitorandclass.Seealsoexportlist,importlist,implementclause,implementbyclauseanddeferredsubprogram.See
alsoobjectclass.
init arrayinitialization
Syntax init
Description
Theinit(initialization)keywordisusedfortwodifferentpurposesinTuring.Themostcommonisforinitializingarrays,recordsandunions.Thelesscommonisforrecordingparametervaluesinsubprogramsforlateruseinpostconditions.
Example
varmensNames:array1..3ofstring:=
init("Tom","Dick","Harry")
putmensNames(2)%ThisoutputsDick
varnames:array1..2,1..3ofstring:=
init("Tom","Dick","Harry",
"Alice","Barbara","Cathy")
putnames(2,1)%ThisoutputsAlice
Details
Theorderofinitializingvaluesformulti-dimensionalarraysisbasedonvaryingtherightsubscripts(indexes)mostrapidly.Thisiscalledrowmajororder.Initializationofrecordsandunionsisanalogoustoinitializingarrays.Valuesarelistedintheorderinwhichtheyappearinthetype.Seearray,record,anduniontypes.
Example
Thisprocedureissupposedtosetintegervariableitoanintegerapproximationofitssquareroot.Theinitclauserecordstheinitialvalueofiasjsoitcanbeusedinthepostconditiontomakesurethattheapproximationissufficientlyaccurate.Thenamejcanbeusedonlyinthepostconditionandnowhereelseintheprocedure.
procedureintSqrt(vari:int)
prei>=0
initj:=i
postabs(i-sqrt(j))<=1
…statementstoapproximatesquareroot…
endintSqrt
Seealso preandpostassertionsandprocedureandprocessdeclarations.
Input
Description
Thisunitcontainsthepredefinedproceduresthatdealwithhandlinginputonacharacter-by-characterbasis.
AllroutinesintheInputmoduleareexportedunqualified.(Thismeansyoucancalltheentrypointsdirectly.)
EntryPoints
getch Getsthenextcharacterinthekeyboardbuffer(procedurewithastring(1)argument).
hasch Returnstrueiftherearecharacterswaitinginthekeyboardbuffer.
getchar Getsthenextcharacterinthekeyboardbuffer(functionreturningachar).
Pause Waitsforakeytobepressed.KeyDown Detectwhichkeysarecurrentlypressed.Flush Emptythekeyboardbuffer.
Input.getch PartofInputmodule
Syntax getch(varch:string(1))
Description
Thegetchprocedureisusedtoinputasinglecharacterwithoutwaitingfortheendofaline.Theparameterchissettothenextcharacterinthekeyboardbuffer(theoldestnot-yet-readcharacter).
Example
ThisprogramcontainsaprocedurecalledgetKeywhichcausestheprogramtowaituntilakeyispressed.
View.Set("graphics")
proceduregetKey
varch:string(1)
getch(ch)
endgetKey
fori:1..1000
puti:4,"Pausetillakeyispressed"
getKey
endfor
Details
Thescreenshouldbeina"screen"or"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
Somekeys,suchastheleftarrowkey,insertkey,deletekey,andfunctionkeysdonotproduceordinarycharactervalues.Thesekeystrokesarereturnedbygetchasspecialvalues.SeeAppendixDforthesevalues.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallinggetchorbycallingInput.getch.
Seealsohasch(hascharacter)procedurewhichisusedtoseeifacharacterhasbeentypedbutnotyetread.
Input.getchar PartofInputmodule
Syntax getchar:char
Description
Thegetcharfunctionisusedtoinputasinglecharacterwithoutwaitingfortheendofaline.Thenextcharacterinthekeyboardbuffer(theoldestnot-yet-readcharacter)isreturned.
Example
ThisprogramcontainsaprocedurecalledgetKeywhichcausestheprogramtowaituntilakeyispressed.
View.Set("graphics")
proceduregetKey
varch:char
ch:=getchar
endgetKey
fori:1..1000
puti:4,"Pausetillakeyispressed"
getKey
endfor
Details
Thescreenshouldbeina"screen"or"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
Somekeys,suchastheleftarrowkey,insertkey,deletekey,andfunctionkeysdonotproduceordinarycharactervalues.Thesekeystrokesarereturnedbygetchasspecialvalues.SeeAppendixDforthesevalues.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallinggetcharorbycallingInput.getchar.
Seealsohasch(hascharacter)procedurewhichisusedtoseeifacharacterhasbeentypedbutnotyetread.
Input.hasch PartofInputmodule
Syntax hasch:boolean
DescriptionThehaschprocedureisusedtodetermineifthereisacharacterthathasbeentypedbutnotyetbeenread.
Example
Theflushproceduregetsridofanycharactersthathavebeentypedbutnotyetread.
procedureflush
varch:string(1)
loop
exitwhennothasch
getch(ch)%Discardthischaracter
endloop
endflush
Details
Thescreenshouldbeina"screen"or"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallinghaschorbycallingInput.hasch.
Seealso getchandgetchar.
Input.Flush PartofInputmodule
Syntax Input.Flush
Description
TheInput.Flushprocedureemptiesthekeyboardbuffer.Itisoftenusedtoavoidaccidentallyreadingmultiplekeystrokesbecausetheuserpressedakeyfortoolong,causingautorepeat.
Example
Thisprogramechoesinputfromthekeyboardatarateof10characterspersecond.Ifyouholddownakey,theechoingwillstopassoonasyoustoppressingthekey.WithouttheInput.Flush,theprogramcontinuestoechomanymorekeystrokesthathaveaccumulatedinthekeyboardbuffer.
loop
ifhaschthen
putgetchar..
Input.Flush
delay(100)
endif
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingInput.Flush,notbycallingFlush.
Input.KeyDown PartofInputmodule
Syntax Input.KeyDown(varchars:arraycharofboolean)
Description
TheInput.Keydownprocedureallowsaprogramtoreadwhichkeysarecurrentlybeingpressed.Thisprocedureisdifferentfromgetchinthatitallowsaprogramtodetectwhenauserpressesandreleasesabutton.Assuch,itisnottobeusedinconjunctionwithgetch.
Theprocedurecanbeusedingameswhereanactiontakesplacewhileakeyisdepressed.
Example
DetermineiftheTkeyispressed.Notethatwecheckforthelowercaseletter.
varchars:arraycharofboolean
Input.KeyDown(chars)
ifchars('t')then
put"TheTkeyispressed"
endif
Details
Thearrayreturnedisalistofallthecharacters.Akeyiscurrentlypressedifthearrayelementwiththecorrespondingcharacteristrue.Forexample,theakeyispressedischars('a')istrue.Notethateachkeyisindividuallyrepresented,soiftheuserhaspressedShift+atogeta'A',thenInput.KeyDownwouldregisterShiftand'a'aspressed,butnot'A'.
AfulllistofallthepossiblecharactersthatcanbesetwithInput.KeyDowncanbefoundintheKeyCodesappendix.
Details
Thearrayreturnedisalistofallthecharacters.Akeyiscurrentlypressedifthearrayelementwiththecorrespondingcharacteristrue.Forexample,theakeyispressedischars('a')istrue.Notethateachkeyisindividuallyrepresented,soiftheuserhaspressedShift+atogeta'A',thenInput.KeyDownwouldregisterShiftand'a'aspressed,butnot'A'.
Details
Thenumberofkeysthatcanbepressedsimultaneouslyishardwaredependent.Mostkeyboardscandetectaminimumoftwokeys+Shift+Control+Alt.Thismeansthatifyouaredesigningatwoplayergametobeplayedatasinglekeyboardandyouwishtomakecertainthatplayerscannot“hogthekeyboard”byholdingdownkeys,youshouldnotusemorethan6differentkeysandthreeofthemshouldbetheShift,ControlandAltkeys.
Example
Theprogramreadsthekeyboardanddisplaysamessagewhilethearrowkeysarepressed.Itcandetectuptoallfourarrowkeyspressedatonce.
varchars:arraycharofboolean
loop
Input.KeyDown(chars)
locate(1,1)
ifchars(KEY_UP_ARROW)then
put"UpArrowPressed"..
else
put""..
endif
ifchars(KEY_RIGHT_ARROW)then
put"RightArrowPressed"..
else
put""..
endif
ifchars(KEY_LEFT_ARROW)then
put"LeftArrowPressed"..
else
put""..
endif
ifchars(KEY_DOWN_ARROW)then
put"DownArrowPressed"..
else
put""..
endif
endloop
Execute
Example
Anotherexampleisavailablethatchecksforallpossiblekeys.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingInput.KeyDown,notbycallingKeyDown.
Input.Pause PartofInputmodule
Syntax Input.Pause
Description
TheInput.Pauseproceduresimplywaitsforakeytobepressedandthenreturns.Itechoesthekeypressedifechomodeisset.(SeeView.Setforsettingechomode)
Thissubprogramhelpsavoidhavingtodeclareavariabledeclarationandthenmakeacalltogetchorgetchar.
Example
Thisprogrampausesaftereverynamereadfromthefile.
varf:int
varline:string
open:f,"data.txt",get
loop
exitwheneof(f)
get:f,line:*
putname
Input.Pause
endloop
close:f
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingInput.Pause,notbycallingPause.
int integertype
Syntax int
Description
Theint(integer)typehasthevalues…2,1,0,1,2…Integerscanbecombinedbyvariousoperatorssuchasaddition(+)andmultiplication(*).Integerscanalsobecombinedwithrealnumbers,inwhichcasetheresultisgenerallyarealnumber.Anintegercanalwaysbeassignedtoarealvariable,withimplicitconversionto
Examplevarcounter,i:int
varj:int:=9
vartax:=0%Thetypeisimplicitlyint
Details
SeealsoexplicitIntegerConstant.Therealtypeisusedinsteadofinthavefractionalpartsasin16.837.Seetherealtypefordetails.
Theoperatorsonintegersare+,-,*(multiply),div(truncatingintegerdivision),(integerremainder),**(exponentiation),aswellascomparisons(+,<=).Theoperatorsand,orandxorcanbeappliedtonon-negativeintegervalues.Thebit-wisebooleanresultisproducedasaninteger(actually,asanaturalnumber).Theshr(shiftright)andshl(shiftleft)operatorsarealsointroduced.
Realnumberscanbeconvertedtointegersusingceil(ceiling),floordescriptionsofthesefunctions).Integerscanbeconvertedtorealnumbersusingintreal,butinpracticethisisrarelyused,becauseanintegervalueusedinplaceofarealvaluewillbeautomaticallyconvertedtoreal.
IntegerscanbeconvertedtostringsandbackusingintstrandstrintconvertedtocorrespondingASCII(orEBCDIC)charactersusingchrthedescriptionsofthesefunctions.
Pseudo-randomsequencesofintegerscanbegeneratedusingrandint
IncurrentimplementationsofTuring,therangeofintegersisfrom-2147483647to2147483647.Inotherwords,themaximumsizeofintegeris2**31-1.SeeThisrangeexistsbecauseintegersarestoredin4bytes.Theremainingnegativevalue,-2147483648recordsuninitialization.Thetypesint1,int2andintegersthatfitinto1,2or4bytes.Theintntypes(int1,int2andint4
checkedforinitializationandallowalltheirbitpatternsasnumbers.
Thenaturalnumbertypenatallowsonlythenon-negativevalues:0,1,2,3,…Naturalnumbervaluescanbeusedwheneverintegervaluesareexpectedandviceversa,giventhatthevaluedoesnotexceedtherangeoftheexpectedtype.
Seealso natandintn.
intn n-byteintegertype
Dirty
Syntax (a) int1 %1-byteinteger (b) int2 %2-byteinteger (c) int4 %4-byteinteger
Description
Theintn(n-byteinteger)typesaremachine-dependenttypesthatoccupyaspecifiednumberofbytes.Bycontrast,theinttypeisinprincipleamachine-independentandmathematicaltype(itoverflows,however,whenthevalueistoolargeorsmall,thatis,whenthevaluedoesnotfitinto4bytes).
Examplevarcounter1:int1%Rangeis-128..127
varcounter2:int2%Rangeis-32768..32767
varcounter4:int4%Rangeis-2147483648..2147483647
Details
IncurrentimplementationsofTuring,therangeoftheintis-2147483647to2147483647,whichmeansthattheint4typeallowsonemorevalue,-2147483648.Thisextravalueisusedininttorepresentthestateofbeinginitialized.Theintntypesallowuseofallpossiblevaluesthatfitintonbytesandtherebycannotcheckforinitialization.
TheintntypesareliketheClanguagetypesshortint,int,andlongint,exceptthatthenumberofbytesoccupiedbytheCtypesdependsontheparticularCcompiler.
Seealsothenatntypeswhicharenbytenatural(non-negative)values.Seealsointandnat.
intreal integer-to-realfunction
Syntax intreal(i:int):real
Description
Theintrealfunctionisusedtoconvertanintegertoarealnumber.Thisfunctionisrarelyused,becauseinTuring,anintegervaluecanbeusedwhereeverarealvalueisrequired.Whentheintegervalueisusedwherearealvalueisrequired,theintrealfunctionisimplicitlycalledtodotheconversionfrominttoreal.
Seealso floor,ceilandroundfunctions.
intstr integer-to-stringfunction
Syntax intstr(i:int[,width:int[,base:int]]):string
Description
Theintstrfunctionisusedtoconvertanintegertoastring.Thestringisequivalenttoi,paddedontheleftwithblanksasnecessarytoalengthofwidth,writteninthegivennumberbase.Forexample,intstr(14,4,10)="bb14"wherebrepresentsablank.Thewidthandbaseparametersarebothoptional.Iftheyareomitted,thestringismadejustlongenoughtoholdthevalue,andthenumberbaseis10.Forexample,intstr(14,4)="bb14"andintstr(23)="23".
Thewidthparametermustbenon-negative.Ifwidthisnotlargeenoughtorepresentthevalueofi,thelengthisautomaticallyincreasedasneeded.
Thestringreturnedbyintstrisoftheform:
{blank}[-]digit{digits}
where{blank}meanszeroormoreblanks,[-]meansanoptionalminussign,anddigit{digit}meansoneormoredigits.Theleftmostdigitiseithernon-zeroorelseasinglezerodigit.Inotherwords,leadingzerosaresuppressed.
ThelettersA,B,C…areusedtorepresentthedigitvalues10,11,12,…Thebasemustbeintherange2to36(36becausetherearetendigitsand26letters).Forexample,intstr(255,0,16)="FF".
Theintstrfunctionistheinverseofstrint,soforanyintegeri,
strint(intstr(i))=i.
Seealso
chr,ordandstrintfunctions.Seealsothenatstrandstrnatfunctions.SeealsoexplicitIntegerConstantsforthewaytowritenonbase10valuesinaprogram.
invariant assertion
Syntax
AninvariantAssertionis:
invarianttrueFalseExpn
Description
Aninvariantassertionisaspecialformofanassertstatementthatisusedonlyinloopandforstatementsandinmodules,monitors,andclasses.Itisusedtomakesurethataspecificrequirementismet.ThisrequirementisgivenbythetrueFalseExpn.ThetrueFalseExpnisevaluated.Ifitistrue,alliswellandexecutioncontinues.Ifitisfalse,executionisterminatedwithanappropriatemessage.Seeassert,loopandforstatementsandthemoduledeclarationsformoredetails.
Example
Thisprogramusesaninvariantinaforloop.TheinvariantusesthefunctionnameInListtospecifythatakeyhasnotyetbeenfoundinanarrayofnames.
varname:array1..100ofstring
varkey:string
…inputnameandkey…
functionnameInList(n:int):boolean
fori:1..n
ifkey=name(i)then
resulttrue
endif
endfor
resultfalse
endnameInList
forj:1..100
invariantnotnameInList(j-1)
ifkey=name(j)then
put"Foundnameat",j
exit
endif
endloop
Joystick
Description
ThisunitcontainsthepredefinedsubprogramthatdealwithreadingthejoystickinaTuringprogram.Theroutinesallowyoutogetthecurrentjoystickpositionandwhethereitheroneofthetwobuttonsarepressed.
AllroutinesintheJoystickmoduleareexportedqualified(andthusmustbeprefacedwith"Joystick.").AlltheconstantsareexportedunqualifiedandthusdonotneedtheJoystickprefix.
EntryPoints
joystick1,joystick2 joysticknamecontants(exportedunqualified)
GetInfo Readsthecurrentvalueofajoystickandstatusofthejoystickbuttons.
Joystick.GetInfo PartofJoystickmodule
SyntaxJoystick.GetInfo(joystick:int,varxPos,yPos:int,btn1Pressed,btn2Pressed:boolean)
Description
Readsthepositionandbuttonstatusofthejoystickspecifiedbytheparameter.ThexandyparameterarereturnedinthexPosandyPosIfbutton1orbutton2onthejoystickarecurrentlypressed,btn1Pressedbtn2Pressedwillbesettotrue.Thejoystickparametercanbeeitherorjoystick2.
ThexandypositionsvaryfromjoyMintojoyMax.Tousethemwithrespecttoascreen,thecoordinatesreturnedfromJoystick.GetInfomustbetranslatedintoscreencoordinates.Thefollowingformulacanbeused:
screenX=round(maxx*(xPosjoyMin)/(joyMax
screenY=round(maxy*(yPosjoyMin)/(joyMax
Details
TheJoystickmodulecontainsundocumentedsubprogramsforthosewhoneedtoaccessmorethantwobuttonsoraxesonajoystick.ContactHoltSoftwareifyouneedmoreinformation.
Example
Thefollowingprogramoutputsthecurrentlocationofjoystick#1anddrawsacursoronthescreentopointoutwhereitisshowing.
varjx,jy,x,y,ox,oy:int:=1
varb1,b2,oB1,oB2:boolean:=false
loop
Joystick.GetInfo(joystick1,jx,jy,b1,b2)
%Convertjoystickcoordinatesintoscreencoordinates.
x=round(maxx*(jxjoyMin)/(joyMaxjoyMin
y=round(maxy*(jyjoyMin)/(joyMaxjoyMin
ifxnot=oxorynot=oyorb1not=oB1or
Text.Locate(1,1)
put"x=",x,"y=",y,"b1=",b1
View.Set("xor")
Draw.Line(ox10,oy,ox+10,oy,brightred
Draw.Line(ox,oy10,ox,oy+10,brightred
Draw.Line(x10,y,x+10,y,brightred
Draw.Line(x,y10,x,y+10,brightred
ox:=x
oy:=y
oB1:=b1
oB2:=b2
endif
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingJoystick.GetInfobycallingGetInfo.
Keyboard
Description
ThisunitcontainsalltheconstantsrepresentingboththecharactersandtheirordinalvaluesforallpossiblekeystrokesthatcanbereadbyTuring.
Constantsbeginningwith“KEY_”arecharvalues.ThesearethevaluesreturnedbygetchandusedasanindexintotheInput.KeyDownarray.TheconstantsthattheconstantsKEY_KEYPAD_5,KEY_SHIFT,KEY_CTRLandKEY_ALTcanonlybeusedinconjunctionwithInput.KeyDown.Thegetchandgetcharsubprogramsdonotreturnthesevalues.AllotherconstantswithwithSHIFT,CTRLandALTaspartofthenamecannotbecheckedforintheInput.KeyDownarray.
Constantsbeginningwith“ORD_”areintvaluesandrepresenttheordinalvalues(valuesreturnedbytheordfunction)forallthepossiblekeystrokes.
Hereisalistofmostoftheconstants
KEY_F1..KEY_F12
KEY_CTRL_A..KEY_CTRL_Z
KEY_SHIFT_F1.. KEY_ALT_A..KEY_ALT_Z
KEY_HOME
KEY_SHIFT_F12KEY_CTRL_F1..KEY_CTRL_F12
KEY_ALT_1..KEY_ALT_0
KEY_ALT_F1..KEY_ALT_F12
KEY_UP_ARROW KEY_CTRL_UP_ARROWKEY_PGUP KEY_CTRL_PGUPKEY_LEFT_ARROW KEY_CTRL_LEFT_ARROWKEY_RIGHT_ARROW KEY_CTRL_RIGHT_ARROWKEY_END KEY_CTRL_ENDKEY_DOWN_ARROW KEY_CTRL_DOWN_ARROWKEY_PGDN KEY_CTRL_PGDNKEY_INSERT KEY_CTRL_INSERTKEY_DELETE KEY_CTRL_DELETEKEY_BACKSPACE KEY_KEYPAD_5*KEY_TAB KEY_SHIFT*KEY_ENTER KEY_CTRL*KEY_ESC KEY_ALT*KEY_CTRL_OPEN_BRACKET KEY_CTRL_BACKSLASHKEY_CTRL_CLOSE_BRACKET KEY_CTRL_CARETKEY_CTRL_UNDERSCORE KEY_CTRL_BACKSPACEKEY_ALT_MINUS KEY_ALT_EQUALSKEY_BACK_TAB KEY_SHIFT_TAB
Aboveconstantswith“ORD_”insteadof“KEY_”
ORD_A..ORD_Z ORD_0..ORD_9ORD_LOWER_A..ORD_LOWER_Z ORD_SPACE ORD_EXCALAMATION_MARKORD_QUOTATION_MARK ORD_HAS_MARKORD_DOLLAR_SIGN ORD_PERCENT_SIGN
ORD_AMPERSAND ORD_SINGLE_QUOTEORD_OPEN_PARENTHESIS ORD_CLOSE_PARENTHESISORD_ASTERISK ORD_PLUSORD_COMMA ORD_MINUSORD_PERIOD ORD_DOTORD_SLASH ORD_COLONORD_SEMICOLON ORD_LESS_THANORD_EQUALS ORD_GREATER_THANORD_QUESTION_MARK ORD_AT_SIGNORD_OPEN_BRACKET ORD_BACKSLASHORD_CLOSE_BRACKET ORD_CARETORD_UNDERSCORE ORD_APOSTROPHEORD_OPEN_BRACE ORD_BARORD_CLOSE_BRACE ORD_TILDE
Charactersmarkedwithanasterisk(*)arekeysthatcanonlybedetectedusingInput.KeyDown.
AllconstantsintheKeyboardmoduleareexportedunqualified.(Thismeansyoucanusetheconstantsdirectlywithouthavingtousethequalifier"Keyboard.".)
Seealsogetch,getchar,andInput.KeyDown.
length ofastringfunction
Syntax length(s:string):int
DescriptionThelengthfunctionreturnsthenumberofcharactersinthestring.Thestringmustbeinitialized.Forexample,length("table")is5.
Example
Thisprograminputsthreewordsandoutputstheirlengths.
varword:string
fori:1..3
getword
putlength(word)
endfor
Ifthewordsare"cat","robin"and"crow",theprogramwilloutput3,5and4.
Details
Thelengthfunctiongivesthecurrentlengthofthestring.Tofindthemaximumlengthofastring,useupper.Forexample,giventhedeclarationvars:string(10),upper(s)returns10.
Seealso upper.
Limits
Description
Thisunitcontainsconstantsandfunctionsusedindeterminingthemathematicalaccuracyofthelanguage.
AllroutinesintheLimitsmoduleareexportedqualified(andthusmustbeprefacedwith"Limits.")exceptmaxint,maxnat,minintandminnat,whichareexportedunqualified(thismeansyoucancallthoseentrypointsdirectly).
EntryPoints
DefaultFW Defaultfractionwidthusedinprintingusingthe"put"statement.
DefaultEW Defaultexponentwidthusedinprintingusingthe"put"statement.
minint TheminimumintegerinTuring(exportedunqualified).
maxint ThemaximumintegerinTuring(exportedunqualified).
minnat TheminimumnaturalnumberinTuring(exportedunqualified).
maxnat ThemaximumnaturalnumberinTuring(exportedunqualified).
RealnumbersarerepresentedinTuringas:f*(radix**e)or0wherefornon-zerof:(1/radix)<=abs(f)andabs(f)<1.0minexp<=eande<=maxexp.
Radix The"radix"(usually2).NumDigits Thenumberofradixdigitsinf.MinExp "minexp"(thesmallestexponentallowed).MaxExp "maxexp"(thelargestexponentallowed).GetExp Functionthatreturnsthevalueof"e".SetExp Procedurethatsetsthevalueof"e".
Rreb Therelativeround-offerrorbound.
ln naturallogarithmfunction
Syntax ln(r:real):real
DescriptionThelnfunctionisusedtofindthenaturallogarithm(basee)ofanumber.Forexample,ln(1)is0.
Example
Thisprogramprintsoutthelogarithmsof1,2,3,…upto100.
fori:1..100
put"Logarithmof",i,"is",ln(i)
endfor
DetailsSeealsotheexp(exponential)function.Youcannottakethelogarithmofzerooranegativenumber.
Note logn(i)=ln(i)/ln(n)
Seealsoexp(theexponentiationfunction).
SeealsopredefinedunitMath.
locate procedure
Syntax locate(row,column:int)
Description
Thelocateprocedureisusedtomovethecursorsothatthenextoutputfromputwillbeatthegivenrowandcolumn.Row1isthetopofthescreenandcolumn1istheleftsideofthescreen.
Example
Thisprogramoutputsstarsofrandomcolorstorandomlocationsonthescreen.Thevariablecolrispurposelyspelleddifferentlyfromthewordcolortoavoidtheprocedureofthatname(usedtosetthecolorofoutput).Therownumberispurposelychosensothatitisonelessthanmaxrow.Thisavoidsthescrollingofthescreenwhichoccurswhenacharacterisplacedinthelastcolumnofthelastrow.
setscreen("screen")
varrow,column,colr:int
loop
randint(row,1,maxrow-1)
randint(column,1,maxcol)
randint(colr,0,maxcolor)
color(colr)
locate(row,column)
put"*"..%Usedot-dottoavoidclearingendofline
endloop
Details
Thelocateprocedureisusedtolocatethenextoutputbasedonrowandcolumnpositions.Seealsothelocatexyprocedurewhichisusedtolocatetheoutputbasedxandypositions,wherex=0,y=0istheleftbottomofthescreen.
Thescreenshouldbeina"screen"or"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
Seealsosetscreenanddrawdot.
SeealsopredefinedunitText.
locatexy graphicsprocedure
Syntax locatexy(x,y:int)
Description
Thelocatexyprocedureisusedtomovethecursorsothatthenextoutputfromputwillbeatapproximately(x,y).Theexactlocationmaybesomewhattotheleftofxandbelowytoforcealignmenttoacharacterboundary.
Example
Thisprogramoutputs"Hello"startingatapproximately(100,50)onthescreen.
setscreen("graphics")
locatexy(100,50)
put"Hello"
Details
Thelocatexyprocedureisusedtolocatethenextoutputbasedonxandypositions,wherethepositionx=0,y=0istheleftbottomofthescreen.Seealsothelocateprocedurewhichisusedtolocatetheoutput-basedrowandcolumnpositions,whererow1isthetoprowandcolumn1istheleftcolumn.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealsosetscreenanddrawdot.
SeealsopredefinedunitText.
loop statement
Syntax
AloopStatementis:
loop statementsAndDeclarations endloop
Description
Aloopstatementcausesthestatements(anddeclarations)inittoberepeatedlyexecuted.Thiscontinuesuntilterminatedbyoneofitsenclosedexitstatements(orbyanenclosedreturnorresultstatement).
Example
Outputonseparatelines:Happy,Happy,Happy,etc.
loop
put"Happy"
endloop
Example
ReadwordsuptothewordStop.
varword:string
loop
getword
exitwhenword="Stop"
endloop
Details
Aloopstatementcancontainmorethanoneexit,ornoneatall(inwhichcaseitisaninfiniteloop).Whentheexitwhenisatthebeginningoftheloop,theloopworkslikePascal'sdowhile;whenattheend,theloopworkslikePascal'srepeatuntil.
Justprecedingthestatementsanddeclarations,youareallowedtowritean"invariantclause"oftheform:
invarianttrueFalseExpn
Thisclauseisequivalentto:asserttrueFalseExpn.
lower bound
Syntax lower(reference[,dimension]):int
Description
Thelowerattributeisusedtofindthelowerboundofanarray,string,char(n)ornon-opaquesubrangetype.Sincethelowerboundisnecessarilyknownatcompiletime,lowerisrarelyused.
Seealso upperwhichfindstheupperbound.
Math
Description
Thisunitcontainsallthemathematicalroutines.Therearethreeroutinesthatarepartofthelanguage,butareconceptuallypartoftheMathunit.
AllroutinesintheMathunitexceptMath.DistanceandMath.DistancePointLineareexportedunqualified.(Thismeansyoucancalltheentrypointsdirectly.)Math.DistanceandMath.DistancePointLineareexportedqualified.AllconstantsintheMathunitareexportedqualified.(BothMath.PIandMath.Emustbeprefacedwith"Math.".)
DescriptionsofallthesubprogramsintheMathmodulecanbefoundinthischapter.
ConstantsMath.PI Theconstantp(3.14...).Math.E Thenaturalbasee(2.718...).
EntryPoints
abs* Theabsolutevaluefunction.arccos Thearccosfunction(radians).arccosd Thearccosfunction(degrees).arcsin Thearcsinfunction(radians).arcsind Thearcsinfunction(degrees).arctan Thearctanfunction(radians).arctand Thearctanfunction(degrees).cos Thecosinefunction(radians).cosd Thecosinefunction(degrees).exp Theexponentiationfunction.ln Thenaturallogarithmfunction.max* Themaximumvaluefunction.min* Theminimumvaluefunction.sign Thesignfunction.sin Thesinefunction(radians).sind Thesinefunction(degrees).
tan Thetangentfunction(radians).tand Thetangentfunction(degrees).sqrt Thesquarerootfunction.Distance Thedistancebetweentwopoints.
DistancePointLine Thedistancebetweenapointandalinesegment.
*Partofthelanguage,conceptuallypartoftheMathunit.
Math.Distance PartofMathmodule
Syntax Math.Distance(x1,y1,x2,y2:real):real
Description Math.Distanceisusedtocalculatethedistancebetweentwopoints.(x1,y1)isthelocationofthefirstpoint,and(x2,y2)isthelocationofthesecondpoint.
Details TheparameterstoMath.Distancearereal,butyoucanpassintegervariablesandconstants.
Example Thisprogamdrawstwocircleswithradius75onthescreenandoutputswhethertheytouch.
varx1,y1,x2,y2:int
constRADIUS: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
ifMath.Distance(x1,y1,x2,y2)<RADIUS*2then
put"Thetwocirclestouch"
else
put"Thetwocirclesdonottouch"
endif
Execute
Status Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMath.Distance,notbycallingDistance.
Math.DistancePointLine PartofMathmodule
Syntax Math.DistancePointLine(xp,yp,x1,y1,x2,y2:real):real
Description Math.DistancePointLineisusedtocalculatethedistancebetweenapointandalinesegment.Itisoftenusedingamestodetermineifacollisionhasoccurred.(xp,yp)isthelocationbetweenthepoint.(x1,y1)and(x2aretheendpointsofthelinesegment.
Details TheparameterstoMath.DistancePointLinearereal,butyoucanpassintegervariablesandconstants.Theparametersareinthesameorderasthesubprogramname(thatispoint,thenline).
Example Thisprogamdrawsalinesegmentandacirclewithradius75onthescreenandoutputswhethertheytouch.
varxp,yp,x1,y1,x2,y2:int
constRADIUS: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)
ifMath.DistancePointLine(xp,yp,x1,y1,x2,y2
put"Thecircletouchestheline"
else
put"Thecircledoesnottouchtheline"
endif
Execute
Status Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMath.DistancePointLine,notbycallingDistancePointLine.
max maximumfunction
Syntax max(expn,expn)
Description
Themaxfunctionisusedtofindthemaximumoftwonumbers(thetwoexpn's).Forexample,max(5,7)is7.Ifbothnumbersareint,theresultisint.Ifbothnumbersarenat(naturalnumbers),theresultisnat.Butifoneorbothofthenumbersarereal,theresultisreal.Seealsotheminfunction.
Example
Thisprogramoutputs85.72.
varx:real:=74.61
vary:real:=85.72
putmax(x,y)%Outputs85.72
Example
Thisprograminputs10numbersandoutputstheirmaximum.
varm,t:real
getm%Inputfirstnumber
fori:2..10%Handleremaining9numbers
gett
m:=max(m,t)
endfor
put"Themaximumis",m
Seealso SeealsopredefinedunitMath.
maxcol maximumcolumnfunction
Syntax maxcol:int
DescriptionThemaxcolfunctionisusedtodeterminethenumberofcolumnsonthescreen.
ExampleThisprogramoutputsthemaximumcolumnnumber.
put"Numberofcolumnsonthescreenis",maxrow
Details
ForIBMPCcompatiblesaswellasmostUNIXdumbterminals,in"text"or"screen"mode,maxcol=80.ForthedefaultIBMPCcompatible"graphics"mode(CGA),maxcol=40.
Seealso locateprocedureforanexampleoftheuseofmaxcol.
maxcolor graphicsfunction
Syntax maxcolor:int
Description
Themaxcolorfunctionisusedtodeterminethemaximumcolornumberforthecurrentmodeofthescreen.Thealternatespellingismaxcolour.
Example
Thisprogramoutputsthemaximumcolornumber.
setscreen("graphics")
…
put"Themaximumcolornumberis",maxcolor
Details
Thescreenshouldbeina"screen"or"graphics"mode.Ifitisnot,itwillautomaticallybesetto"screen"mode.Seesetscreenfordetails.
ForIBMPCcompatiblesin"screen"mode,maxcolor=15.ForthedefaultIBMPCcompatible"graphics"mode(CGA),maxcolor=3.
Seealso
drawdotandpaletteforexamplesoftheuseofmaxcolor.Seethecolorprocedurewhichisusedforsettingthecurrentlyactivecolor.
maxint maximumintegerfunction
Syntax maxint:int
DescriptionThemaxintfunctionisusedtodeterminethelargestinteger(int)thatcanbeusedinaprogram.
ExampleThisprogramoutputsthemaximuminteger.
put"Thelargestintegerthatcanbeusedis",
Details
IncurrentTuringandOOTimplementations,intvaluesarestoredin4bytes,i.e.,32bits.Thisdeterminesthemaximumintvalue,whichis2**311,equaling2147483647.
Thereisananomalyincomputerarithmeticinthattheabsolutevalueofthelargestnegativeintegerisonelargerthanmaxint.Turingreservesthisextravaluetorepresenttheuninitializedinteger.Thisvaluecanbecomputedbutanyattempttoassignittoanintvariableisdetectedasanoverflow.Youcanusethisextravaluebyusingtheint4typeinsteadofint,butthistypehasnoinitializationchecking.
Seealsomaxnatandminint.
SeealsoOOTpredefinedunitMath.
maxnat maximumnaturalnumberfunction
Syntax maxnat:nat
DescriptionThemaxnatfunctionisusedtodeterminethelargestnaturalnumberthatcanbeusedinaprogram.
ExampleThisprogramoutputsthemaximumnaturalnumber.
put"Thelargestnaturalnumberthatcanbeusedis",
Details
Incurrentimplementations,naturalnumbersarestoredin4bytes,i.e.,32bits.Thisdeterminesthemaximumnaturalnumber,whichis2**32-2,equaling4294967294.
Infourbytesitispossibletorepresentonemorevalue,namely,2**32-1=4294967295.ThisextravalueisusedinTuringtorepresenttheuninitializednaturalnumber.Althoughitcanbecomputed,anyattempttoassignittoavariableisdetectedasanoverflow.Youcanusethisextravaluebyusingthetypeinsteadofnat,butthistypehasnoinitializationchecking.
Seealsomaxintandminnat.
SeealsopredefinedunitLimits.
maxrow maximumrowfunction
Syntax maxrow:int
DescriptionThemaxrowfunctionisusedtodeterminethenumberofrowsonthescreen.
ExampleThisprogramoutputsthemaximumrownumber.
put"Numberofrowsonthescreenis",maxrow
DetailsForIBMPCcompatibles,maxrow=25.FormanyUNIXdumbterminals,maxrow=24.
Seealso locateprocedureforanexampleoftheuseofmaxrow.
maxx graphicsfunction
Syntax maxx:int
DescriptionThemaxxfunctionisusedtodeterminethemaximumvalueofxforthecurrentgraphicsmode.
Example
Thisprogramoutputsthemaximumxvalue.
setscreen("graphics")
…
put"Themaximumxvalueis",maxx
Details
Thescreenshouldbeina"graphics"mode.Ifitisnot,itwillautomaticallybesetto"graphics"mode.Seesetscreenfordetails.
ForthedefaultIBMPCcompatiblegraphicsmode(CGA),maxx=319.
Seealsodrawdotforanexampleoftheuseofmaxxandforadiagramillustratingxandypositions.
maxy graphicsfunction
Syntax maxy:int
DescriptionThemaxyfunctionisusedtodeterminethemaximumvalueofyforthecurrentgraphicsmode.
Example
Thisprogramoutputsthemaximumyvalue.
setscreen("graphics")
…
put"Themaximumyvalueis",maxy
Details
Thescreenshouldbeina"graphics"mode;.Ifitisnot,itwillautomaticallybesetto"graphics"mode.Seesetscreenfordetails.
ForthedefaultIBMPCcompatiblegraphicsmode(CGA),maxy=199.
Seealsodrawdotforanexampleoftheuseofmaxyandforadiagramillustratingxandypositions.
min minimumfunction
Syntax min(expn,expn)
Description
Theminfunctionisusedtofindtheminimumoftwonumbers(thetwoexpn's).Forexample,min(5,7)is5.Ifbothnumbersareint,theresultisint.Ifbothnumbersarenat(naturalnumbers),theresultisnat.Butifoneorbothofthenumbersarereal,theresultisreal.Seealsothemaxfunction.
Example
Thisprogramoutputs74.61.
varx:real:=74.61
vary:real:=85.72
putmin(x,y)%Outputs74.61
Example
Thisprograminputs10numbersandoutputstheirminimum.
varm,t:real
getm%Inputfirstnumber
fori:2..10%Handleremaining9numbers
gett
m:=min(m,t)
endfor
put"Theminimumis",m
Seealso SeealsopredefinedunitMath.
minint minimumintegerfunction
Syntax minint:int
DescriptionTheminintfunctionisusedtodeterminethesmallestinteger(int)thatcanbeusedinaprogram.
ExampleThisprogramoutputsthemaximuminteger.
put"Thesmallestintegerthatcanbeusedis",
Details
Incurrentimplementations,intvaluesarestoredin4bytes,i.e.,32bits.Thisdeterminestheminimumintvalue,whichis-2**31-1,equaling-2147483647.
Thereisananomalyincomputerarithmeticinthattheabsolutevalueofthelargestnegativeintegerisonelargerthanmaxint.Turingreservesthisextravaluetorepresenttheuninitializedinteger.Thisvaluecanbecomputedbutanyattempttoassignittoanintvariableisdetectedasanoverflow.Youcanusethisextravaluebyusingtheint4typeinsteadofbutthistypehasnoinitializationchecking.
Seealsominnatandmaxint.
SeealsopredefinedunitLimits.
minnat minimumnaturalnumberfunction
Syntax minnat:nat
DescriptionTheminnatfunctionisusedtodeterminethesmallestnaturalnumberthatcanbeusedinaprogram.
ExampleThisprogramoutputsthesmallestnaturalnumber.
put"Thesmallestnaturalnumberthatcanbeusedis",
Details
IncurrentTuringandOOTimplementations,naturalnumbersarestoredin4bytes,i.e.,32bits.However,theminimumnaturalnumberinallimplementationsis0.minnatisprovidedforpurposesofsymmetrywithminint,maxint
Infourbytesitispossibletorepresentonemorevalue,namely,2**32-1=4294967295.ThisextravalueisusedinTuringtorepresenttheuninitializednaturalnumber.Althoughitcanbecomputed,anyattempttoassignittoadetectedasanoverflow.Youcanusethisextravaluebyusingthenat4ofnat,butthistypehasnoinitializationchecking.
Seealsominintandmaxnat.
SeealsopredefinedunitLimits.
mod modulooperator
Syntax mod
Description
Themod(modulo)operatorproducesthemoduloofonenumberwithanother.Inotherwords,theresultisalwaysanumberbetween0andthesecondoperand.Ifbothoperandsarepositive,theresultisidenticaltotheremainderoperator.Forexample,7mod2produces1and12mod5produces3.
Example
Inthisexample,hoursisthecurrenttime.Itismovedbackandforthbyarandomamount,butthefinalresultmustalwaysbebetween1and12(themodoperationproducesanumberbetween0and11andthen0becomes12).
varhours:int:=12
varhoursPassed:int
put"Thetimeisnow",hours,"o'clock"
loop
randint(hoursPassed,-12,12)
exitwhenhoursPassed=0
ifhoursPassed<0then
puthoursPassed,"hoursbefore"..
else
puthoursPassed,"hourslater"..
endif
puthours,"o'clock"..
hours:=(hours+hoursPassed)mod12
ifhours=0then
hours=12
endif
put"itwas",hours,"o'clock"
endloop
Details
Ifthesecondoperandispositive,thentheresultisalwaysnon-negative.Likewise,ifthesecondoperandisnegative,thentheresultisalwaysnon-positive.Ifbothoperandsarenegative,theresultisthesameastheremainderoperator.
Seealsoinfixoperators,precedenceofoperatorsandtheremanddivoperators.
module declaration
Syntax
AmoduleDeclarationis:
moduleid [implementimplementItem] [implementbyimplementByItem] [import[var]importItem {,[var]importItem}] [export[howExport]id{,[howExport]id}] statementsAndDeclarations endid
Description
Amoduledeclarationcreatesapackageofvariables,constants,types,subprograms,etc.Thenameofthemodule(id)isgivenintwoplaces,justaftermoduleandjustafterend.Itemsdeclaredinsidethemodulecanbeaccessedoutsideofthemoduleonlyiftheyareexported.Itemsfromoutsidethemodulethataretobeusedinthemoduleneedtobeimported(unlesstheyarepredefinedorpervasive).
Example
Thismoduleimplementsastackofstrings.
modulestack%ImplementsaLIFOlistofstrings
exportpush,pop
vartop:int:=0
varcontents:array1..100ofstring
procedurepush(s:string)
top:=top+1
contents(top):=s
endpush
procedurepop(vars:string)
s:=contents(top)
top:=top-1
endpop
endstack
stack.push("Harvey")
varname:string
stack.pop(name)%ThissetsnametoHarvey
Outsideofthestackmodule,theprocedurespushandpopcanbecalledusingthenotationstack.pushandstack.pop.Thisaccessisallowedbecausepopareexportedfromthemodule.Otheritemsdeclaredinthemodule(contents)cannotbeaccessedfromoutsidebecausetheyarenotexported.
Details
Insomeotherprogramminglanguages,amoduleiscalledapackageobject.
Amoduledeclarationisexecuted(itisinitialized)byexecutingitsdeclarationsandstatements.Forexample,thestackmoduleisinitializedbysettingthevariableto0.Thisinitializationexecutesallthestatementsanddeclarationsinthemodulethatarenotcontainedinproceduresorfunctions.Theinitializationiscompletedbeforeanyprocedureorfunctionofthemodulecanbecalledfromoutsidethemodule.Anexportedsubprogrammustnotbecalleduntilinitializationofthemoduleiscomplete.
Acalltoanexportedprocedureorfunctionfromoutsidethemoduleexecutesthebodyofthatprocedureorfunction(themoduleisnotinitializedwitheachsuchcall).Seealsomonitorandclassdeclarations.
Theimportlistgivesthenamesofitemsdeclaredoutsidethemodulethatcanbeaccessedinsidethemodule.Sincestackhasnoimportlist,itisnotallowedtoaccessanynamesdeclaredoutsideofit.Seealsoimportlists.Separately-compiledunitsthatareimportedareinitializedbeforetheimportingunit.
Theexportlistisusedtoimplementinformationhiding,whichisolatesimplementationdetailsinsidethemodule.Theexportlistgivesthenamesofitemsdeclaredinsidethemodulethatcanbeusedoutsidethemodule.Forexample,pushandpopareexportedfromstack.Eachsuchuseofanexporteditemmustbeprecededbythemodulenameandadot,forexample,(Seeunqualifiedforadviceonhowtoavoidusingtheprefix"stack.thatarenotexported,suchastopandcontents,cannotbeaccessedoutsidethemodule.
Procedures,functions,variables,constantsandtypescanbeexported;modules,monitorsorclassescannotbeexported.
Aclassisessentiallyatemplateforcreatingindividualmodules(objects).Seeclassfordetails.Amonitorisessentiallyamoduleinwhichonlyoneprocesscanbeactiveatatime.Seemonitorandprocessfordetails.
Theopaquekeywordisused(only)inexportliststoprecedeexportedtypenamesthathavedeclarationsinthemodule.Outsideofthemodule,thetypewillbedistinctfromallotherstypes.Thismeans,forexample,thatiftheopaquetypeisarecord,itsfieldscannotbeaccessedoutsideofthemodule.Opaquetypesareusedtoguaranteethatcertainitemsareinspectedandmanipulatedinonlyoneplace,namely,insidethemodule.Thesetypesaresometimescalledabstractdatatypes.Seealsoexportlists,whichalsodescribesunqualifiedandpervasiveexports.
Implementandimplement-bylistsareusedtoseparateamodule'sinterfacefromitsbody.Thisallowsonlyapartofamodule(itsinterface)tobevisibletoitsusers(itsimporters),whilehidingitsimplementation.Seeimplementimplementbylists.
Example
Useanopaquetypetoimplementcomplexarithmetic.
modulecomplex
exportopaquevalue,constant,add,
…otheroperations…
typevalue:
record
realPt,imagPt:real
endrecord
functionconstant(realPt,imagPt:real):
varanswer:value
answer.realPt:=realPt
answer.imagPt:=imagPt
resultanswer
endconstant
functionadd(L,R:value):value
varanswer:value
answer.realPt:=L.realPt+R.realPt
answer.imagPt:=L.imagPt+R.imagPt
resultanswer
endadd
…otheroperationsforcomplexarithmeticgohere…
endcomplex
varc,d:complex.value:=complex.constant(1,5)
%canddbecomethecomplexnumber(1,5)
vare:complex.value:=complex.add(c,d)
%ebecomesthecomplexnumber(2,10)
Details
Moduledeclarationscanbenestedinsideothermodulesbutcannotbenestedinsideproceduresorfunctions.Amodulemustnotcontainabindasoneofits(outermost)declarations.Areturnstatementcannotbeusedasoneofthe(outermost)statementsinamodule.
ThesyntaxofamoduleDeclarationpresentedabovehasbeensimplifiedbyleavingoutpre,invariantandpostclauses;thefullsyntaxis:
moduleid
[implementimplementItem]
[implementbyimplementByItem]
[import[var]importItem{,[var]importItem
[export[howExport]id{,[howExport]id
[pretrueFalseExpn]
statementsAndDeclarations
[invarianttrueFalseExpn]
statementsAndDeclarations
[posttrueFalseExpn]
endid
Thetrue/falseexpressioninthepreandpostclausesmustbetruewheninitializationreacheseachofthem.Afterthat,thesehavenoeffect.Thetrue/falseexpressionintheinvariantmustbetrueanytimethemoduleisexited(whenfinishinginitializationorwhenreturningfromanexternalcalltoanexportedsubprogram)orcalled(viaanexportedsubprogram).Theseclauses(pre,postandinvariant)arenotinheritedbyexpansions.Forexample,ifmoduleBinheritsA,thesubprogramsofBareboundbyB'sclausesandnotbyA's.
Seealsounit,monitorandclass.Seealsoexportlist,importlist,implementimplementbylist,inheritlistanddeferredsubprogram.
monitor declaration
Syntax
AmonitorDeclarationis:
monitorid [implementimplementItem] [implementbyimplementByItem] [import[var]importItem {,[var]importItem}] [export[howExport]id{,[howExport]id}] statementsAndDeclarations endid
Description
Amonitorisaspecialpurposemodule(seemodule)thatisusedwithconcurrentprocesses(seeprocess).Atmost,oneconcurrentprocess(seeprocess)canbeactiveinamonitoratatime.Thismeansthataprocesswillbeblockedifitcallsamonitorthatisalreadyactive.Theprocesswillnotbeallowedtoproceeduntilthemonitorisinactive.Themonitorprovidesmutuallyexclusiveaccesstothemonitor'sinternaldata.
Thismonitorcontrolsaccesstothecountvariablesoitcanbeupdatedbytwoprocesses(theobserverandthereporter)withoutbeingcorruptedbythisconcurrentaccess.Generally,itisnotsafetohaveoneprocessupdateavariablethatotherprocessesaresimultaneouslyaccessing.Theobserverprocessrepeatedlyincrementsthecounterwhenitobservesanevent.Thereporterprocessrepeatedlywritesoutthenumberofeventsthathaveoccurredsincethelastreport,resettingthecountertozero.
monitorcontroller
exportobserve,report
varcounter:int:=0
procedureobserve
counter:=counter+1
Example
endobserve
procedurereport(varn:int)
n:=counter
counter:=0
endreport
endcontroller
processobserver
loop
…observeoneevent…
controller.observe
endloop
endobserver
processreporter
varn:int
loop
controller.report(n)
…reportnevents…
endloop
endreporter
forkobserver%Activatetheobserver
forkreporter%Activatethereporter
Details
Amonitorisessentiallyamoduleinwhichonlyoneprocesscanbeactiveatatime.Seemoduledeclarationsfordetailsaboutinitialization.Initializationisthesameformodulesandmonitors.
Amonitorcancontainwaitstatements(thatputprocessestosleep)andsignalstatements(thatwakethemupagain).Thesestatementsoperateonconditionvariables,whichareessentiallyqueuesofsleepingprocesses.
Aclassisessentiallyatemplateforcreatingindividualmodules(objects).Seeclassfordetails.Iftheclassdeclarationisprecededbythekeywordmonitor,thecreatedmodulesareactuallymonitors.Monitorclassescanonlyinherit(inheritfrom)othermonitorclasses.
Thebodyofamonitorhasthesameformasthatofamodule,exceptthatmodules,monitorsandprocessescannotbedeclaredinsidemonitors,andcertainstatements(waitandsignal)areallowedinmonitors.
Details
ThesyntaxofamonitorDeclarationpresentedabovehasbeensimplifiedbyleavingoutpre,invariantandpostclauses.Seemoduleforanexplanationoftheseextrafeatures.ThereisalsoanoptionalcompilerTimeIntegerExpressioninthefirstline,whichisexplainedbelow.Thefullsyntaxis:
monitorid[:compileTimeIntegerExpn]
[implementimplementItem]
[implementbyimplementByItem]
[import[var]importItem{,[var]importItem
[export[howExport]id{,[howExport]id
[pretrueFalseExpn]
statementsAndDeclarations
[invarianttrueFalseExpn]
statementsAndDeclarations
[posttrueFalseExpn]
endid
IftheoptionalcompileTimeIntegerExpressionispresent,thisisadevicemonitor.Itsexclusiveaccessisenforcedbyanimplementation-dependenttrick,suchasexecutingitatahardwareprioritylevelgivenbytheexpression.Adevicemonitorisrestrictedfromcallingmonitors(directlyorindirectly).Thisrestrictionisimposedtoeliminatethepossibilityofblockingaprocesswithanon-zerohardwarepriority(asthiswouldinadvertentlyallowmultipleentryintoadevicemonitor).Itistheprogrammer'sresponsibilitytomeetthisrestriction;thecompilerwillnotingeneralenforcetherestriction.Thecurrent(1999)implementationignoresthiscompileTimeIntegerExpression.
Anunexportedparameterlessprocedureinamonitorcanbespecifiedtobeaninterrupthandlingprocedurebyspecifyingadeviceinitsheader,usingtheform:
procedureid[:deviceSpecification]
ThedeviceSpecificationisacompiletimenaturalnumberthatdesignates,totheimplementation,theclassofinterruptsthateffectivelycallthisprocedure.Interrupthandlingprocedurescannotbecalledexplicitlywithintheprogram.
Details Therearetworestrictionsthattheprogrammermustfollowwhenusinginterrupthandlingprocedures;theserestrictionswillnotnecessarilybeenforcedbythesoftware.Thefirstisthataninterrupthandlingproceduremustnotexecuteawait,eitherdirectlyorindirectly,bycallinganotherprocedure.Thesecondisthattheinterrupthandlingproceduremustnotdirectlyorindirectlycauseanexception,unlesstheexceptionwillbecaughtbyanexceptionhandlerthatisactivateddirectlyorindirectlybytheinterrupthandlingprocedure.
Details
Declarationsofmonitorswithinmonitorsaredisallowed.Thiswouldberedundantanyway,asonlyoneprocesscanbeinsidetheoutermonitor,sotheinnermonitorisguaranteedtobesuccessful.
Declarationsofclasseswithinmonitorsarealsodisallowed.
Anysubprogramdeclaredwithinasubprogramisnowallowedtobeassignedtoasubprogramvariable,norpassedasaparametricsubprogram.
Seealsounit,moduleandclass.Seealsoexportlist,importlist,implementlist,implementbylistanddeferredsubprogram.
Mouse
Description
ThisunitcontainsthepredefinedsubprogramsthatdealwithusingthemouseinaTuringprogram.Theroutinesallowyoutogetthecurrentmousecursorposition,checkifabuttonhasbeenpressedandgettheinformationifithas.Therearealsoroutinestohideandshowthemouseonsystemswhereitmakessense.(OnGUIbasedsystemsliketheMacintosh,themousecan'tbehiddenasitmaybeneededbyotherapplicationsrunningatthesametime.)
AllroutinesintheMousemoduleareexportedqualified(andthusmustbeprefacedwith"Mouse.").
EntryPoints
Where Getsthecurrentlocationofthemousecursorandstatusofthemousebuttons.
ButtonMoved Checkstoseeifamousebuttonhasbeenpressed.
ButtonWait Getsinformationaboutamousebuttonbeingpressedsuchaswhereitwaspressed,whichbuttonwaspressed,etc.
ButtonChoose Selectsthemodeforthemouse(eithersinglebuttonmodeormulti-buttonmode).
Mouse.ButtonChoose PartofMousemodule
Syntax Mouse.ButtonChoose(choice:string)
Description
TheMouse.ButtonChooseprocedureisusedtochangethemodeofthemouse.InTuring,themousecaneitherbein"single-buttonmode"orin"multi-buttonmode".In"single-buttonmode"themouseistreatedasaonebuttonmouse.Abuttonisconsideredpressedwhenanybuttonispressedandreleasedonlywhenallbuttonshavebeenreleased.
InTuring,themousestartsin"single-buttonmode".
Theparameterchoicecanbeoneof"singlebutton","onebutton"(whichswitchthemouseinto"single-buttonmode")or"multibutton"(whichswitchesthemouseinto"multi-buttonmode").
Example
Aprogramthatdisplaysthestatusofthemouseatthetopleftcornerofthescreen.
Mouse.ButtonChoose("multibutton")
varx,y,button,left,middle,right:int
Mouse.Where(x,y,button)
left:=buttonmod10%left=0or1
middle:=(button-left)mod100%middle=0or10
right:=button-middle-left%right=0or100
ifleft=1then
put"leftbuttondown"
endif
ifmiddle=10then
put"middlebuttondown"
endif
ifright=100then
put"rightbuttondown"
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMouse.ButtonChoose,notbycallingButtonChoose.
Seealso
Mouse.ButtonMovedandMouse.ButtonWaittogetmouseeventssavedinaqueue.SeealsoMouse.Wheretogetthecurrentstatusofmousebutton(s).
Mouse.ButtonMoved PartofMousemodule
Syntax Mouse.ButtonMoved(motion:string):boolean
Description
TheMouse.ButtonMovedfunctionindicateswhetherthereisamouseeventoftheappropriatetypeonthemousequeue.Eventsareeither"up","down","updown"or"downup"events(althoughthe"downup"and"updown"arethesameevent).
Theparametermotionmustbeoneof"up","down","updown"or"downup".Ifaneventofthetyperequestedisinthequeue,Mouse.ButtonMovedreturnstrue.Iftheeventisnotinthequeue,thenMouse.ButtonMovedreturnsfalse.
In"single-buttonmode"(wherethemouseistreatedlikeaone-buttonmouse),a"down"eventoccurswheneverallthebuttonsareupandabuttonispressed.An"up"eventtakesplacewhenthelastbuttonisreleasedsothatnobuttonsremainpressed.
In"multi-buttonmode",a"down"eventoccurswheneveranybuttonispressed,andan"up"eventoccurswheneveranybuttonisreleased.
Example
Thisprogramdrawsrandomcirclesonthescreenuntiltheuserclicksthemousebutton,whereuponisstartsdrawingrandomboxes.Clickingthemousebuttonswitchesbetweenthetwo.
varcircles:boolean:=true
loop
varx,y,radius,clr:int
ifMouse.ButtonMoved("down")then
varbuttonnumber,buttonupdown:int
Mouse.ButtonWait("down",x,y,buttonnumber
buttonupdown)
circles:=notcircles
endif
x:=Rand.Int(0,maxx)
y:=Rand.Int(0,maxy)
radius:=Rand.Int(0,100)
clr:=Rand.Int(0,maxcolor)
ifcirclesthen
Draw.FillOval(x,y,radius,radius,clr
else
Draw.FillBox(x,y,x+radius,y+radius
endif
endloop
Example
Thisisanexampledemonstratinghowtocheckforbothcharacterandmouseinputatthesametime.
varch:string(1)
varx,y,btnnum,btnupdown:int
loop
ifhaschthen
getch(ch)
Text.Locate(1,1)
put"Thecharacterenteredisa:",ch
endif
ifMouse.ButtonMoved("down")then
Mouse.ButtonWait("down",x,y,btnnum,
Text.Locate(1,1)
put"Thebuttonwasclickedatposition:",
endif
endloop
Details
Mouse.ButtonMovedcanbethoughtofasthemouseequivalentofhaschinthattheybothcheckforsomethinginaqueueandbothreturnimmediately.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMouse.ButtonMoved,notbycallingButtonMoved.
Seealso
Mouse.ButtonMovedtogetmouseeventssavedinthequeue.SeealsoMouse.ButtonChoosetoswitchbetween"single-buttonmode"and"multi-buttonmode".
Mouse.ButtonWait PartofMousemodule
SyntaxMouse.ButtonWait(motion:string, varx,y,buttonNumber,buttonUpDown:int)
Description
TheMouse.ButtonWaitproceduregetsinformationaboutamouseeventandremovesitfromthequeue.
Theparametermotionmustbeoneof"up","down","updown"or"downup".Ifaneventofthetyperequestedisinthequeue,Mouse.ButtonWaitreturnsinstantly.Ifthereisn'tsuchanevent,Mouse.ButtonWaitwaitsuntilthereisoneandthenreturns(muchlikegetchhandleskeystrokes).
In"single-buttonmode"(wherethemouseistreatedlikeaone-buttonmouse),a"down"eventoccurswheneverallthebuttonsareupandabuttonispressed.An"up"eventtakesplacewhenthelastbuttonisreleasedsothatnobuttonsremainpressed.
In"multi-buttonmode",a"down"eventoccurswheneveranybuttonispressed,andan"up"eventoccurswheneveranybuttonisreleased.
Theparametersxandyaresettothepositionofthemousecursorwhenthebuttonwaspressed.Theparameterbuttonnumberissetto1whenin"single-buttonmode".In"multi-buttonmode",itissetto1iftheleftbuttonwaspressed,2ifthemiddlebuttonwaspressed,and3iftherightbuttonwaspressed.Theparameterbuttonupdownissetto1,ifabuttonwaspressedand0ifabuttonwasreleased.
Thisprogramdrawslines.Itstartsalinewheretheuserpressesdownandcontinuestoupdatethelinewhilethemousebuttonishelddown.Whenthebuttonisreleased,thelineispermanentlydrawandtheusercandrawanotherline.
varx,y,btnNumber,btnUpDown,buttons:int
varnx,ny:int
loop
Mouse.ButtonWait("down",x,y,btnNumber,btnUpDown
Example nx:=x
ny:=y
loop
Draw.Line(x,y,nx,ny,0)%Erasepreviousline
exitwhenMouse.ButtonMoved("up")
Mouse.Where(nx,ny,buttons)
Draw.Line(x,y,nx,ny,1)%Drawlinetoposition
endloop
Mouse.ButtonWait("up",nx,ny,btnNumber,btnUpDown
Draw.Line(x,y,nx,ny,2)%Drawlinetofinalposition
endloop
Example
Thisisanexampledemonstratinghowtocheckforbothcharacterandmouseinputatthesametime.
varch:string(1)
varx,y,btnNum,btnUpDown:int
loop
ifhaschthen
getch(ch)
Text.Locate(1,1)
put"Thecharacterenteredisa:",ch
endif
ifMouse.ButtonMoved("down")then
Mouse.ButtonWait("down",x,y,btnNum,
Text.Locate(1,1)
put"Thebuttonwasclickedatposition:",
endif
endloop
Details
Mouse.ButtonWaitcanbethoughtofasthemouseequivalentofgetchinthattheybothreadsomethinginaqueueandbothwaituntiltheygetthethingthey'relookingfor.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMouse.ButtonWait,notbycallingButtonWait.
Seealso
Mouse.ButtonWaittoseeifanappropriateeventisinthequeue.SeealsoMouse.ButtonChoosetoswitchbetween"single-buttonmode"and"multi-buttonmode".
Mouse.Where PartofMousemodule
Syntax Mouse.Where(varx,y,button:int)
Description
TheMouse.Whereprocedureisusedtogetcurrentinformationaboutthestatusofthemouse.Theparametersxandyaresettothecurrentlocationofthemousecursor.Iftheprogramisrunningonasystemusingwindows,thecursormaybeoutsidethewindow.Thismeansthatxandymaybesettovaluesoutsideoftheboundsof0tomaxxand0tomaxy.
Theparameterbuttonissetdependingonthecurrentmode.In"single-buttonmode"(wherethemouseistreatedlikeaone-buttonmouse),buttonissetto0ifallthemousebuttonsareup,and1ifanyofthemousebuttonsaredown.In"multi-buttonmode",buttonisassignedthesumof1iftheleftbuttonisdown,10ifthemiddlebuttonisdown,and100iftherightbuttonisdown.Thusifbuttonhasthevalueof101,thenitmeansthattheleftandrightmousebuttonsweredepressed.
Example
Aprogramthatdisplaysthestatusofthemouseatthetopleftcornerofthescreen.
varx,y,button:int
loop
Mouse.Where(x,y,button)
Text.Locate(1,1)
ifbutton=0then
putx:4,"",y:4,"buttonup"
else
putx:4,"",y:4,"buttondown"
endif
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMouse.Where,notbycallingWhere.
Mouse.ButtonMovedandMouse.ButtonWaittogetmouse
Seealso eventssavedinaqueue.SeealsoMouse.ButtonChoosetoswitchbetween"single-buttonmode"and"multi-buttonmode".
mousewhere
Syntax mousewhere(varx,y,button:int)
Description
Themousewhereprocedureisusedtogetcurrentinformationaboutthestatusofthemouse.Theparametersxandyaresettothecurrentlocationofthemousecursor.Iftheprogramisrunningonasystemusingwindows,thecursormaybeoutsidethewindow.Thismeansthatxandymaybesettovaluesoutsideoftheboundsof0tomaxxand0tomaxy.
Theparameterbuttonissetdependingonthecurrentmode.In"single-buttonmode"(wherethemouseistreatedlikeaone-buttonmouse),buttonissetto0ifallthemousebuttonsareup,and1ifanyofthemousebuttonsaredown.In"multi-buttonmode",buttonisassignedthesumof1iftheleftbuttonisdown,10ifthemiddlebuttonisdown,and100iftherightbuttonisdown.Thusifbuttonhasthevalueof101,thenitmeansthattheleftandrightmousebuttonsweredepressed.
Example
Aprogramthatdisplaysthestatusofthemouseatthetopleftcornerofthescreen.
varx,y,button:int
loop
mousewhere(x,y,button)
locate(1,1)
ifbutton=0then
putx:4,"",y:4,"buttonup"
else
putx:4,"",y:4,"buttondown"
endif
endloop
Seealso
buttonmovedandbuttonwaittogetmouseeventssavedinaqueue.Seealsobuttonchoosetoswitchbetween"single-buttonmode"and"multi-buttonmode".
Music
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithsoundandmusic.Someoftheseroutineshavenotbeenimplementedatthetimeofthewritingofthismanualandwillbeimplementedinfuturereleases.
AllroutinesintheMusicmoduleareexportedqualified(andthusmustbeprefacedwith"Music.").
EntryPoints
Play Playsaseriesofnotes.
PlayFile Playsmusicfromafile,returningwhenthefileisfinishedplaying.Filemustbeinanallowableformat.
PlayFileReturn Playsmusicfromafile,returningassoonasthemusicstarts.Filemustbeinanallowableformat.
PlayFileLoop Playsmusicfromafile,loopingoverandover.Returnsassoonasthemusicstarts.Filemustbeinanallowableformat.
PlayFileStop Immediatelyterminatesanyplayingmusicfiles.
Sound Playsaspecifiedfrequencyforaspecifiedduration.
SoundOff Immediatelyterminatesanysoundplaying.
Music.Play PartofMusicmodule
Syntax Music.Play(music:string)
Description
TheMusic.Playprocedureisusedtosoundmusicalnotesonthecomputer.
Soundsareproducedsynchronouslyonaperprocessbasis.ThismeansthatwhenaprocessexecutesaMusic.SoundorMusic.Playcommand,itstopsuntilthecommandisfinished.However,otherprocesseswillcontinuetoexecuting.
ExampleThisprogramsoundsthefirstthreenotesoftheCscale.
Music.Play("cde")
Example
ThisprogramplaysfrommiddleCtooneoctaveabovemiddleCanddownagainin8thnotes.
Music.Play("8cdefgab>c")
Music.Play("<bagfedc")
Execute
Details
Thesyntaxoftheplaystringmaybeenhancedinthefuture.
TheMusic.Playproceduretakesstringscontainingcharactersthatspecifynotes,rests,sharps,flatsandduration.Thenotesarethelettersatog(orAtoG).Arestisp(forpause).Asharpis+andaflatis-.Thedurationsare1(wholenote),2(halfnote),4(quarternote),8(eightnote)and6(sixteenthnote).Thecharacter>raisestothenextoctaveand<lowers.Forexample,thisisthewaytoplayCandthenCsharponeoctaveabove
middleCwitharestbetweenthem,allinsixteenthnotes:Music.Play(">6cpc+").BlankscanbeusedforreadabilityandareignoredbyMusic.Play.
TheMusic.Playprocedurerequiresthatthemachinehaveasoundcardinordertoplaytones.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMusic.Play,notbycallingPlay.
SeealsotheMusic.Soundprocedure,whichmakesasoundofagivenfrequency(Hertz)andduration(milliseconds).
Music.PlayFile PartofMusicmodule
Syntax Music.PlayFile(fileName:string)
Description
TheMusic.PlayFileprocedureisusedtoplayafileofmusic.Thefilemustbeinoneoftheacceptableformatsandthemachine,musthavetheappropriatehardware.
ThefileNameparametermustgivetheformatofthefile:
WAVfiles "WAV:filename"or"filename.WAV" MP3files "MP3:filename"or"filename.MP3" MIDIfiles "MIDI:filename"or"filename.MIDI"
Soundsareproducedsynchronouslyonaperprocessbasis.ThismeansthatwhenaprocessexecutesaMusic.Sound,Music.PlayorMusic.PlayFilecommand,itstopsuntilthecommandisfinished.However,otherprocesseswillcontinueexecuting.
Details
Toplaymusicwhileperforminganyotheractivity,thecalltoMusic.PlayFilemustbeexecutedinitsownprocess.Theprocessisthencalledusingtheforkcommand.Whenaforkcommandisgiven,executionstartsontheprocess(likeaprocedurecall)andcontinuesfollowingtheforkcommandatthesametime.
Example
Thisprogramplaysthemusicinthefile"branden3.wav"whiledrawingovalsonthescreen.
processDoMusic
loop
Music.PlayFile("branden3.wav")
endloop
endDoMusic
forkDoMusic
varx,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)
endloop
Execute
DetailsToplayasoundfilerequiresthatthecomputerbeequippedwithasoundcardandspeakers.
Details
TheTuring4.1softwarecanplayfilesinthefollowingaudioformats:WAVE(.wav)files,MIDIfiles(.midior.mid),andMP3files(.mp3).Ingeneral,MIDIfilesarethemostefficientandthusarethepreferredformforlongermusicpieceslikebackgroundmusic.WAVEfilescanrecordanything,notjustmusic,soareoftenusedforsoundeffects.
Details
TheTuring4.1softwarecanalsoplaymusiconacompactdisk.Toplaythecompletecontentsofthecompactdisk,thefilenameis“cd”.Toplayasingletrackfromacompactdisk,thefilenameis“cd:[tracknumber]”.
Music.PlayFile("cd")%PlaytheentireCD
Music.PlayFile("cd:3")%PlaythethirdtrackontheCD
Details
OnthePC,differentformatsofmusiccanplaysimultaneously.ThismeansthataprogrammightuseaMIDIfileasabackgroundsoundtrackandthenuseWAVEfilesforindividualsoundeffects.Thesoundeffectswouldnotinterferewiththebackgroundmusic.Playingasecondmusicfilewiththesameformatasanalreadyplayingpieceimmediatelyhaltsthefirstpieceandstartsthesecond.Thiscanbeusedtostopasingletypeofmusicbyplayingashortsilentpieceofmusic.
Thisprogrambouncesamapleleafaroundthescreenwithbackgroundmusicandasoundeffectwhenthemapleleafhitsanedge.Whentheuserpressesanykey,theprogramimmediatelyexits.
Example
constSTAR_SIZE:int:=80
varpic,x,y,dx,dy:int
varfinished:boolean:=false
%Playsoundeffectonce.
processBoing
Music.PlayFile("boing.wav")
endBoing
%Loopplayingbackgroundmusicuntil'finished'istrue.
processBackgroundMusic
loop
exitwhenfinished
Music.PlayFile("background.mid")
endloop
endBackgroundMusic
%Gettheoriginalpicture
Draw.FillStar(3,3,STAR_SIZE-3,STAR_SIZE-3,
pic:=Pic.New(0,0,STAR_SIZE,STAR_SIZE)
cls
%Settheinitiallocationanddirectionofmovement
x:=Rand.Int(0,maxx-STAR_SIZE)
y:=Rand.Int(0,maxy-STAR_SIZE)
dx:=1
dy:=1
forkBackgroundMusic%Startbackgroundmusicplaying
loop
ifx+dx<0orx+dx>maxx-STAR_SIZEthen
dx:=-dx
forkBoing
endif
ify+dy<0ory+dy>maxy-STAR_SIZEthen
dy:=-dy
forkBoing
endif
x+=dx
y+=dy
Pic.Draw(pic,x,y,picCopy)
exitwhenhasch
Time.Delay(5)
endloop
%Stopthebackgroundmusic.
finished:=true
Music.PlayFileStop
Execute
Seealso
Music.PlayFileStoptohaltamusicfilethatiscurrentplaying,Music.PlayFileReturnforaprocedurethatstartsamusicfileplayingandreturnsimmediately(meaningthatyoudonotneedtouseprocessandforkstatements),andMusic.PlayFileLoopthatstartsamusicfileplayingcontinuouslyuntilitisstoppedwithouttheuseofprocessorfork.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMusic.PlayFile,notbycallingPlayFile.
Music.PlayFileLoop PartofMusicmodule
Syntax Music.PlayFileLoop(fileName:string)
Description
TheMusic.PlayFileLoopprocedureisusedtoplayafileofmusiccontinuously,loopinguntiltheprogramishaltedortheMusic.PlayFileStopcommandisgiven.Thefilemustbeinoneoftheacceptableformatsandthemachine,musthavetheappropriatehardware.
ThefileNameparametermustgivetheformatofthefile:
WAVfiles "WAV:filename"or"filename.WAV" MP3files "MP3:filename"or"filename.MP3" MIDIfiles "MIDI:filename"or"filename.MIDI"
TheMusic.PlayFileLoopprocedureisusedtoprovidecontinuousbackgroundmusicforaprogram.Whencalled,themusicstartsplaying,andtheprocedurereturnsimmediately.
Details
UnlikeMusic.PlayFile,theMusic.PlayFileLoopproceduredoesnothavetobecalledinaseparateprocess.However,themusicwillnotstopplaying(norwillaprogramthatcallsthisprocedureterminate)untilMusic.PlayFileStop
Example
Thisprogramcontinuouslyplaysthemusicinthefile"branden3.wavdrawingovalsonthescreen.
Music.PlayFileLoop("branden3.wav")
varx,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)
exitwhenhasch
endloop
Music.PlayFileStop
Execute
DetailsToplayasoundfilerequiresthatthecomputerbeequippedwithasoundcardandspeakers.
Details
TheTuring4.1softwarecanplayfilesinthefollowingaudioformats:WAVE(.wav)files,MIDIfiles(.midior.mid),andMP3files(.mp3).Ingeneral,MIDIfilesarethemostefficientandthusarethepreferredformforlongermusicpieceslikebackgroundmusic.WAVEfilescanrecordanything,notjustmusic,soareoftenusedforsoundeffects.
Details
TheTuring4.1softwarecanalsoplaymusiconacompactdisk.Toplaythecompletecontentsofthecompactdisk,thefilenameis“cd”.Toplayasingletrackfromacompactdisk,thefilenameis“cd:[tracknumber]”.
Music.PlayFileLoop("cd")%PlaytheentireCD
Music.PlayFileLoop("cd:3")%PlaythethirdtrackontheCD
Details
OnthePC,differentformatsofmusiccanplaysimultaneously.ThismeansthataprogrammightuseaMIDIfileasabackgroundsoundtrackandthenuseWAVEfilesforindividualsoundeffects.Thesoundeffectswouldnotinterferewiththebackgroundmusic.Playingasecondmusicfilewiththesameformatasanalreadyplayingpieceimmediatelyhaltsthefirstpieceandstartsthesecond.usedtostopasingletypeofmusicbyplayingashortsilentpieceofmusic.
Thisprogrambouncesamapleleafaroundthescreenwithbackgroundmusicandasoundeffectwhenthemapleleafhitsanedge.Whentheuserpressesanykey,theprogramimmediatelyexits.
constSTAR_SIZE:int:=80
varpic,x,y,dx,dy:int
%Gettheoriginalpicture
Draw.FillStar(3,3,STAR_SIZE-3,STAR_SIZE-3,
Example
pic:=Pic.New(0,0,STAR_SIZE,STAR_SIZE)
cls
%Settheinitiallocationanddirectionofmovement
x:=Rand.Int(0,maxx-STAR_SIZE)
y:=Rand.Int(0,maxy-STAR_SIZE)
dx:=1
dy:=1
Music.PlayFileLoop("background.mid")%Startbackgroundmusicplaying
loop
ifx+dx<0orx+dx>maxx-STAR_SIZEthen
dx:=-dx
Music.PlayFileReturn("boing.wav")
endif
ify+dy<0ory+dy>maxy-STAR_SIZEthen
dy:=-dy
Music.PlayFileReturn("boing.wav")
endif
x+=dx
y+=dy
Pic.Draw(pic,x,y,picCopy)
exitwhenhasch
Time.Delay(5)
endloop
%Stopthebackgroundmusic.
Music.PlayFileStop
Execute
Seealso Music.PlayFileStoptohaltamusicfilethatiscurrentplaying.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMusic.PlayFileLoopbycallingPlayFileLoop.
Music.PlayFileReturn PartofMusicmodule
Syntax Music.PlayFileReturn(fileName:string)
Description
TheMusic.PlayFileReturnprocedureisusedtoplayafileofmusic.Thefilemustbeinoneoftheacceptableformatsandthemachine,musthavetheappropriatehardware.
ThefileNameparametermustgivetheformatofthefile:
WAVfiles "WAV:filename"or"filename.WAV" MP3files "MP3:filename"or"filename.MP3" MIDIfiles "MIDI:filename"or"filename.MIDI"
UnlikeMusic.PlayFile,theMusic.PlayFileReturnprocedureshouldnotbecalledinaseparateprocess.Instead,theprocedurereturnsimmediately.ThismakesMusic.PlayFileReturneasiertouse,butmakesitunsuitableforplayingasetoffilessequentially.
Example
Thisprogramplaysthemusicinthefile"branden3.wav"oncewhiledrawingovalsonthescreen.Ifthemusichasnotfinishedwhentheuserpressesakey,itishaltedusingMusic.PlayFileStop
Music.PlayFileReturn("branden3.wav")
varx,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)
exitwhenhasch
endloop
Music.PlayFileStop
Execute
DetailsToplayasoundfilerequiresthatthecomputerbeequippedwithasoundcardandspeakers.
Details
TheTuring4.1softwarecanplayfilesinthefollowingaudioformats:WAVE(.wav)files,MIDIfiles(.midior.mid),andMP3files(.mp3).Ingeneral,MIDIfilesarethemostefficientandthusarethepreferredformforlongermusicpieceslikebackgroundmusic.WAVEfilescanrecordanything,notjustmusic,soareoftenusedforsoundeffects.
Details
TheTuring4.1softwarecanalsoplaymusiconacompactdisk.Toplaythecompletecontentsofthecompactdisk,thefilenameis“cd”.Toplayasingletrackfromacompactdisk,thefilenameis“cd:[tracknumber]”.
Music.PlayFileReturn("cd")%PlaytheentireCD
Music.PlayFileReturn("cd:3")%PlaythethirdtrackontheCD
Details
OnthePC,differentformatsofmusiccanplaysimultaneously.ThismeansthataprogrammightuseaMIDIfileasabackgroundsoundtrackandthenuseWAVEfilesforindividualsoundeffects.Thesoundeffectswouldnotinterferewiththebackgroundmusic.Playingasecondmusicfilewiththesameformatasanalreadyplayingpieceimmediatelyhaltsthefirstpieceandstartsthesecond.usedtostopasingletypeofmusicbyplayingashortsilentpieceofmusic.
Thisprogrambouncesamapleleafaroundthescreenwithbackgroundmusicandasoundeffectwhenthemapleleafhitsanedge.Whentheuserpressesanykey,theprogramimmediatelyexits.
constSTAR_SIZE:int:=80
varpic,x,y,dx,dy:int
%Gettheoriginalpicture
Draw.FillStar(3,3,STAR_SIZE-3,STAR_SIZE-3,
Example
pic:=Pic.New(0,0,STAR_SIZE,STAR_SIZE)
cls
%Settheinitiallocationanddirectionofmovement
x:=Rand.Int(0,maxx-STAR_SIZE)
y:=Rand.Int(0,maxy-STAR_SIZE)
dx:=1
dy:=1
Music.PlayFileLoop("background.mid")%Startbackgroundmusicplaying
loop
ifx+dx<0orx+dx>maxx-STAR_SIZEthen
dx:=-dx
Music.PlayFileReturn("boing.wav")
endif
ify+dy<0ory+dy>maxy-STAR_SIZEthen
dy:=-dy
Music.PlayFileReturn("boing.wav")
endif
x+=dx
y+=dy
Pic.Draw(pic,x,y,picCopy)
exitwhenhasch
Time.Delay(5)
endloop
%Stopthebackgroundmusic.
Music.PlayFileStop
Execute
Seealso Music.PlayFileStoptohaltamusicfilethatiscurrentplaying.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMusic.PlayFileReturnnotbycallingPlayFileReturn.
Music.PlayFileStop PartofMusicmodule
Syntax Music.PlayFileStop
Description
TheMusic.PlayFileStopprocedureisusedtotostopallmusicfilescurrentlyplaying.ThisincludesprocessesthatareexecutingtheMusic.PlayFileprocedure(theyexitimmediatelyandstartexecutingthenextstatementintheprocess),andtheMusic.PlayFileReturnandMusic.PlayFileLoopstatements,whichsimplystopplayingthemusic.
Details
InTuring,aprogramwillnothaltexecutionuntilallprocesseshaveterminated.Thismeansthatifyouareplayingbackgroundmusic,theprogramwillnotterminate,evenifexecutionreturnsfromthemainprogramunlessthebackgroundmusicishalted.
Example
Thisprogramplaysthebackgroundmusicfor30secondsandthenterminates.Notethatitisimportanttosettheflag(finished)beforecallingMusic.PlayFileStop.IfMusic.PlayFileStopcomesfirst,itispossibleforprocesstoreturnfromMusic.PlayFile,looparound,skipovertheexitwhenandcallMusic.PlayFileagainbeforethefinishedflagisset.
varfinished:boolean:=false
%Loopplayingbackgroundmusicuntil'finished'istrue.
processBackgroundMusic
loop
exitwhenfinished
Music.PlayFile("background.mid")
endloop
endBackgroundMusic
forkBackgroundMusic%Startthebackgroundmusic
Time.Delay(30000)%Waitfor30seconds
%Stopthebackgroundmusic.
finished:=true%Theflagmustbesetfirst
Music.PlayFileStop%Music.PlayFilewillreturnimmediately
Execute
Seealso Music.PlayFileforplayingmusicfilesandalargerexample.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMusic.PlayFileStop,notbycallingPlayFileStop.
Music.Sound PartofMusicmodule
Syntax Music.Sound(frequency,duration:int)
Description
TheMusic.Soundstatementisusedtocausethecomputertosoundanoteofagivenfrequencyforagiventime.Thefrequencyisincyclespersecond(Hertz).Thetimedurationisinmilliseconds.Forexample,middleAonapianois440Hertz,soMusic.Sound(440,1000)playsmiddleAforonesecond.
Soundsareproducedsynchronouslyonaperprocessbasis.ThismeansthatwhenaprocessexecutesaMusic.SoundorMusic.Playcommand,itstopsuntilthecommandisfinished.However,otherprocesseswillcontinueexecuting.
Example
Thisprogramplaysasirensoundinthebackground.
processsiren
loop
fori:100..3000by100
Music.Sound(i,50)%Soundnote
endfor
fordecreasingi:2900..200by100
Music.Sound(i,50)%Soundnote
endfor
endloop
endsiren
forksiren
…therestoftheprogramgoesherewhilethesirencontinues…
Execute
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingMusic.SoundnotbycallingSound.
SeealsoMusic.Playstatement,whichplaysnotesbasedonmusicalnotation.Forexample,Music.Play("8C")playsaneighthnoteofmiddleC.
Music.SoundOff PartofMusicmodule
Syntax Music.SoundOff
DescriptionTheMusic.SoundOffprocedurestopsanysoundormusicthatiscurrentlyplayingoriswaitingtoplay.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingMusic.SoundOff,notbycallingSoundOff.
SeealsoMusic.Play,Music.PlayFile,andMusic.Soundprocedures,whichmakesoundsthatcanbeturnedoffwithMusic.SoundOff.
named type
Syntax
AnamedTypeisoneof:
(a) typeId (b) moduleId.typeId
DescriptionAtypecanbegivenaname(typeId)andlaterthisnamecanbeusedinsteadofwritingoutthetype.
Example
Inthisexample,phoneRecordisanamedtype.
typephoneRecord:
record
name:string(20)
phoneNumber:int
address:string(50)
endrecord
…
varoneEntry:phoneRecord
varphoneBook:array1..100ofphoneRecord
Details
Form(a)isthemostcommonkindofnamedtype.Form(b)isusedwhenthetypenamehasbeenexportedfromamodule.
Arrayswhoseboundsarenotknownatcompiletimecannotbenamed.
nargs numberofarguments
Syntax nargs:int
Description
Thenargsfunctionisusedtodeterminethenumberofargumentsthathavebeenpassedtoaprogramfromthecommandline.Forexample,iftheprogramisrunfromtheTuringenvironmentusing
:rfile1file2
thennargswillreturn2.Ifaprogramcalledprog.xisrununderUNIXusingthiscommand:
prog.xfile1file2
thevalueofnargswillsimilarlybe2.
Thenargsfunctionisusuallyusedtogetherwiththefetchargfunctiontoaccesstheargumentsthathavebeenpassedtotheprogram.
Seealso fetchargforanexampleoftheuseofnargs.
nat naturalnumbertype
Syntax nat
Description
Thenat(naturalnumber)typehasthevalues0,1,2,3…Naturalnumberscanbecombinedbyvariousoperators,suchasaddition(+)andmultiplication(*).Naturalnumberscanbecombinedwithintegers(typeint),inwhichcasetheresultisaninteger.Naturalnumberscanalsobecombinedwithrealnumbers,inwhichcasetheresultisgenerallyarealnumber.Naturalnumberscanalwaysbeassignedtorealvariables,withimplicitconversiontoreal.
Example varcounter:nat
varj:nat:=9
SeealsoexplicitIntegerConstant.Thenattypeisusedinsteadofintwhenthevaluesareknowntobenon-negative.
TheTuringoperatorsonnaturalnumbersarethesameasthoseforintegers:+,-,*(multiply),div(truncatingintegerdivision),mod(integerremainder),**(exponentiation),aswellascomparisons(+,not=,>,>=,<,<=).Theoperatorsand,orandxortobeappliedtonaturalnumbervalues.Thebit-wisebooleanresultisproducedasanaturalnumber.Theshr(shiftright)andshl(shiftleft)operatorsarealsointroduced.
Inthecurrentimplementation,therangeofnaturalnumbersisfrom0to4294967294.Inotherwords,themaximumvalueofanaturalnumberis2**32-2.Thisrangeexistsbecausenaturalnumbersarestoredin4bytes.Thetypesnat1,nat2andnat4specifynaturalnumbersthatfitinto1,2or4bytes.
Explicitconstantssuchas213and0areconsideredtobeintegers.Asaresultthetypeoftaxinthisdeclarationisint:
vartax:=0%Thetypeisint
Naturalnumbervaluescanbeusedwheneverintegervaluesare
Details
expectedandviceversa,giventhatthevaluedoesnotexceedtherangeoftheexpectedtype.
Whenintegerandnaturalnumbersarecombinedusingabinaryoperatorsuchas+,theresultisaninteger.Thismeans,forexample,thatifcounterisanaturalnumber,counter+1isconsideredtobeaninteger.Aslongastheresultfitsintotherangethatistheintersectionoftherangesofintandnat,theresultwillbeasexpected.Anomaliesoccurwhentheresultis(orwouldbe)greaterthanthelargestinteger(maxint=2147483647).Forexample,ifnaturalnumbernisgreaterthanmaxint,theexpressionn+1willoverflow,becauseitsresultisanint(because1isanint).Toavoidthisproblem,youmustbecarefulthatbothoperandsarenaturalnumbers.
Supposewehavethisdeclaration:
constnatOne:nat:=1
Wecansafelycomputen+natOnebecausebothoperandshavetypenat.
Naturalnumberscanbeconvertedtorealnumbersusingnatreal,butinpracticethisisrarelyused,becauseanaturalvalueusedinplaceofarealvaluewillbeautomaticallyconvertedtoreal.
Naturalnumberscanbeconvertedtostringsandbackusingnatstrandstrnat.
IntheClanguage,anaturalnumberissaidtobe"unsigned".
Seealso maxnat,int,natn,intn,natstr,strnatandnatreal.
natn n-bytenaturalnumbertype
Dirty
Syntax (a) nat1 %1-bytenaturalnumber (b) nat2 %2-bytenaturalnumber (c) nat4 %4-bytenaturalnumber
Description
Thenatn(n-bytenaturalnumber)typesaremachine-dependenttypesthatoccupyaspecifiednumberofbytes.Bycontrast,thenattypeisinprincipleamachine-independentandmathematicaltype(itoverflows,however,whenthevalueistoolargeorsmall,thatis,whenthevaluedoesnotfitinto4bytes).
Examplevarcounter1:nat1%Rangeis0..255
varcounter2:nat2%Rangeis0..65536
varcounter4:nat4%Rangeis0..4294967295
Details
InTuring,therangeofthenatis0to4294967294,whichmeansthatthenat4typeallowsonemorevalue,4294967295.Thisextravalueisusedinnattorepresentthestateofbeinguninitialized.Thenatntypesallowuseofallpossiblevaluesthatfitintonbytesandtherebyeliminatescheckingforinitialization.
ThenatntypesareliketheClanguagetypesshortunsigned,unsigned,andlongunsigned,exceptthatthenumberofbytesoccupiedbytheCtypesdependsontheparticularCcompiler.
Seealsotheintntypeswhicharenbyteintegervalues.Seealsonatandint.
natreal naturalnumbertorealfunction
Syntax natreal(n:nat):real
Description
Thenatrealfunctionisusedtoconvertanaturalnumbertoarealnumber.Thisfunctionisrarelyused,becauseinTuring,anaturalnumbercanbeusedanyplacearealvalueisrequired.Whenthisisdone,thenatrealfunctionisimplicitlycalledtodotheconversionfromnattoreal.Thenatrealfunctionissimilartointreal,exceptthatnatrealhandlesvaluesthatarelargerthanintvaluesanddoesnothandlenegativevalues.
Seealso nat.Seealsotheintreal,floor,ceilandroundfunctions.
natstr natural-number-to-stringfunction
Syntax natstr(n:nat[,width:int[,base:int]]):string
Description
Thenatstrfunctionisusedtoconvertanaturalnumbertoastring.Thestringisequivalentton,paddedontheleftwithblanksasnecessarytoalengthofwidth,writteninthegivennumberbase.Forexample,natstr(14,4,10)="bb14"wherebrepresentsablank.Thewidthandbaseparametersarebothoptional.Ittheyareomitted,thestringismadejustlongenoughtoholdthevalueandthenumberbaseis10.Forexample,natstr(23)="23".
Thewidthparametermustbenon-negative.Ifwidthisnotlargeenoughtorepresentthevalueofi,thelengthisautomaticallyincreasedasneeded.
Thestringreturnedbynatstrisoftheform:
{blank}digit{digits}
where{blank}meanszeroormoreblanksanddigit{digit}meansoneormoredigits.Theleftmostdigitiseithernon-zero,orasinglezerodigit;inotherwords,leadingzerosaresuppressed.
ThelettersA,B,C…areusedtorepresentthedigitvalues10,11,12,…Thebasemustbeintherange2to36(36becausetherearetendigitsand26letters).Forexample,natstr(255,0,16)="FF".
Thenatstrfunctionistheinverseofstrnat,soforanynaturalnumbern,strnat(natstr(n))=n.
Seealso
chr,ordandstrnatfunctions.Seealsotheintstrandstrintfunctions.SeealsoexplicitIntegerConstantforthewaytowritevaluesinbase2andbase16inaprogram.
Net
Description
TheNetmoduleallowsTCP/IPequippedmachinestocommunicate.Inthecurrentimplementation(WinOOT3.0),thisisavailableonlyunderWin32(Windows95,98,NTandlater).
Toallowtwomachinestocommunicate,theremustbeaserver(whichcallsNet,WaitForConnection)andaclient(whichcallsNet.OpenConnection).Theserverwaitsuntilaclientconnectsandthenstartscommunicationbetweenthetwo.Whenaconnectionisestablished,anetstreamisreturnedthatcanbeusedinthesamefashionasafilestream(i.e.usingputsandgets).Oncetheconnectionisfinished,theprogramscallNet.CloseConnection.
Foreaseofreadingwebpages,theNet.OpenURLConnectionopensupaURLforreadingwiththegetstatement.ItisuptotheuserprogramtointerprettheHTMLorfilelocatedattheURL.
AllsubprogramsintheNetunitareexportedqualified(andthusmustbeprefacedwith"Net.").
EntryPoints
WaitForConnection Waitsuntilaclientconnectstoaspecifiedport.
OpenConnection Opensaconnectiontoaspecifiedmachine.
OpenURLConnection OpensaconnectiontoafilespecifiedbyaURL.
CloseConnection Closesaspecifiedconnection.
BytesAvailable Returnsthenumberofbytesavailabletobereadfromanetstream.
CharAvailable Returnstrueifthereisacharacteravailabletobereadfromanetstream.
LineAvailable
Returnstrueifthereisalineoftextavailabletobereadfromanet
stream.
TokenAvailable Returnstrueifthereisatokenavailabletobereadfromanetstream.
HostAddressFromName Returnsahost'saddressgivenitshostname.
HostNameFromAddress Returnsahost'snamegivenitsaddress.
LocalAddress Returnsthehostnameofthelocalmachine.
LocalName ReturnstheTCP/IPaddressofthelocalmachine.
Net.BytesAvailable PartofNetmodule
Syntax Net.BytesAvailable(netStream:int):int
DescriptionReturnsthenumberofbytesavailableforreadingfromthenetstreamspecifiedbythenetStreamparameter.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.BytesAvailable,notbycallingBytesAvailable.
SeealsoNet.CharAvailable,Net.LineAvailable,andNet.TokenAvailable.
Net.CharAvailable PartofNetmodule
Syntax Net.CharAvailable(netStream:int):boolean
Description
ReturnstrueifacharacteriswaitingtobereadfromthenetstreamspecifiedbythenetStreamparameter.IfNet.CharAvailablereturnstrue,thenasinglecharactercanbereadfromthestreamwithoutblocking.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
ThefollowingprogramfragmentreadsacharacterfromnetStreamonlyifthereisonewaitingtoberead.
ifNet.CharAvailable(netStream)then
varch:char
get:netStream,ch
putch..
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.CharAvailable,notbycallingCharAvailable.
SeealsoNet.BytesAvailable,Net.LineAvailable,andNet.TokenAvailable.
Net.CloseConnection PartofNetmodule
Syntax Net.CloseConnection(netStream:int)
Description
ClosesanetworkconnectionmadewithNet.OpenConnectionorNet.WaitForConnection.Aftertheconnectionisclosed,thenetstreamcannotbeusedforanypurposeoneithersideoftheconnection.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
Thefollowingprogramfragmentconnectstoport5300onthemachinespecifiedbynetAddress,sendstheworkOKtoitandclosestheconnection.
netStream:=Net.OpenConnection(netAddress,chatPort
ifnetStream<=0then
put"Unabletoconnectto",netAddress
return
endif
put:netStream,"OK"
Net.CloseConnection(netStream)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.CloseConnection,notbycallingCloseConnection.
Seealso Net.OpenConnectionandNet.WaitForConnection.
Net.HostAddressFromName PartofNetmodule
SyntaxNet.HostAddressFromName(hostName:string):string
DescriptionReturnsthenumericTCP/IPaddressofthemachinewhosehostnameisspecifiedbythehostNameparameter.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
Thefollowingprogramprintsoutthehostnameofthecurrentmachine.
varhostName:string:="www.holtsoft.com"
put"Themachineaddressof",hostName,"is",
Net.HostAddressFromName(hostName)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.HostAddressFromName,notbycallingHostAddressFromName.
Seealso Net.HostNameFromAddress.
Net.HostNameFromAddress PartofNetmodule
SyntaxNet.HostNameFromAddress(hostAddr:string):string
DescriptionReturnstheTCP/IPhostnameofthemachinewhosenumericaddressisspecifiedbythehostAddrparameter.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
ThefollowingprogramprintsoutthehostnameofthemachinewhoseTCP/IPnumericaddressis"128.100.5.1".
varhostAddr:string:="128.100.5.1"
put"Themachinenameof",hostAddr,"is",
Net.HostNameFromAddress(hostAddr)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.HostNameFromAddress,notbycallingLocalName.
Seealso Net.HostAddressFromName.
Net.LineAvailable PartofNetmodule
Syntax Net.LineAvailable(netStream:int):boolean
Description
ReturnstrueifalineofinputiswaitingtobereadfromthenetstreamspecifiedbythenetStreamparameter.IfNet.LineAvailablereturnstrue,thenalineofinputcanbereadfromthestreamwithoutblocking.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
ThefollowingprogramfragmentreadsacharacterfromnetStreamonlyifthereisonewaitingtoberead.
ifNet.LineAvailable(netStream)then
varline:string
get:netStream,line:*
putline
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.LineAvailable,notbycallingLineAvailable.
SeealsoNet.BytesAvailable,Net.CharAvailable,andNet.TokenAvailable.
Net.LocalAddress PartofNetmodule
Syntax Net.LocalAddress:string
Description
ReturnstheTCP/IPnumericaddressofthemachinetheprogramisrunningon.Thenumericaddressisoftheformxxx.yyy.zzz.wwwwhereeachsegmentisanumberfrom0to255.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
ThefollowingprogramprintsouttheTCP/IPnumericaddressofthecurrentmachine.
put"Yourmachineaddressis",Net.LocalAddress
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.LocalAddress,notbycallingLocalAddress.
Seealso Net.LocalName.
Net.LocalName PartofNetmodule
Syntax Net.LocalName:string
DescriptionReturnstheTCP/IPhostnameofthemachinetheprogramisrunningon.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
Thefollowingprogramprintsoutthehostnameofthecurrentmachine.
put"Yourmachinenameis",Net.LocalName
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.LocalName,notbycallingLocalName.
Seealso Net.LocalAddress.
Net.OpenConnection PartofNetmodule
SyntaxNet.OpenConnection(netAddr:string,port:int):int
Description
AttemptstoopenaconnectiontoportspecifiedbytheportparameteronthemachinespecifiedbynetAddrparameter.Theremustbeaprogramlisteningtothatportfortheconnectiontobemade.InOOT,thisisdoneusingtheNet.WaitForConnectionfunction.
Ifsuccessful,Net.OpenConnectionreturnsanetworkstreamdescriptorwhichcanbeusedwiththeput,get,read,andwritestatementsandeoffunctiontosendandreceivedatatothelisteningprogram.ItisalsotheparameterusedfortheNet.CloseConnection,Net.BytesAvailable,Net.CharAvailable,Net.LineAvailable,andNet.TokenAvailablefunctions.
ThenetAddrparameterisastringspecifyingthenetaddressofthemachinetobeconnectedto.Thiscaneitherbethefullhostnameorthenumericaladdress.
Ingeneral,systemprogramlisteninonportswithnumbersbelow1024.Portnumbersabove1024aregenerallyavailableforusebyusercreatedprograms.
Theprogramwillwaitforanindeterminateamountoftimetomaketheconnection.Ifitfails,itwillreturnanon-positivevalue.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Thefollowingprogramimplementsa"Chat"program.Oneuserrunstheprogramontheirmachineasaserver,whichwaitsfor
Example
anothermachinetoconnecttoit.Theseconduserspecifiesthemachinetoconnecttoandthenconnects.Thetwocanthentypeateachother.
%The"Chat"program
constchatPort:int:=5055
varchoice:int
loop
put"Enter1torunchatserver"
put"Enter2torunchatsession"
put"Choice:"..
getchoice
exitwhenchoice=1orchoice=2
endloop
varnetStream:int
varnetAddress:string
ifchoice=1then
netStream:=Net.WaitForConnection(chatPort
else
put"Entertheaddresstoconnectto:"..
getnetAddress
netStream:=Net.OpenConnection(netAddress,
ifnetStream<=0then
put"Unabletoconnectto",netAddress
return
endif
endif
Draw.Cls
put"Connectedto",netAddress
varlocalRow:int:=2
varlocalCol:int:=1
varremoteRow:=maxrowdiv2
varremoteCol:int:=1
varch:char
View.Set("noecho")
loop
ifhaschthen
ch:=getchar
put:netStream,ch
ifch='\n'then
localRow:=localRowmod(maxrowdiv
localCol:=1
Text.Locate(localRow,localCol)
put""%Cleartoendofline
Text.Locate(localRow,localCol)
else
Text.Locate(localRow,localCol)
putch..
localCol+=1
endif
endif
ifNet.CharAvailable(netStream)then
get:netStream,ch
ifch='\n'then
remoteRow:=remoteRowmod(maxrowdiv
1+(maxrowdiv2)
remoteCol:=1
Text.Locate(remoteRow,remoteCol)
Text.Locate(remoteRow,remoteCol)
else
Text.Locate(remoteRow,remoteCol)
putch..
remoteCol+=1
endif
endif
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.OpenConnection,notbycallingOpenConnection.
Seealso Net.WaitForConnectionandNet.CloseConnection.
Net.OpenURLConnection PartofNetmodule
Syntax Net.OpenURLConnection(urlAddr:string):int
Description
AttemptstoopenahttpconnectiontoptheURL(UniversalResourceLocator)specifiedbytheurlAddr.
Ifsuccessful,Net.OpenURLConnectionreturnsanetworkstreamdescriptorwhichcanbeusedwiththegetstatementandeoffunctiontoreadthewebpagelocatedattheURL.
Theprogramwillwaitforanindeterminateamountoftimetomaketheconnection.Ifitfails,itwillreturnanon-positivevalue.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
Thefollowingprogramprintsoutthecontentsofthefilespecifiedbytheuser.
varurl:string
put"EntertheURLtoload:"..
geturl
varnetStream:int
varline:string
netStream:=Net.OpenURLConnection(url)
ifnetStream<=0then
put"Unabletoconnectto",url
return
endif
loop
exitwheneof(netStream)
get:netStream,line
putline
endloop
Net.CloseConnection(netStream)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.OpenURLConnection,notbycallingOpenURLConnection.
Seealso Net.CloseConnection.
Net.TokenAvailable PartofNetmodule
Syntax Net.TokenAvailable(netStream:int):boolean
Description
ReturnstrueifalineofinputiswaitingtobereadfromthenetstreamspecifiedbythenetStreamparameter.IfNet.TokenAvailablereturnstrue,thenasingletoken(charactersurroundedbywhitespace)canbereadfromthestreamwithoutblocking.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
Example
ThefollowingprogramfragmentreadsacharacterfromnetStreamonlyifthereisonewaitingtoberead.
ifNet.TokenAvailable(netStream)then
vartoken:string
get:netStream,token
puttoken
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.TokenAvailable,notbycallingTokenAvailable.
SeealsoNet.BytesAvailable,Net.CharAvailable,andNet.LineAvailable.
Net.WaitForConnection PartofNetmodule
SyntaxNet.WaitForConnection(port:int,varnetAddr:string):int
Description
Listensforaconnectionattheportspecifiedbytheportparameter.Whenanotherprogramconnectstotheport,thenthefunctionreturns.TheaddressoftheconnectingmachineisspecifiedinthenetAddrparameterandtheNet.WaitForConnectionreturnsanetworkstreamdescriptorwhichcanbeusedwiththeput,get,read,andwritestatementsandeoffunctiontosendandreceivedatatotheconnectingprogram.ItisalsotheparameterusedfortheNet.CloseConnection,Net.BytesAvailable,Net.CharAvailable,Net.LineAvailable,andNet.TokenAvailablefunctions.
InOOT,theconnectiontoaportismadewiththeNet.OpenConnectionfunction.
ThenetAddrparameterisastringspecifyingthenetaddressofthemachinethatconnectedtotheport.Itisthemachinesnumericaladdress.
Ingeneral,systemprogramlisteninonportswithnumbersbelow1024.Portnumbersabove1024aregenerallyavailableforusebyusercreatedprograms.
Theprogramwillwaitforindefinitelyforaconnectiontomadetotheport.
Details
TheNetmodulerequiresaTCP/IPstacktobeinstalledandoperatinginordertofunction.Itdoesnotcommunicateusinganyotherprotocols
ItispossibleforFirewallstointerferewiththeactionsoftheNetmodule,preventingconnectionsfromtakingplace.
SeeNet.OpenConnectionforanexampleof
Example Net.WaitForConnection.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingNet.WaitForConnection,notbycallingWaitForConnection.
Seealso Net.OpenConnectionandNet.CloseConnection.
new statement
Syntax
AnewStatementis:
new[collectionOrClassId,]pointerVariableReference
Description
Anewstatementcreates(allocates)anewelementandassignsitslocationtothepointervariable.Thiselementcanbeanobjectofacollectionorclassoravalueofatype.IfthecollectionOrClassIdisomitted,thechoiceofelementisdeterminedbythetypeofthepointer.Forexample,ifthepointeristoclassC,anobjectofclasswillbeallocated.
Example
Usingacollection,declarealistofrecordsandallocateonerecord.
varlist:collectionof
record
contents:string(10)
next:pointertolist%Shortform:next:^list
endrecord
varfirst:pointertolist%Shortform:var
newlist,first%Shortform:newfirst
Example
Usingaclass,createanobjectofthatclass.Theobjectislocatedbythe
classnode
exportvarnext,varname
name:string(25)
next:pointertonode%Shortform:next:^node
endnode
varstart:pointertonode%Shortform:varstart:^node
newnode,start%Shortform:newstart
Example
Usingarecordtype,declarealistofrecordsandallocateonerecord.
typeitem:
record
contents:string(10)
next:pointertoitem%Shortform:next:^item
endrecord
varfirst:pointertoitem%Shortform:var
newfirst
Details
Astheexamplesinthissectionshow,apointercanlocateoneofthreethings:anobjectofacollection,anobjectofaclassoravalueofatype.
Inthenewstatement,thecollectionOrClassIdcanbeomitted.Ifthepointerlocatesatype,itmustbeomitted.Thefreestatementisusedtodeallocateanelement.
Animportedclasscanhaveoneofitsobjectscreated(bythenewstatement)onlyiftheclassisimportedvar.
Ifthereisnomorespacetoallocateanelement,newwillsetthepointertobethevalue,andtheprogramwillcontinueexecuting.
IfthepointerlocatesclassCandCcontainsanimplementbylist,theobjectcreatedbynewistheinheritedobject(throughanynumberoflevelsofimplementpointer,however,remainsapointertoC.
TheformnewpisashortformfornewC,pwhenCistheclassorcollectiongiveninp'stype.
IfpisapointertoclassCandChasadescendant(expansion)classstatementcanbeusedtoallocateanobjectoftypeD,asin:
newD,p%AllocatesanobjectofclassD
IfDhasanimplementbyclause,theexpansioniscreated.
Details
Thenewstatementcanalsobeusedtoresizeaflexiblearray.Ifanarrayhasbeendeclaredflexibleusingthesyntax.
varname:flexiblearrayindexType{,indexType
Theindicesmayhavecompile-timeorrun-timeupperbounds(thelowerboundmustbecompile-time).Theupperboundscanbechangedbyusing:
newname,newUpper1{,newUpper2}
Theexistingarrayentrieswillretaintheirvalues,exceptthatanyindexmadesmallerwillhavethecorrespondingarrayentrieslost.Anyindexmadelargerwillhavethenewarrayentriesuninitialized(ifapplicable).
Additionally,theupperbound(bothinthedeclarationandthenewstatement)canbe
madeonelessthanthelowerbound.Thiseffectivelymakesanarraythatcontains0elements.Itcanlaterbeincreasedinsizewithanothernew.
Inthecurrentimplementation(1999),withamulti-dimensionalarraywithanon-zeronumberoftotalelements,itisarun-timeerrortochangeanybutthefirstdimension(unlessoneofthenewupperboundsisonelessthanthecorrespondinglowerbound,giving0elementsinthearray)asthealgorithmtorearrangetheelementmemorylocationshasnotyetbeenimplemented.
Currently,onlyvariablescanbedeclaredinthisform.Thereisnoflexiblearrayparametertype,althoughaflexiblearraycanbepassedtoanarrayparameterwith"*"astheupperbound.
Example Seearrayforanexampleofflexiblearrays.
Seealso
classandcollectiondeclarations,pointertype,freestatement,nilvalueandimplementbylist.
Forflexiblearrays,seealsoarrayandflexible.
nil pointertoacollection
Syntax nil[(collectionOrClassId)]
Description
Thenilpointerdoesnotlocateanyelement(object).Pointerslocateitemsincollections,classesandtypes.ThecollectionOrClassIdisoptional.
Thisnilpointerisdistinctfrompointerstoactualelements,anditcanbecomparedtothesepointers.Itisalsodistinctfromtheuninitializedpointervalue.
Example
Inthisexample,thepointercalledfirstissettothenilpointerofcollectionc,thatis,tonil(c).
varc:collectionof
record
name:string(50)
next:pointertoc
endrecord
varfirst:pointertoc:=nil(c)
Details
Seealsocollection,classandpointer.WhenniliswrittenwithoutthecollectionOrClassId,itcanbeassignedtoapointertoanycollection,classortype.
ThetypeofnilwithoutthecollectionOrClassIdiseffectivelyapointertoeveryClass,animaginaryclassthathasnoobjectsandisthedescendantofallclasses.Thisimpliesthatitcanbeassignedtoanyotherclasspointer,becauseitisadescendantofallclasses.
Turingallowsyoutowritenil(id)afteraforwarddeclarationofid(thenameofacollection,classortype)before(andafter)theresolutionoftheid.
not true/false(boolean)operator
Syntax not
DescriptionThenot(booleannegation)operatorproducestheoppositeofatrue/falsevalue.Forexample,not(x>y)isequivalenttox<=y.
Examplevarerror:boolean:=false
varsuccess:boolean
…
success:=noterror%successbecomestheoppositeoferror
Details
Thenotoperatortakestrueandproducesfalseandtakesfalseandproducestrue.Thenotoperatorcanbewrittenas~.Seealsothebooleantype,prefixoperators,andprecedenceofoperators.
Thenotoperatorcanbeappliedtosets.
objectclass ofapointer
Syntax objectclass(pointerExpn)
Description
Theobjectclassattributeisusedtofindtheclassofanobjectlocatedbyapointer.ThepointerExpnmustbeanexpressionthatisapointertoaclass.
Example
Seeclassforanexampleofclassesandinheritance,inwhichaclasscalledTextFileisinheritedbyaclasscalledDevice.TheDeviceclassaddsanewexportedprocedurecalledioCtl.Inthepresentexample,objectclassisusedtotesttomakesurethatthetextFilePtrcurrentlylocatesanobjectthatwascreatedasaDevice(orasadescendantofDevice).ThenotationDevice(textFilePtr)convertsthepointertobeapointertoaDevicesothatioCtlcanbecalled.
vartextFilePtr:^TextFile
…
ifobjectclass(textFilePtr)>=Devicethen
%CansafelytreatobjectasaDevice
Device(textFilePtr).ioCtl
…
endif
Details
Thisexampleusestheclasscomparisonoperator>=whichmeans"isadescendantof".Seeclass.
Youcanonlyuseobjectclassinclasscomparisons.Inparticular,objectclasscannotbeusedtodeclarepointers.Forexample,this:
varp:^objectclass(q)
isnotallowed.
opaque type
Description
WhenatypeTisexportedfrommodule,monitororclassMusingthekeywordopaque,thetypeM.Tisdistinctfromallothertypes.OpaquetypesareusedtoguaranteethatupdatestovaluesofthetypearedonewithinM.
Seealso
moduledeclarationsforanexampleofanopaquetypeusedtoimplementcomplexarithmetic.Seealsoequivalenceoftypesforthedefinitionofthetypematchingrulesforopaquetypes.
open filestatement
Syntax
AnopenStatementisoneof:
(a) open:fileNumberVar,fileName,ioCapability {,ioCapability} (b) open:fileNumberVar,argNum,ioCapability {,ioCapability}
Description
Theopenstatementconnectstheprogramtoafilesotheprogramcanperformoperationssuchasreadonthefile.Inform(a),theopenstatementtranslatesafileName,suchas"Master",toafilenumbersuchas5.Form(b),whichisless-commonlyused,opensafilewhosenameisgivenbyaprogramargument.Thisisdescribedbelow.
Thereadstatementusesthefilenumber,notthefilename,toaccessthefile.Whentheprogramisfinishedusingthefile,itdisconnectsfromthefileusingthestatement.EachioCapabilityisthenameofanoperation,suchasreadperformedonthefile.
Example
Thisprogramsillustrateshowtoopen,readandthencloseafile.
varfileName:string:="Master"%Nameoffile
varfileNo:int%Numberoffile
varinputVariable:string(100)
open:fileNo,fileName,read
…
read:fileNo,inputVariable
…
close:fileNo
TheopenstatementalwayssetsthefileNumbertoapositivenumber.Ifthefails(generallybecausethefiledoesnotexist),thefileNumberissettoanon-positivenumber.Itiswisetocheckthatthestreamnumberisgreaterthanzerobeforeusingitfurther.
AnioCapabilityisoneof:
get,put,read,write,seek,mod
Details
Afilecanbeaccessedusingonlythestatementscorrespondingtotheinput/outputcapabilitieswithwhichitwasopened.Note:tellisallowedonlyiftheopenisforseek.
TheopenstatementtruncatesthefiletolengthzeroiftheioCapabilitiesputorwritebutnotmod(whichstandsformodify).Inallothercases,theexistingfileintact.ThemodioCapabilityspecifiesthatthefileistobemodifiedwithoutbeingtruncated.Eachopenpositionstothebeginningofafile.Thereisnomechanismtodeleteafile.
Toopenforappendingtotheendofthefile,onehastoopenforseekwriteorputandthenseektotheendofthefile.Seetheseekstatement.
Mixedmodefiles,whichcombinegetandread(orputandwrite),aresupportedbysomeoperatingsystems,suchasUNIX,butnotbyothers,suchasMicrosoftWindows.
OnMicrosoftWindows,oneshouldnotethatopeningfilesinotherdirectoriesusesthebackslashcharacter.ThisisbecausethebackslashisaspecialcharacterinTuring(asin\tfortaband\nforanewline).Togetasinglebackslash,use\\.
e.g.open:f,"C:\\STUDENTS\\SMITH\\ACCT.DAT",
Form(b)ofthesyntaxallowsyoutoopenafilewhosenameisgivenasaprogramargumentonthecommandline.Forexample,underUNIX,thecommandline:
prog.xinfileoutfile
specifiestoexecuteprog.xwithprogramargumentsinfileandoutfiletheTuringprogrammingenvironment,theruncommandcanacceptprogramarguments.TheargNumberisthepositionoftheargumentonthecommandline.(Thefirstargumentisnumber1.)Thenameofthefiletobeopenedisthecorrespondingprogramargument.Ifthereisnosuchargument,orifthefilecannotbeopenedsuccessfully,fileNumberVariableissettozero.Seealsogivesthenumberofarguments,andfetcharg,whichgivesthen-thargumentstring.
Programargumentfilesreferencedbyargumentnumberandusedinorwritestatementsneednotbeexplicitlyopened,butareimplicitlyopenedwiththecapabilitycorrespondingtotheinput/outputstatementinwhichtheyarefirstused.(ThefileNumbergivesthenumberoftheargument.)
Theoperatingsystemstandardfiles(error,outputandinput)areaccessedusingfilenumbers0,-1,and-2,respectively(althoughthismaybesubjecttochange).Thesefilesarenotopenedexplicitly,butareusedsimplybyusingform(b)withthenumber.Bewareoftheanomalouscaseofafailedopenthatgivesyoufilenumber0.Asubsequentuseofthisnumberinaputwillproduceoutputthatgoestothestandarderrorstream,withnowarningthatthefileyouattemptedtoopenisnotactuallybeingused.
Toappendtoafile,thefilemustbeopenedwiththemodandseekthentheremustbeaseektotheendoffile.Forexample:
varstreamnumber:int
open:streamnumber,"myfile",put,mod,seek
seek:streamnumber,*
put:streamnumber,"Thisappearsattheendofthefile"
Thereisanolderandstillacceptableversionofopenthathasthissyntax:
open(varfileNumber:int,fileName:string,
Themodemustbe"r"(forget)or"w"(forput).
Details
ThepathnamespecifiedintheopenstatementandelsewherecanalwaysbeinUNIXformat(i.e.withforwardslashes,aninitialforwardslashindicatinganabsolutedirectory).OnthePC,absolutepathswouldhavetheform:
a:/dir1/dir2/filename
OntheMacintosh,theywouldhavetheform:
/volumename/directory1/directory2/filename
NotethatinadditiontotheUNIXpathformat,onthePC,youcanalwaysusestandardPCpathnotationandontheMacintosh,youcanusestandardMacintoshpathnotation.OntheMacintoshvolume,directoryandfilenamescanhavespacesinthem.
Allroutines(suchastheFileandDirmoduleroutines)willreturnfilesnamesinUNIXformat,regardlessofthemachinetheprogramisrunon.
Seealso close,get,put,read,write,seekandtellstatements.
or operator
Syntax AorB
Description
Theor(boolean)operatoryieldsaresultoftrueifatleastone(orboth)oftheoperandsistrue.orisashortcircuitoperator.Forexample,ifAistrueinAorBthenBisnotevaluated.
Examplevarsuccess:boolean:=false
varcontinuing:=true%thetypeisboolean
…
continuing:=continuingorsuccess
Details
continuingissettofalse,ifandonlyif,bothcontinuingandsuccessarefalse.SinceTuringusesshortcircuitoperators,oncecontinuingistrue,successwillnotbelookedat.
Theoroperatorcanbeappliedtonaturalnumbers.Theresultisthenaturalnumberthatisthebit-wiseoroftheoperands.Seenat(naturalnumber).
Seealso
boolean(whichdiscussestrue/falsevalues),explicitTrueFalseConstant(whichdiscussesthevaluestrueandfalse),precedenceandexpn(expression).
ord character-to-integerfunction
Syntax ord(ch:char):int
Description
Theordfunctionacceptsanenumeratedvalue,char,orastringoflength1,andreturnsthepositionofthevalueintheenumeration,orofthecharacterintheASCII(orEBCDICforIBMmainframes)sequence.Valuesofanenumeratedtypearenumberedlefttorightstartingatzero.Forexample,ord("A")is65.Theordfunctionistheinverseofchr,soforanycharacterc,chr(ord(c))=c.
Seealso chr,intstrandstrintfunctions.
parallelget parallelportfunction
Syntax parallelget:int
Description
TheparallelgetprocedureisusedonaPCtoreadthevalueofcertainpinsontheparallelport.ThisportcorrespondstotheMS-DOSdevice"LPT1".Thisprocedurecanbeusedtocontrolrobotsandperipherals.
Example
ThisprogramreadsandprintsthevaluesofthefivedatapinsofthePC'sparallelport.
constval:int:=parallelget%Readinthesetofpinvalues
put"Pin10is:",(valdiv64)mod2
put"Pin11is:",(valdiv128)mod2
put"Pin12is:",(valdiv32)mod2
put"Pin13is:",(valdiv16)mod2
put"Pin15is:",(valdiv8)mod2
Details
Thefivepinsthatareusedforparallelinputarepins10-15.Theparallelgetprocedurereturnsthesumof
64 Pin10high 128 Pin11high 32 Pin12high 16 Pin13high 8 Pin15high
Themodanddivoperatorscanbeusedtodeterminewhichpinsarehighorlow.
Seealsotheparallelputprocedureforadiagramofthepins.Thatprocedurevaluesontheparallelport.
parallelput parallelportprocedure
Syntax parallelput(p:int)
Description
TheparallelputprocedureisusedonaPCtosetthevaluesonthedatapinsontheparallelport.ThisportcorrespondstotheMS-DOSdevice"LPT1".Thisprocedurecanbeusedtocontrolrobotsandperipherals.
Example
Thisprogramsetsdatabit0,databit1andsoontodatabit7.
fori:0..7
parallelput(2**i)%Setdatabitiontheparallelport
put"Databit",i,"orPin",i+2,"hasjustbeenset"
endfor
Details
TheparallelputprocedureisusedtosettheeightdatabitsonthePC'sparallelport.Thesedatabits0-7correspondtopins2-9ontheparallelport.
Thevaluesenttoparallelputisthesumofthefollowing:
1 Databit0 16 Databit4 2 Databit1 32 Databit5 4 Databit2 64 Databit6 8 Databit3 128 Databit7
Forexample,thecommandparallelput(97)setsdatabits0,5and6high(97=1+32+64)andsetstheotherdatapinslow.Becausethereareonly8datapinsintheparallelport,thevaluepassedtoparallelputmustbefrom0to255.
Theparallelputprocedureisnotmeantforsendingastreamofcharacterstotheparallelport(forexample,ifyouwanttosendthestring"Hello"totheprinter).Ifyouwanttodothis,openthefile"LPT1"using
theopenstatementandputtothefile.
Seealsotheparallelgetfunction,whichisusedtoreadthevaluesofpinsontheparallelport.
paramDeclaration parameterdeclaration
Syntax
AparamDeclarationisoneof:
(a) [var]id{,id}:typeSpec (b) subprogramHeader
Description
Aparameterdeclaration,whichispartoftheheaderofaprocedureorfunction,specifiesaformalparameter(seealsoprocedureandfunctiondeclarations).Form(a)aboveisthemostcommoncase.Form(b)specifiesproceduresandfunctionsthatarethemselvespassedasparameters.
Example
procedureputTitle(title:string)
%Theparameterdeclarationis:title:string
puttitle
endputTitle
procedurex(vars:array1..*ofstring(*))
%Seteachelementofstothenullstring
fori:1..upper(s)
s(i):=""
endfor
endx
Details
Parameterstoaproceduremaybedeclaredusingvar,whichmeansthattheparametercanbechangedinsidetheprocedure.Forexample,sischangedintheprocedure.Ifaparameterisdeclaredwithoutvar,itcannotbechanged.(ThisdiffersfromPascal,wherenon-varparameterscanbechanged.)Parameterstofunctionscannotbedeclaredtobevar.
Parametersdeclaredvararepassedbyreference,whichmeansthatapointertothevalueispassedtotheprocedure,ratherthanpassingtheactualvalue.Thisimpliesthatinthecallp(a(i)),inwhicharrayelementa(i)ispassedtoprocedurep,achangetoiinpdoesnotchangetheelementreferredtobyp'sactualparameter.Everynon-scalar(notinteger,subrange,real,boolean,enumerated,pointerorthechartype)parameterispassedbyreferencewhetherornotitisdeclaredvar.Inallothercases(scalarnon-varparameters)theparameterispassedbyvalue(theactualvalueiscopiedtotheprocedure).
Theupperboundofanarrayorstringthatisaformalparametermaybespecifiedasanasterisk(*),asisdoneaboveforparametersinprocedurex.Thisspecifiesthatthesizeoftheupperboundisinheritedfromthecorrespondingactualparameter.Parametersdeclaredusingstararecalleddynamicparameters.
Thenamesoftheformalparametersmustbedistinctfromeachother,fromtheprocedureorfunctionname,andfrompervasiveidentifiers.However,theyneednotbedistinctfromnamesoutsideoftheprocedureorfunction.
Example
Findthezerooffunctionf.Thisexampleillustratesform(b),whichisaparameterthatisafunction.SeealsosubprogramHeader.
functionfindZero(functionf(x:real):real
left,right,accuracy:real):
presign(f(left))not=sign(f(right)
andaccuracy>0
varL:real:=left
varR:real:=right
varM:real
constsignLeft:=sign(f(left))
loop
M:=(R+L)/2
exitwhenabs(R-L)<=accuracy
ifsignLeft=sign(f(M))then
L:=M
else
R:=M
endif
endloop
resultM
endfindZero
Details
Form(b)ofparamDeclarationisusedtospecifyformalparametersthatarethemselvesproceduresorfunctions.Forexample,inthefindZerofunction,formalparameterthatisitselfafunction.Thesubprogramtypecanbeusedtoreplaceform(b).Inparticular,theheadertothefindZerofunctioncanbereplacedbythefollowingwithnochangeintheaction.Thenamesgandxservenopurpose,exceptasplaceholdersinthedeclarationoff.
functionfindZero(f:functiong(x:real):
left,right,accuracy:real):
Parametersthataredeclarednonvarshould,inprinciple,beconstant.
Details
Unfortunately,thereisananomaloussituationinwhichthesecanchange.Thisoccurswhentheparameterispassedbyreference,becauseitisanonscalarsuchasastring.Iftheactualparameterischangedwhilethesubprogramisexecuting,theformalparameterwillchangeaswell.
Youcanalsooptionallyusetheregisterkeywordtorequestthatthevariablebeplacedinamachineregister.Thischangesform(a)toallowtheoptionaluseoftheregisterkeyword.Thesyntaxforform(a)isactually:
[var][register]id{,id}:[cheat]typeSpec
Inthecurrent(1999)implementation,programsareruninterpretivelyusingpseudo-code,whichhasnomachineregisters,andtheregisterkeywordisignored.Seeregisterforrestrictionsontheuseofregisterparameters.
Theoptionalkeywordcheatmeansthattheparameterhasatypecheat.SeeAnyvariableorconstantnonscalar(inotherwords,itemspassedbyreference)canbepassedtoatypecheatparameter.Theinternalrepresentationwillbeinterpretedasavalueofthespecifiedtype.Thisisdangerousasitprovidesunconstrainedaccesstotheunderlyingcomputermemory.
Example
Thisprocedureoutputsthevaluesofnbytesstartingattheaddressofformalparametera,usingaparametertypecheat.
proceduredump(a:cheatarray0..10000ofnat1
fori:0..n-1
puti,a(i):4
endfor
enddump
vars:string:="abc"
dump(s,5)%Dumps5bytes,startingwith
pause statement
Syntax
ApauseStatementis:
pauseexpn
Description
Thepausestatementblockstheprogram(orjusttheprocessinthecaseofaconcurrentprogram)foragivennumberofsimulatedtimeunits.Theexpnmustbeanon-negativeintvaluegivingthenumberoftimeunits.Thisisanalogoustothedelaystatement,whichcausesblockingforagivenamountofrealtime(actualphysicaltime).
Theinterpretermaintainsacounterwhichitconsiderstobesimulatedtime.Theonlyexecutionthatcausesthiscountertoincreaseisthepausestatement.Theprocessexecutingthepauseisblockeduntilthecounterhascountedforwardthenumberofunitsgivenbyexpn.Allotherstatements(exceptwait)areconsideredtobeinfinitelyfast.Severalprocessescanbeexecutingpausestatementssimultaneously.
TheuseofsimulatedtimeallowsTuringtobeusedasasimulationlanguageinwhichthepausestatementsimulatesthepassageoftimeinthesimulatedsystem.
PC
Description
ThisunitcontainsthepredefinedsubprogramsthatdealwithdirectaccesstothehardwareundertheIBMPCarchitecture.
AllroutinesinthePCunitareexportedqualified(andthusmustbeprefacedwith"PC.").
EntryPoints
ParallelGet Returnsthevalueofthepinssetontheparallelport.
ParallelPut Setsthevaluesofthepinsontheparallelport.
PC.ParallelGet PartofPCmodule
Syntax PC.ParallelGet(port:int):nat1
Description
ThePC.ParallelGetfunctionisusedtoreadthevalueofcertainpinsonaparallelport.Theportisspecifiedwiththeportparameterwhichcanhavethevalue1,2or3correspondingto"LPT1","LPT2"and"LPT3".Thisprocedurecanbeusedtocontrolrobotsandperipherals.
Example
ThisprogramreadsandprintsthevaluesofthefivedatapinsofthePC'sparallelport.
%ReadinthesetofpinvaluesfromLPT1
constval:int:=PC.ParallelGet(1)
put"Pin10is:",(valdiv64)mod2
put"Pin11is:",(valdiv128)mod2
put"Pin12is:",(valdiv32)mod2
put"Pin13is:",(valdiv16)mod2
put"Pin15is:",(valdiv8)mod2
Details
Thefivepinsthatareusedforparallelinputarepins10-15.ThePC.ParallelGetprocedurereturnsthesumof
64 Pin10high 128 Pin11high 32 Pin12high 16 Pin13high 8 Pin15high
Themodanddivoperatorscanbeusedtodeterminewhichpinsarehighorlow.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPC.ParallelGet,notbycallingParallelGet.
PC.ParallelPutprocedureforadiagramofthepins.That
Seealso procedureisusedtosetthevaluesontheparallelport.
PC.ParallelPut PartofPCmodule
Syntax PC.ParallelPut(port:int,value:int)
Description
ThePC.ParallelPutprocedureisusedonaPCtosetthevaluesonthedatapinsontheparallelport.Theportisspecifiedwiththeportparameterwhichcanhavethevalue1,2or3correspondingto"LPT1","LPT2"and"LPT3".Thisprocedurecanbeusedtocontrolrobotsandperipherals.
Example
Thisprogramsetsdatabit0,databit1andsoontodatabit7.
fori:0..7
%SetdatabitionparallelportLPT2
PC.ParallelPut(2,2**i)
put"Databit",i,"orPin",i+2,"hasjustbeenset"
endfor
Details
ThePC.ParallelPutprocedureisusedtosettheeightdatabitsonthePC'sparallelport.Thesedatabits0-7correspondtopins2-9ontheparallelport.
ThevaluesenttoPC.ParallelPutisthesumofthefollowing:
1 Databit0 16 Databit4 2 Databit1 32 Databit5 4 Databit2 64 Databit6 8 Databit3 128 Databit7
Forexample,thecommandPC.ParallelPut(97)setsdatabits0,5and6high(97=1+32+64)andsetstheotherdatapinslow.Becausethereareonly8datapinsintheparallelport,thevaluepassedtoPC.ParallelPutmustbefrom0to255.
ThePC.ParallelPutprocedureisnotmeantforsendingastreamofcharacterstotheparallelport(forexample,ifyouwanttosendthestring"Hello"totheprinter).Ifyouwanttodothis,openthefile"LPT1"usingtheopenstatementandputtothefile.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPC.ParallelPut,notbycallingParallelPut.
SeealsoPC.ParallelGetfunction,whichisusedtoreadthevaluesofpinsontheparallelport.
pervasive declarationmodifier
Description
Whenavariable,constant,typeorsubprogramisdeclared,youcanspecifythatitistobepervasive,whichmeansthatitdoesnotneedtobeexplicitlyimportedintomodules,monitorsorclassesinthecurrentscope.Thekeywordcanbeabbreviatedasanasterisk(*).
Example
varpervasivecounter:int%Shortform:var*count:int
const*maxCounter:int:=100
procedure*p(x:real)
…
endp
DetailsThekeywordpervasiveisalsousedinexportlistsalongwiththekeywordunqualified.Seeexportlistfordetails.
Seealsovardeclaration,constdeclaration,proceduredeclaration,functionsubprogramheaderandexportlistforusesofpervasive.
Pic
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithtakingpicturesofpartofthescreen,displayingthemandmovingpicturesfromfiletoscreenandback.
AllroutinesinthePicunitareexportedqualified(andthusmustbeprefacedwith"Pic.").
EntryPoints
New Createsapicturefromaspecifiedportionofthescreen.
Draw Drawsapictureonthescreen.
DrawSpecial Drawsapictureonthescreenusingspecialeffects.
DrawSpecialBack Drawsapictureonthescreenwhilecontinuingexecutionusingspecialeffects.
Free FreesupthepicturecreatedbyusingNeworFileNew.
FileNew Createsapicturefromafileinanallowedformat.
Save Savesapictureasafileinanallowedformat.
ScreenLoad Displaysafileinanallowedformatonthescreendirectly.
ScreenSave Savesaspecifiedportionofthescreenasafileinanallowedformat.
Rotate Createsanewpicturebyrotatinganexistingpicture.
Scale Createsanewpicturebyscalinganexistingpicture.
Flip Createsanewpicturebyflippinganexistingpictureupside-down.
Mirror Createsanewmirror-imageofanexistingpicture.Createsanewpicturebyblending
Blend twoexistingpicturestogether.
Blur Createsanewpicturebyblurringanexistingpictures.
Width Returnsthewidthofapicture.Height Returnstheheightofapicture.
Frames Returnsthethenumberofframesinamulti-frameGIFfile.
FileNewFrames Createsanarrayofpicturesfromamulti-frameGIFfile.
DrawFrames Drawsaseriesofpicturesonthescreeninsequencewhilecontinuingexecution.
DrawFramesBack Drawsaseriesofpicturesonthescreeninsequence.
SetTransparentColor SetsthecolortobeignoredwhenusingpicMergemode.
SetTransparentColour SetsthecolortobeignoredwhenusingpicMergemode.
Pic.Blend PartofPicmodule
Syntax Pic.Blend(picID1,picID2,pct:int):int
Description
Pic.Blendisusedtocreateanewpicturebyblendingtwoidenticallysizedpictures.Theresultingpictureiscreatedbytakingpct%ofthefirstpictureandaddingitto(100-pct)%ofthesecondpicture.
Details
Notethattheblendedpictureisanewlycreatedpicture.Whenitisnolongerneeded,itsmemoryshouldbereleasedbyusingPic.Free.
Notethatifpctis100,thentheresultingpicturewillbeidenticaltois0,thentheresultingpicturewillbeidenticaltopicID2.
Example
Theprogramcreatestwoidenticallysizedpictures,blendsthemtogetheranddisplaysallthreepictures.Youcanvarytheblendpercentagetoobtaindifferentresults.
View.Set("graphics:340;140,nobuttonbar")
%Createtheoriginalpictures
varpic1,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
%Createnewpicturebyblending30%frompic1,70%frompic2
picBlended:=Pic.Blend(pic1,pic2,30)
%Drawthethreeimages
Pic.Draw(pic1,10,10,picCopy)
Pic.Draw(pic2,120,10,picCopy)
Pic.Draw(picBlended,230,10,picCopy)
OutputfromtheProgram
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.BlendBlend.
Pic.Blur PartofPicmodule
Syntax Pic.Blur(picID,blurAmount:int):int
Description
Pic.Blurisusedtocreateanewpicturebyblurringanexistingpicture.Theresultingpictureiscreatedbymixingpixelsinapicturewithpixelsadjacenttoit.AstheblurAmountincreases,theimagegrowsmoreandmoreblurry.
Details
Notethattheblurredpictureisanewlycreatedpicture.Whenitisnolongerneeded,itsmemoryshouldbereleasedbyusingPic.Free.
NotethatthisisafairlyCPUintensiveroutine.Onslowmachines,toasecondormorewhenblurAmountislarge.Insuchcases,itisbettertoprecomputethepicturesbeforestartingtheprogram.Thesecondexampleshowsthisbeingdone.
Example
Theprogramcreatesapictureandthenprogressivelyblursit.
View.Set("graphics:270;120,nobuttonbar")
%Createtheoriginalpicture
varf:=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)
varoldPic:int
oldPic:=Pic.New(0,0,maxx,maxy)
loop
varnewPic:int
%Createthenewpicturebyblurringtheoldpicture
newPic:=Pic.Blur(oldPic,10)
%Freetheoldpicturesowedon'trunoutofmemory
Pic.Free(oldPic)
Pic.Draw(newPic,0,0,picCopy)
delay(300)
oldPic:=newPic
endloop
Outputatstart Afterseveralloops
Execute
Execute
Byprecalculatingandsavingtheresultsoftheblurredpicture,youvisualeffectwhereanobjectseemstocomeintofocus.Theprogrambelowblursanimage,savingeachstep.Itthendrawstheimagesinreverseorder,makingitappearasiftheimageisbecomingsuccessivelysharper.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Blur,notbycallingBlur.
Pic.Draw PartofPicmodule
Syntax Pic.Draw(picID,x,y,mode:int)
Description
Pic.Drawisusedtodrawapictureonthescreen.Thepictureisdrawnwiththelowerleftcornerat(x,y).
Themodeparameterhasoneofthefollowingvalues:
picCopy Thisdrawsthepictureontopofwhatwasunderneath,obscuringitcompletely.
picXor
ThisdrawsthepictureXORingitwiththebackground.InDOS,youcanusethisfunctiontodoanimation.DrawinganobjectontopofitselfwithXORerasesitandrestoresthebackground.
picMerge
ThisdrawsthepicturelikepicCopyexceptthatanyoccurrenceofthebackgroundcolorinthepictureisnotdrawntothescreen.Thisallowsyoutodrawanirregularly-shapedobjectanddrawittothescreen.
picUnderMerge
Thisdrawsthepicture,butonlywherethebackgroundcolorwasdisplayedunderneathit.Theeffectofthisistomakethepictureappeartobedisplayedbehindthebackground.
Execute
IfthePic.Drawcallfails,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Details
DisplayModeswithPic.Draw
Example
Theprogramdrawsagraphiconthescreenandthenrepeatsit50timesinrandompositions.
varpicID:int
varx,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)
fori:1..50
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
Pic.Draw(picID,x,y,picCopy)
endfor
Pic.Free(picID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Draw,notbycallingDraw.
Seealso
View.Updateforinformationonhowtoproducesmoothanimation.
Pic.DrawSpecialforinformationonhowtomakepicturesappearusingspecialeffectssuchaswipesandslides.
Pic.DrawFramesforinformationonhowtodisplaymultipleframeimagessuchasareobtainedfromGIFfiles.
Pic.DrawFrames PartofPicmodule
Syntax
Pic.DrawFrames(picIds:array1..*ofint,x,y,mode:
numFrames,delayBetweenFrames:int,eraseAfterboolean)
Description
Pic.DrawFramesisusedtodrawasetofpicturesstoredinanarrayofpicturesaredisplayedoneatatime,andthereisadelayofdelayBetweenFramesmillisecondsbetweenframes.Thex,y,andmodeparametersarethesameasinPic.Draw.ThenumFramesparameterspecifiesthenumberofframestobedrawn(thepicIdsarraymustbeatleastthisbig).TheeraseAfterparameterspecifieswhetherthelastframeoftheanimationshouldbeleftontheRunwindowwhenthecallfinishes.IferaseAfterissettotrue,thenthebackgroundisrestoredafterthelastpicturehasbeendrawnanddelayBetweenFramesmillisecondshaspassed.
Details
GIFfilescancontainmultipleframes(pictures).AnimatedGIFsfunctionbyeachframeintheGIFoneafteranotherwithadelaybetweenthem.
TuringallowsuserstoloadmultipleframeGIFimagesintoaseriesintoanarrayusingthePic.FileNewFramesprocedure.TheusercandeterminehowmanyframesarefoundintheGIFfileusingPic.Frames.TheframescanbesequentiallydisplayedusingeitherPic.DrawFramesorPic.DrawFramesBackwhichdisplaytheimagesoneatatime.(Pic.DrawFramesreturnsimageshavebeendisplayed,Pic.DrawFramesBackreturnsimmediatelyallowingtheprogramtocontinueexecutionwhiletheframesarebeingdisplayed.
Pic.FramesisafunctionwhichreturnsthenumberofframesfoundintheGIF.itisusedonaGIFthatdoesnotcontainmultipleimages,oronanon-GIFimagefile,itreturns1.
TheprogramloadsamultipleframeGIFcalled"globe.gif"anddisplaysit.
%Determinethenumberofframesin"globe.gif"
varnumFrames:=Pic.Frames("globe.gif")
%Loadthepicture
vardelayTime:int
varpics:array1..numFramesofint
Example Pic.FileNewFrames("globe.gif",pics,delayTime)
Pic.DrawFrames(pics,10,10,picCopy,numFrames
fori:1..numFrames
Pic.Free(pics(i))
endfor
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.DrawFramesbycallingDrawFrames.
Seealso
Pic.FramesforinformationonhowtodeterminethenumberofframesinaGIFimage.
Pic.FileNewFramesforinformationonhowtoloadaGIFimagewithmultipleframesintoanarrayofints.
Pic.DrawFramesBackforinformationonhowtosequentiallydisplaytheimagesstoredinarrayofpictureswhilecontinuingtoexecutetheprogram.
Pic.DrawFramesBack PartofPicmodule
SyntaxPic.DrawFramesBack(picIds:array1..*ofint,x,y,mode numFrames,delayBetweenFrames:int,eraseAfter
Description
Pic.DrawFramesBackisverysimilartoPic.DrawFrames.TheonlyPic.DrawFramesBackreturnsimmediatelyafterbeingcalledandprogramexecutioncontinueswhiletheframesarebeingdrawn.Thisallowsyoutocontinuetodrawothergraphicsbeingdrawn.
Forexample,thisprocedureisnecessaryifyouwanttohavetwosetsofframesbeingdrawnsimultaneously.
Details
Ifyouarewishtohaveseveralsetsofimagesdisplayedatthesametime,youmustusePic.DrawFramesBacktodisplayeachsetofimagesbutthelastandthenusedisplaythelastsetsothatTuringwillwaituntiltheyarecompletedbefore
Ifyouwanttodrawthesamesetofframescontinuously,donotuse
fori:1..20
Pic.DrawFrames(pics,10,10,picCopy,10,50,false
%DonotusePic.DrawFramesBackinthepreviousstatement
endfor
Ifyoudo,Turingwillattempttoruneachofthecallsatthesametime,andtheanimationwillappeartoonlyrunonce.
Details
GIFfilescancontainmultipleframes(pictures).AnimatedGIFsfunctionbyeachframeintheGIFoneafteranotherwithadelaybetweenthem.
TuringallowsuserstoloadmultipleframeGIFimagesintoaseriesPic.FileNewFramesprocedure.TheusercandeterminehowmanyframesarefoundinusingPic.Frames.TheframescanbesequentiallydisplayedusingeitherPic.DrawFramesBackwhichdisplaytheimagesoneatatime.(Pic.DrawFramesimageshavebeendisplayed,Pic.DrawFramesBackreturnsimmediatelyallowingtheprogramtocontinueexecutionwhiletheframesarebeingdisplayed.
Pic.FramesisafunctionwhichreturnsthenumberofframesfoundintheGIF.thatdoesnotcontainmultipleimages,oronanon-GIFimagefile,
Example
TheprogramloadsamultipleframeGIFcalled"globe.gif"anddisplaysit.
%Determinethenumberofframesin"globe.gif"
varnumFrames:=Pic.Frames("globe.gif")
%Loadthepicture
vardelayTime:int
varpics:array1..numFramesofint
Pic.FileNewFrames("globe.gif",pics,delayTime)
fori:1..50
Pic.DrawFramesBack(pics,10,10,picMerge,
Pic.DrawFramesBack(pics,20+Pic.Width(pics(1)),10,
%All50iterationswillexecuteatonceifthenextcallis
%Pic.DrawFramesBack,andnotPic.DrawFrames
Pic.DrawFrames(pics,30+2*Pic.Width(pics(1)),10,
endfor
fori:1..numFrames
Pic.Free(pics(i))
endfor
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.DrawFramesDrawFrames.
Seealso
Pic.FramesforinformationonhowtodeterminethenumberofframesinaGIFimage.
Pic.FileNewFramesforinformationonhowtoloadaGIFimagewithmultipleframesintoanarrayofints.
Pic.DrawFramesBackforinformationonhowtosequentiallydisplaytheimagesstoredinarraypictureswhilecontinuingtoexecutetheprogram.
Pic.DrawSpecial PartofPicmodule
Syntax Pic.DrawSpecial(picID,x,y,mode,transition,duration:
Pic.DrawSpecialisusedtodrawapictureonthescreenwithaspecialeffectsuchasawipe,aslide,orafade-in.Thepictureisdrawnwiththelowerleftcorneratdurationspecifieshowlongthetransitionshouldtakeinmilliseconds.fade-incouldbespecifiedtolast1/2asecondbyusingadurationof500.
ThemodeparameteristhesameasinPic.Newandhasoneofthefollowingvalues:
picCopy Thisdrawsthepictureontopofwhatwasunderneath,completely.
picXor ThisdrawsthepictureXORingitwiththebackground.canusethisfunctiontodoanimation.DrawinganobjectontopofitselfwithXORerasesitandrestoresthebackground.
picMerge ThisdrawsthepicturelikepicCopyexceptthatanyoccurrenceofthebackgroundcolorinthepictureisnotdrawntothescreen.Thisallowsyoutodrawanirregularly-shapedobjectanddrawitto
picUnderMerge Thisdrawsthepicture,butonlywherethebackgrounddisplayedunderneathit.Theeffectofthisistomakethepictureappeartobedisplayedbehindthebackground.
Thetransitionparameterindicatesthespecialeffectandhasoneofthefollowingvalues:
picWipeLeftToRight
Thepictureappearsasasolidblackbarsweepsfromlefttoright,"revealing"thenewpictureasthescreenunderneathreplaced.
Inthepicturebelow,"toTuring"isreplacingthe"Welcome"underneathasthebarsweepsfromlefttoright.
picWipeLeftToRight-halfwaythrough
transition
picWipeRightToLeft,picWipeTopToBottom,picWipeBottomToTop
AspicWipeLeftToRight,exceptthebarsweepsindifferentdirections.
picWipeUpperLeftToLowerRight
Thepictureappearsasasolidblackbarsweepsfromtheupperleftcornerdowntothelowerright,"revealing"thenewpictureunderneaththepictureisreplaced.
Inthepicturebelow"toTuring"isreplacingthe"Welcome"underneathasthebarsweepsfromupper-lefttolower-right.
picWipeUpperLeftToLowerRight-halfwaythroughtransition
picWipeUpperRightToLowerLeft,picWipeLowerLeftToUpperRight,picWipeLowerRightToUpperLeft
AspicWipeLeftToRight,exceptthebarsweepsindifferentdirections.
picWipeCentreToEdge,picWipeCenterToEdge
Thepictureappearsinsideanexpandingblackoutlinedboxasitsweepsfromthecentreouttotheedges,"revealing"thenewscreenunderneaththepictureisreplaced.
Inthepicturebelow,"toTuring"isreplacingthe"Welcome"underneathastheboxexpandsfromthecentreout.
picWipeCentreToEdge-halfwaythroughtransition
picWipeLeftToRightNoBar,
Description
picWipeRightToLeftNoBar,picWipeTopToBottomNoBar,picWipeBottomToTopNoBarpicWipeUpperLeftToLowerRightNoBar,picWipeUpperRightToLowerLeftNoBar,picWipeLowerLeftToUpperRightNoBar,picWipeLowerRightToUpperLeftNoBar,picWipeCentreToEdgeNoBar,picWipeCenterToEdgeNoBar
Astheconstantsabove,expectthereisnobartomarkthesweepacross.Thebargenerallylooksbetterwhendisplayingofasimilarone.Nobarisusuallywhentheimagesarecompletelydifferent(asintwophotographs,andsoon).
picSlideLeftToRight
Thepicture"slidesin"fromtheleftasasolidblackbarsweepsfromlefttoright,"pushing"thescreenunderneathofftherightedgeofthedrawingarea.
Inthepicturebelow"toTuring"isreplacingthe"Welcome"originallypresent,"pushing"the"Welcome"totherightslidesinfromtheleft.
picSlideLeftToRight-halfwaythroughtransition
picSlideRightToLeft,picSlideTopToBottom,picSlideBottomToTop
AspicSlideLeftToRight,exceptthebarsweepsindifferentdirections.
picSlideLeftToRightNoBar,picSlideRightToLeftNoBar,picSlideTopToBottomNoBar,picSlideBottomToTopNoBar
Astheconstantsabove,expectthereisnobartomarkthesweepacross.Thebargenerallylooksbetterwhendisplayingofasimilarone.Nobarisoftenwhentheimagesarecompletelydifferent(asintwophotographs,andsoon).
Thepicture"grows"fromtheleftasasolidblackbarsweepsfromlefttoright,"squeezing"thescreenunderneathedgeofthedrawingarea.
picGrowLeftToRight
Inthepicturebelow"toTuring"isreplacingthe"Welcome"originallypresent,"squeezing"the"Welcome"totheright"grows"fromtheleft.
picGrowLeftToRight-halfwaythroughtransition
picGrowRightToLeft,picGrowTopToBottom,picGrowBottomToTop
AspicGrowLeftToRight,exceptthebarsweepsindifferentdirections.
picGrowCentreToEdge,picGrowCenterToEdge
Thepicture"grows"fromthecentreasaoutlinedblackboxsweepsfromoutward,replacingthescreenunderneath.
Inthepicturebelow"toTuring"isreplacingthe"Welcome"originallypresent,as"toTuring"growsforthecentre.
picGrowCentreToEdge-halfwaythroughtransition
picGrowLowerLeftToUpperRight
Thepicture"grows"fromthelower-leftcornerasaoutlinedblackboxsweepsrightandupward,replacingthescreen
Inthepicturebelow"toTuring"isreplacingthe"Welcome"originallypresent,as"toTuring""grows"fromthelower-left.
picGrowLowerLeftToUpperRight-halfwaythroughtransition
picGrowUpperLeftToLowerRight,picGrowLowerRightToUpperLeft,picGrowUpperRightToLowerLeft
AspicGrowLowerLeftToUpperRighttheboxsweepsindifferentdirections.
picGrowLeftToRightNoBar,picGrowRightToLeftNoBar,picGrowTopToBottomNoBar,picGrowBottomToTopNoBarpicGrowUpperLeftToLowerRightNoBar,picGrowLowerLeftToUpperRightNoBar,picGrowUpperRightToLowerLeftNoBar,picGrowLowerRightToUpperLeftNoBar,picGrowCentreToEdgeNoBar,picGrowCenterToEdgeNoBar
Astheconstantsabove,expectthereisnobartomarkthesweepacross.Thebargenerallylooksbetterwhendisplayingofasimilarone.Nobarisusuallywhentheimagesarecompletelydifferent(asintwophotographs,andsoon).
picFadeIn
Thepicture"fadesin"overtopoftheimageunderneathit.Attheendofthetransition,thenewimagecompletelyreplacestheimageunderneathit.
picFadeIn-halfwaythroughtransition
picBlend
Thistransitionissomewhatdifferentbecauseitdoesn'ttakeanytimetoexecute.picBlendcausesthenewimagetobeblendedwiththebackground.Thecanbeusedbyitself,inwhichcase,imageis70%thenewimage,30%theoldimage.Youcanalsoaddanumberfrom1to100topicBlend,inwhichcase,theblendiswhateverwasaddedfrom(1-100)ofimageovertopoftheoldimage.transitionofpicBlend+15woulddisplayanimagethatiscomposedof15%thenewimageand85%theoldimage.)
picBlend-redstarblendedwithbluecircle
Execute
Details
ThePic.DrawSpecialrequiresamoderatelyfastmachinetooperatesuccessfully(PentiumIIIorhigher).ThepicFadeInandpicBlendtransitionsdonotworkwellon8-bit(256color)displays.OnMicrosoftWindowsmachines,youcandeterminetheofthedisplay(thenumberofcolorsavailable)byselectingtheDisplayfromtheStartmenu.Youcanalsousethe
Config.Display(cdNumMaxColors)
functiontodeterminethebit-depthofthedisplay(anythingover256colorswillproduceacceptableresults).
Details
IfthePic.DrawSpecialcallfails,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramdrawsabluestaronthescreen,thenaredcircle,thenhavethetworeplaceeachotherwithavarietyoftransitions.
varredID,blueID:int
varx,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
Pic.DrawSpecial(blueID,50,50,picCopy,picWipeTopToBottom
Pic.DrawSpecial(redID,50,50,picCopy,picSlideLeftToRight
Pic.DrawSpecial(blueID,50,50,picCopy,picSlideTopToBottom
Pic.DrawSpecial(redID,50,50,picCopy,picFadeIn
Pic.DrawSpecial(blueID,50,50,picCopy,picBlend
Pic.Free(redID)
Pic.Free(blueID)
Execute
Execute
Thefollowingprogramdemonstrateseachofthedifferentspecialeffects,firstusingpicturescontainingtext,thenpicturesloadedfromphotographs,thenbothatonce.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.DrawSpecialDrawSpecial.
Seealso
Pic.Drawforinformationonthemeaningofthemodeargument.
Pic.DrawSpecialBackforinformationonhowtocontinueexecutingtheprogramwhileaspecialeffectisoccurring.Thisallowsonetoproduceseveralspecial
Pic.DrawSpecialBack PartofPicmodule
Syntax Pic.DrawSpecialBack(picID,x,y,mode,transition,duration
Description
Pic.DrawSpecialBackisverysimilartoPic.DrawSpecial.TheonlyPic.DrawSpecialBackreturnsimmediatelyafterbeingcalledandprogramexecutioncontinueswhilethespecialeffectcontinues.Thisallowsyoutocontinuetodrawothergraphicseffectiscontinuing.
Forexample,thisprocedureisnecessaryifyouwanttohavetwopicturesbeingdrawnusingspecialeffectssimultaneously.
Details
Ifyouarewishtohaveseveralimagesdisplayedatthesametimeusingspecialeffects,youmustusePic.DrawSpecialBacktodisplayalltheimagesbutthelastandthenusethelastimagesothatTuringwillwaituntilthespecialeffectsarecompletedbeforecontinuingexecution.
Ifyouwanttodrawtheseveralspecialeffectscontinuouslyoverthesamelocation,donotusePic.DrawSpecialBack.
Pic.DrawSpecial(pic1,10,10,picCopy,picWipeLeftToRight
Pic.DrawSpecial(pic2,10,10,picCopy,picFadeIn,1000)
Ifyoudo,Turingwillattempttoruneachofthecallsatthesametime,andmostofthespecialeffectswillnotbeseen.
Description
Pic.DrawSpecialBackisusedtodrawapictureonthescreenwithaspecialeffectsuchasawipe,aslide,orafade-in.NotethatalltheparametersareidenticaltotheparametersofThepictureisdrawnwiththelowerleftcornerat(x,y).Thedurationtransitionshouldtakeinmilliseconds.Forexample,afade-incouldbyusingadurationof500.
ThemodeparameteristhesameasinPic.Newandhasoneofthefollowingvalues:
picCopy Thisdrawsthepictureontopofwhatwasunderneath,
picXor ThisdrawsthepictureXORingitwiththebackground.functiontodoanimation.DrawinganobjectontopofitselfwithXORerasesandrestoresthebackground.
picMerge ThisdrawsthepicturelikepicCopyexceptthatanyoccurrenceofthebackgroundcolorinthepictureisnotdrawntothescreen.Thisallowsyouirregularly-shapedobjectanddrawittothescreen.
picUnderMerge Thisdrawsthepicture,butonlywherethebackgroundunderneathit.Theeffectofthisistomakethepictureappeartobedisplayedbehindthebackground.
SeePic.DrawSpecialforthelistofpossiblevaluesforthetransition
Details
ThePic.DrawSpecialBackrequiresamoderatelyfastmachinetooperatesuccessfully(PentiumIIIorhigher).ThepicFadeInandpicBlendtransitionsdonotworkwellon8-bit(256color)MicrosoftWindowsmachines,youcandeterminethebit-depthofthedisplay(thenumberofcolorsavailable)byselectingtheDisplaycontrolpanelfromtheStartmenu.
Config.Display(cdNumMaxColors)
functiontodeterminethebit-depthofthedisplay(anythingover256colorswillproduceacceptableresults).
DetailsIfthePic.DrawSpecialBackcallfails,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextual
Example
Theprogramdrawsabluestaronthescreen,thenaredcircle,thenreplaceeachsimultaneously,side-by-side.
varredID,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
Pic.DrawSpecial(blueID,160,10,picCopy,picWipeRightToLeftNoBar
Pic.DrawSpecialBack(blueID,10,10,picCopy,picSlideLeftToRightNoBar
Pic.DrawSpecial(redID,160,10,picCopy,picSlideRightToLeftNoBar
Pic.DrawSpecialBack(redID,10,10,picCopy,picGrowRightToLeftNoBar
Pic.DrawSpecial(blueID,160,10,picCopy,picGrowLeftToRightNoBar
Pic.DrawSpecialBack(blueID,10,10,picCopy,picWipeTopToBottomNoBar
Pic.DrawSpecial(redID,160,10,picCopy,picWipeTopToBottomNoBar
Pic.DrawSpecialBack(redID,10,10,picCopy,picFadeIn
Pic.DrawSpecial(blueID,160,10,picCopy,picFadeIn
Pic.Free(redID)
Pic.Free(blueID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.DrawSpecialBackDrawSpecialBack.
Seealso
Pic.Drawforinformationonthemeaningofthemodeargument.
Pic.DrawSpecialforinformationonhowtodrawspecialeffectsandwaitforcompletioneffect.
Pic.FileNew PartofPicmodule
Syntax Pic.FileNew(fileName:string):int
Description
Pic.FileNewisusedtoobtainapicturefromafile.ThePic.FileNewprocedureallocatesthememoryforthepicture,whichcanbeverylargeforpicturesoflargeareas.ThememoryisfreedupwhentheprogramcallsPic.FreewiththepictureID.ThepicturecanbeusedwiththePic.DrawandPic.Save.
ThefileNameparametermustgivetheformatofthefile:
GIFfiles "GIF:filename"or"filename.GIF" JPGfiles "JPG:filename"or"filename.JPG" BMPfiles "BMP:filename"or"filename.BMP"
DetailsVariousversionsofTuringcanconvertdifferentformatsoffiles.Turing4.1forWindowscanloadBMP,GIFandJPGfiles.
Details
For,multi-frameGIFfiles(GIFfilesthathaveseveralframesorpicturesandareusedforanimation),Pic.FileNewwillonlyloadthefirstframe.SeethePic.FileNewFramesandPic.Frameforinformationonloadinganddisplayingamulti-frameGIFfile.
Details
IfthePic.FileNewcallfails,thenitreturns0.AlsoError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramreadsagraphicfromthefilemypic.bmpandthendrawsit50times.
varpicID:int
varx,y:int
picID:=Pic.FileNew("mypic.bmp")
fori:1..50
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
Pic.Draw(picID,x,y,picCopy)
endfor
Pic.Free(picID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.FileNew,notbycallingFileNew.
Pic.FileNewFrames PartofPicmodule
SyntaxPic.FileNewFrames(pathName:string,varpicIDs:arrayint,vardelayTime:int)
Description Pic.FileNewFramesloadsmultiplepicturesstoredinasinglemultiframeGIFimagefileintoanarrayofintegers.
Details
GIFfilescancontainmultipleframes(pictures).AnimatedGIFsfunctionbydisplayingeachframeintheGIFoneafteranotherwithadelaybetweenthem.ThisdelaycanalsobespecifiedintheGIFfile.
Pic.FileNewFramesreadstheseriesofframesfromthemultiframeGIFfile,andturnseachframeintoapicture.ThepictureisthenassignedtoanelementinthepicIDsarray.Ifthearrayisnotlargeenough,thenanerroroccursandnoareloaded.
Pic.FileNewFramesalsoreadsthedelayspecifiedintheGIFfileandsetsdelayTimetothedelayinmilliseconds.NotethatmanymultipleframeGIFfilesdonotspecifyadelay,inwhichcasedelayTimewillbesetto0.
InordertodeterminethenumberofframesinmultipleframeGIFfile,youmustusethePic.Framesfunction.ThisreturnsanumberthatcanbeusedtodeclarethearraythatwillbepassedtoPic.FileNewFrames.
varnumFrames=Pic.Frames("mypic.gif")
varpics:array1..numFramesofint
vardelayTime:int
Pic.FileNewFrames("mypic.gif",pics,delayTime)
TheframescanbesequentiallydisplayedusingeitherPic.DrawFramesPic.DrawFramesBackwhichdisplaytheimagesoneatatime.(Pic.DrawFramesreturnsoncealltheimageshavebeendisplayed,Pic.DrawFramesBackreturnsimmediatelyallowingtheprogramtocontinueexecutionwhiletheframesarebeingdisplayed.
Details
GIFfilescanhaveatransparentcolor.Thiscolorwillbeaddedtothecolorpalette,ifnotalreadypresent.ThusyoumaynoticethatmaxcolorchangesaftercallingPic.FileNeworPic.FileNewFrames.TheGIFimagewillbebedisplayedwithoutthetransparentcolorifmodeparameterinanyofthePic.Draw...
proceduresissettopicMerge.
Details
Eachpictureisinthearrayhasbeenallocatedbythesystemandshouldbefreedseparatelyoncetheprogramisfinishedwiththepictures.Failingtodosocanuseupthesystem'smemory.
Example
TheprogramloadsamultipleframeGIFcalled"globe.gif"anddisplaysit.
%Determinethenumberofframesin"globe.gif"
%Createtheoriginalpicture
varnumFrames:=Pic.Frames("globe.gif")
%Loadthepicture
vardelayTime:int
varpics:array1..numFramesofint
Pic.FileNewFrames("globe.gif",pics,delayTime)
Pic.DrawFrames(pics,10,10,picCopy,numFrames
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.FileNewFramesnotbycallingFileNewFrames.
Seealso
Pic.FramesforinformationonhowtodeterminethenumberofframesinaGIFimage.
Pic.DrawFramesforinformationonhowtosequentiallydisplaytheimagesstoredinarrayofpictures.
Pic.DrawFramesBackforinformationonhowtosequentiallydisplaytheimagesstoredinarrayofpictureswhilecontinuingtoexecutetheprogram.
Pic.Flip PartofPicmodule
Syntax Pic.Flip(picID:int):int
Description
Pic.Flipisusedtocreateanewpicturebyflippingthepicturevertically.Theresultingpictureisexactlythesamesizeastheoriginal,exceptitappears“upside-down”.
DetailsNotethattheupside-downpictureisanewlycreatedpicture.Whenlongerneeded,itsmemoryshouldbereleasedbyusingPic.Free.
Example
Theprogramloadsapicturefromafile,flipsitandthendrawstheoriginalandtheupside-downimagesidebysideinawindowafterresizingthewindowtofitthetwopictures.
%Gettheoriginalpicture
varpic,newPic,width,height:int
pic:=Pic.FileNew("lighthouse.jpg")
newPic:=Pic.Flip(pic)
width:=Pic.Width(pic)
height:=Pic.Height(pic)
%Drawthetwoimages:originalandflipped
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
OutputfromtheProgram
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Flip,notbycallingFlip.
Pic.Frames PartofPicmodule
Syntax Pic.Frames(pathName:string):int
DescriptionPic.FramesisusedtodeterminethenumberofframesfoundinamultipleframeGIFfile.
Details
GIFfilescancontainmultipleframes(pictures).AnimatedGIFsfunctionbyeachframeintheGIFoneafteranotherwithadelaybetweenthem.
TuringallowsuserstoloadmultipleframeGIFimagesintoaseriesintoanarrayusingthePic.FileNewFramesprocedure.TheusercandeterminehowmanyframesarefoundintheGIFfileusingPic.Frames.TheframescanbesequentiallydisplayedusingeitherPic.DrawFramesorPic.DrawFramesBackwhichdisplaytheimagesoneatatime.(Pic.DrawFramesreturnsimageshavebeendisplayed,Pic.DrawFramesBackreturnsimmediatelyallowingtheprogramtocontinueexecutionwhiletheframesarebeingdisplayed.
Pic.FramesisafunctionwhichreturnsthenumberofframesfoundintheGIF.itisusedonaGIFthatdoesnotcontainmultipleimages,oronanon-GIFimagefile,itreturns1.
Example
TheprogramloadsamultipleframeGIFcalled"globe.gif"anddisplaysit.
%Determinethenumberofframesin"globe.gif"
varnumFrames:=Pic.Frames("globe.gif")
%Loadthepicture
vardelayTime:int
varpics:array1..numFramesofint
Pic.FileNewFrames("globe.gif",pics,delayTime)
Pic.DrawFrames(pics,10,10,picCopy,numFrames
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.FramescallingFrames.
Seealso
Pic.FileNewFramesforinformationonhowtoloadaGIFimagewithmultipleframesintoanarrayofints.
Pic.DrawFramesforinformationonhowtosequentiallydisplaytheimagesstoredinarrayofpictures.
Pic.DrawFramesBackforinformationonhowtosequentiallydisplaytheimagesstoredinarrayofpictureswhilecontinuingtoexecutetheprogram.
Pic.Free PartofPicmodule
Syntax Pic.Free(picID:int)
Description
Pic.FreeisusedtoreleasethememoryallocatedbyPic.New.ItfreesupthememoryallocatedtotheparameterpicID.ThismeansthatpicIDcannotbeusedinaorDraw.SaveprocedureafterPic.Freeiscalled.
Turinghasalimitednumberofpicturesthatareavailableatanyonetime(approximately1,000).Aprogramthatcontinuouslyallocatespictures(usingorPic.FileNew)willeventuallyfailifitdoesnotfreethepicturesusingwell,ifaprogramallocateshundredsofpicturesanddoesnotfreeanyofthem,thememorydevotedtothepictureswillnotbefreedandeventuallytheprogrammayexhaustthememoryonthemachine.
Details
IfPic.FreeispassedaninvalidpictureID,afatalerroroccurs.Iftheforother(non-fatal)reasons,Error.Lastwillreturnanon-zerovalueindicatingreasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Theprogramanimatesapicturemovingacrossabackground.Eachabouttomovetoanewlocation,apictureofthebackgroundatthatlocationistaken.Whenthepictureistobemovedtothenextlocation,thebackgroundpictureisdrawnovertopofthepicture,thus"erasing"it.ThePic.Freecommandfreesbackgroundpictureonceitisnolongerinuse.Withoutit,theprogramwoulduseupallthepictureidentifiersandcrashafteroneortwomovesacrossthewindow.
Theanimationintheexampleflickersslightly.SeeView.Updateforinformationontoproduceflicker-freeanimation.
varpicID,bgID:int
varx,y,c,direction:int
%Createthepicturebeingmoved
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)
%Createabackground
Example fori:1..1000
x:=Rand.Int(0,maxx)
y:=Rand.Int(0,maxy)
c:=Rand.Int(9,15)%Usebrightcolors
Draw.FillBox(x,y,x+30,y+30,c)
endfor
x:=1
y:=100
direction:=1
%Mainloop
loop
%Takeapictureofthebackground
bgID:=Pic.New(x,y,x+100,y+100)
Pic.Draw(picID,x,y,picCopy)%Drawthepicture
delay(20)%Delay20milliseconds
Pic.Draw(bgID,x,y,picCopy)%Drawthebackgroundoverthepicture
Pic.Free(bgID)%Freethebackground
ifx<=0or(x+100)>=maxxthen
direction:=-direction
endif
x+=direction
endloop
Execute
StatusExportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Free,notbycalling
Pic.Height PartofPicmodule
Syntax Pic.Height(picID:int):int
Description
Pic.HeightreturnsthewidthinpixelsofthepicturerepresentedbypicID.
ThisfunctionisoftenusedinconjunctionwithPic.WidthtoobtainthedimensionsofapictureloadedusingPic.FileNew.
Example
Theprogramdrawsloadsapicturefromthefilelighthouse.jpgandproceedstotiletheentirerunwindowwithcopiesofthepicture.
varpic:int:=Pic.FileNew("lighthouse.jpg")
varwidth:int:=Pic.Width(pic)
varheight:int:=Pic.Height(pic)
varx,y:int:=0
loop
exitwheny>maxy
loop
exitwhenx>maxx
Pic.Draw(pic,x,y,picCopy)
x:=x+width
endloop
x:=0
y:=y+height
endloop
OutputofExampleProgram
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Height,notbycallingHeight.
SeealsoPic.Widthtoobtainapicture'swidthandPic.FileNewtoloadapicturefromagraphicsfile.
Pic.Mirror PartofPicmodule
Syntax Pic.Mirror(picID:int):int
Description
Pic.Mirrorisusedtocreateanewpicturebyflippingthepicturehorizontally.Theresultingpictureisexactlythesamesizeastheoriginal,exceptitappearsasa“mirrorimage”.
Details
Notethatthemirror-imagedpictureisanewlycreatedpicture.Whenitisnolongerneeded,itsmemoryshouldbereleasedbyusingPic.Free.
Example
Theprogramdrawsacrescentonthescreen,takesapictureofitandthencreatesasecondpicturebymirror-imagingthecrescent.Itthendrawsboththeoriginalpictureandthemirror-imagedversion.
View.Set("graphics:210;125,nobuttonbar")
%Gettheoriginalpicture
varpic,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
%Drawthetwoimages:originalandflipped
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)
OutputfromtheProgram
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Mirror,notbycallingMirror.
Pic.New PartofPicmodule
Syntax Pic.New(x1,y1,x2,y2:int):int
Description
Pic.Newisusedtoobtainapictureofaportionofthescreen.ThePic.Newprocedureallocatesthememoryforthepicture,whichcanbeverylargeforpicturesoflargeareas.ThememoryisfreedupwhentheprogramcallsPic.FreewiththepictureID.ThepicturecanbeusedwiththePic.DrawandPic.Save.
Thepictureisofthescreenareadefinedbytherectangle(x1,y1)-(x2,y2).
Details
IfthePic.Newcallfails,thenitreturns0.AlsoError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
Theprogramdrawsagraphiconthescreenandthendrawsit50times.
varpicID:int
varx,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)
fori:1..50
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
Pic.Draw(picID,x,y,picCopy)
endfor
Pic.Free(picID)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.New,notbycallingNew.
Pic.Rotate PartofPicmodule
Syntax Pic.Rotate(picID,angle,x,y:int):int
Description
Pic.Rotateisusedtocreateanewpicturebyrotatinganalreadyexistingpicture.Rotationcaneitherbearoundaspecificpointinthepicture(oftenusedforrotatingapicureinplace)orjustageneralrotation.
Theangleisspecifiedindegrees.Therotationisdoneinacounter-clockwisedirection.TheoriginalpictureisnotmodifiedbythecalltoPic.Rotateandmuststillbefreedwhennolongerused.ThepictureproducedbyPic.Rotatemaybeadifferentsizethantheoriginalpicture.
The(x,y)pointisthepointaroundwhichtherotationistotakeplaceandisrelativetothepicturebeingrotated.Ifitisnotimportanttorotatethepictureinplace,xandyshouldbesetto-1,whichmakethenewpicturetheminimumsizerequiredtofittherotatedimage.
Details
ThePic.Rotatecommandcanfail,inwhichcaseitreturns0.TheError.LastMsgfunctioncanthenbeusedtoobtainmoreinformationaboutthefailure.
Details
Ifxandyaresettoapointinthepicture(ratherthan1),itispossibleforpartsoftheoriginalpicturetoberotatedofftheleftandbottomedgeofthenewpicture.ThisoccursbecausePic.Rotateguaranteesthatthepointspecifiedby(x,y)intheoriginalpicturewillbelocatedat(x,y)intherotatedpicture.Youcanavoidlosingpartsofthepicturebymakingcertainthereisamarginofbackgroundcolorontheleftandbottomsidesofthepicture.
Aswell,anypixelsintherotatedpicturethatwerenotpartoftheoriginalpicturearesettothebackgroundcolor.
Details
Rotationcanbeslowonoldermachines.Programsthatareusinganimationshouldcreateandstorealltherotatedimagesthatmaybeneeded.Oftenpicturesofanobjectatvariousanglesarestoredinanarray.
Example
Thisprogramdraws“Hello”onthescreenrotatedat0,45and90degrees.
View.Set("graphics:200;150,nobuttonbar")
varf:int:=Font.New("Serif:36")
Font.Draw("Hello",10,10,f,black)
varpic:int:=Pic.New(5,5,120,45)
varpic45:int:=Pic.Rotate(pic,45,-1,-1)
varpic90:int:=Pic.Rotate(pic,90,-1,-1)
Pic.Draw(pic45,5,50,picCopy)
Pic.Draw(pic90,150,5,picCopy)
OutputfromProgram
Execute
Example
Thisprogrammovesaspinning“Hello”aroundthescreen,bouncingitofftheedgesoftheoutputwindow.Noticethattheoriginalpicturecontainsadequatespaceontheleftandbottomsidestocontaintherotation.
View.Set("graphics:300;250,nobuttonbar")
varpic:array0..35ofint
varf:int:=Font.New("Serif:36")
constCTR: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
forangle:1..35
pic(angle):=Pic.Rotate(pic(0),angle*10,
endfor
varx:int:=CTR
vary:int:=CTR
vardx:int:=1
vardy:int:=1
loop
forangle:0..35
Pic.Draw(pic(angle),x-CTR,y-CTR
ifx+dx<CTRorx+dx>maxx-CTRthen
dx:=dx
endif
ify+dy<CTRory+dy>maxy-CTRthen
dy:=dy
endif
x+=dx
y+=dy
delay(50)
endfor
endloop
Execute
DetailsNotethattherotatedpictureisanewlycreatedpicture.Whenitisnolongerneeded,itsmemoryshouldbereleasedbyusingPic.Free
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Rotate,notbycallingRotate.
Pic.Save PartofPicmodule
Syntax Pic.Save(picID:int,fileName:string)
Description
Pic.Saveisusedtosaveapictureonthescreentoafile.
ThefileNameparametermustgivetheformatofthefile:
BMPfiles "BMP:filename"or"filename.BMP"
Details
VariousversionsofTuringcansavedifferentformatsoffiles.Turing4.1forWindowscansaveonlyBMPformatfiles,astheyareloss-lessandcanhandle24-bitdepthimages.
Details
IfPic.SaveispassedaninvalidpictureID,afatalerroroccurs.Ifthecallfailsforother(non-fatal)reasons,Error.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
TheprogramdrawsagraphiconthescreenandthensavesitasaBMPfile.
varpicID:int
varx,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)
ThefollowingtwoprogramssaveandloadafileinBMPformat.
%Programtosaveapictureinmypic.bmp
varpicID:int
varx,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)
Example %Programtoloadthepicturebackagainanddraw50copies
varpicID:int
varx,y:int
picID:=Pic.FileNew("mypic.bmp")
fori:1..50
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
Pic.Draw(picID,x,y,picCopy)
endfor
Pic.Free(picID)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Save,notbycallingSave.
Pic.Scale PartofPicmodule
Syntax Pic.Scale(picID,newWidth,newHeight:int):int
Description
Pic.Scaleisusedtocreateanewpicturebyscaling(resizing)analreadyexistingpicture.Rotationcaneitherbearoundaspecificpointinthepicture(oftenusedforrotatingapicureinplace)orjustageneralrotation.
ThenewWidthandnewHeightparametersarethedesiredwidthandheightofthenewpicture.ThenewWidthandnewHeightparametersmaybenegative,inwhichcasepictureismirrorimage(newWidthisnegative)orupside-down(newHeightnegative)andtheabsolutevaluesareusedforthenewwidthandheightvalues.
DetailsThePic.Scalecommandcanfail,inwhichcaseitreturns0.TheError.LastMsgfunctioncanthenbeusedtoobtainmoreinformationaboutthefailure.
Details
Creatingalargerpicturebyscalingasmallerpicturewillresultina"grainy"imagewitheachpixelbeingscaledupinto2or3pixels.Ingeneralimagequalityalargepictureisscaleddown.However,whenalargepictureisscaleddown,thinone-pixelwidelinescan"disappear".
Inordertoscaleapicturewhileretainingitsoriginalaspectratio,scalewithmultiplesoftheoriginalwidthandheight.ThewidthandheightofapicturecanbeobtainedusingPic.WidthandPic.Height.
Details
Scalingcanbeslowonoldermachines.Programsthatareusinganimationshouldcreateandstoreallthescaledimagesthatmaybeneeded.Oftenpicturesofanobjectatvarioussizesarestoredinanarray.
DetailsNotethatthescaledpictureisanewlycreatedpicture.Whenitisnolongerneeded,itsmemoryshouldbereleasedbyusingPic.Free.
Thisprogramdrawsasetofstarsscaledat50%,100%and150%onNotehowsomesingle-pixellinesareremovedwhenthepictureisscaleddown..
%The"Pic.ScaleExample"program.
constSTAR_SIZE:int:=70
varpic:int
Example
varnewPic:int
varpicWidth,picHeight:int
%Gettheoriginalpicture
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)
forx:1..3
fory:1..3
newPic:=Pic.Scale(pic,x*picWidthdiv
y*picHeightdiv2)
Pic.Draw(newPic,(x-1)*maxxdiv3+5,
(y-1)*maxydiv3+20,picCopy)
Pic.Free(newPic)
Draw.Text(realstr(x/2,0)+"x"+
(x-1)*maxxdiv3+5,(y
defFontID,black)
endfor
endfor
OutputfromProgram
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.ScaleScale.
Pic.ScreenLoad PartofPicmodule
Syntax Pic.ScreenLoad(fileName:string,x,y,mode:int)
Description
Pic.ScreenLoaddisplaysapicturefromafilestraighttothescreen.
ThefileNameparametermustgivetheformatofthefile:
JPGfiles "JPG:filename"or"filename.JPG" BMPfiles "BMP:filename"or"filename.BMP"
Thexandyparameterssetthelowerlefthandcornerofthepicture.
Themodeparameterhasoneofthefollowingvalues:
picCopy Thisdrawsthepictureontopofwhatwasunderneath,obscuringitcompletely.
picXOR
ThisdrawsthepictureXORingitwiththebackground.InDOS,youcanusethisfunctiontodoanimation.DrawinganobjectontopofitselfwithXORerasesitandrestoresthebackground.
picMerge
ThisdrawsthepicturelikepicCopyexceptthatanyoccurrenceofthebackgroundcolorinthepictureisnotdrawntothescreen.Thisallowsyoutodrawanirregularly-shapedobjectanddrawittothescreen.
picUnderMerge
Thisdrawsthepicture,butonlywherethebackgroundcolorwasdisplayedunderneathit.Theeffectofthisistomakethepictureappeartobedisplayedbehindthebackground.
VariousversionsofTuringcanconvertdifferentformatsoffiles.Turing4.1forWindowscanloadBMPfilesandJPGfiles.Unfortunately,duetostrictlyenforcedpatentsontheGIF
Details compressionalgorithm,TuringwillnotimplementimportationofGIFpicturesuntilthepatentsexpireinJune2004.
Details
Atthetimeofwriting,MacOOTsupportedonlyPICTfiles.Consultthereleasenotestofindoutwhichfileformatsarecurrentlysupported.
Details
IfthePic.ScreenLoadfails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
TheprogramdisplaysapictureonthescreenfromthePCXfilemypic.BMP.
Pic.ScreenLoad("mypic.bmp",0,0,picCopy)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.ScreenLoad,notbycallingScreenLoad.
Pic.ScreenSave PartofPicmodule
Syntax Pic.ScreenSave(x1,y1,x2,y2:int,fileName:string)
Description
Pic.ScreenSavesavesaportionofthescreenintoafileinaformatspecifiedbythefilename.
Thepicturesavedtothefileistheportionofthescreendefinedbytherectangle(x1,y1)-(x2,y2).
ThefileNameparametermustgivetheformatofthefile:
BMPfiles "BMP:filename"or"filename.BMP"
Details
VariousversionsofTuringcansavedifferentformatsoffiles.Turing4.1forWindowscansaveBMP.Unfortunately,duetostrictlyenforcedpatentsontheGIFcompressionalgorithm,TuringwillnotimplementsavingofGIFpicturesuntilthepatentsexpireinJune2004.
Details
IfthePic.ScreenSavefails,thenError.Lastwillreturnanon-zerovalueindicatingthereasonforthefailure.Error.LastMsgwillreturnastringwhichcontainsthetextualversionoftheerror.
Example
TheprogramdrawsagraphicandsavesitasaPICTfilecalleddraw.
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
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.ScreenSave,notbycallingScreenSave.
Pic.SetTransparentColor PartofPicmodule
Syntax Pic.SetTransparentColor(colorNumber:int)
Description
ThePic.SetTransparentColorproceduresetsthecolorinthepicturethatshouldbeconsideredtransparentwhenthepictureisdrawnusingthepicMergeorpicUnderMergemodes.Ifnocolorisspecified,thenthedefaultbackgroundcolor(colorbg,usuallywhite)isusedasthetransparentcolor.
Details
ThiscallisoftenusedwhendisplayingimagesthatwereoriginallystoredasGIFsandtranslatedintoanotherformat.ManyGIFshaveatransparentcolorthatcanbenon-white.Tousethiscall,youmustknowthecolornumberthatrepresentsthecolorintheimagethatistobetransparent.
Example
Thisprogramdisplaystwoimagesloadedfromthesamefile.Inthesecondimage,thetransparentcolorhasbeensettobrightred(thatis,thepartsoftheimagethataremeanttobetransparentareinbrightred).
varpic1:int:=Pic.FileNew("airplane.bmp")
varpic2:int:=Pic.FileNew("airplane.bmp")
Pic.SetTransparentColor(pic2,brightred)
setscreen("offscreenonly")
forx:100..maxx-100
cls
put"Thelowerimagehasthetransparentcolorsettobrightred"
Pic.Draw(pic1,x,150,picMerge)
Pic.Draw(pic2,x,50,picMerge)
View.Update
delay(5)
endfor
Execute
Pic.SetTransparentColourisanalternatespellingfor
Details Pic.SetTransparentColor.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.SetTransparentColor,notbycallingSetTransparentColor.
Seealso Pic.DrawandPic.FileNew.
Pic.Width PartofPicmodule
Syntax Pic.Width(picID:int):int
Description
Pic.WidthreturnsthewidthinpixelsofthepicturerepresentedbypicID.
ThisfunctionisoftenusedinconjunctionwithPic.HeighttoobtainthedimensionsofapictureloadedusingPic.FileNew.
Example
Theprogramdrawsloadsapicturefromthefilelighthouse.jpgandproceedstotiletheentirerunwindowwithcopiesofthepicture..
varpic:int:=Pic.FileNew("lighthouse.jpg")
varwidth:int:=Pic.Width(pic)
varheight:int:=Pic.Height(pic)
varx,y:int:=0
loop
exitwheny>maxy
loop
exitwhenx>maxx
Pic.Draw(pic,x,y,picCopy)
x:=x+width
endloop
x:=0
y:=y+height
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingPic.Width,notbycallingWidth.
SeealsoPic.Heighttoobtainapicture'sheightandPic.FileNewtoloadapicturefromagraphicsfile.
play procedure
Syntax play(music:string)
DescriptionTheplayprocedureisusedtosoundmusicalnotesonthecomputer.
ExampleThisprogramsoundsthefirstthreenotesoftheCscale.
play("cde")
Example
ThisprogramplaysfrommiddleCtooneoctaveabovemiddleCanddownagainin8thnotes.
play("8cdefgab>c")
play("<bagfedc")
Details
Theplayproceduretakesstringscontainingcharactersthatspecifynotes,rests,sharps,flatsandduration.Thenotesarethelettersatog(orAtoG).Arestisp(forpause).Asharpis+andaflatis-.Thedurationsare1(wholenote),2(halfnote),4(quarternote),8(eightnote)and6(sixteenthnote).Thecharacter>raisestothenextoctaveand<lowers.Forexample,thisisthewaytoplayCandthenCsharponeoctaveabovemiddleCwitharestbetweenthem,allinsixteenthnotes:play(">6cpc+").Blankscanbeusedforreadabilityandareignoredbyplay.
UndersomesystemssuchasUNIX,theplayproceduremayhavenoeffect.
Thecurrent(1999)implementationdoesnotsupportplay.
Seealso
theplaydonefunction,whichisusedtoseeifanotehasfinishedsounding.Seealsothesoundprocedure,whichmakesasoundofagivenfrequency(Hertz)andduration(milliseconds).
SeealsopredefinedunitMusic.
playdone function
Syntax playdone:boolean
DescriptionTheplaydonefunctionisusedtodeterminewhennotesplayedbytheplayprocedurehavefinishedsounding.
Example
ThisprogramsoundsthefirstthreenotesoftheCscaleandoutputs"Alldone"assoonastheyarefinished.Withouttheloop,themessagewouldcomeoutbeforethenotesarefinished.
play("cde")
loop
exitwhenplaydone
endloop
put"Alldone"
DetailsUndersomesystemssuchasUNIX,theplaydoneproceduremaybemeaningless.
Seealso
theplayprocedure.Seealsothesoundprocedurewhichmakesasoundofagivenfrequency(Hertz)andduration(milliseconds).
SeealsopredefinedunitMusic.
pointer type
Syntax ApointerTypeisoneof:
(a) [unchecked]pointertocollectionId %Shortform:^collectionId (b) [unchecked]pointertoclassId %Shortform:^classId (c) [unchecked]pointertotypeSpec %Shortform:^typeSpec
Description
Avariabledeclaredasapointertypeisusedtolocateanelementofacollectionorclassoravalueofatype.Thenewstatementcreatesanewelement(orvalue)andplacestheelement'slocationinapointervariable.Thefreestatementdestroysanelementlocatedbyapointervariable.
Example
Usingacollection,declarealistorrecordsandallocateonerecord.
varlist:collectionof
record
contents:string(10)
next:pointertolist
endrecord
varfirst:pointertolist
newlist,first
Example
Createacollectionthatwillrepresentabinarytree.
vartree:collectionof
record
name:string(10)
left,right:pointertotree
endrecord
varroot:pointertotree
newtree,root
tree(root).name:="Adam"
Usingaclass,createanobjectofthatclass.Theobjectislocatedbythe
Example
startpointer.ThenamefieldoftheobjectissettoEd.
classnode
exportvarnext,varname
name:string(25)
next:pointertonode%Shortform:next:^node
endnode
varstart:pointertonode%Shortform:varstart:^node
newnode,start%Shortform:newstart
node(start).name:="Ed"%Shortform:start->name:=
Forcollectionsandclasses,apointeriseffectivelyasubscript(anindex)forthatcollectionorclass.Pointerscanbeassigned,comparedforequalityandpassedasparameters.
Thekeywordspointertocanbereplacedbytheshortform^,asin
varfirst:^item
GivenapointerpthatlocatesanobjectofclassorcollectionC,theobjectisreferencedasC(p)orastheshortform^p.AfieldfoftheobjectisreferencedasC(p).for^p.forastheshortformp->f.Forexample,intheclassgivenabove,thenamefieldoftheobjectlocatedbythestartcanbesettoAliceby:
start->name:="Alice"
Pointerstotypesusethesamenotation,exceptthatpointerstotypesarenotallowedtousetheformtypeSpec(p).Seeclassforanexampleoftheuseofaclasswithpointers.
Thecarat^iscalledthedereferencingoperatorandhasthehighestprecedence.Forexample,in^p.a,thecaratappliestopandnottoapply^toallofp.a,useparentheses:^(p.a).Severalcaratscanappearinarow,forexample,
varr:^^int
declaresapointertoapointertoanintegerand^^risthenotationforreferencingtheinteger.
Areferencecannotbeginwithaleftparenthesis,butcanbesurroundedby^(…),asin^(q.b).Iffisaparameterlessfunctiondeclaredwithout
Details parenthesesthatreturnsapointer,theform^fcallsfbeforedereferencingthepointer.
Bydefault,allpointersarechecked.ThismeansthereisaruntimetesttomakesurethatreferencessuchasC(p)actuallylocateelements,i.e.,thatisinitialized,isnotnilandisnotdangling(locatinganobjectthathasbeenfreed).Thischeckingrequiresextraspace(theimplementationattachesatimestamptoeachpointerandobject)andtime.Inhigh-performanceprogramsinwhichthisextraspaceandtimearenotacceptable,thepointercanbedeclaredtobeunchecked.Whenthisisdone,theprogrambecomesdangerousanditistheprogrammer'sresponsibilitytomakesurethatallpointerusageisvalid.
Ifthisisnotthecase,theprogrambecomessusceptibletouncontrolledcrashes.
Checkedpointerscannotbeassignedtouncheckedpointersnorviceversa.However,youmay,atyourperil,useanimplementation-dependentcheat,toconvertacheckedpointertoauncheckedpointer,asin:
typecheckedPtr:^R
typeuncheckedPtr:unchecked^R
varc:checkedPtr%cisancheckedpointer
varu:uncheckedPtr%uisanunchecked
…
u:=cheat(uncheckedPtr,d)%Thisisatype
UncheckedpointersareequivalenttothepointersoftheClanguage,whichareinherentlyerrorproneandcausedifficulttolocatebugs.Anentirecollection(butnotaclass)canbedeclaredunchecked,inwhichcaseallofitspointersareimplicitlyunchecked.Seecollection.
Seealso
inheritlistsforadescriptionoftheassignabilityrulesforpointers.Seeclassesandcollectionsformoredetailsabouttheuseofpointers.Seealsonewandfreestatements.Seealsonil,objectclassandanyclass.
post assertion
Syntax
AnpostAssertionis:
posttrueFalseExpn
Description
Apostassertionisaspecialformofanassertstatementthatisusedinaprocedureorfunction.Itisusedtogiverequirementsthatthebodyoftheprocedureorfunctionissupposedtosatisfy.TheserequirementsaregivenbythetrueFalseExpn.Afterthebodyhasexecutedandjustbeforetheprocedureorfunctionreturns,thetrueFalseExpnisevaluated.Ifitistrue,alliswellandexecutioncontinues.Ifitisfalse,executionisterminatedwithanappropriatemessage.Seeassertstatementsandprocedureandfunctiondeclarationsformoredetails.Seealsopreandinvariantassertions.
Example
Thisfunctionissupposedtoproduceanintegerapproximationofthesquarerootofintegeri.Thepostconditionrequiresthatthisresult,whichiscalledanswer,mustbewithinadistanceof1fromthecorrespondingrealnumbersquareroot.
functionintSqrt(i:int)answer:int
prei>=0
postabs(answer-sqrt(i))<=1
…statementstoapproximatesquareroot…
endintSqrt
Details
Apostassertioncanalsobeusedinamodule,monitor,classorprocessdeclarationtomakesurethattheinitializationsatisfiesitsrequirements.
Seealso moduleandprocess.
pre assertion
Syntax
AnpreAssertionis:
pretrueFalseExpn
Description
Apreassertionisaspecialformofanassertstatementthatisusedatthebeginningofaprocedureorfunction.Itisusedtogiverequirementsthatthecalleroftheprocedureorfunctionsissupposedtosatisfy.TheserequirementsaregivenbythetrueFalseExpn.ThetrueFalseExpnisevaluated.Ifitistrue,alliswellandexecutioncontinues.Ifitisfalse,executionisterminatedwithanappropriatemessage.Seeassertstatementsandprocedureandfunctiondeclarationsformoredetails.Seealsopostandinvariantassertions.
Example
Thisfunctioncomputestheaverageofnvalues.Itspreconditionrequiresthatmustbestrictlypositive,toavoidthepossibilityofdividingbyzerowhencomputingtheaverage.
functionaverage(a:array1..*ofreal,n:
pren>0
varsum:real:=0
fori:1..n
sum:=sum+a(i)
endfor
resultsum/n
endaverage
DetailsApreassertioncanalsobeusedinamodule,monitor,classorprocessdeclarationtomakesurethatrequirementsforinitializationaremet.
Seealso moduleandprocess.
precedence ofoperators
Description
Turing'sprecedencerulesdeterminetheorderofapplyingoperatorsinanexpressionsuchas3+4*5.Theserulesstate,forexample,thatmultiplicationisdonebeforeaddition,sothisexpressionisequivalentto3+(4*5).
Parenthesizedpartsofanexpressionareevaluatedbeforebeingused.Forexample,in(1+2)*3,theadditionisdonebeforethemultiplication.
Theprecedencerulesaredefinedbythistable,inwhichoperatorsappearingearlierinthetableareappliedfirst.Forexample,multiplicationisappliedbeforeaddition:
(1) **,^,# (2) prefix+and- (3) *,/,div,mod,rem,shr,shl (4) infix+,-,xor
(5) <,>,=,<=,>=,not=,in,notin (6) not (7) and (8) or
(9) => (booleanimplication)
Operatorsappearingonasinglelineinthistableareappliedfromlefttoright.Forexample,abcisthesameis(ab)c.
Herearesomeexamplesillustratingprecedence,inwhichtheleftandrightexpressionsareequivalent:
1**2 (1**2) a+b*c a+(b*c) a*b/c (a*b)/c
borcandd bor(candd) x<yandy<z (x<y)and(y<z)
ThefinalexampleillustratesthefactthatinTuring,parenthesesarenotrequiredwhencombiningcomparisonsusingandandor.ThesewouldberequiredinthePascallanguage.
Thetypecheatoperator#isappliedaftersubscripting,subprogramcalling,dotting,and>.Forexample,ineachofthefollowing,#appliestotheentirereferencetotheright.
#a(i) #r.y #p->x
Thepointerfollowingoperator^isappliedbeforesubscripting,subprogramcalling,dotting,and->.Forexample,inthefollowing,^appliestoa,randp.
^a(i) ^r.y ^p->x
Useparenthesestoforce^toapplytomoreofthereference.Forexample,in^(a(i)),the^appliestoa(i).
Seealsoinfixandprefixoperators.Seetheint,real,string,boolean,set,enum,charandchar(n)types.
pred predecessorfunction
Syntax pred(expn)
Description
Thepredfunctionacceptsaninteger,character,oranenumeratedvalueandreturnstheintegerminusone,thepreviouscharacter,orthepreviousvalueintheenumeration.Forexample,pred(7)is6.
Example
ThispartofaTuringprogramfillsuparrayawiththeenumeratedvaluesred,yellow,green,red,yellow,green,etc.
typecolors:enum(green,yellow,red)
vara:array1..100ofcolors
varc:colors:=colors.red
fori:1..100
a(i):=c
ifc=colors.greenthen
c:=colors.red
else
c:=pred(c)
endif
endfor
Details Itisillegaltoapplypredtothefirstvalueofanenumeration.
Seealso succ,lowerandupperfunctions.
prefix operator
Syntax
AprefixOperatorisoneof:
(a) + %Integerandrealidentity
%(doesnotchangevalue)
(b) %Integerandrealnegation
(c) not %Not(Booleannegation)
(d) # %Typecheat
(e) ^ %Pointerfollowing
Description
Aprefixoperatorisplacedbeforeavalueoroperandtoproduceanothervalue.Forexample,ifthevalueofxisseven,then-xisnegativeseven.Therearealsoinfixoperatorssuchasmultiplication(*)andaddition(+),whichareplacedbetweentwovaluestoproduceathirdvalue.Seeinfixoperator.
The+andprefixoperatorscanbeappliedonlytonumericvalues(integer,realandnaturalnumbers).Thenotprefixcanbeappliedonlytotrue/false(boolean)values.Forexamplenot(x>y)isequivalenttox<=y.Thenotoperatorproducestruefromfalseandfalsefromtrue.
The#operatorsisatypecheat(seecheat),andthe^operatorispointerfollowing(seepointer).
Seealso
int,realandbooleantypes,aswellasprecedence(fortheorderofapplyingoperators)andinfixoperators.
procedure declaration
Syntax
AprocedureDeclarationis:
procedureid[(paramDeclaration{,paramDeclaration})]
statementsAndDeclarations endid
Description
Aproceduredeclarationcreates(butdoesnotrun)anewprocedure.Thenameoftheprocedure(id)isgivenintwoplaces,justafterprocedureandjustafterend.
Example
proceduregreetings
put"Helloworld"
endgreetings
greetings%ThisoutputsHelloworld
proceduresayItAgain(msg:string,n:int)
fori:1..n
putmsg
endfor
endsayItAgain
sayItAgain("Toot",2)%Tootisoutputtwice
proceduredouble(varx:real)
x:=2*x
enddouble
vary:real:=3.14
double(y)%Thisdoublesthevalueofy
Thesetofparametersdeclaredwiththeprocedurearecalledformalparameters.Inthedoubleprocedure,forexample,xisaformalparameter.Aprocedureiscalled(invoked)byaprocedurecallstatementwhichconsistsoftheprocedure'snamefollowedbytheparenthesizedlistofactualparameters(ifany).Forexample,double(y)isacallhavingyasanactualparameter.Ifthereareno
Details
parameters(seethegreetprocedureabove),thecalldoesnothaveparentheses.Thekeywordprocedurecanbeabbreviatedtoproc.
Ordinarily,aprocedurereturns(finishesandgoesbacktotheplacewhereitwascalled)byreachingitsend.However,thereturnstatementinaprocedurecausesittoreturnimmediately.Notethatreturncanalsobeusedinthemainprogramtocauseittohaltimmediately.
Onlyparametersdeclaredusingvarmaybechangedintheprocedure,forexample,xischangedinthedoubleprocedure.Theupperboundsofarraysandstringsthatareparametersmaybedeclaredtobeanasterisk(*).Thismeansthattheboundisthatoftheactualparameter.SeeparamDeclarationfordetailsaboutparameters.
Proceduresandfunctionscannotbedeclaredinsideotherproceduresandfunctions.
ThesyntaxofaprocedureDeclarationpresentedabovehasbeensimplifiedbyleavingouttheoptionalimportlist,precondition,initclause,postconditionandexceptionhandler.Thefullsyntaxis
procedure[pervasive]id
[([paramDeclaration{,paramDeclaration}])]
[:deviceSpecification]
[pretrueFalseExpn]
[initid:=expn{,id:=expn}]
[posttrueFalseExpn]
[exceptionHandler]
statementsAndDeclarations
endid
Aproceduremustbedeclaredbeforebeingcalled.Toallowformutuallyrecursiveprocedures,thereareforwarddeclarationsofprocedureswithlaterdeclarationofeachprocedurebody.Seeforwardandbodydeclarationsforexplanations.
importlist,precondition,initclause,postconditionandexceptionHandlerforexplanationsofthesefeatures.Seepervasiveforinformationonpervasiveprocedures.See
Seealso exceptionHandler.TheoptionaldeviceSpecificationisusedonlyinproceduresdeclaredinmonitorsandisusedtocreateaninterrupthandlingprocedure.Seemonitorfordetails.
procedureCall statement
Syntax
AprocedureCallis:
procedureId[([expn{,expn}])]
Description
Aprocedurecallisastatementthatcalls(invokesoractivates)aprocedure.Iftheprocedurehasparameters,aparenthesizedlistofexpressions(expns)mustfollowtheprocedure'sname(procedureId).
Example
proceduregreet
put"Hello"
endgreet
greet%Thisisacalltothegreetprocedure
proceduretimes(vari:int,factor:int)
i:=factor*i
endtimes
varj:int
times(j,4)%Multiplyjby4
Aparameterdeclaredintheheaderofaprocedureisaformalparameter.Forexample,iandfactoraboveareformalparameters.Eachexpressioninthecallisanactualparameter.Forexample,jand4aboveareactualparameters.
Ifaformalparameterisdeclaredusingvar,thentheexpressionpassedtothatparametermustbeavariablereference(soitsvaluecanpotentiallybechangedbytheprocedure).Thismeans,forexample,thatitwouldbeillegaltopassj+3asthefirstparametertotimes.Thevariablereferenceandtheformalparametermusthaveequivalenttypes(seeequivalencefordetails).
Eachactualparameterpassedtoanon-varformalparametermustbeassignabletothatparameter(seeassignabilityfordetails).SeealsoprocedureDeclaration.
Details InthisexplanationofprocedureCall,wehaveuptothispointignoredthepossibilityofproceduresexportedfrommodules,monitorsandclasses.IftheprocedureisbeingcalledfromoutsideofamoduleormonitorMfromwhichithasbeenexported,thesyntaxoftheprocedureCallis:
M.procedureId[([expn{,expn}])]
Inotherwords,themoduleormonitornameandadotmustprecedetheprocedure'sname.Iftheprocedureisbeingcalledfromoutsideofaclassfromwhichithasbeenexported,thesyntaxoftheprocedureCallisoneof:
(a)classId(p).procedureId[([expn{,expn
(b)p->procedureId[([expn{,expn}])]
Inthese,pmusttheapointervaluethatlocatesanobjectintheclass.Form(b)isashortformforform(a).
Seealso class.
process declaration
Syntax
AprocessDeclarationis:
processid[([paramDeclaration{,paramDeclaration}])]
statementsAndDeclarations endid
Description
Aprocessdeclarationismuchlikeaproceduredeclaration,butisactivatedbyaforkstatementratherthanbyacall.Theforkstatementstartsconcurrent(parallel)executionoftheprocesswhilethestatementsfollowingtheforkcontinuetoexecute.
Example
Thisprograminitiates(forks)twoconcurrentprocesses,oneofwhichrepeatedlyoutputsHiandtheotherHo.TheresultingoutputisanunpredictablesequenceofHi'sandHo'sasgreetingsexecutestwiceconcurrently,oneinstancewithwordsettoHiandtheotherwithwordsettoHo.
processgreetings(word:string)
loop
putword
endloop
endgreetings
forkgreetings("Hi")
forkgreetings("Ho")
Theprocessdeclarationcreatesatemplateforaprocess(aconcurrentactivity),whichisactivatedbyaforkstatement.
Aprocessdeclarationcanappearwhereveramoduledeclarationisallowedexceptthataprocessdeclarationisnotallowedinaclass.Thedeclarationsandstatementsinaprocessdeclarationarethesameasthoseinaprocedure.
SeeparamDeclarationfordetailsaboutparameters.Thereisananomalyinparameterstoprocesses,thatcanleadtoerrors.In
Details
particular,non-varparametersthatarenon-scalars(suchasstringsandarrays)arepassedbyreference.Theresultisthatthetargetofthereferencemaychangevaluewhiletheprocessisexecuting,whichinturnmeansthattheseeminglyconstantparameterisnotreallyconstant.Forexample,ifthestringvariableswerepassedtothegreetingsprocessandsubsequentlychanged,thevalueofgreetings'formalparameterwouldchange.
ThesyntaxofaprocessDeclarationpresentedabovehasbeensimplifiedbyleavingouttheoptionalstacksize(compileTimeExpn),importlist,precondition,initclause,postconditionandexceptionhandler.
Thefullsyntaxis:
process[pervasive]id
[([paramDeclaration{,paramDeclaration
[:compileTimeExpn]
[pretrueFalseExpn]
[initid:=expn{,id:=expn}]
[posttrueFalseExpn]
[exceptionHandler]
statementsAndDeclarations
endid
Seepervasiveforinformationonpervasiveprocesses.TheoptionalcompileTimeExpnfollowingtheparameterlist(ifany)isusedtospecifythenumberofbytesfortheprocess'stack.
Seealsoimportlist,precondition,initclause,postconditionandexceptionHandlerforexplanationsoftheseadditionalfeatures.
program a(main)program
Syntax
Aprogramis:
statementsAndDeclarations
DescriptionATuringprogramconsistsofalistofstatementsanddeclarations.
ExampleThisisacompleteTuringprogram.ItoutputsAlanM.Turing.
put"AlanM.Turing"
Example
ThisisacompleteTuringprogram.Itoutputsatriangleofstars.
varstars:string:="*"
loop
putstars
stars:=stars+"*"
endloop
Example
ThisisacompleteTuringprogram.ItoutputsHelloonceandGoodbyetwice.
proceduresayItAgain(what:string,n:int)
fori:1..n
putwhat
endfor
endsayItAgain
sayItAgain("Hello",1)
sayItAgain("Goodbye",2)
Details
Inaprogramtherecanbemanyunits(seeunit),oneofwhichistheprogram(calledthemainprogram),theothersofwhicharemodules,monitorsandclasses.Themainprogramisoptionallyprecededbyanimportlist,whichliststheunitsthatituses.
Seealso importlist.
put statement
Syntax
AputStatementis:
put[:fileNumber,]putItem{,putItem}[..]
Description
TheputstatementoutputseachoftheputItems.Usually,anewlineisstartedintheoutputafterthefinalputItem.Iftheoptionaldot-dot(..)ispresent,though,subsequentoutputwillbecontinuedonthecurrentoutputline.Withcharactergraphics,theomissionofdot-dotcausestheremainderoftheoutputlinetobeclearedtoblanks.
Ordinarily,theoutputgoestothescreen.However,ifthefileNumberispresent,theoutputgoestothefilespecifiedbythefilenumber(seetheopenstatementfordetails).Also,outputcanberedirectedfromthescreentoafile,inwhichcaseallputstatementswithoutafilenumberaresenttothefileinsteadofthescreen.
Example
varn:int:=5
put"Aliceowesme$",n
%Outputis:Aliceowesme$5
%Notethatnoextraspaceis
%outputbeforeanintegersuchasn.
Example
StatementOutputNotes
put2424
put1/100.1%Trailingzerosomitted
put100/1010%Decimalpointomitted
put5/31.666667%6fractiondigits
putsqrt(2)1.414214%6fractiondigits
put4.86*10**94.86e9%Exponentfor=1e6
put121:5bb121%Width5;bisblank
put1.37:6:3b1.370%Fractionwidthof3
put1.37:11:3:2bb1.370e+00%Exponentwidthof2
put"Say\"Hello\""Say"Hello"
put"XX":4,"Y"XXbbY%Blankshownasb
puttrueandfalsefalse%Putoutabooleanvalue
put1<2true%Putoutabooleanvalue
Example
Asingleblanklineisoutputthisway:
put""%Outputnullstringthennewline
Thisputstatementissometimesusedtocloseoffalinethathasbeenoutputpiecebypieceusingputwithdot-dot.
Details
ThegeneralformofaputItemisoneof:
(a) expn[:widthExpn[:fractionWidth[:exponentWidth]]] (b) skip
SeetheaboveexamplesforusesofwidthExpn,fractionWidthandexponentWidth.Fortheexactmeaningofthesethreewidths,seethedefinitionsofthefunctionsrealstr,frealstranderealstr.Theskipitemisusedtoendthecurrentoutputlineandstartanewline.
Details
Theputsemanticsallowput'sofenumvalues.Thevaluesprintedaretheelementnamesthemselves,casesensitive.Forexample:
typecolors:enum(red,green,blue)
varc:colors:=colors.red
putc%outputs"red"(withoutthequotes)
Details
Theputsemanticsallowput'sofbooleanvalues.Thevaluesprintedareeither“true”or“false”(withoutthequotes).Forexample:
varc:boolean:=trueorfalse
putc%outputs"true"(withoutthequotes)
quit failstatement
Syntax
AquitStatementis:
quit[guiltyParty][:quitReason]
Description
Thequitstatementcausesaprogram(orconcurrentprocess)tofail.Thefailure(calledanexception)eitherabortstheprogram(orprocess)orcausescontroltobepassedtoanexceptionhandler.
Example
IntheinputLinesprocedure,halttheprogramifendoffileisencounteredbeforethestring"stop"isread.Notethatareturnstatementintheprocedurewouldterminatetheprocedurebutnottheentireprogram.
varline:array1..50ofstring
procedureinputLines
vari:int:=0
loop
ifeofthen
put"Missing'stop'ininput"
quit%Haltentireprogram
endif
i:=i+1
getline(i)
exitwhenline(i)="stop"
endloop
endinputLines
inputLines
Inthesimplecase,theoptionalguiltyPartyandquitReasonareomitted.TheguiltyPartyoptionisusedtospecifythepositionoffailure.SeeexceptionHandlerforanexampleofaquitstatementusedinconjunctionwithahandler.Ahandler,whichislocatedatthebeginningofasubprogrambody,isgivencontrolwhenaquitisexecutedorafailure,suchasdivisionbyzero,occursinthesubprogram.
Details
TheguiltyPartyoptionisusedtodesignatethelocationofthefailure,forexample,totellthedebuggerwhatlineisconsideredtobethelocationofthefailure.AguiltyPartyisoneof:
(a) < (b) >
IfguiltyPartyisomitted,thefailureisconsideredtooccuratthequitstatement.Ifitis<,thefailureisconsideredtooccuratthecalltothepresentsubprogram.Forexample,ifthepresentsubprogramimplementssquarerootsqrtandispassedanegativeargument,itcanuse<tospecifythatthecallerprovidedafaultyargument.IfguiltyPartyis>,thismeansthefailurehasalreadyoccurredandisbeingpassedontothenexthandlerortothesystem.Tosummarize,thethreepossibilitiesfordesignatingthelocationofthefailureare:
(a) < Calleriscauseoffailure
(b) > Theexceptionbeinghandledisthecause.
(c) (omittedguiltyParty)Thepresentquitisthecause.
ThequitReasonisanintegerexpressionwhichisusedtoidentifythekindoffailure.Ifitisomitted,adefaultvalueischoseninthefollowingmanner.IfguiltyPartyisomittedoris<,thedefaultis1.IfguiltyPartyis>andanexceptionhandlerisactive,thedefaultisthequitReasonoftheexceptionbeinghandled.Ifnoexceptionisbeinghandled,thedefaultis1.Inthecaseofprogramabortion,theimplementationmaypassthequitReasontotheoperatingsystemorprogrammingenvironment.
Seealso exceptionHandler,returnandresult.
Rand
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwithrandomnumbers.
AllroutinesintheRandunitareexportedqualified(andthusmustbeprefacedwith"Rand.").
EntryPoints
Real Returnsarandomrealnumber.Int Returnsarandominteger.Reset Setstheseedinthedefaultsequencetoadefaultvalue.
Set Setstheseedinthedefaultsequencetoaspecifiedvalue.
Next Returnsarandomrealnumberfromasequence.Seed Setsaseedinasequence.
Rand.Int PartofRandmodule
Syntax Rand.Int(low,high:int):int
Description
TheRand.Intstatementisusedtocreateapseudo-randomintegerintherangelowtohigh,inclusive.Forexample,ifiisaninteger,afteri:=Rand.Int(i,1,10),iwouldhaveavaluesuchas7or2or10.
Example
Thisprogramsimulatestherepeatedrollingofasixsideddie.
loop
put"Rolled",Rand.Int(1,6)
endloop
Details
TheRand.Intstatementsetsitsparametertothenextvalueofasequenceofpseudo-randomintegersthatapproximatesauniformdistributionovertherangelow=i=high.Itisrequiredthatlow=high.
Eachtimeaprogramruns,Rand.Intusesadifferentpseudo-randomnumbersequence.Toalwaysgetthesamesequence(actually,tostartthesequenceatthesamepoint),usetheRand.Setprocedure.
Touseseveralsequencesofrepeatablepseudo-randomnumbersequences,usetheRand.SeedandRand.Nextprocedures.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRand.Int,notbycallingInt.
Seealso Rand.Real,Rand.Set,Rand.SeedandRand.Next.
Rand.Next PartofRandmodule
Syntax Rand.Next(seq:1..10):real
Description
TheRand.Nextprocedureisusedwhenyouneedseveralsequencesofpseudo-randomnumbers,andyouneedtobeabletoexactlyrepeatthesesequencesforanumberofsimulations.TheRand.Nextprocedureisthesameasrand,exceptseqspecifiesoneoftenindependentandrepeatablesequencesofpseudo-randomrealnumbers.
TheRand.Seedprocedureisusedtostartoneofthesesequencesataparticularpoint.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRand.Next,notbycallingNext.
Seealso Rand.Seed,Rand.Int,Rand.RealandRand.Next.
Rand.Real PartofRandmodule
Syntax Rand.Real:real
Description
TheRand.Realfunctionreturnsapseudo-randomnumberintherangezerotoone.Forexample,ifxisarealnumber,afterx:=Rand.Real,xwouldhaveavaluesuchas0.729548or0.352879.
Example
ThisprogramrepeatedlyandrandomlyprintsoutHiho,hihoorIt'sofftoworkwego.
loop
ifRand.Real>0.5then
put"Hiho,hiho"
else
put"It'sofftoworkwego"
endif
endloop
Details
TheRand.Realfunctionsetsitsparametertothenextvalueofasequenceofpseudo-randomrealnumbersthatapproximatesauniformdistributionovertherange0<r<1.
Eachtimeaprogramruns,Rand.Realusesadifferentpseudo-randomnumbersequence.Toalwaysgetthesamesequence(actually,tostartthesequenceatthesamepoint),usetheRand.Setprocedure.
Touseseveralsequencesofrepeatablepseudo-randomnumbersequences,usetheRand.SeedandRand.Nextprocedures.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRand.Real,notbycallingReal.
Seealso Rand.Int,Rand.Set,Rand.SeedandRand.Next.
Rand.Reset PartofRandmodule
Syntax Rand.Reset
Description
Thisisaprocedurewithnoparametersthatresetsthesequencesofpseudo-randomnumbersproducedbyRand.RealandRand.Int.Thisallowsidenticalexecutionsofthesameprogramtoproduceidenticalresults.
Example
Thisprogramsimulatestherepeatedrollingofasixsideddie.Eachtimetheprogramruns,thesamesequenceofrollsoccurs.
Rand.Reset
loop
put"Rolled",Rand.Int(1,6)
endloop
Details
IfRand.ResetandRand.Setarenotused,eachtimeaprogramrunsRand.RealandRand.Intuseadifferentpseudo-randomnumbersequence.Togetthesamesequenceeachtime(actually,tostartthesequenceatadifferentpoint),useRand.ResetorRand.Set.
TheRand.Resetprocedurecanbecalledanytime.However,tomakeitwork,itshouldonlybecalledonceperprogram.AnycalltoRand.Resetafterthefirstoneisignored.
Touseseveralsequencesofrepeatablepseudo-randomnumbersequences,usetheRand.SeedandRand.Nextprocedures.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRand.Reset,notbycallingReset.
Seealso Rand.Set,Rand.Int,Rand.Real,Rand.SeedandRand.Next.
Rand.Seed PartofRandmodule
Syntax Rand.Seed(seed:nat4,seq:1..10)
Description
TheRand.SeedprocedurerestartsoneofthesequencesgeneratedbyRand.Next.EachrestartwiththesameseedcausesRand.Nexttoproducethesamesequenceforthegivensequence.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRand.Seed,notbycallingSeed.
Seealso Rand.Next,Rand.Int,Rand.Real,andRand.Set.
Rand.Set PartofRandmodule
Syntax Rand.Set(seed:nat4)
Description
Thisproceduresetstheseedforsequencesofpseudo-randomnumbersproducedbyRand.RealandRand.Int.Thisallowsidenticalexecutionsofthesameprogramtoproduceidenticalresults.
Example
Thisprogramsimulatestherepeatedrollingofasixsideddie.Eachtimetheprogramruns,thesamesequenceofrollsoccurs.
Rand.Set(16#1234ABCD)
loop
put"Rolled",Rand.Int(1,6)
endloop
Details
IfRand.ResetandRand.Setarenotused,eachtimeaprogramrunsRand.RealandRand.Intuseadifferentpseudo-randomnumbersequence.Togetthesamesequenceeachtime(actually,tostartthesequenceatadifferentpoint),useRand.ResetorRand.Set.
Touseseveralsequencesofrepeatablepseudo-randomnumbersequences,usetheRand.SeedandRand.Nextprocedures.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRand.Set,notbycallingSet.
Seealso Rand.Reset,Rand.Int,Rand.Real,Rand.SeedandRand.Next.
rand randomrealnumberprocedure
Syntax rand(varr:real)
Description
Therandstatementisusedtocreateapseudo-randomnumberintherangezerotoone.Forexample,ifxisarealnumber,afterrand(x),xwouldhaveavaluesuchas0.729548or0.352879.
Example
ThisprogramrepeatedlyandrandomlyprintsoutHiho,hihoorIt'sofftoworkwego.
varr:real
loop
rand(r)
ifr>0.5then
put"Hiho,hiho"
else
put"It'sofftoworkwego"
endif
endloop
Details
Therandstatementsetsitsparametertothenextvalueofasequenceofpseudo-randomrealnumbersthatapproximatesauniformdistributionovertherange0<r<1.
Eachtimeaprogramruns,randusesadifferentpseudo-randomnumbersequence.Togetthesamesequence(useRand.Set).
Touseseveralsequencesofrepeatablepseudo-randomnumbersequences,usetherandseedandrandnextprocedures.
Inmanylanguages,randwouldbeafunctionratherthanaprocedure.IthasbeendesignedasaprocedureinTuringtorespectthemathematicalideathateverycalltoafunctionusingthesamearguments(ornoargumentsatall)shouldreturnthesamevalue.Ifrandwereafunction,thiswouldnotbetrue.
Seealsorandint,randomize,randseedandrandnext.
SeealsopredefinedunitRand.
randint randomintegerprocedure
Syntax randint(vari:int,low,high:int)
Description
Therandintstatementisusedtocreateapseudo-randomintegerintherangelowtohigh,inclusive.Forexample,ifiisaninteger,afterrandint(i,1,10),iwouldhaveavaluesuchas7or2or10.
Example
Thisprogramsimulatestherepeatedrollingofasixsideddie.
varroll:int
loop
randint(i,1,6)
put"Rolled",i
endloop
Details
Therandintstatementsetsitsparametertothenextvalueofasequenceofpseudo-randomintegersthatapproximatesauniformdistributionovertherangelow=i=high.Itisrequiredthatlow=high.
Eachtimeaprogramruns,randintusesthesamepseudo-randomnumbersequence.Togetadifferentsequence(actually,tostartthesequenceatadifferentpoint),usetherandomizeprocedure.
Touseseveralsequencesofrepeatablepseudo-randomnumbersequences,usetherandseedandrandnextprocedures.
Seealso rand,randomize,randseedandrandnext.
randnext procedure
Syntax randnext(varv:real,seq:1..10)
Description
Therandnextprocedureisusedwhenyouneedseveralsequencesofpseudo-randomnumbers,andyouneedtobeabletoexactlyrepeatthesesequencesforanumberofsimulations.Therandnextprocedureisthesameasrand,exceptseqspecifiesoneoftenindependentandrepeatablesequencesofpseudo-randomrealnumbers.
Therandseedprocedureisusedtostartoneofthesesequencesataparticularpoint.
Seealso randseed,randint,randandrandnext.
randomize procedure
Syntax randomize
Description
Thisprocedureisobsolete.Itwasoriginallyusedtoproduceadifferentsequenceofrandomnumberseachtimeaprogramexecuted.WithcurrentversionsofTuring,therandomnumbersequenceis“randomized”eachtimeaTuringprogramisexecuted,eliminatingtheneedforthisprocedure.
Toresettherandomnumbersequenceandthusallowforapredeterminedsequenceofpseudo-randomnumbers,useRand.Set.
Seealsorandint,rand,randseedandrandnext.
SeealsopredefinedunitRand.
randseed procedure
Syntax randseed(seed:int,seq:1..10)
Description
Therandseedprocedurerestartsoneofthesequencesgeneratedbyrandnext.Eachrestartwiththesameseedcausesrandnexttoproducethesamesequenceforthegivensequence.
Seealso randnext,randint,rand,andrandomize.
read filestatement
Dangerousparts
Syntax
AreadStatementis:
read:fileNumber[:status],readItem{,readItem}
Description
ThereadstatementinputseachofthereadItemsfromthespecifiedfile.Theseitemsareinputdirectlyusingthebinaryformatthattheyhaveonthefile.Inotherwords,theitemsarenotinsource(ASCIIorEBCDIC)format.Inthecommoncase,theseitemshavebeenoutputtothefileusingthewritestatement.
Bycontrast,thegetandputstatementsusesourceformat,whichapersoncanreadusinganordinarytexteditor.
Example
Thisexampleshowshowtoinputacompleteemployeerecordusingareadstatement.
varemployeeRecord:
record
name:string(30)
pay:int
dept:0..9
endrecord
varfileNo:int
open:fileNo,"payroll",read
…
read:fileNo,employeeRecord
ThefileNumbermustspecifyafilethatisopenwithreadcapability(oraprogramargumentfilethatisimplicitlyopened).
Theoptionalstatusisanintvariablethatissettoimplementation-dependentinformationabouttheread.Ifstatusisreturnedaszero,thereadwassuccessful.Otherwisestatusgivesinformationabouttheincompleteorfailedread(whichisnotdocumentedhere).Youcommonlyusestatuswhenyouarereadingarecordorarrayfromafileandyouarenotsureiftheentireitemexistsonthefile.Ifitdoesnot
Details
exist,thereadwillfailpartwaythrough,butyourprogramcancontinueanddiagnosetheproblembyinspectingstatus.
AreadItemis:
variableReference[:requestedSize[:actualSize
EachreadItemspecifiesavariabletobereadininternalform.TheoptionalrequestedSizeisanintegervaluegivingthenumberofbytesofdatatoberead.TherequestedSizeshouldbelessthanorequaltothesizeoftheitem'sinternalforminmemory(elseawarningmessageisissued).IfnorequestedSizeisgiven,thesizeoftheiteminmemoryisused.TheoptionalactualSizeisanintvariablethatissettothenumberofbytesactuallyread.
Anarray,recordorunionmaybereadandwrittenasawhole.
Itisdangeroustoreadintopointervariables,asthisallowsthepossibilityofcreatingincorrectaddressesinthepointers.ItisalsodangeroustoreadmorebytesthanareinthereadItem.
Seealso thewrite,open,close,seek,tell,getandputstatements.
real therealnumbertype
Syntax real
Description
Therealnumbertypeisusedfornumbersthathavefractionalparts,forexample,3.14159.Realnumberscanbecombinedbyvariousoperatorssuchasaddition(+)andmultiplication(*).Realnumberscanalsobecombinedwithintegers(wholenumbers,suchas23,0and-9),inwhichcasetheresultisgenerallyarealnumber.Anintegercanalwaysbeassignedtoarealvariable,withimplicitconversiontoreal.
Examplevarweight,x:real
varx:real:=9.83
vartax:=0.7%Thetypeisimplicitlyrealbecause
%0.7isarealnumber
Details
SeealsoexplicitRealConstant.Theinttypeisusedinsteadofreal,whenvaluesarewholenumbers.Seeintfordetails.
Realnumberscanbeconvertedtointegersusingceil(ceiling),floor,orround.Realnumberscanbeconvertedtostringsusingerealstr,frealstr,andrealstr.Theseconversionfunctionscorrespondexactlytotheformattingusedfortheputstatementwithrealnumbers.Stringscanbeconvertedtorealnumbersusingstrreal.Seedescriptionsoftheseconversionfunctions.
Thepredefinedfunctionsforrealnumbersincludemin,max,sqrt,sin,cons,arctan,sind,cosd,arcand,lnandexp.Seethedescriptionsofthesefunctions.
Pseudo-randomsequencesofrealnumberscanbegeneratedusingrand.Seethedescriptionofthisprocedure.
TheTuringReportgivesaformaldefinition(notrepeatedhere)ofimplementedrealnumbersintermsoftheirrequiredaccuracyrelativetoinfinitelyaccurate(mathematical)realnumbers.
Turingimplementsrealnumbersusing8bytefloatingpointrepresentation.Thisprovides14to16decimaldigitsofprecisionandanexponentrangeofatleast-38..38.ThePCandMacintoshversionsofTuringhave16decimaldigitsofaccuracybecausetheyuseIEEEstandardfloatingpointrepresentation.
Seealso realn.
realn n-byterealnumbertype
Syntax (a) real4 %4-byterealnumber (b) real8 %8-byterealnumber
Description
Therealn(n-byterealnumber)typesaremachine-dependenttypesthatoccupyaspecifiednumberofbytes.Bycontrast,therealtypeis,inprinciple,amachine-independentandmathematicaltype(however,itoverflowswhentheexponentofthevalueistoolargeorsmallandithasonlyalimitedamountofprecision).
Example varwidth:real4
varheight:real8
Details
Turingimplementsthetyperealusing8bytefloatingpointrepresentation.Thisprovides14to16decimaldigitsofprecisionandanexponentrangeofatleast-38..38.ThePCandMacintoshversionsofTuringhave16decimaldigitsofaccuracybecausetheyuseIEEEstandardfloatingpointrepresentation.
Thisimpliesthatreal8andrealareessentiallythesametype,soinpracticethereisnoadvantagetousingreal8ratherthanreal.However,real4hastheadvantageofoccupyinghalfasmuchspace(withcorrespondinglyreducedprecision).
Arithmeticforallrealtypes(real,real4andreal8)iscarriedoutwiththeaccuracyandexponentrangeof8-bytereals.
Thetypereal4issometimescalledsingleprecision(becauseitoccupiesasingle4-byteword)andreal8issometimescalleddoubleprecision.
realstr real-to-stringfunction
Syntax realstr(r:real,width:int):string
Description
Therealstrfunctionisusedtoconvertarealnumbertoastring.Forexample,realstr(2.5e1,4)="bb25"wherebrepresentsablank.Thestringisanapproximationtor,paddedontheleftwithblanksasnecessarytoalengthofwidth.
Thewidthparametermustbenon-negative.Ifthewidthparameterisnotlargeenoughtorepresentthevalueofritisimplicitlyincreasedasneeded.Thedisplayedvalueisroundedtothenearestdecimalequivalentwiththisaccuracy.Inthecaseofatie,thedisplayvalueisroundedtothenextlargervalue.
Thestringrealstr(r,width)isthesameasthestringfrealstr(r,width,defaultfw)whenr=0orwhen1e-3<abs(r)<1e6,otherwisethesameaserealstr(r,width,defaultfw,defaultew),withthefollowingexceptions.Withrealstr,trailingfractionzeroesareomitted,andthedecimalpointisomittediftheentirefractioniszero.(Theseomissionstakeplaceeveniftheexponentpartisprinted.)Ifanexponentisprinted,anyplussignandleadingzeroesareomitted.Thus,wholenumbervaluesareingeneraldisplayedasintegers.
Defaultfwisanimplementation-definednumberoffractionaldigitstobedisplayed.Formostimplementations,defaultfwwillbe6.
Defaultewisanimplementation-definednumberofexponentdigitstobedisplayed.Formostimplementations,defaultewwillbe2.
Therealstrfunctionapproximatestheinverseofstrreal,althoughround-offerrorskeepthesefrombeingexactinverses.
Seealso theerealstr,frealstr,strreal,intstrandstrintfunctions.
record type
Syntax
ArecordTypeis:
record id{,id}:typeSpec {id{,id}:typeSpec} endrecord
Description
Eachvalueofarecordtypeconsistsoffields,onefieldforeachname(id)declaredinsidetherecord.Inthefollowingexample,thefieldsarename,phoneNumberandaddress.
Example
typephoneRecord:
record
name:string(20)
phoneNumber:int
address:string(50)
endrecord
…
varoneEntry:phoneRecord
varphoneBook:array1..100ofphoneRecord
vari:int
oneEntry.name:="Turing,Alan"
…
phoneBook(i):=oneEntry%Assignwholerecord
Details
Inarecord,id'soffieldsmustbedistinct.However,theseneednotbedistinctfromidentifiersoutsidetherecord.Recordscanbeassignedasawhole(torecordsofanequivalenttype),buttheycannotbecompared.AsemicoloncanoptionallyfolloweachtypeSpec.
Anyarraycontainedinarecordmusthaveboundsthatareknownatcompiletime.
Thenotation>canbeusedtoaccessrecordfields.Forexample,ifpisapointertophoneRecord,p>namelocatesthenamefield.Seepointer.
register usemachineregister
Dirty
Description
Whenavariable,constantorparameterisdeclared,youcanrequestthattheitembeplacedinamachineregister.Thisshouldbedoneonlyforprogramsrequiringconsiderableefficiency.
Example
varregistercounter:int
constregistermaxCounter:int:=100
procedurep(registerx:real)
…
endp
Details
Itemscanberequestedtobeinregistersonlyiftheyarelocaltoasubprogram(notglobalvariables,declaredinthemainprogram,amodule,monitororclass).Itemsrequestedtobeinregisterscannotbeboundto,passedtoreferenceparameters,havetheiraddresstakenbyaddr,orhavecertaintypecheatsappliedtothem(sinceamachineregisterhasnoaddress).
Therequesttousearegistermaybeignored.Forexample,thecurrent(1999)interpretiveimplementationusespseudo-code,whichhasnomachineregisters,andsoignorestheregisterkeyword.Forthesyntaxofusingthiskeyword,seevardeclaration,constdeclarationandparamDeclaration.
rem remainderoperator
Syntax rem
Description
Therem(remainder]operatorproducestheremainderofonenumberdividedbyanother.Forexample,7rem2produces1and-12rem5produces-2.
Example
Inthisexample,eggCountisthetotalnumberofeggs.Thefirstputstatementdetermineshowmanydozeneggsthereare.Thesecondputstatementdetermineshowmanyextraeggstherearebeyondthelastdozen.
vareggCount:int
geteggCount
put"Youhave",eggCountdiv12,"dozeneggs"
put"Youhave",eggCountrem12,"leftover"
Seealsoinfixoperators,precedenceofoperatorsandthemodanddivoperators.
repeat makecopiesofstring
function
Syntax repeat(s:string,i:int):string
DescriptionTherepeatfunctionreturnsicopiesofstringscatenatedtogether.Forexample,repeat("X",4)isXXXX.
Example
ThisprogramoutputsHoHoHo.
varword:string:="Ho"
putrepeat(word,3)
Details
Ifiislessthanorequaltozero,thenullstring""isreturned.Therepeatfunctionisoftenusedforspacingofoutput.Forexample,thisstatementskips20blanksbeforeoutputtingx.
putrepeat("",20),x
result statement
Syntax
AresultStatementis:
resultexpn
DescriptionAresultstatement,whichmustappearonlyinafunction,isusedtoprovidethevalueofthefunction.
Example
Thisfunctiondoublesitsparameter.
functiondouble(x:real):real
result2*x
enddouble
putdouble(5.3)%Thisoutputs10.6
Example
Thisfunctionfindsthepositionofanameinalist.
functionfind(a:array1..100ofstring):
fori:1..100
ifa(i)=namethen
resulti
endif
endfor
endfind
Details
Theexecutionofaresultstatementcomputesthevalueoftheexpression(expn)andterminatesthefunction,returningthevalueasthevalueofthefunction.
Theexpressionmustbeassignabletotheresulttypeofthefunction,forexample,indouble,2*xisassignabletoreal.(SeetheassignmentStatementforthedefinitionofassignable.)
Afunctionmustterminatebyexecutingaresultstatementandnotbyreachingtheendofthefunction.
return statement
Syntax
AreturnStatementis:
return
Description
Areturnstatementterminatestheprocedure(ormainprogram)inwhichitappears.Ordinarily,aprocedure(ormainprogram)terminatesbyreachingitsend;thereturnstatementisusedtocauseearlytermination.
Example
ThisproceduretakesnoactioniftheerrorHasOccurredflaghasbeensettotrue.
proceduredouble
iferrorHasOccurredthen
return%Terminatethisprocedure
endif
…handleusualcaseinthisprocedure…
enddouble
DetailsAreturnmustnotappearasastatementin(theoutermostlevelof)amodule,norcanitappearinafunction.
RGB
Description
Thisunitcontainsthepredefinedconstantsforthebasiccolorsandthesubprogramstochangethecolorpalette.
AllsubprogramsintheRGBunitareexportedqualified(andthusmustbeprefacedwith"RGB.").AllthecolorconstantsareexportedunqualifiedandthusdonotneedtheRGBprefix.
Details
Foraprogramthatdisplaysthe256predefinedcolors(andtheirassociatedcolornumbers)inTuring,runthe"Colors.t"program.
Details
Thefollowingnamescanbeusedforcolors.TheyrepresentcolornumbersandthuswillnotbeaccurateifRGB.SetColorhasbeenusedtochangecolornumbers0through15.
black,blue,green,cyan,red,magenta,purple,brown,white,gray,grey,brightblue,brightgreen,brightcyan,brightred,brightmagenta,brightpurple,yellow,brightwhite,darkgray,darkgrey
Theremainingfourcolorsrepresenttheforegroundcolor(blackonWindowsortheMacintosh,whiteonaDOSsystem)andthebackgroundcolor(whiteonWindowsorMacintosh,blackonaDOSsystem).UsingthesefourcolorsallowsyoutowriteprogramsthatworkonbothWindowsandDOSversionsofTuring.
colorfg,colourfg,colorbg,colourbg
Turingusesapalettetoaccesscolorsfordisplay.Thispaletteisa
Details
listofcolornumbersandtheirassociatedactualcolor.TheTuringpalettestartswith256entries(thecolornumbersfrom0to255).With16,24,and32-bitcolordisplays,however,aTuringprogramcandisplaythousandsofcolorsatonce.Thesecolors,however,willallhavecolornumbersassociatedwiththem.Forexample,ifaTuringprogramloadsaJPEGimage,theremaybethousandsofcolorsonthescreen,butthenumberofcolornumberswillstayat256.Likewise,16,24,and32-bitcolordisplays,ifyouloadapictureinGIFformatthathasa256colorsthataredifferentfromtheinitialTuringcolorpalette,theywillappearintherunwindow.However,theywillnotbeaddedtoTuring'scolorpalette.
IfyouattempttodeterminethecolornumberofaparticularpixelthatdoesnotmatchanyofthecolorsinTuring'scolorpalette,thenTuringwillreturnthecolornumberofthecolorintheTuringpalettethatmostcloselymatchesthatcolorofthepixel.
EntryPoints
GetColorGetColour Getsthecurrentred,greenandbluevaluesofa
specifiedcolornumber.SetColorSetColour Setsthered,greenandbluevaluesofa
specifiedcolornumber.AddColorAddColour Createsanewcolornumberwithaspecified
red,greenandbluevalue.
RGB.AddColor PartofRGBmodule
Syntax RGB.AddColor(redComp,greenComp,blueComp:real):int
Description
TheRGB.AddColorfunctionattemptstocreateanewcolorwiththered,greenandbluecomponentsspecified.Ifsuccessful,thefunctionreturnsanewcolornumber(usuallyonegreaterthanmaxcolor)andmaxcolorisupdatedbyadding1toit.Ifitisunsuccessful,thefunctionreturns1andError.LastandError.LastMsgcanbeusedtodeterminethecauseoftheproblem.
Thered,greenandbluevaluesmustnormalizedtobebetween0and1.Thustoaddthepureredtothecolorpalette,youwouldcall:
newColor:=RGB.AddColor(1.0,0.0,0.0)
newColorwouldbesettothecoloradded,or1iftheattempttoaddacolorfailed.
Example
Thisprogramaddsapaletteof16bluestotheendofthecolorpalette.
varclr:int
forblueShade:0..15
clr=RGB.AddColor(0,0,blueShade/15)
ifclr=1then
put"Coloraddfailedonshadenumber",
exit
else
put"Addedcolornumber",clr
endif
endfor
Details RGB.AddColourisanalternatespellingforRGB.AddColor.
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
RGB.AddColor,notbycallingAddColor.
Seealso RGB.GetColorandRGB.SetColor.
RGB.GetColor PartofRGBmodule
SyntaxRGB.GetColor(colorNumber:int, varredComp,greenComp,blueComp:real)
Description
TheRGB.GetColorprocedurereturnsthered,greenandbluecomponentstothecolorassociatedwiththecolorNumberparameter.Thered,greenandbluevaluesarenormalizedtobebetween0and1.Thuscolorwhitereturns1.0fortheredComp,greenCompandblueCompvaluesandcolorblackreturns0.0forallthree.
Example
Thisprogramgetsthecomponentsofalltheavailablecolors.
put"ColorRedGreenBlue"
forclr:0..maxcolor
varredComp,greenComp,blueComp:int
RGB.GetColor(clr,redComp,greenComp,blueComp
putclr:4,"",redComp:6:4,"",greenComp
blueComp:6:4
endfor
Details RGB.GetColourisanalternatespellingforRGB.GetColor.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRGB.GetColor,notbycallingGetColor.
Seealso RGB.SetColorandRGB.AddColor.
RGB.maxcolor PartofRGBmodule
Syntax maxcolor:int
Description
Themaxcolorfunctionisusedtodeterminethemaximumcolornumberforthecurrentmodeofthescreen.Thealternatespellingismaxcolour.
Example
Thisprogramoutputsthemaximumcolornumber.
setscreen("graphics")
…
put"Themaximumcolornumberis",maxcolor
Details
Thescreenshouldbeina"screen"or"graphics"mode.Ifitisnot,itwillautomaticallybesetto"screen"mode.SeeView.Setfordetails.
ForIBMPCcompatiblesin"screen"mode,maxcolor=15.ForthedefaultIBMPCcompatible"graphics"mode(CGA),maxcolor=3.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallingmaxcolororbycallingRGB.maxcolor.
Seealso
Draw.Dotforexamplesoftheuseofmaxcolor.SeetheText.Colorprocedurewhichisusedforsettingthecurrently-activecolor.
RGB.SetColor PartofRGBmodule
SyntaxRGB.SetColor(colorNumber:int, redComp,greenComp,blueComp:real)
Description
TheRGB.SetColorfunctionsetsthered,greenandbluecomponentsofthecolorassociatedwiththecolorNumberparameter.Thered,greenandbluevaluesmustnormalizedtobebetween0and1.ThustosetthecolorassociatedwiththecolorNumberparametertopurered,youwouldcall:
RGB.SetColor(colorNumber,1.0,0.0,0.0)
ItiswisetouseError.LastandError.LastMsgtochecktoseeifthecolorchangeissuccessful.
Example
Thisprogramsetsalltheavailablecolorstoshadesofred
forclr:0..maxcolor
ifnotRGB.SetColor(clr,clr/maxcolor,0,0)
put"Colorsetfailedoncolornumber",
exit
endif
endfor
Details RGB.SetColourisanalternatespellingforRGB.SetColor.
Details
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingRGB.SetColor,notbycallingSetColor.
Seealso RGB.GetColorandRGB.AddColor.
round real-to-integerfunction
Syntax round(r:real):int
Description
Theroundfunctionisusedtoconvertarealnumbertoaninteger.Theresultisthenearestintegertor.Inthecaseofatie,thenumericallylargervalueisreturned.Forexample,round(3)is3,round(2.85)is3andround(-8.43)is-8.
Seealso thefloorandceilfunctions.
scalar type
Syntax
AscalarTypeisoneof:
(a) standardType %int,real,booleanorstring
(b) enumeratedType (c) subrangeType (d) pointerType (e) char (f) intn (g) natn (h) realn
(i) namedType %Mustnameoneoftheabovetypes
Description
Scalartypesaresometimescalledsimpleorprimitivetypes.Thenon-scalartypesarestrings,sets,arrays,records,unionsandinOOTchar(n).Theyaredefinedusingscalartypes.Scalartypesarepassedbyvaluetoparameters,whilenon-scalarsarepassedbyreference(bypassinganimplicitpointertothenon-scalarvalue).
Description
IncurrentTuringimplementationsscalartypesaredirectlyrepresentedin1,2,4or8bytesinacomputer'smemory.Thisimpliesthattheycanbeefficientlypassedbyvalue.
seek (file)statement
Syntax
AseekStatementisoneof:
(a) seek:fileNumber,filePosition (b) seek:fileNumber,*
Description
Randomaccessofbothsource(ASCIIorEBCDIC)andinternalform(binary)filesisprovidedbytheseekandtellstatements.Theseekstatementrepositionsthespecifiedfilesothatthenextinput/outputoperationwillbeginatthespecifiedpoint(filePosition)inthefile.
ThefileNumbermustspecifyafilethatisopenwithseekcapability.ThefilePositionisanon-negativeintegeroffsetinbytesfromthebeginningofthefile.Usually,thisisanumberreturnedbythetellstatement.(Thefirstpositioninthefileispositionzero.)
Form(b)specifiesthatthenextoperationistobeginatthepositionimmediatelyfollowingthecurrentendofthefile.AfilePositionofzerospecifiesthatthenextoperationistostartatthebeginningofthefile.Seekingtoapositionbeyondthecurrentendofthefileandthenwriting,automaticallyfillstheinterveningpositionswiththeinternalrepresentationofzero.
Example
Thisexampleshowshowtouseseektoappendtotheendofafile.
varemployeeRecord:
record
name:string(30)
pay:int
endrecord
varfileNo:int
open:fileNo,"payroll",write,seek,mod
seek:fileNo,*%Seektotheendofthefile
write:fileNo,employeeRecord
%Thisrecordisaddedtotheendofthefile
Seealsoread,write,open,close,tell,getandputstatements.Anotherexampleuseofseekisgivenwiththeexplanationofthetellstatement.
self pointertocurrentobject
Syntax self
DescriptionTheselffunctionproducesapointertothecurrentobject.Thisfunctioncanbeusedonlyinsideaclassdeclaration.Seeclass.
Example
Enterthecurrentobjectontoalistofdisplayableobjects.Themodulecalleddisplayablehasexportedaprocedurecalledenterwhoseparametertypeispointertoanyclass.SinceselfisapointertoCandCisadescendantofanyclass,itislegaltopassselftodisplayable.enter.
classC
importdisplayable
…
displayable.enter(self)…
…
endC
Details
Itisillegaltocalltheexportedentriesofaclassuntilthecurrentobjecthasbeencompletelyinitialized,so,manycallstothecurrentobjectusingselfwillnotbelegal.
ThenotationtocallexportedsubprogrampofanenclosingclassCorofitsancestorD,isC.porD.p.Callsofthisform,whichcanappearonlywithinclassC,callthesubprograminC(orinDinthecaseofD.p)regardlessoftheobjecttype,orofanyoverriding,orofthestatusofinitialization.
separator betweentokensinaprogram
Description
ATuringprogramismadeupofasequenceoftokens(seetokens),suchasvar,x,:,andint.Thesetokensmayhaveseparatorsbetweenthem.Aseparatorisacomment(seecomment),blank,tab,formfeedoranendofline.
set type
Syntax
AsetTypeis:
setoftypeSpec
Description
Eachvalueofasettypeconsistsofasetofelements.ThetypeSpec,whichisrestrictedtobeingasubrangeoranenumeratedtype,givesthetypeoftheseelements.
Example
ThesmallSettypeisdeclaredsothatitcancontainanyandallofthevalues0,1and2.Variablesisinitializedtobethesetcontaining1and2.
typesmallSet:setof0..2
vars:smallSet:=smallSet(0,1)
…
if2insthen…
Details
Inclassicalmathematics,thesetconsistingof0and1iswrittenas{0,1}.ThisiswritteninTuringusingasetconstructorconsistingofthenameofthesettypefollowedbyaparenthesizedlistofelements,whichinthisexampleissmallInt(0,1).Theemptysetiswritten,forexample,assmallInt().ThefullsetiswrittenassmallInt(all),sosmallInt(all)=smallInt(0,1,2).
Setscanbeassignedasawhole(tosetsofanequivalenttype).Seealsoequivalenceoftypes.
Theoperatorstocombinetwosetsareunion(+),intersection(*),setsubtraction(-),equality(=),inequality(not=),subset(<=),strictsubset(<),superset(>=),strictsuperset(>),andxor("exclusiveor"alsoknownassymmetricdifference).Onlysetswithequivalenttypes(equalboundsontheirindextypes)canbecombinedbytheseoperators.Theoperatorswhichdetermineifanelementis,orisnot,inasetareinandnotin.Forexample,thetesttoseeif2isinsetsiswrittenintheaboveexampleas:2ins.
TheindexTypeofasettypemustcontainatleastoneelement.For
example,therange1..0wouldnotbeallowed.SeealsoindexType.InTuring,setsarelimitedtoatmost31elements.OOTallowsaverylargenumberofelements.
Details
Itisillegaltodeclarean"anonymous"set.Theonlylegaldeclarationforansetisinatypedeclaration.Forexample,thefollowingisnowillegal:
vara:array1..10ofsetof0..3
Giventhatthereisno(easy)wayofgeneratingasetvaluewithoutitbeinganamedtype,thisshouldnotimpactanybutthemostbizarrecode.
Seealso precedenceofoperatorsfortheorderofapplyingsetoperations.
setConstructor
Syntax
AsetConstructoris:
setTypeId(membersOfSet)
Description
Eachvalueofasettypeconsistsofasetofelements.Inclassicalmathematics,thesetconsistingof0and1iswrittenas{0,1}.ThisiswritteninTuringusingasetconstructorconsistingofthenameofthesettype(setTypeId)followedbyaparenthesizedlistofelements.
Example
ThesmallSettypeisdeclaredsothatitcancontainanyandallofthevalues0,1and2.Variablesisinitializedtobethesetcontaining1and2.Theset{0,1}iswritteninthisTuringexampleassmallInt(0,1).
typesmallSet:setof0..2
vars:smallSet:=smallSet(0,1)
…
if2insthen…
Details
TheformofmembersOfSetisoneof:
(a)expn{,expn}%Listofmembersofset
(b)all%Allmemberofindextypeofset
(c)%Nothing,meaningtheemptyset
Theemptysetiswritten,forexample,assmallInt().ThefullsetiswrittenassmallInt(all),sosmallInt(all)=smallInt(0,1,2).Seealsothesettype.
ThesyntaxofsetConstructorasgivenabovehasbeensimplifiedbyignoringthefactthatsettypescanbeexportedfrommodules.Whenasettypeisexportedandusedoutsideofamodule,youmustwritethemodulename,adotandthenthetypename.Forexample,thesetconstructorabovewouldbewrittenasm.smallSet(1,2),wheremisthemodulename.
setpriority procedure
Syntax setpriority(p:nat)
Description
Thesetpriorityprocedureisusedtosetthepriorityofaprocessinaconcurrentprogram.Thisprioritycannotbecountedontoguaranteecriticalaccesstosharedvariables.Asmallervalueofpmeansincreasedspeed.Theargumenttosetprioritymaybelimitedtotherange0to2**15-1.
Seealsogetpriority,forkandmonitor.
SeealsopredefinedunitConcurrency.
setscreen graphicsprocedure
setscreen("graphics:300;100")
Thisprogramoutputsthesquarerootsforthefirst200numbers.Theusercaninspectalltheoutputandprintthevaluesaftertheprogramhasfinishedexecution
setscreen("text")
forvalue:1..200
putvalue:3,"",sqrt(value)
endfor
Thisprogramcreatesawindowwithoutabuttonbaratthetopthatissizedtofitthescreen.Itthendrawsan“X”inredinthewindow.
setscreen("graphics:max;max,nobuttonbar")
drawline(0,0,maxx,maxy,red)
drawline(maxx,0,0,maxy,red)
Syntax setscreen(s:string)
Example
Hereareexampleusesofthesetscreenprocedure.Inmanycases,thesewillappearasthefirststatementoftheprogram.Theycan,however,appearanyplaceinaprogram.
setscreen("graphics")%Entergraphicsmode
setscreen("graphics:400;300")%Changewindowto400x300
setscreen("nocursor")%Turnoffcursor
setscreen("noecho")%Donotechokeys
Description
Thesetscreenstatementisusedtochangethemodeofthescreen,aswellasthewayinwhichTuringdoesinputandoutput.Theparametertosetscreenastring,suchas"graphics".Thestringcontainsoneormoreoptionsseparatedbycommas,suchas"text,noecho".
UsersshouldlookatView.Setinordertofindouttheimplementationspecifieddetailsofsetscreenontheirsystems.
Therearetwoscreenmodes,textandgraphics.Intextmode,outputtothewindowisonlyallowedusingputandget.Attemptingtousegraphicsormovingthecursorusinglocatewillresultinanerror.However,awindowin
Details
textmodewillkeepalltextoutputsenttoit.Anyoutputthatscrollsofftheedgeofthewindowcanbereadbyadjustingthescrollbarsofthewindow.Printingatextoutputwindowprintsalltheoutputsenttothewindow,notjusttheoutputcurrentlyvisibleinthewindow.Programsoftenusewhentheyaredisplayinglargeamountsoftextdatathattheusermaywishtovieworprintlater.Savingthecontentsofatextoutputwindowcreatesatextfilecontainingalltheoutputsenttothewindow.
Ingraphicsmode,aprogramcanusebothputandget,locateandgraphicscommandstosendoutputtothewindow.However,anyoutputthatscrollsoffthewindowislost.Printingthewindowoutputsthecurrentcontentsofthewindow.SavingagraphicsoutputwindowsavesthecurrentcontentsofthewindowasaBMPfile.
Wheretheoptionstosetscreenaremutuallyexclusive,theyarelistedherewiththedefaultunderlined.Herearetheoptions:
"graphics","text",Setsthemodeofthewindowtothegivenmode.Asizecanforthewindowcanbespecifiedatthesametime.Ifthewindowmodeorsizechanges,thenthewindowwillbecleared.
Tospecifythesizeofawindowingraphicsmode,thegraphicscanhaveamodifierintheform"graphics:<width>;<height>".Thissetsthewindowtobe<width>pixelsby<height>pixelsinsize.Themaximumsizeofawindowisthesizeofthescreen.
Tospecifythesizeofawindowintextmode,thetextcanhaveamodifierintheform"text:<rows>;<columns>".Thissetsthewindowtobe<rowslinesinheightby<columns>charactersinwidth.Themaximumsizeofawindowisthesizeofthescreen.
Tosetawindowtothemaximumsizeavailableonthescreen,you"max"forthe<width>,<height>,<rows>or<columns>parameters.
"cursor","nocursor"Causesthecursortobeshown(orhidden).Thecursoronlyappearswhentheprogramiswaitingforkeyboardinputfromtheuser.
"echo","noecho"Causes(orsuppresses)echoingofcharactersthataretyped.Echoingiscommonlyturnedoffininteractiveprogramstokeeptypedcharactersfrombeingechoedatinappropriateplacesonthescreen.
"nooffscreenonly","offscreenonly"Causesor(suppresses)outputfrombeingsenttothevisiblewindow.Whentheoffscreenonlyoptionisactive,anytextandgraphicsoutputisdrawntotheoffscreenbufferthatismaintainedforeveryRunwindowbutnotdrawntothescreen.View.Updateisthenusedtocopytheentirecontentsoftheoffscreenbuffertothewindow.Byallowingnumerousdrawingcommandstobesenttotheoffscreenbufferandthenupdatingthewindowatonetime,itispossibletogetsmootheranimation.
"msdos","nomsdos"CausesthewindowtousetheMS-DOScharacterset(withlinedrawingcharacters)insteadoftheWindowsANSIcharacterset.The"nomsdos"optioncausesthewindowtousetheWindowsANSIcharacterset.Notethatthe"msdos"optiononlyworksiftheWindowsfont(usuallyCourierNew)supportsit.
"buttonbar","nobuttonbar"Causesor(suppresses)thedisplayofabuttonbaratthetopoftheoutputwindowwhichallowstheusertoeasilystopprogramexecutionorsaveandprinttheoutputwindow.
Example Thisprogramcreatesagraphicswindowthatis300pixelsby100pixels.
Seealso
theDrawmodule,thedraw…subprogramsandtheView.Updateprocedurefordoingsmoothanimation.SeealsoView.Setforfurthersetscreenincludingpositioningtheoutputwindowonthescreen.
shl shiftleftoperator
Syntax AshlB
Description
Theshl(shiftleft)operatorproducesthevalueofAshiftedBbitstotheleft.BothAandBmustbenon-negativeintegers(naturalnumbers).
Example
Assignthebase2value11toiandthenshiftitleftby2placesandassigntheresultingbase2value1100toj.
vari,j:int
i:=2#11%2#11=3(base10)
j:=ishl2%jbecomes2#1100=12(base10)
Details
Theshloperatorisdefinedmathematically(inamachine-independentway)asfollows:AshlB=A*(2**B).Overflowoccurswhentheresultexceedsthemaximumvalueofthenat4(4-bytenaturalnumber)type.
ValueAcanbeofanyintegertype(aslongasitisnon-negative)oranynaturalnumbertype.
Theshloperatorhasthesameprecedenceasthe*operator.
Seealso
shr(shiftright),or,andandxor,whichalsoarebitmanipulationoperatorsthatactonnon-negativevalues.SeealsoexplicitIntegerConstantwhichdescribesvaluessuchas2#1100.
shr shiftrightoperator
Syntax AshrB
Description
Theshr(shiftright)operatorproducesthevalueofAshiftedBbitstotheright.BothAandBmustbenon-negativeintegers(naturalnumbers).
Example
Assignthebase2value1101toiandthenshiftitrightby2placesandassigntheresultingbase2value11toj.
vari,j:int
i:=2#1101%2#1101=13(base10)
j:=ishr2%jbecomes2#11=3(base10)
Details
Theshroperatorisdefinedmathematically(inamachine-independentway)asfollows:AshrB=Adiv2**B.
ValueAcanbeofanyintegertype(aslongasitisnon-negative)oranynaturalnumbertype.
Theshroperatorhasthesameprecedenceasthe*operator.
Seealso
shl(shiftleft),or,andandxor,whichalsoarebitmanipulationoperatorsthatactonnon-negativevalues.SeealsoexplicitIntegerConstantwhichdescribesvaluessuchas2#1101.
sign function
Syntax sign(r:real):-1..1
Description
Thesignfunctionisusedtodeterminewhetheranumberispositive,zeroornegative.Itreturns1ifr>0,0ifr=0,and-1ifr<0.Forexample,sign(5)is1andsign(-23)is-1.
Example
Thisprogramreadsinnumbersanddeterminesiftheyarepositive,zeroornegative:
varx:real
getx
casesign(x)of
label1:put"Positive"
label0:put"Zero"
label-1:put"Negative"
endcase
Seealso SeealsopredefinedunitMath.
signal wakeupaprocessstatement
Syntax
AsignalStatementis:
signalvariableReference
Description
Asignalstatementisusedinaconcurrentprogramtowakeupaprocessthatisblocked(waitingonaconditionvariable).Thestatementcanonlybeusedinsideamonitor(aspecialkindofmodulethathandlesconcurrency).Asignalstatementoperatesonaconditionvariable(thevariableReference),whichisessentiallyaqueueofsleepingprocesses.Seeconditionforanexampleofasignalstatement.
Details
Asignalstatementwakesuponeprocessthatisdoingawaitonthespecifiedconditionqueue,ifsuchaprocessexists.Iftheconditionisdeferred(ortimeout;seecondition),thesignalercontinuesinthemonitor,andtheawakenedprocessisallowedtocontinueonlywhenthemonitorbecomesinactive.Asignaltoanimmediate(non-deferred)conditioncausesthesignaledprocesstobeginrunninginthemonitorimmediately.Thesignalingprocesswaitstore-enterthemonitorwhenthemonitorbecomesinactive.
Seealsoconditionandwait.Seealsomonitorandfork.Seealsoempty.Seealsopause.
simutime simulatedtimefunction
Syntax simutime:int
DescriptionThesimutimefunctionreturnsthenumberofsimulatedtimeunitsthathavepassedsinceprogramexecutionbegan.
Details
Simulatedtimeonlypasseswhenallprocessareeitherpausedorwaiting.ThissimulatesthefactthatCPUtimeiseffectivelyinfinitelyfastwhencomparedto"pause"time.
Example
Thisprintsoutthesimulatedtimepassingbetweentwoprocesses.Thiswillprintout3,5,6,9,10,12,15,15,18,20,21,…
processp(t:int)
loop
pauset
putsimutime
endloop
endp
forkp(3)
forkp(5)
Execute
Seealso SeealsopredefinedunitConcurrency.
sin sinefunction(radians)
Syntax sin(r:real):real
DescriptionThesinfunctionisusedtofindthesineofananglegiveninradians.Forexample,sin(0)is0.
Example
Thisprogramprintsoutthesineofp/6,2p/6,3p/6,upto12p/6radians.
constpi:=3.14159
fori:1..12
constangle:=i*pi/6
put"Sinof",angle,"is",sin(angle)
endfor
Execute
Seealso
thecosandtanfunctionsforcalculatingcosineandtangent.
thesindfunctionwhichfindsthesineofananglegivenindegrees.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
sind sinefunction(degrees)
Syntax sind(r:real):real
DescriptionThesindfunctionisusedtofindthesineofananglegivenindegrees.Forexample,sind(0)is0.
Example
Thisprogramprintsoutthesineof30,60,90,upto360degrees.
fori:1..12
constangle:=i*30
put"Sinof",angle,"is",sind(angle)
endfor
Execute
Seealso
thecosdandtandfunctionsforcalculatingcosineandtangent.
thesinfunctionwhichfindsthesineofananglegiveninradians.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
sizeof sizeofatype
Dirty
Syntax sizeof(typeNameOrVariableReference)
Description
Thesizeofattributeisusedtofindthenumberofbytesusedtorepresentthetypeorvariable.Thisisimplementation-dependent(dirty).
Example
Thesizeofint2andnat2is2.
vari:int2
constnat2size:=sizeof(i)%sizeis2
Details
ThetypeNameOrVariableReferencemustbethenameofauser-definedtype,avariablereference,abasictype(suchasreal),oraconstant.
Inprinciple,sizeofreturnsthenumberofstorageunitswhichwouldnotnecessarilybe8-bitbytes.Forexample,insomeoldermachines,suchastheCDC6000series,thestorageunitsare60bitwords.However,almostallmoderncomputersuse8-bitbytessothesearetheunitsofsizeof.
Bewarethatsizesmayreflectalignmentconstraintsintheunderlyingcomputer.Forexample,stringsizesmayberoundeduptoevenvalues(2-bytewordalignments).
Seealso
theindirectionoperator@,cheat,explicitIntegerConstant(howtowritehexadecimalconstants),andpointers(inparticularuncheckedpointers).Seealsoaddr,whichreturnstheaddressofavariable.
sizepic graphicsfunction
Syntax sizepic(x1,y1,x2,y2:int):int
Description
Thesizepicfunctionisusedtodeterminethesizebufferneededtorecordapicturefromthescreen(seedescriptionoftakepic).Thisgivestheminimumnumberofelementsoftheintarrayusedbytakepic.Thebufferisusedbydrawpictomakecopiesofthepictureonthescreen.
Example
Thisprogramoutputsthesizeofarrayneededtoholdapicturewithleftbottomcorneratx=10,y=20andrighttopcorneratx=50,y=60.
setscreen("graphics")
…
put"Thesizeofthearrayneedstobe",
sizepic(10,20,50,60)
Details
Seetakepicforanexampleoftheuseofsizepicandforfurtherinformationaboutbuffersfordrawingpictures.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Seealso
drawpic.Seealsosetscreen,maxx,maxy,drawdot,drawline,drawbox,anddrawoval.
SeealsopredefinedunitPic.
skip usedingetstatement
Syntax skip
Description
Usingskipasaninputiteminagetstatementcausesthecurrentinputtobeskippeduntilanon-whitespacetokenisencountered.Whitespaceincludesallblanks,tabs,formfeedsandnewlines.
Example
Theskipinputitemwasoriginallyintendedtobeusedtoseeifmoreinputexistsinaninputfile.ThisusehasbeenlargelymaderedundantbyachangeintheTuringlanguage.ThenewversionofTuringreadsatoken,asingetsbutnotingets:*orgets:3,andautomaticallyskipsanywhitespacefollowingtheinputvalue,butwillnotgobeyondthebeginningofthenextinputline.Originallythisautomaticskippingdidnottakeplace,soskipwasrequired.Theformofaninputloopthatusedskipwasasfollows:
loop
getskip%Thisislinenowredundant
exitwheneof
get…
…
endloop
Details
Theskipbypassesallwhitespacecharactersincludinganytrailingnewlinesandblanklines.Byskippingthesecharacters,atrueend-of-fileconditionwasdetected.Otherwise,theend-of-filecouldhavebeenhiddenbyanywhitespacefollowingthelastinputitem.WiththechangeinTuring,thelinegetskipisnolongerneeded(althoughitstillworkscorrectly).
Example
Theskipcanalsobeusedtocorrectlyidentifythestartofalongstring(usuallytobereadinlineorcountedmode).Here,itskipsthewhitespaceandtrailingnewlineasfollows:
vari:int
varline:string
loop
geti,skip,line:*
…
endloop
Details
Thefirstiteminthegetstatementreadsanintegerbyskippingallwhitespaceandreadingdigitsuntilwhitespaceisencountered.Theinputstreamisthenleftwiththewhitespaceasthenextinputcharacter.Theskipthenskipspastthewhitespace,effectivelybeginningthenextinputatthenextnon-whitespacecharacter.Thistruncatesleadingblanksandhasanother,potentiallymoreimportant,effect.Iftheintegeristhelastdataonalineandthestringisonafollowingline,theskipisnecessarytoavoidsettinglinetoanullstringvalue.
Seealso getstatementandloopstatement.
skip usedinputstatement
Syntax skip
DescriptionUsingskipasanoutputiteminaputstatementcausesthecurrentoutputlinetobeendedandanewlinetobestarted.
Example
Thisexample,TobeisoutputononelineandOrnottobeonthenext.
put"Tobe",skip,"Ornottobe"
Details Usingskipisequivalenttooutputtingthenewlinecharacter"\n".
sound statement
Syntax sound(frequency,duration:int)
Description
Thesoundprocedureisusedtocausethecomputertosoundanoteofagivenfrequencyforagiventime.Thefrequencyisincyclespersecond(Hertz).Thetimedurationisinmilliseconds.Forexample,middleAonapianois440Hertz,sosound(440,1000)playsmiddleAforonesecond.
Example
Thisprogramsoundsthefrequencies100,200upto1000eachforhalfasecond.
fori:1..10
puti
sound(100*i,500)%Soundnotefor1/2second
endfor
Details
OnIBMPCcompatibles,thehardwareresolutionofdurationisinunitsof55milliseconds.Forexample,sound(440,500)willdelaytheprogrambyabouthalfasecond,butmaybeoffbyasmuchas55milliseconds.
Details ThesoundproceduredoesnotcurrentlyworkunderMacOOT.
Seealso
playstatement,whichplaysnotesbasedonmusicalnotation.Forexample,play("8C")playsaneighthnoteofmiddleC.Seealsothedelay,clock,sysclock,wallclock,timeanddatestatements.
SeealsopredefinedunitMusic.
Sprite
Description
SpritesareawayofdoinganimationinTuringbypassingthePicmodule.Aspriteisessentiallyapicturewithaspecificlocationand"depth".YoucreateaspritebycallingSprite.NewwithapicIDreceivedfromPic.New.YoucanthenmovethespritearoundbycallingSprite.SetPosition.Whenyouarefinishedwiththesprite,youcallSprite.Free.
Notethatspritesworkbestwhentheyaremoderatelysmall.Ifyouhavelargesprites,youwillcontinuetohaveflashing.
AllsubprogramsintheSpriteunitareexportedqualified(andthusmustbeprefacedwith"Sprite.").
EntryPoints
New Createsanewspritefromapicture.Free Disposesofaspriteandfreeupitsmemory.
SetHeight
Setstheheightofasprite.Spriteswithagreaterheightappearabovespriteswithalesserheight.Thebackgroundisconsideredheight0.Theheightmaybenegative.
SetPosition Setsthelocationofthesprite.Canspecifythecenterofthespriteorthelower-leftcorner.
SetFrameRate Setsthemaximumnumberoftimesasecondthespriteswillbemovedonscreen.
ChangePic Changesthepictureassociatedwithasprite.
Animate Changesthelocationandthepictureassociatedwithasprite.Usedforanimatingamovingchangingimage.
Show Showsapreviouslyhiddensprite.Hide Hidesavisiblesprite.
Sprite.Animate PartofSpritemodule
SyntaxSprite.Animate(spriteID,picID,x,y:int,centered:boolean)
Description
MovesthespritespecifiedbyspriteIDtothelocationspecifiedby(true,thenthespriteiscenteredon(x,y).Otherwise(x,y)specifiesthelower-leftcornerofthesprite.Atthesametime,itchangesthepictureassociatedwiththesprite.
AsimpleexampleoftheSprite.Animateprocedurewouldbeofapictureassociatedwiththespritewouldconstantlychangeasthefigurewaswalking.Atthesametime,thelocationofthefigurewouldalsochange.
Example
HereisaprogramthatloadsaseriesofimagesfromananimatedGIFfilecalled"mypic.gif".ItworksbyloadingtheimagesfromtheGIFfileintoanarray(seePic.FileNewFramesformoreinformation)andthendisplaystheimagessequentiallyonthescreen,movingtheimageeightpixelseachtime.
varnumFrames:=Pic.Frames("mypic.gif")
%Loadthepicture
vardelayTime:int
varpics:array1..numFramesofint
Pic.FileNewFrames("mypic.gif",pics,delayTime)
varsprite:int
sprite:=Sprite.New(pics(1))
Sprite.SetPosition(sprite,0,100,false)
Sprite.Show(sprite)
forx:8..maxxby8
Sprite.Animate(sprite,pics((xdiv8)mod
delay(40)%Stopspritefrommovingtooquickly
endfor
Sprite.Free(sprite)
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.AnimateAnimate.
Seealso Sprite.New,Sprite.SetPositionandSprite.ChangePic.
Sprite.ChangePic PartofSpritemodule
Syntax Sprite.ChangePic(spriteID,picID:int)
Description
Changesthepictureassociatedwithaspritewhilemaintainingthespritesheightandvisibilitystatus.AtypicaluseSprite.ChangePicwouldbetoanimateaspritethatstaysinposition.
Example
HereisaprogramthattthatloadssiximagesfromfilesPic1.bmpthroughPic6.bmpandthendisplaysthemsequentiallyinthecenterofthescreen.
varpics:array0..5ofint
varsprite:int
fori:1..6
pics(i1):=Pic.FileNew("Pic"+intstr(
ifError.Lastnot=0then
put"Errorloadingimage:",Error.LastMsg
return
endif
endfor
figure:=Sprite.New(pics(0))
Sprite.SetPosition(sprite,maxxdiv2,maxydiv
Sprite.Show(sprite)
fori:1..100
Sprite.ChangePic(sprite,pics(imod6))
endfor
Sprite.Free(sprite)
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.ChangePic,notbycallingChangePic.
Seealso Sprite.New.
Sprite.Free PartofSpritemodule
Syntax Sprite.Free(spriteID:int)
DescriptionDestroysthespriteandfreesupthememorythespriteused.ItisanerrortousethespriteIDafterthespritehasbeenfreed.
Example SeeSprite.AnimateforanexampleofSprite.Free.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.Free,notbycallingFree.
Seealso Sprite.New.
Sprite.Hide PartofSpritemodule
Syntax Sprite.Hide(spriteID:int)
DescriptionHidesapreviouslyvisiblesprite.Sprite.Hidehasnoeffectifthespriteisalreadyinvisible.
Example
Thefollowingprogramanimatesfourballsonthescreen.Whentheballsareclosetoeachotherortoawall,theyappear,otherwisetheyarehidden.
varpic,sprite,x,y,dx,dy,radius:array1..6
varvisible:array1..6ofboolean
setscreen("nocursor")
%Createallthesprites.
fori:1..6
radius(i):=Rand.Int(10,25)
Draw.FillOval(25,25,radius(i),radius(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
y(i):=Rand.Int(radius(i),maxy‹radius
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),
Sprite.SetHeight(sprite(i),i)
visible(i):=false
endfor
%Nowmoveallthespritesaroundthescreen.
loop
fori:1..6
ifx(i)+dx(i)<radius(i)or
x(i)+dx(i)>maxxradius(i
dx(i):=dx(i)
endif
x(i):=x(i)+dx(i)
ify(i)+dy(i)<radius(i)or
y(i)+dx(i)>maxyradius(i
dy(i):=dy(i)
endif
y(i):=y(i)+dy(i)
endfor
fori:1..6
varnear:boolean:=false
if(x(i)<50)or(x(i)>maxx50)or
(y(i)<50)or(y(i)>maxy50)
near:=true
endif
ifnotnearthen
forj:1..6
ifinot=jthen
ifsqrt((x(i)‹x(j))**2+
(y(i)‹y(j))**2)<100
near:=true
exit
endif
endif
endfor
endif
ifnearandnotvisible(i)then
Sprite.Show(sprite(i))
visible(i):=true
elsifnotnearandvisible(i)then
Sprite.Hide(sprite(i))
visible(i):=false
endif
Sprite.SetPosition(sprite(i),x(i),y
endfor
Time.Delay(40)
exitwhenhasch
endloop
fori:1..6
Sprite.Free(sprite(i))
endfor
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.HidecallingHide.
Seealso Sprite.Show.
Sprite.New PartofSpritemodule
Syntax Sprite.New(picID:int):int
Description
CreatesanewspritefromapicturespecifiedbypicID.ThespritestartsinvisibleandshouldbegivenadepthusingSprite.SetHeightandaposition,givenSprite.SetPositionbeforebeingmadevisibleusingSprite.Show.Whenyouarefinishedusingthesprite,thespriteshouldbefreedusingSprite.Free.
Spritesworkbestwhentheyareofmoderatesize.Largespriteswillcauseflashingwhenmovedacrossthescreen.
Anythingthatisiscolor0inthepicturewillnotappearwhenthespriteisdrawn.Inotherwords,color0istransparent.(Thisisbydefault.Youcansetthetransparentcolorforaspritebysettingthepicture'stransparentcolourusingPic.SetTransparentColor.
Example SeeSprite.AnimateforanexampleofSprite.New.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.New,notbycallingNew.
SeealsoSprite.SetHeight,Sprite.SetPosition,Sprite.ShowandSprite.Free.
Sprite.SetFrameRate PartofSpritemodule
Syntax Sprite.SetFrameRate(framesPerSec:int)
Description
Specifiesthemaximumnumberoftimespersecondthatspritepositionswillbechangedonthescreen.Thehigherthenumber,thesmoothertheanimationwillappear(andthemoreprocessortimewillbeusedtoperformtheanimation).
Details
Whenyouchangethepositionorappearanceofasprite,Turingdoesnotupdatethewindowimmediately.Instead,itwaitsacertainlengthoftimeandthenupdatesallspritesthathavemovedsincethelastupdate.Thisallowsforrelativelysmoothanimation.
ThismeansthatyouhaveasimpleloopthatcallsSprite.SetPosition200timesasecond,theimageofthespriteonthescreenisstillonlybeingmoved(bydefault)33timesasecond.
YoucanspecifyhowmanytimesasecondTuringcheckstoseeifaspritehasmovedbyusingtheSprite.SetFrameRateprocedure.Ratesof5-10willmakethemovementofthespritesseemverychoppy.Ratesof100aremoreorlesscompletelysmooth(themaximumis120)andmostCRT'swillnotnoticeanydifferenceafter60.Thedefaultrateis33framespersecond.Youshouldnotethatifyousettheratehigherthanyourcomputercanhandle,everyotherpartofyourprogramwillslowdownasTuringwillbecheckingforspritemovementratherthanexecutingyourprogram.
AmodernPC(2+GHzwithadecentgraphicscard)canprobablyhandleaframerateof60+,dependingonthenumberofsprites.APentiumIIIshouldprobablyusethedefaultrate.Slowermachinesshouldprobablyusealowerrate(around20).Experimentationisthebestwaytodeterminetheidealframerate.
Status
Exportedqualified.
Thismeansthatyoucanonlycallthefunctionbycalling
Sprite.SetFrameRate,notbycallingSetFrameRate.
Sprite.SetHeight PartofSpritemodule
Syntax Sprite.SetHeight(spriteID,newHeight:int)
Description
SetstheheightofthespritespecifiedbyspriteIDtothevaluespecifiedbynewHeight.
Theheightofaspritedetermineswhichspriteappearsaboveanotherwhentheyoverlap.The"higher"sprite(theonewiththegreaterheight)willappearontopofthespritewiththelowerheight,evenifthelowerspriteisdrawnsecond.
Thebackground(i.e.anynon-sprite)isconsideredtobeinheight0.Spriteswithanegativeheightwillappear"behind"thebackground.Notethatiftwospriteshavethesameheight,theonedrawnlastwillappearabovethefirstone.
Example SeeSprite.HideforanexampleofSprite.SetHeight.
Details
Itshouldbenotedthatalotmorecomputationmustbedonetodisplayspriteswithanegativeheight.Ifyouareonaslowermachineandperformanceisnotsufficient,considertryingtoeliminatetheuseofspritesmovingbehindthebackground.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.SetPosition,notbycallingSetPosition.
Seealso Sprite.New.
Sprite.SetPosition PartofSpritemodule
SyntaxSprite.SetPosition(spriteID,x,y:int,centered:boolean)
Description
MovesthespritespecifiedbyspriteIDtothelocationspecifiedby(x,y).Ifcenteredistrue,thenthespriteiscenteredon(x,y).Otherwise(x,y)specifiesthelower-leftcornerofthesprite.
Example SeeSprite.HideforanexampleofSprite.SetPosition.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.SetPosition,notbycallingSetPosition.
Seealso Sprite.New.
Sprite.Show PartofSpritemodule
Syntax Sprite.Show(spriteID:int)
DescriptionDisplaysapreviouslyhiddensprite.Sprite.Showhasnoeffectifthespriteisalreadyvisible.
Example SeeSprite.HideforanexampleofSprite.Show.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSprite.Show,notbycallingShow.
Seealso Sprite.Hide.
sqrt squarerootfunction
Syntax sqrt(r:real):real
DescriptionThesqrtfunctionisusedtofindthesquarerootofanumber.Forexample,sqrt(4)is2.
Example
Thisprogramprintsoutthesquarerootsof1,2,3,…upto100.
fori:1..100
put"Squarerootof",i,"is",sqrt(i)
endfor
Details
Itisillegaltotrytotakethesquarerootofanegativenumber.Theresultofsqrtisalwayspositiveorzero.
Theoppositeofasquarerootisthesquare.Forexample,thesquareofxiswrittenisx**2.
Seealso SeealsopredefinedunitMath.
standardType
Syntax
AstandardTypeisoneof:
(a) int (b) real
(c)string[(maximumLength)]
(d) boolean
(e) nat %naturalnumber
(f) intn %n-byteinteger(n=1,2,4)
(g) natn %n-bytenatural(n=1,2,4)
(h) realn %n-bytereal(n=4,8)
(i) char %singlecharacter
(j) char(n) %ncharacters
DescriptionThestandardtypescanbeusedthroughoutaprogram.Theyshouldnotbeincludedinanimportlist.
Seealsoint,real,stringandboolean.Seealsonat,intn,natn,realn,char,char(n)
statement
Syntax
Astatementisoneof:
(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…endfor
(k) loopStatement %loop…endloop
(l) exit[whentrueFalseExpn] (m) ifStatement %if…endif
(n) caseStatement %case…endcase
(o) asserttrueFalseExpn (p) begin statementsAndDeclarations end
(q) procedureCall %procedureId[(parameters)]
(r) return (s) resultexpn
(t) new[collectionId,]pointerVariableReference
(u) free[collectionId,]pointerVariableReference
(v) tagunionVariableReference,expn
(w) forkStatement %fork… (x) signalvariableReference
(y) waitvariableReference[,expn]
(z) pauseexpn
(aa) quit[guiltyParty][:quitReason] (bb) unchecked (cc) checked
Description
Astatement(orcommand)causesaparticularaction,forexample,theputStatement:
put"Hello"
outputsHello.Seethedescriptionsoftheindividualstatementsforexplanationsoftheiractions.Eachstatementcanoptionallybyfollowedbyasemicolon(;).
Examplewidth:=24%Assignmentstatement
put"Helloworld"%Putstatement
exitwheni=100%Exitstatement
assertwidth<320%Assertstatement
Details
Youcanusearesultstatementonlyinafunction.Youcanuseareturnstatementonlytoterminateaprocedureorthemainprogram(butnottoterminatetheinitializationofamodule).Seealsoresultandreturn.
Thereareanumberofpredefinedprocedures,suchasdrawline,whicharenotlistedasstatementsabove.Theseareconsideredprocedurecalls,whichisoneformofstatement.
statementsAndDeclarations
Syntax
StatementsAndDeclarationsare:
{statementOrDeclaration}
Description
StatementsAndDeclarationsarealistofstatementsanddeclarations.Forexample,aTuringprogramconsistsofalistofstatementsanddeclarations.Thebodyofaprocedureisalistofstatementsanddeclarations.
EachstatementOrDeclarationisoneof:
(a)statement
(b)declaration
Seealsostatementanddeclaration.
Example
ThislistofstatementsanddeclarationsisaTuringprogramthatoutputsHelloFrank.
varname:string
name:="Frank"
put"Hello",name
Str
Description
Thisunitcontainsthepredefinedconstantsformanipulatingstrings.
SeveralroutinesintheStrmoduleareexportedunqualified.
EntryPoints
Lower Convertastringtolowercase.Upper Convertastringtouppercase.Trim Removeleadingandtrailingblanks.index Findsaspecifiedstringinanotherstring.length Returnsthelengthofastring.
repeat Createsastringbyrepeatingaspecifiedstringanumberoftimes.
Str.Lower PartofStrmodule
Syntax Str.Lower(s:string):string
Description
TheStr.Lowerfunctiontakesthestringsandreturnsastringinwhichalltheuppercaselettersareconvertedtolowercase.Forexample,Str.Lower("ABC123def")returns"abc123def".
Example
Thisprogramobtainslinesoftextfromtheuserandoutputsthelinesconvertedtolowercase.
varline:string
loop
put"Enteralineoftext(emptytoquit):"..
getline:*
exitwhenline=""
put"Thelowercaseversion:",Str.Lower(line
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingStr.Lower,notbycallingLower.
Seealso Str.UpperandStr.Trim.
Str.Trim PartofStrmodule
Syntax Str.Trim(str:string):string
Description
TheStr.Trimfunctiontakesthestringstrandreturnsastringinalltheleadingandtrailingspaces(thespacesatthebeginningandtheend)aredeleted.Forexample,Str.Trim("Thisisatest")returns"Thisisatest".Ifstronlyhasspacesinit,thenStr.Trimwillreturnanemptystring.
Example
Thisprogramobtainsinputfromtheuseruntiltheuserentersalinewithnon-whitespacecharactersinit.
varline:string
loop
put"Enteranon-emptylineoftext:"..
getline:*
exitwhenStr.Trim(line)not=""
endloop
put"Youentered",line
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingStr.Trim,notbycallingTrim.
Seealso Str.LowerandStr.Upper.
Str.Upper PartofStrmodule
Syntax Str.Upper(s:string):string
Description
TheStr.Upperfunctiontakesthestringsandreturnsastringinwhichallthelowercaselettersareconvertedtouppercase.Forexample,Str.Upper("ABC123def")returns"ABC123DEF".
Example
Thisprogramobtainslinesoftextfromtheuserandoutputsthelinesconvertedtouppercase.
varline:string
loop
put"Enteralineoftext(emptytoquit):"..
getline:*
exitwhenline=""
put"Theuppercaseversion:",Str.Upper(line
endloop
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingStr.Upper,notbycallingUpper.
Seealso Str.LowerandStr.Trim.
Stream
Description
ThisunitcontainsthepredefinedsubprogramsthatdealwithI/Ostreams.ThebasicI/OinTuringisdonewithI/Ostatements.However,extrafunctionsareallpartoftheStreamunit.
AllroutinesintheStreamunitareexportedqualified(andthusmustbeprefacedwith"Stream."),withtheexceptionofeofwhichispartofthelanguagebutconceptuallypartofthisunitandisconsideredtobeexportedunqualified.
EntryPoints
eof* Determinesiftheendoffilehasbeenreached.Flush Flushesaspecifiedstream.FlushAll Flushesallopenoutputstreams.
*Partofthelanguage,conceptuallypartoftheStreamunit.
Stream.eof PartofStreammodule
Syntax eof(streamNumber:int):boolean
Description
Theeof(endoffile)functionisusedtodetermineifthereisanymoreinput.Itreturnstruewhentherearenomorecharacterstoberead.Theparameteranditsparenthesesareomittedwhenreferringtothestandardinput(usuallythisisthekeyboard);otherwisetheparameterspecifiesthenumberofastream.Thestreamnumberhasbeendetermined(inmostcases)byanopenstatement.
Example
Thisprogramreadsandoutputsallthelinesinthefilecalled"info".
varline:string
varfileNumber:int
open:fileNumber,"info",get
loop
exitwheneof(fileNumber)
get:fileNumber,line:*
putline
endloop
Details
Seealsothedescriptionofthegetstatement,whichgivesmoreexamplesoftheuseofeof.Seealsotheopenandreadstatements.
Whentheinputisfromthekeyboard,theusercansignalend-of-filebytypingcontrol-ZonaPC(orcontrol-DonUNIX).Ifaprogramtestsforeofonthekeyboard,andtheuserhasnottypedcontrol-Z(orcontrol-D)andtheuserhastypednocharactersbeyondthosethathavebeenread,theprogrammustwaituntilthenextcharacteristyped.Oncethischaracteristyped,theprogramknowswhetheritisattheendoftheinput,andreturnsthecorrespondingtrueorfalsevalueforeof.
Status
PartofthelanguageandonlyconceptuallypartoftheStreamunit.
Thismeansthatyoucanonlycallthefunctionbycallingeof,notbycallingStream.eof.
Stream.Flush PartofStreammodule
Syntax Stream.Flush(streamNumber:int)
DescriptionTheStream.FlushprocedureisusedtoflushanybufferedoutputassociatedwiththestreamNumberparameter.
Details
Turingautomaticallyflushesanybufferedoutputwhenastreamisclosed.Turingalsoautomaticallyclosesanyopenfileswhenexecutionisterminated.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingStream.Flush,notbycallingFlush.
Stream.FlushAll PartofStreammodule
Syntax Stream.FlushAll
DescriptionTheStream.FlushAllprocedureisusedtoflushanybufferedoutputinanyopenfile.
Details
Turingautomaticallyflushesanybufferedoutputwhenastreamisclosed.Turingalsoautomaticallyclosesanyopenfileswhenexecutionisterminated.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingStream.FlushAll,notbycallingFlushAll.
string type
Syntax
AstringTypeis:
string[(maximumLength)]
Description
EachvariablewhosetypeisastringTypecancontainasequence(astring)ofcharacters.ThelengthofthissequencemustnotexceedthestringType'smaximumlength.
Examplevarname:string
name:="Nancy"
varlicenceNumber:string(6)
licenceNumber:="175AJN"
Details
Stringscanbeassignedandtheycanbecomparedforbothequalityandforordering.Seealsostringcomparisonandassignmentstatement.
Stringscanbecatenated(joinedtogether)usingthe+operatorandseparatedintosubstrings.Seecatenationandsubstring.Stringfunctionsareprovidedtofindthelengthofastring,tofindwhereonestringappearsinsideanother,andtomakerepeatedcopiesofastringalljoinedtogether.Seelength,index,andrepeat.
Astringtypewrittenwithoutamaximumlengthislimitedtoholdingamaximumof255characters.
ThemaximumLengthofastring,ifgivenasapartofthetype,mustbeknownatcompiletime,andmustbeatleast1andatmost255.Themaximumlengthofastringisgivenbyupper,forexample,upper(licenceNumber)is6.Seealsoupper.
Inthedeclarationofastringthatisavarformalparameterofaprocedureorfunction,themaximumLengthcanbewrittenasanasterisk(*).Here,themaximumlengthistakentobethatofthecorrespondingactualparameter,asin:
proceduredeblank(vars:string(*)).
Thestarcanalsobeusedwhentheparameterisanarrayofstrings.
SeealsoexplicitStringConstantsforexactrulesforwritingstringvaluessuchas"Nancy".Seealsochar(n)andchartypes.
string comparison
Syntax
AstringComparisonisoneof:
(a) stringExpn=stringExpn (b) stringExpnnot=stringExpn (c) stringExpn>stringExpn (d) stringExpn<stringExpn (e) stringExpn>=stringExpn (f) stringExpn<=stringExpn
DescriptionStrings(stringExpns)canbecomparedforequality(=andnot=)andforordering(>,<,>=and<=).
Examplevarname:string:="Nancy"
varlicenceNumber:string(6)
licenceNumber:="175AJN"
Details
Twostringsareconsideredtobeequal(=)iftheyhavethesamelengthandaremadeup,characterbycharacter,ofthesamecharacters.Iftheydiffer,theyareconsideredtobeunequal(not=).
Orderingamongstringsisessentiallyalphabeticorder.StringSisconsideredtocomebeforestringT,thatisS<T,ifthetwoareidenticaluptoacertainpositionandafterthatposition,eitherthenextcharacterofScomesbeforethenextcharacterofT,orelsetherearenomorecharactersinSwhileTcontainsmorecharacters.
S>T(ScomesafterT)meansthesamethingasT<S.S>=TmeansthesamethingasS>TorS=T.S<=TmeansthesamethingasS<TorS=T.
ASCIIgivestheorderingamongindividualcharacters.Itspecifies,amongotherthings,thatlettercapitalLcomes
alphabeticallybeforecapitalletterMandsimilarlyforsmall(lowercase)letters.
OnIBMmainframecomputers,theEBCDICspecificationofcharactersmaybeusedinsteadofASCII.
strint string-to-integer
function
Syntax strint(s:string[,base:int]):int
Description
Thestrintfunctionisusedtoconvertastringtoaninteger.Theintegerisequivalenttostrings.Thenumberbaseparameterisoptional,forexample,strint("47")=47.InTuringproper,thebaseisnotallowedandisassumedtobe10.
Stringsmustconsistofapossiblynullsequenceofblanks,thenanoptionalplusorminussign,andfinallyasequenceofoneormoredigits.Fornumberbaseslargerthan10,thedigitscanincludea,b,c…(alternatelyA,B,C…)whichrepresentthedigitvalues10,11,12…Thebase,ifgiven,mustbeintherange2to36(36becausethereare10basetendigitsand26letters).Forexample,strint("FF",16)=255.
Theintstrfunctionistheinverseofstrint,soforanyintegeri,
strint(intstr(i))=i.
Seealso chr,ord,intstrandstrnatfunctions.
strintok string-to-integer
function
Syntax strintok(s:string[,base:int]):boolean
Description
Thestrintokfunctionisuseddeterminewhetherthestrintfunctioncanbeusedtoconvertthestringtoanintegerwithoutcausinganerror.Ifthestringcanbesuccessfullyconverted,thenstrintokreturnstrue,otherwiseitreturnsfalse.
Stringsshouldconsistofapossiblynullsequenceofblanks,thenanoptionalplusorminussign,andfinallyasequenceofoneormoredigits.Fornumberbaseslargerthan10,thedigitscanincludea,b,c…(alternatelyA,B,C…)whichrepresentthedigitvalues10,11,12…Ifsiscorrectlyconstructed,thenstrnatokwillreturntrue,otherwiseitreturnsfalse.Thebase,ifgiven,mustbeintherange2to36(36becausethereare10basetendigitsand26letters).Forexample,strintok("FF",16)=true.
Seealso strintfunctionthatdoestheactualconversion.
strnat stringtonaturalnumberfunction
Syntax strnat(s:string[,base:int]):nat
Description
Thestrnatfunctionisusedtoconvertastringtoanaturalnumber.Thenaturalnumberisequivalenttostrings.Thenumberbaseparameterisoptional,forexample,strnat("47")=47.
Stringsmustconsistofapossiblynullsequenceofblanks,thenanoptionalplussign,andfinallyasequenceofoneormoredigits.Fornumberbaseslargerthan10,thedigitscanincludea,b,c…(alternatelyA,B,C…)whichrepresentthedigitvalues10,11,12…Thebase,ifgiven,mustbeintherange2to36(36becausethereare10basetendigitsand26letters).Forexample,strnat("FF",16)=255.
Thenatstrfunctionistheinverseofstrnat,soforanynaturalnumbern,strnat(natstr(n))=n.
Thestrnatfunctionissimilartostrint,exceptthatstrnathandlesvaluesthatarelargerthanintvaluesanddoesnothandlenegativevalues.
Seealso thechr,ord,intstrandstrintfunctions.
strnatok stringtonaturalnumberfunction
Syntax strnatok(s:string[,base:int]):boolean
Description
Thestrnatokfunctionisuseddeterminewhetherthestrnatfunctioncanbeusedtoconvertthestringtoanaturalnumberwithoutcausinganerror.Ifthestringcanbesuccessfullyconverted,thenstrnatokreturnstrue,otherwiseitreturnsfalse.
Stringsshouldconsistofapossiblynullsequenceofblanks,thenanoptionalplussign,andfinallyasequenceofoneormoredigits.Fornumberbaseslargerthan10,thedigitscanincludea,b,c…(alternatelyA,B,C…)whichrepresentthedigitvalues10,11,12…Ifsiscorrectlyconstructed,thenstrnatokwillreturntrue,otherwiseitreturnsfalse.Thebase,ifgiven,mustbeintherange2to36(36becausethereare10basetendigitsand26letters).Forexample,strnatok("FF",16)=true.
Seealso strnatfunctionthatdoestheactualconversion.
strreal string-to-realfunction
Syntax strreal(s:string):real
Description
Thestrrealfunctionisusedtoconvertastringtoarealnumber.Forexample,strreal("2.5e1")willproduceanapproximationtothenumber25.0.
Stringsmustconsistofapossiblynullsequenceofblanks,thenanoptionalplusorminussignandfinallyanexplicitunsignedrealorintegerconstant.
Therealstr,erealstrandfrealstrfunctionsapproximatetheinverseofstrreal,althoughround-offerrorskeepthesefrombeingexactinverses.
Seealso realstr,erealstr,frealstr,intstrandstrintfunctions.
strrealok string-to-realfunction
Syntax strrealok(s:string):boolean
Description
Thestrrealokfunctionisuseddeterminewhetherthestrrealfunctioncanbeusedtoconvertthestringtoarealnumberwithoutcausinganerror.Ifthestringcanbesuccessfullyconverted,thenstrrealokreturnstrue,otherwiseitreturnsfalse.
Stringsshouldconsistofapossiblynullsequenceofblanks,thenanoptionalplusorminussignandfinallyanexplicitunsignedrealorintegerconstant.Ifitdoesso,thenstrrealokwillreturntrue,otherwiseitreturnsfalse.
Seealso strrealfunctionthatdoestheactualconversion.
subprogramHeader
Syntax
AsubprogramHeaderisoneof:
(a) procedure[pervasive]id
[([paramDeclaration{,paramDeclaration}])]
(b) function[pervasive]id
[([paramDeclaration{,paramDeclaration}])]
[id]:typeSpec
Description
Asubprogramheaderisusedtodescribetheinterfacetoasubprogram.Subprogramheadersareusedwithinotherlanguagefeaturessuchassubprogramtypesandexternaldeclarations.
Parameterlesssubprogramsmayuseparentheses(withnothingbetweenthem),asisrequiredintheCprogramminglanguage.Theseparenthesescanbeusedtodisambiguatebetweenthecalltothesubprogram(parenthesespresent)andareferencethesubprogram(parenthesesmissing).
Supposefisaparameterlesssubprogramdeclaredwithoutparenthesesandgisaparameterlesssubprogramdeclaredwithparentheses.Theirheadersare:
proceduref
procedureg()
Inaprogram,fandg()arecallstothesefunctions,whilegisareferenceto(notacallto)theprocedure.Thereisnowaytowriteareferencetof.Whenindoubt,useparenthesesinthedeclaration,asinthecaseforg,sothatcallsalwayshaveparenthesesandreferencesalwaysdonot.Areferencetoasubprogramcanbeassignedtoasubprogramvariable.Seesubprogramtype.
ExampleSpecifythattisthetypeofprocedurewithavarintegerparameterandarealparameter.SeealsosubprogramType.
typet:procedureq(varj:int,y:real)
Details
Thekeywordpervasivecanbeinsertedjustafterprocedureorfunction.Whenthisisdone,thesubprogramisvisibleinsideallsubconstructsofthesubprogram'sscope.Withoutpervasive,thesubprogramisnotvisibleinsidemodulesunlessexplicitlyimported.Pervasivesubprogramsneednotbeimported.Youcanabbreviatepervasiveasanasterisk(*).
Seealso pervasive.
subprogramType
Syntax
AsubprogramTypeis:
subprogramHeader
Description
Avariableorconstantcancontainareferencetoasubprogram.ThetypeofthevariableorconstantisasubprogramType.SeealsosubprogramHeader.
Example
Inthefollowingtisasubprogramtype,anduisavariableoftypetinitializedtorefertoprocedurernd.
procedurernd(vari:int,x:real)
i:=round(x)
endrnd
typet:procedureq(varj:int,y:real)
varu:t:=rnd%Procedurevariableureferstornd
…
varj:int
u(j,24.6)%Callprocedureureferringtornd
…
varv:=u%Subprogramvariablevinitializedtou
Details
Thenameofthesubprogram,forexampleq,andtheparameters,forexampleiandx,havenomeaninginasubprogramtype.Theyarepresentonlybecauseoftheformofsubprogramheaders.
Ifvisavariableorconstantthatreferstoasubprogram,vcanbecalled,comparedforequalitytoothersubprogramvariables,assignedandpassedasaparameter.Variablevisnotaninteger,stringorpointerandcannotparticipateintheircorrespondingoperations.
Areferencetoasubprogram,ratherthatthecodeofthesubprogram,iscontainedinavariablevwhosetypeisasubprogramtype.Thisimpliesthataddr(v)istheaddressofthereferencetosubprogram,ratherthantheaddressofthesubprogram.Theaddressofthecodeisgivenby#v.Seecheatforanexplanationofthe#operator.
Youcannotassignareferencetoasubprogramexportedfromaclass.Thisrestrictionexistsbecausethesesubprogramsaremeaninglesswithoutanaccompanyingreferencetoanobject.
Manypotentialusesofsubprogramvariablesarebetterprogrammedusingclassesandoverridingexportedsubprograms.Seeclass.
subrangeType
Syntax
AsubrangeTypeis:
expn..expn
DescriptionAsubrangetypedefinesasetofvalues,forexample,thesubrange1..4consistsof1,2,3and4.
Example
vari:1..10%icanbe1,2…upto10
typexRange:0..319%Defineintegersubrange
varpixels:arrayxRangeofint
%Arrayelementsare
%numbered0,1,…319
fork:xRange%krangesfrom0to319
pixels(k):=0
endfor
Details
Asubrangemustcontainatleastoneelement.Inotherwords,thesecondexpression(expn)mustbeatleastaslargeasthefirstexpression.
Thelowerboundofasubrangemustbeknownatcompiletime.Theupperboundisallowedtobearuntimevalueonlyinonesituationandthatiswhenitgivestheupperboundofanarraybeingdeclaredinavariabledeclaration,inotherwordswhendeclaringadynamicarray.
Subrangesareusuallyasubsetoftheintegers,asin1..10.Youcanalsohavesubrangesofenumeratedtypesandcharacters(thechartype).
Youcanapplyloweranduppertosubrangetypes.
substring ofanotherstring
Syntax
Asubstringisoneof:
(a) stringReference(leftPosition..rightPosition) (b) stringReference(charPosition)
Description
Asubstringselectsapartofanotherstring.Inform(a)thesubstringstartsattheleftpositionandrunstotherightposition.Inform(b),thesubstringisonlyasinglecharacter.Turingsupportsubstringsofchar(n)values.
Example
varword:string:="bring"
putword(2..4)%Outputsrin
putword(3)%Outputsi
putword(2..*)%Outputsring;thestar
%theendofthestring.
putword(*-2..*-1)%Outputsin
Details
Theleftmostpossiblepositioninastringisnumbered1.Thelastpositioninastringcanbewrittenasanasterisk(*).Forexample,word(2..*)isequivalenttoword(2..length(word)).
EachofleftPosition,rightPosition,andcharPositionmusthaveoneoftheseforms:
(a)expn (b)* (c)*-expn
TheexactrulesfortheallowedvaluesofleftPositionandrightPositionare:
(1)leftPositionmustbeatleast1, (2)rightPositionmustbeatmostlength(stringReference),and (3)thelengthoftheselectedsubstringmustzeroormore.
Thisspecificallyallowsnullsubstringssuchasword(1,0)inwhichrightPositionis0andword(6,5)inwhichleftPositionisonemorethatlength(stringReference).
Notethatsubstringsarenotassignable.Forexample,ifsisastring,thestatements(3):="a"isillegalinTuring.
Turingsupportssubstringsofchar(n)values.Seechar(n).Ifasubstringofchar(n)valuethastwooperands,asint(2..77),theresulttypeofthisoperationisastring.Ifthesubstringhasoneoperand,asint(7),thisbecomes,ineffect,asubscriptintoanarrayofcharacters.Theresultisareferencetoachar,whichcanbeassignedtoorpassedtoavarparameter.
Seealsostring,char,char(n),explicitStringConstant,explicitCharConstantcatenationandlength.
succ successorfunction
Syntax succ(expn)
Description
Thesuccfunctionacceptsaninteger,characteroranenumeratedvalueandreturnstheintegerplusone,thenextcharacter,orthenextvalueintheenumeration.Forexample,succ(7)is8.
Example
ThispartofaTuringprogramfillsuparrayawiththeenumeratedvaluesgreen,yellow,red,green,yellow,red,etc.
typecolors:enum(green,yellow,red)
vara:array1..100ofcolors
varc:colors:=colors.green
fori:1..100
a(i):=c
ifc=colors.redthen
c:=colors.green
else
c:=succ(c)
endif
endfor
Details Youcannotapplysucctothelastvalueofanenumeration.
Seealso thepred,lowerandupperfunctions.
Sys
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwiththeoperatingsystemdirectly(gettingtheprocessid,gettingruntimeargumentsandexecutingcommandsintheoperatingsystem,etc.).
AllroutinesintheSysunitareexportedqualified(andthusmustbeprefacedwith"Sys.").
EntryPoints
GetComputerName Getsthenameofthecomputer.
GetEnv Getsastringassociatedwithanenvironmentvariable.
GetPid GetsthecurrentprocessIDforTuring.
GetUserName Getsthenameoftheusercurrentlyloggedon.
Exec Executesaprogramoropensadatafileusingtheoperatingsystem.
Nargs Getsthenumberofruntimearguments(exportedunqualified).
FetchArg Getsaspecifiedruntimeargument(exportedunqualified).
Sys.Exec PartofSysmodule
Syntax Sys.Exec(command:string):boolean
Description
TheSys.Execfunctionisusedtoexecuteanapplicationormoreoften,openadatafilewithitsassociatedapplication.Sys.ExeccanbeusedtolaunchsuchprogramsastheInternetBrowserbyspecifyingaURL.Sys.Execlaunchestheapplicationassociatedwithfile'ssuffix.(Inessence,itperformsthesameoperationasifauserdoubleclickedonthefile.)
Example
ThisprogramlaunchesaninternetbrowserandpointsittoHoltSoftware'shomepage.Itthenlaunchesamovieusingthedefaultvideoplayer.
ifnotSys.Exec("http://www.holtsoft.com/turing/support")
put"TheSys.Execcallfailed"
put"Error:",Error.LastMsg
endif
ifnotSys.Exec("skate.avi")then
put"TheSys.Execcallfailed"
put"Error:",Error.LastMsg
endif
DetailsWhentheSys.Execprocedureisused,theexecutingprogramcontinuesexecutionimmediatelywhilethelaunchedapplicationisrunning.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.ExecExec.
Seealso Sys.Nargs,Sys.FetchArgandSys.GetEnvfunctions.
Sys.FetchArg PartofSysmodule
Syntax System.FetchArg(i:int):string
Description
TheSys.FetchArgfunctionisusedtoaccessthei-thargumentthathasbeenpassedtoaprogramfromthecommandline.Forexample,iftheprogramisrunfromtheTuringenvironmentusing
:rfile1file2
thenSys.FetchArg(2)willreturn"file2".Ifaprogramcalledprog.xunderUNIXusingthiscommand:
prog.xfile1file2
thevalueofSys.FetchArg(2)willsimilarlybe"file2".
TheSys.Nargsfunction,whichgivesthenumberofargumentspassedtotheprogram,isusuallyusedtogetherwiththeSys.FetchArgfunction.ParameteripassedtoSys.FetchArgmustbeintherange0..Sys.Nargs
The0-thargumentisthenameoftherunningprogram.
Example
Thisprogramlistsitsownnameanditsarguments.
put"Thenameofthisprogramis:",Sys.FetchArg
fori:1..Sys.Nargs
put"Argument",i,"is",Sys.FetchArg(i
endfor
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.FetchArgbycallingFetchArg.
Seealso Sys.Nargs
Sys.GetComputerName PartofSysmodule
Syntax Sys.GetComputerName:string
Description
TheSys.GetComputerNamefunctionisusedtodeterminethenameofthecomputer.OnthePC,thisistheNetBIOSname.Itreturns“NoName”ifanamecouldnotbedetermined.
Example
Thisprogramoutputsagreetingtotheuser.
varcomputerName,userName:string
computerName:=Sys.GetComputerName
userName:=Sys.GetUserName
put"Hello",userName,"on",computerName
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.GetComputerName,notbycallingGetComputerName.
SeealsoSys.GetUserNametoobtaintheusernameoftheusercurrentlyloggedin.
Sys.GetEnv PartofSysmodule
Syntax Sys.GetEnv(symbol:string):string
Description
TheSys.GetEnvfunctionisusedtoaccesstheenvironmentstringwhosenameissymbol.Thesestringsaredeterminedbytheshell(commandprocessor)ortheprogramthatcausedyourprogramtorun.SeealsotheSys.NargsandSys.FetchArgfunctions.
Example
OnaPC,thisretrievestheenvironmentvariableUSERLEVELandprintsextrainstructionsifUSERLEVELhadbeensettoNOVICE.USERLEVELcanbesettoNOVICEwiththecommandSETUSERLEVEL=NOVICEintheautoexec.batfileorinanybatchfile.
constuserLevel:string
userLevel:=Sys.GetEnv("USERLEVEL")
ifuserLevel="NOVICE"then
…%putasetofinstructions
endif
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.GetEnv,notbycallingGetEnv.
Sys.GetPid PartofSysmodule
Syntax Sys.GetPid:int
Description
TheSys.GetPidfunctionisusedtodeterminetheI.D.(number)thatidentifiesthecurrentoperatingsystemtask(process).Bewarethatthereareprocesses,activatedbytheforkstatement,thatareindependentoftheoperatingsystemstasks.
UnderUNIX,thenumberisused,forexample,forcreatingauniquenameofafile.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.GetPid,notbycallingGetPid.
Seealso Sys.Nargs,Sys.FetchArgandSys.GetEnv.
Sys.GetUserName PartofSysmodule
Syntax Sys.GetUserName:string
Description
TheSys.GetUserNamefunctionisusedtodeterminethenameofthecurrentuser.Itreturns“Unknown”ifanamecouldnotbedetermined.
Example
Thisprogramoutputsagreetingtotheuser.
varcomputerName,userName:string
computerName:=Sys.GetComputerName
userName:=Sys.GetUserName
put"Hello",userName,"on",computerName
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.GetUserName,notbycallingGetUserName.
Seealso Sys.GetComputerNametoobtainthenameofthecomputer.
Sys.Nargs PartofSysmodule
Syntax Sys.Nargs:int
Description
TheSys.Nargsfunctionisusedtodeterminethenumberofargumentsthathavebeenpassedtoaprogramfromthecommandline.Forexample,iftheprogramisrunfromtheTuringenvironmentusing
:rfile1file2
thenSys.Nargswillreturn2.Ifaprogramcalledprog.xisrununderUNIXusingthiscommand:
prog.xfile1file2
thevalueofSys.Nargswillsimilarlybe2.
TheSys.NargsfunctionisusuallyusedtogetherwiththeSys.FetchArgfunctiontoaccesstheargumentsthathavebeenpassedtotheprogram.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingSys.Nargs,notbycallingNargs.
Seealso Sys.FetchArgforanexampleoftheuseofSys.Nargs.
sysclock millisecsusedprocedure
Syntax sysclock(varc:int)
Description
ThesysclockstatementisusedonamultitaskingsystemsuchasUNIXtodeterminetheamountoftimethathasbeenusedbythisprogram(process).Variablecisassignedthenumberofcentralprocessormillisecondsassignedtothisprogram.Thisisoflittleuseonapersonalcomputer,wheresysclockreturnsthesamevalueasclock.
Example
OnaUNIXsystem,thisprogramtellsyouhowmuchtimeithasused.
vartimeUsed:int
sysclock(timeUsed)
put"Thisprogramhasused",timeUsed,
"millisecondsofCPUtime"
Seealsodelay,time,clock,wallclockanddatestatements.
SeealsopredefinedunitTime.
system statement
Syntax system(command:string,varret:int)
Description
Thesystemstatementisusedtoexecutetheshell(operatingsystem)ifitweretypedattheterminal.Thereturncodeisinret.Areturncodeof0(zero)meansnodetectederrors.Areturncodeof127meansthecommandprocessorcouldnotbeaccessed.Areturncodeof126meansthecommandprocessordidnothaveroomtorunonthePC.
Example
ThisprogramcreatesadirectorylistingwhenrununderDOSonanIBMPCcompatiblecomputer.ThesameprogramwillrununderUNIXbychanging"to"ls".
varsuccess:int
system("dir",success)
ifsuccessnot=0then
ifsuccess=127then
put"Sorry,can'tfind'command.com'"
elsifsuccess=126then
put"Sorry,noroomtorun'dir'"
else
put"Sorry,'dir'didnotwork"
endif
endif
Details
Whenthesystemprocedureisused,theexecutingprogramusuallyremainsinmemorywhilethesystemcommandisexecuting,andonceexecutionofthesystemcommandisfinished,controlreturnstotheoriginalprogram.However,onthePC,thereisvariantofthesystemprocedurethatallows"chaining".Thismeansthatwhenthesystemcommandisexecuted,theoriginallyrunningprogramis"thrownaway"(i.e.removedfrommemory).Whentheexecutedprogramterminates,oneisreturnedtoDOS.
Tochainanotherprogram,oneprepends"chain:"tothestartcommand
i.e.system("chain:myprog.exe",retCode)
Notethatthiscommandis"hazardous".Specifically,ifyoucallitfromTuring(asopposedtoaprogramcompiledwithTComp)andyouhavenotsavedyoursourcefile,youwillloseit!Turingwillberemovedfrommemorywithoutanywarning
whenthesystemprocedureisexecuted.Likewiseanyopenfileswillbeclosedinstantly.Thismeansthereisadangerifallfileswerenotproperlyclosedbeforethesystemprocedurewascalled.
The"chain:"commandisoftenusedforstartingmenuprograms,wheretheuserselectsaprogramtorunanddoesn'twantTuringtoremaininmemory.ItcanalsobeusedwithextraordinarilylargeTuringprogramsthatcanbesplitintodifferentparts.ByusingTCompandcompilingeachpartseparately,onecanhaveeachprogramcalltheotherandneverhaveallpartsinmemoryatonce.
Example
Thisprogramuseschainingtolaunchoneofseveralpossibleprogramsbasedonuserchoice.Itgivesanerrorifforsomereasonthesystemcommandfailstowork.Itassumesthatc:\chemistry.exe,c:\math.exe,c:\english.exeandc:\history.exealreadyexist.
varchoice,success:int
put"Enterthesubject(1-4):"..
getchoice
varcommand:string
casechoiceof
%Notetheuseofthedoublebackslashinthefilename
%isbecausethebackslashisaspecialcharacterinTuring(as
%in\tfortaband\nforanewline).Togetasinglebackslash
%oneuses\\.
label1:command:="c:\\chemistry.exe"
label2:command:="c:\\math.exe"
label3:command:="c:\\english.exe"
label4:command:="c:\\history.exe"
label:put"Choicemustbefrom1-4."
assertfalse%Wasn'ta1-4.Terminate.
endcase
system("chain:"+command,success)
%IfIreachthisline,thesystemcommandfailedandoneshouldgive
%anerrormessage.
put"Systemcalledfailed."
put"Program\"",command,"\"couldn'tberun."
assertfalse%Terminatetheprogram
Details
HerearethepossibleerrorsunderPC-Turing
-1 NotenoughmemorytoloadCOMMAND.COM -2 Notenoughmemorytoruncommand -3 Argumentlistgreaterthan128bytesorenvironmentinfo
-4 Couldn'tfindCOMMAND.COM -5 COMMAND.COMcorrupt -6 -noshelloptionisselected,thesystemprocedureis disallowed
Seealsonargs,fetchargandgetenvfunctions.
SeealsopredefinedunitSys.
tag statement
Syntax
AtagStatementis:
tagunionVariableReference,expn
DescriptionAtagstatementisaspecial-purposeassignmentthatisusedforchangingthetagofaunionvariable.
Example
Inthisexample,thetagfieldofunionvariablevissettobepassenger,therebyactivatingthepassengerfieldofv.
typevehicleInfo:
unionkind:passenger..recreational
labelpassenger:
cylinders:1..16
labelfarm:
farmClass:string(10)
label:%Nofieldsfor"otherwise"clause
endunion
varv:vehicleInfo
…
tagv,passenger%Activatepassengerpart
Details
Atagstatementistheonlywaytomodifythetagfieldofaunionvariable(otherthanbyassigninganentireunionvaluetotheunionvariable).
Youcannotaccessaparticularsetoffieldsofaunionunlessthetagissettomatchthecorrespondinglabelvalue.
Seealso uniontypes.
takepic graphicsprocedure
setscreen("graphics")
…drawhappyfaceinthebox(0,0)to(100,100)…
%Createbufferbigenoughtoholdhappyface
varface:array1..sizepic(0,0,100,100)ofint
%Copypictureintothebuffer,whichisthefacearray
takepic(0,0,100,100,face)
%Redrawthepicturewithitsleftbottomat(200,0)
drawpic(200,0,face,0)
Syntax takepic(x1,y1,x2,y2:int,varbuffer:array1..*ofint)
Description
Thetakepicprocedureisusedtorecordthepixelvaluesinarectangle,withleftbottomandrightcornersof(x1,y1)and(x2,y2),inthebufferarray.Thisrequiresasufficiently-largebuffer(seesizepic).Thedrawpicprocedureisusedtomakecopiesoftherecordedrectangleonthescreen.
Example
Afterdrawingahappyface,thisprogramcopiesthefacetoanewlocation.
Execute
Theintegervaluesthattakepicplacesinthebuffercanbereadorwritten(usingthereadandwritestatements).Unfortunately,ifa
Details
valuehappenstobethepatternusedtorepresenttheuninitializedvalue(thelargestnegativenumberthehardwarecanrepresent)assignment(by:=)andputoftheindividualintegervaluesinthebufferwillfail.
Thescreenshouldbeina"graphics"mode.Seethesetscreenprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Details
Thedrawpic,takepic,andsizepicsubprogramshavebeenmadeobsoletebythesubprogramsPic.DrawandPic.NewofthePicmodule.Usersarestronglysuggestedtousethoseroutinesinstead.ThePicmodulealsocontainssubprogramstoloadimagesfromfiles.
Seealso
sizepicanddrawpic.Seealsosetscreen,maxx,maxy,drawdot,drawline,drawbox,anddrawoval.
SeealsopredefinedunitPic.
tan tangentfunction(radians)
Syntax tan(r:real):real
DescriptionThetanfunctionisusedtofindthetangentofananglegiveninradians.Forexample,tan(p/4)is0.5.
Example
Thisprogramprintsoutthetangentof0,p/6,2p/6,3p/6,upto12p/6radians.
fori:0..12
constangle:=i*Math.PI/6
put"Tangentof",angle,"is",tan(angle
endfor
Execute
Details
Anargumenttotanofp/2,3*p/2,etc.mayresultinanoverflow(andhaltoftheprogram)astheresultistechnically¥.(Itmaynotcauseanoverflowduetorounding,inwhichcasetheresultwillsimplybeaverylargenumber.)
Seealso
thesinandcosfunctionsforcalculatingsineandcosine.
thetandfunctionwhichfindsthetangentofananglegivenindegrees.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
tand tangentfunction(degrees)
Syntax tand(r:real):real
DescriptionThetandfunctionisusedtofindthetangentofananglegivenindegrees.Forexample,tand(45)is1.
Example
Thisprogramprintsoutthetangentof0,30,60,90,upto360degrees.
fori:0..12
constangle:=i*30
put"Tanof",angle,"is",tand(angle)
endfor
Execute
Details
Anargumenttotanof90,270,etc.mayresultinanoverflow(andhaltoftheprogram)astheresultistechnically¥.(Itmaynotcauseanoverflowduetorounding,inwhichcasetheresultwillsimplybeaverylargenumber.)
Seealso
thesindandcosdfunctionsforcalculatingsineandcosine.
thetanfunctionwhichfindsthetangentofananglegiveninradians.(2pradiansarethesameas360degrees.)
SeealsopredefinedunitMath.
tell filestatement
Syntax
AntellStatementis:
tell:fileNumber,filePositionVar
Description
ThetellstatementsetsfilePositionVar,whosetypemustbeint,tothecurrentoffsetinbytesfromthebeginningofthespecifiedfile.ThefileNumbermustspecifyafilethatisopenwithseekcapability(orelseaprogramargumentfilethatisimplicitlyopened).Thetellstatementisusefulforrecordingthefilepositionofacertainpieceofdataforlateraccessusingseek.
Example
Thisexampleshowshowtousetelltorecordthelocationofarecordinafile.Thislocationislaterusedbyseektoallowtherecordtoberead.
varemployeeRecord:
record
name:string(30)
pay:int
dept:0..9
endrecord
varfileNo:int
varlocation:int
open:fileNo,"payroll",write,seek
…
tell:fileNo,location%Makenoteofthislocation
write:fileNo,employeeRecord%Writerecordatthislocation
…
seek:fileNo,location%Gobacktolocation
read:fileNo,employeeRecord%Readtherecord
%thatwaspreviouslywritten
Seealso theread,write,open,close,seek,getandputstatements.
Text
Description
Thisunitcontainsthepredefinedsubprogramsthathandlecharacter(text)outputonthescreen(i.e.outputusingput).
AllroutinesintheTextunitareexportedqualified(andthusmustbeprefacedwith"Text.")withtheexceptionofmaxrowandmaxcolwhichareexportedunqualified.
EntryPoints
Cls Clearsthescreentothetextbackgroundcolor.
Color Setsthetextcolorusedbyput.Colour Setsthetextcolorusedbyput.
ColorBack Setsthetextbackgroundcolorusedbyput.
ColourBack Setsthetextbackgroundcolorusedbyput.
Locate Movesthecursortothespecifiedrowandcolumn.
LocateXY Movesthecursortothecursorlocationclosesttoaspecifiedpixelposition.
maxcol Thenumberofcolumnsonthescreen(exportedunqualified).
maxrow Thenumberofrowsonthescreen(exportedunqualified).
WhatRow Returnsthecurrentcursorrow.WhatCol Returnsthecurrentcursorcolumn.WhatColor Returnsthecurrenttextcolor.WhatColour Returnsthecurrenttextcolor.WhatColorBack Returnsthecurrenttextbackgroundcolor.WhatColourBack Returnsthecurrenttextbackgroundcolor.
Text.Cls PartofTextmodule
Syntax Text.Cls
Description
TheText.Cls(clearscreen)procedureisusedtoblankthescreentothetextbackgroundcolor.Thecursorissettothetopleft(torow1,column1).
Details
Thescreenshouldbeina"screen"or"graphics"mode.Ifthescreenmodehasnotbeenset,itwillautomaticallybesetto"screen"mode.SeeView.Setfordetails.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.Cls,notbycallingCls.
Text.Color PartofTextmodule
Syntax Text.Color(Color:int)
Description
TheText.Colorprocedureisusedtochangethecurrently-activecolor.Thisisthecolorofcharactersthataretobeputonthescreen.ThealternatespellingisText.Colour.
Example
Thisprogramprintsoutthemessage"Bravo"threetimes,eachinadifferentcolor.
View.Set("graphics")
fori:1..3
Text.Color(i)
put"Bravo"
endfor
Example
Thisprogramprintsoutamessage.Thecolorofeachletterisdifferentfromtheprecedingletter.Forletternumberithecolornumberisimodmaxcolor+1.Thiscyclesrepeatedlythroughalltheavailablecolors.
View.Set("screen")
constmessage:="HappyNewYear!!"
fori:1..length(message)
Text.Color(imodmaxcolor+1)
putmessage(i)..
endfor
Details
In"screen"modeontheIBMPC,thecolorspecifiedcanactuallyrangefrom0-31.Theupper16colors(16-31)arethesameasthelower16,exceptthattheyblink.
SeeView.Setforthenumberofcolorsavailableinthevarious"graphics"modes.
Thescreenshouldbeina"screen"or"graphics"mode.Ifthescreenmodehasnotbeenset,itwillautomaticallybesetto"screen"mode.SeeView.Setfordetails.
StatusExportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.Color,notbycallingColor.
SeealsoText.ColorBack,Text.WhatColor,Text.WhatCharandView.maxcolor.
Text.ColorBack PartofTextmodule
Syntax Text.ColorBack(Color:int)
Description
TheText.ColorBackprocedureisusedtochangethecurrenttextbackgroundcolor.ThealternatespellingisText.ColourBack.
TheText.ColorBackproceduresetsthetextbackgroundcolortothespecifiedcolor.Thisisthecolorthatsurroundscharacterswhentheyareputontothescreen.OnanIBMPCin"screen"mode,thecolorcanbefrom0-7.(Youcannothavetheupper8colorsastextbackgroundcolors.OnUNIXdumbterminals,Text.ColorBack(1)turnsonhighlightingandText.ColorBack(0)turnsitoff.Onothersystems,thisproceduremayhavenoeffect.
Example
Sincethisprogramisin"screen"mode,changingthebackgroundcolorhasnoimmediatelyobservableeffect.Whenthemessage"Greetings"isoutput,thebackgroundsurroundingeachletterwillbered.
View.Set("screen")
…
Text.ColorBack(red)
put"Greetings"
Details
Thescreenshouldbeina"screen"or"graphics"mode.Ifthescreenmodehasnotbeenset,itwillautomaticallybesetto"screen"mode.SeeView.Setfordetails
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.ColorBack,notbycallingColorBack.
Seealso Text.ColorandText.WhatColorBack.
Text.Locate PartofTextmodule
Syntax Text.Locate(row,column:int)
Description
TheText.Locateprocedureisusedtomovethecursorsothatthenextoutputfromputwillbeatthegivenrowandcolumn.Row1isthetopofthescreenandcolumn1istheleftsideofthescreen.
Example
Thisprogramoutputsstarsofrandomcolorstorandomlocationsonthescreen.Thevariablecolrispurposelyspelleddifferentlyfromthewordcolortoavoidtheprocedureofthatname(usedtosetthecolorofoutput).Therownumberispurposelychosensothatitisonelessthanmaxrow.Thisavoidsthescrollingofthescreenwhichoccurswhenacharacterisplacedinthelastcolumnofthelastrow.
View.Set("screen")
varrow,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"*"..%Usedot-dottoavoidclearingendofline
endloop
Details
TheText.Locateprocedureisusedtolocatethenextoutputbasedonrowandcolumnpositions.SeealsotheText.LocateXYprocedurewhichisusedtolocatetheoutputbasedxandypositions,wherex=0,y=0istheleftbottomofthescreen.
Thescreenshouldbeina"screen"or"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotinoneofthesemodes,itwillautomaticallybesetto"screen"mode.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.Locate,notbycallingLocate.
Seealso View.SetandDraw.Dot.
Text.LocateXY PartofTextmodule
Syntax Text.LocateXY(x,y:int)
Description
TheText.LocateXYprocedureisusedtomovethecursorsothatthenextoutputfromputwillbeatapproximately(x,y).Theexactlocationmaybesomewhattotheleftofxandbelowytoforcealignmenttoacharacterboundary.
Example
ThisprogramoutputsHellostartingatapproximately(100,50)onthescreen.
View.Set("graphics")
Text.LocateXY(100,50)
put"Hello"
Details
TheText.LocateXYprocedureisusedtolocatethenextoutputbasedonxandypositions,wherethepositionx=0,y=0istheleftbottomofthescreen.SeealsotheText.Locateprocedurewhichisusedtolocatetheoutput-basedrowandcolumnpositions,whererow1isthetoprowandcolumn1istheleftcolumn.
Thescreenshouldbeina"graphics"mode.SeetheView.Setprocedurefordetails.Ifthescreenisnotina"graphics"mode,itwillautomaticallybesetto"graphics"mode.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.LocateXY,notbycallingLocateXY.
Seealso View.SetandDraw.Dot.
Text.maxcol PartofTextmodule
Syntax maxcol:int
DescriptionThemaxcolfunctionisusedtodeterminethenumberofcolumnsonthescreen.
ExampleThisprogramoutputsthemaximumcolumnnumber.
put"Numberofcolumnsonthescreenis",maxrow
Details
ForIBMPCcompatiblesaswellasmostUNIXdumbterminals,in"text"or"screen"mode,maxcol=80.ForthedefaultIBMPCcompatible"graphics"mode(CGA),maxcol=40.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallingmaxcolorbycallingText.maxcol.
Seealso Text.Locateprocedureforanexampleoftheuseofmaxcol.
Text.maxrow PartofTextmodule
Syntax maxrow:int
DescriptionThemaxrowfunctionisusedtodeterminethenumberofrowsonthescreen.
ExampleThisprogramoutputsthemaximumrownumber.
put"Numberofrowsonthescreenis",maxrow
DetailsForIBMPCcompatibles,maxrow=25.FormanyUNIXdumbterminals,maxrow=24.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallingmaxroworbycallingText.maxrow.
Seealso Text.Locateprocedureforanexampleoftheuseofmaxrow.
Text.WhatCol PartofTextmodule
Syntax Text.WhatCol:int
DescriptionTheText.WhatColfunctionisusedtodeterminethecursorposition'scolumn.
Example
ThisprogramoutputsThecurrentrowis5,thecurrentcolumnis15.
Text.Locate(5,10)
put"12345"..
put"Thecurrentrowis",Text.WhatRow
put"Thecurrentcolumnis",Text.WhatCol
DetailsThescreenshouldbeina"screen"or"graphics"mode.Text.WhatColfunctionsproperlyevenifthecursorisinvisible.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.WhatCol,notbycallingWhatCol.
Seealso
theText.WhatRowfunction,whichisusedtodeterminethecursorrow.SeealsotheText.Locate,Text.maxrowandText.maxcolprocedure.
Text.WhatColor PartofTextmodule
Syntax Text.WhatColor:int
Description
TheText.WhatColorfunctionisusedtodeterminethecurrenttext(foreground)color,ie.,thecolorusedforcharactersthatareoutputusingput.ThealternatespellingisText.WhatColour.
Example
Thisprogramoutputsthecurrently-activecolornumber.Themessageisalsogiveninthecurrently-activecolor.
View.Set("graphics")
…
put"Thiswritingisincolornumber",Text.WhatColor
DetailsThescreenshouldbeina"screen"or"graphics"mode.SeeView.Setfordetails.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.WhatColor,notbycallingWhatColor.
SeealsotheText.Colorprocedure,whichisusedtosetthecolor.SeealsoText.ColorBackandText.WhatColorBack.
Text.WhatColorBack PartofTextmodule
Syntax Text.WhatColorBack:int
Description
TheText.WhatColorBackfunctionisusedtodeterminethecurrenttextbackgroundcolor.Thealternatespellingiswhatcolourback.
Example
Thisprogramoutputsthecurrently-activebackgroundcolornumber.Thebackgroundcolorofthemessageisdeterminedbythisnumber.
View.Set("screen")
…
put"Thebackgroundofthiswriting"
put"isincolornumber",Text.WhatColorBack
Details
Thescreenshouldbeina"screen"or"graphics"mode.Bewarethatthemeaningofbackgroundcolorisdifferentinthesetwomodes.SeeText.ColorBackfordetails.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.WhatColorBack,notbycallingWhatColorBack.
Seealso Text.ColorandText.WhatColor.
Text.WhatRow PartofTextmodule
Syntax Text.WhatRow:int
DescriptionTheText.WhatRowfunctionisusedtodeterminethecursorposition'srow.
Example
ThisprogramoutputsThecurrentrowis5,thecurrentcolumnis15.
Text.Locate(5,10)
put"12345"..
put"Thecurrentrowis",Text.WhatRow
put"Thecurrentcolumnis",Text.WhatCol
DetailsThescreenshouldbeina"screen"or"graphics"mode.Text.WhatRowfunctionsproperlyevenifthecursorisinvisible.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingText.WhatRow,notbycallingWhatRow.
Seealso
theText.WhatColfunction,whichisusedtodeterminethecursorcolumn.SeealsotheText.Locate,Text.maxrowandText.maxcolprocedure.
Time
Description
Thisunitcontainsthepredefinedsubprogramsthathandleanythingtodowithtime,eitherasadateorasatimer.
AllroutinesintheTimeunitareexportedqualified(andthusmustbeprefacedwith"Time.").
EntryPoints
Sec Returnsthenumberofsecondssince1/1/197000:00:00GMT.
Date Returnsthecurrentdateandtimeasastring.
SecDate Convertsanumberofsecondsintoadate/timestring.
DateSec Convertsadate/timestringtoanumberofseconds.
SecParts
Convertsthenumberofsecondssince1/1/197000:00:00GMTintoadayofmonth,month,year,dayofweek,hour,minuteandsecondintegers.
PartsSec Convertsadayofmonth,month,year,hour,minuteandsecondintegersintothenumberofsecondssince1/1/197000:00:00GMT.
SecStr Convertsthenumberofsecondssince1/1/197000:00:00GMTintoauserspecifiedformattedstringrepresentingthedate.
Elapsed Returnsthenumberofmillisecondselapsedsincetheprogramstartedtorun.
ElapsedCPU ReturnsthenumberofmillisecondsofCPUtimeelapsedsincetheprogramstartedtorun.
Delay Sleepsforaspecifiednumberofmilliseconds.
DelaySinceLast SleepsuntilaspecifiednumberofmillisecondssincethelastcalltoTime.DelaySinceLast.
Time.Date PartofTimemodule
Syntax Time.Date:string
Description
TheTime.Datefunctionreturnsthecurrentdateandtimeasastring.Thereturnedstringintheformat"ddmmmyyhh:mm:ss",wheremmmisthefirst3charactersofthemonth,e.g.,"Apr".Forexample,ifthedateisChristmas1989at9:02:37inthemorning,Time.Datewillreturn"25Dec8909:02:37".Twenty-fourhourtimeisused,soeleventhirtyatnightthesamedaywouldreturn"25Dec8923:30:00"
Example
Thisprogramgreetsyouandtellsyouthedateandtime.
vartheDateTime,theDate,theTime:string
theDateTime:=Time.Date
theDate:=theDateTime(1..9)
theTime:=theDateTime(11..*)
put"Greetings!!Thedateandtimetodayis",
Details
Bewarnedthatonsomecomputers,suchasIBMPCcompatiblesorAppleMacintoshes,thedatemaynotbesetcorrectlyintheoperatingsystem;inthatcase,theTime.Dateprocedurewillgiveincorrectresults.
ThestringformofthedatecanbeconvertedtoanumericformforcomparisonpurposesusingtheTime.DateSecfunction.ThenumericformcanbeconvertedtoastringusingtheTime.SecDatefunction.ThenumericformofthetimecanbeobtainedusingtheTime.Secfunction.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.Date,notbycallingDate.
Seealso Time.Sec,Time.DateSecandTime.SecDatefunctions.
Time.DateSec PartofTimemodule
Syntax Time.DateSec(dateString:string):int
Description
TheTime.DateSecfunctionisusedtoconvertadateandtimestringintoanumber,specifically,thenumberofsecondssince00:00:00GMTJan1,1970.
Thefunctioncanalsoconvertjustthedate("ddmmmyy"),inwhichcaseitreturnsthenumberofsecondssince00:00:00GMTJan1,1970frommidnightoftheenteredday.Itwillalsoconvertatimewithoutthedate("hh:mm:ss"),inwhichcaseitreturnsthenumberofsecondsthathavepassedsincemidnightofthatday.
Iftheformatisincorrectorcan'tbeinterpreted,thenTime.DateSecwillreturn1andError.LastandError.LastMsgwillbesettotheappropriateerror.
Example
Thisprogramgivesthenumberofsecondssince00:00:00GMTJan1,1970.
vartheDateTime,theDate,theTime:string
theDateTime:=Time.Date
theDate:=theDateTime(1..9)
theTime:=theDateTime(11..*)
put"Thenumberofsecondsfrom00:00:00GMTJan1,1970",
"frommidnight",theDate,"is",Time.DateSec
put"Thenumberofsecondsfrommidnightto",theTime
Time.DateSec(theTime)
put"Thenumberofsecondsfrom00:00:00GMTJan1,1970",
"from",theDateTime,"is",Time.DateSec(theDateTime
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.DateSec,notbycallingDateSec.
Seealso Time.Sec,Time.DateandTime.SecDatefunctions.
Time.Delay PartofTimemodule
Syntax Time.Delay(duration:int)
DescriptionTheTime.Delayprocedureisusedtocausetheprogramtopauseforagiventime.Thetimedurationisinmilliseconds.
Example
Thisprogramprintstheintegers1to10withaseconddelaybetweeneach.
fori:1..10
puti
Time.Delay(1000)%Pausefor1second
endfor
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.Delay,notbycallingDelay.
Seealso Time.ElapsedandTime.ElapsedCPU.
Time.DelaySinceLast PartofTimemodule
Syntax Time.DelaySinceLast(duration:int)
Description
TheTime.DelaySinceLastprocedureisusedtocausetheprogramtopauseforagiventimesincethelastcalltoTime.DelaySinceLast.Thetimedurationisinmilliseconds.
Example
Thisprogramoutputsfrom1to100,000,thenoutputshowlongittooktodothis(inmilliseconds).ItthencallsTime.DelaySinceLasttowaituntil10secondshaspassedsincethebeginningoftheprogram(regardlessofhowlongittooktoexecutetheloop).Finallyitoutputshowmanymillisecondshaspassedsincetheprogramstarted.Thisshouldbecloseto10,000milliseconds.
vart:int:=Time.Elapsed
put"Startingnow,countto100,000"
fori:1..100000
puti..
locate(whatrow,1)
endfor
put"Finishedcountingto100,000"
put"Elapsedtime:",Time.Elapsed-t,"milliseconds"
Time.DelaySinceLast(10000)
put"Elapsedtime:",Time.Elapsed-t,"milliseconds"
Execute
TheTime.DelaySinceLastisusuallyusedtotimeaprocesssothatitoperatesonthesamespeednomatterwhatthemachine.Forexample,intheaboveexample,theprogramwillalwyastake10secondstoexecute,regardlessofthespeedofthemachine(up
Details
toapoint).FastmachineswillspendlittletimeintheforloopandlongerwaitingtoreturnfromTime.DelaySinceLast.SlowermachineswilltakelongertoexecutetheloopandwillconsequentlywaitlesstimebeforereturningfromTime.DelaySinceLast.
TheTime.DelaySinceLastprocedureisoftenusedtotimethespeedofanimationingames.
Notethatthisonlyworksuptoapoint.Onaveryslowmachine,theforloopmaytakelongerthan10secondstoexecute,inwhichcasethecalltoTime.DelaySinceLastwillreturninstantly.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.DelaySinceLast,notbycallingDelaySinceLast.
Seealso Time.ElapsedandTime.ElapsedCPU.
Time.Elapsed PartofTimemodule
Syntax Time.Elapsed:int
Description
TheTime.Elapsedfunctionreturnstheamountoftimesinceaprogram(process)startedrunning.Thenumberofmillisecondssincetheprogramstartedrunningisreturned.
Example
Thisprogramtellsyouhowmuchtimeithasused.
vartimeRunning:int
timeRunning:=Time.Elapsed
put"Thisprogramhasrun",timeRunning,"milliseconds"
Details
OnIBMPCcompatibles,thisisthetotaltimesincetheTuringsystemwasstartedup.Thehardwareresolutionofdurationisinunitsof55milliseconds.Forexample,Time.Elapsedmaybeoffbyasmuchas55milliseconds.
OnAppleMacintoshes,thisisthetotaltimesincethemachinewasturnedon.Thehardwareresolutionofdurationisinunitsof17milliseconds(1/60-thofasecond).
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.Elapsed,notbycallingElapsed.
Seealso Time.ElapsedCPUandTime.Delaysubprograms.
Time.ElapsedCPU PartofTimemodule
Syntax Time.ElapsedCPU:int
Description
TheTime.ElapsedCPUfunctionisusedonamultitaskingsystemsuchasUNIXtodeterminetheamountoftimethathasbeenusedbythisprogram(process).Thenumberofcentralprocessormillisecondsassignedtothisprogramisreturned.Thisisoflittleuseonapersonalcomputer,whereTime.ElapsedCPUreturnsthesamevalueasTime.Elapsed.
Example
OnaUNIXsystem,thisprogramtellsyouhowmuchtimeithasused.
vartimeUsed:int
timeUsed:=Time.ElapsedCPU
put"Thisprogramhasused",timeUsed,
"millisecondsofCPUtime"
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.ElapsedCPU,notbycallingElapsedCPU.
Seealso Time.ElapsedandTime.Delaysubprograms.
Time.PartsSec PartofTimemodule
SyntaxTime.PartsSec(year,month,day,hour,minute,second:int):int
Description
TheTime.PartsSecfunctionisusedtoconvertthenumericpartsofadate(specificallytheyear,month,day,hour,minuteandsecond)intothenumberofsecondssince00:00:00GMTJan1,1970andthedatespecifiedbytheparts.
Thefunctioncanalsoconvertatimewithoutadate(year,monthanddayareall0),inwhichcaseitreturnsthenumberofsecondsthathavepassedsincemidnightofthecurrentday.
Ifthenumbersdon'tmakeanysenseorcan'tbeinterpreted,thenTime.PartsSecwillreturn1andError.LastandError.LastMsgwillbesettotheappropriateerror.
Example
Thisprogramgivesthenumberofsecondsbetween00:00:00GMTJan1,1970and9:27inthemorning,ChristmasDay,1989).
put"Thenumberofsecondsfrom00:00:00GMTJan1,1970",
"is",Time.PartsSec(1989,12,25,9,27,0
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.PartsSec,notbycallingPartsSec.
Seealso Time.SecParts,Time.DateandTime.Secfunctions.
Time.Sec PartofTimemodule
Syntax Time.Sec:int
Description
TheTime.Secfunctionreturnsthecurrentdateandtimeasanumber.Thereturnedintegeristhetimeinsecondssince00:00:00GMT(GreenwichMeanTime)January1,1970.
ExampleThisprogramtellsyouhowmanysecondssince1970.
put"Thenumberofsecondssince1970is",Time.Sec
Details
Bewarnedthatonsomecomputers,suchasIBMPCcompatiblesorAppleMacintoshes,thedatemaynotbesetcorrectlyintheoperatingsystem;inthatcase,theTime.Dateprocedurewillgiveincorrectresults.
ThestringformofthedatecanbeconvertedtoanumericformforcomparisonpurposesusingtheTime.DateSecfunction.ThenumericformcanbeconvertedtoastringusingtheTime.SecDatefunction.ThenumericformofthetimecanbeobtainedusingtheTime.Secfunction.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.SecbycallingSec.
Seealso Time.Date,Time.DateSecandTime.SecDatefunctions.
Time.SecDate PartofTimemodule
Syntax Time.SecDate(timeInSecs:int):string
Description
TheTime.SecDatefunctionisusedtoconvertthenumberofsecondssince00:00:00GMTJan1,1970intoadateandtimestring.
IftimeInSecsisincorrectorcan'tbeinterpreted,thenTime.SecDatewillreturntheemptystringandError.LastandError.LastMsgwillbesettotheappropriateerror.
Example
Thisprogramgivesthenumberofsecondssince00:00:00GMTJan1,1970andthedateinstringform.
vartimeInSecs:int:=Time.Sec
vartheDateTime:string
theDateTime:=Time.SecDate(timeInSecs)
put"Thenumberofsecondssince1970is",timeInSecs
put"Greetings!!Thedateandtimetodayis",theDateTime
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.SecDate,notbycallingSecDate.
Seealso Time.Sec,Time.DateandTime.DateSecfunctions.
Time.SecParts PartofTimemodule
SyntaxTime.SecParts(sec:int,varyear,month,day, dayOfWeek,hour,minute,second:int)
Description
TheTime.SecPartsfunctionisusedtoconvertasinglenumberformofthetime(thenumberofsecondssince00:00:00GMTJan1,1970)intoadatewithnumericcomponentparts.
ThedayOfWeekparameteris1forMonday,2forTuesdaythrough7forSunday.
Ifthesecparameterdoesn'tmakeanysenseorcan'tbeinterpreted,thenTime.PartsSecwillsetallthevarparametersto1andError.LastError.LastMsgwillbesettotheappropriateerror.
Example
Thisprogramreturnsthecurrentdayoftheweek.
varyear,month,day,dayOfWeek,hour,minute,second
Time.SecParts(Time.Sec,year,month,day,dayOfWeek
hour,minute,second)
vardays:array1..7ofstring(10):=init("Monday","Tuesday",
"Wednesday","Thursday","Friday","Saturday","Sunday")
put"Thecurrentdayoftheweekis",days(dayOfWeek
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.SecPartscallingSecParts.
Seealso Time.PartsSec,Time.DateandTime.Secfunctions.
Time.SecStr PartofTimemodule
Syntax Time.SecStr(timeInSecs:int,formatString:string):string
Description
TheTime.SecStrfunctionisusedtoconvertthenumberofsecondssince00:00:00GMTJan1,1970intoadateandtimestring.
IftimeInSecsisincorrectorcan'tbeinterpreted,thenTime.SecStrwillreturntheemptystringandError.LastandError.LastMsgwillbesettotheappropriateerror.
Detailsn
TheformatStringparameterspecifieshowtheoutputstringwilllook.TheformatStringconsistsofdifferentlettersspecifyingthedifferentformatsandspacesorcommasbetweentheseletters.Thedifferentletterscanbecombinedtoprovidedifferentdateformats.
Herearetheletters:
a AbbreviatedweekdaynameA Fullweekdaynameb AbbreviatedmonthnameB Fullmonthnamec Dateandtimerepresentationappropriateforlocaled Dayofmonthasdecimalnumber(01-31)H Hourin24-hourformat(00-23)I Hourin12-hourformat(01-12)j Dayofyearasdecimalnumber(001-366)m Monthasdecimalnumber(01-12)M Minuteasdecimalnumber(00-59)p Currentlocale’sA.M./P.M.indicatorfor12-hourclockS Secondasdecimalnumber(00-59)
U Weekofyearasdecimalnumber,withSundayasfirstdayofweek(00-53)
w Weekdayasdecimalnumber(0-6;Sundayis0)
W Weekofyearasdecimalnumber,withMondayasfirstdayofweek(00-53)
x DaterepresentationforcurrentlocaleX Timerepresentationforcurrentlocaley Yearwithoutcentury,asdecimalnumber(00-99)Y Yearwithcentury,asdecimalnumberz,Z Time-zonename
Example
Thisprogramoutputsthecurrentdateandthedaynumberintheyear.Exampleoutput:ThursdayNovember13,2003isdaynumber317of2003
putTime.SecStr(Time.Sec,"ABd,Y"),"isdaynumber",
Time.SecStr(Time.Sec,"j"),"of",Time.SecStr
Execute
Execute
Thisexampledemonstrateseachoftheformattingletters.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingTime.SecStrcallingSecStr.
Time.SecandTime.SecPartsfunctions.
Seealso
time timeofdayasastringprocedure
Syntax time(vart:string)
Description
Thetimestatementisusedtodeterminethecurrenttimeofday.Variabletisassignedastringintheformat"hh:mm:ss".Forexample,ifthetimeistwominutesand47secondsafternineA.M.,twillbesetto"09:02:47".Twenty-fourhourtimeisused.Forexample,eleventhirtyP.M.givesthestring"23:30:00".
Example
Thisprogramgreetsyouandtellsyouthetimeofday.
vartimeOfDay:string
time(timeOfDay)
put"Greetings!!Thetimeis",timeOfDay
Details
BewarnedthatonsomecomputerssuchasIBMPCcompatiblesorAppleMacintoshes,thetimemaynotbesetcorrectlyintheoperatingsystem.Inthiscase,thetimeprocedurewillgiveincorrectresults.
Seealsodelay,clock,sysclock,wallclockanddatestatements.
SeealsopredefinedunitTime.
token ininput
Description
Atokenisessentiallyaword,anumberoraspecialsymbolsuchas:=.InaTuringprogramtherearefourkindsoftokens:keywordssuchasget,identifierssuchasincomeTax,operatorsandspecialsymbols,suchas+and:=,andexplicitconstants,suchas1.5and"Hello".Somekeywords,suchasindex,arereservedandcannotbeusedinprogramstonamevariables,procedures,etc.
Agetstatement,suchas
getincomeTax
usestoken-orientedinput.Thismeansthatwhitespace(blanks,tabs,etc.)isskippedbeforereadingtheinputitemandaftertheitem(uptothebeginningofthenextline).Seethegetstatementfordetails.
Example
Inthisexample,thetokensarevar,x,:,real,x,:=and9.84.
varx:real
x:=9.84
true booleanvalue(notfalse)
Syntax true
DescriptionAboolean(true/false)variablecanbeeithertrueorfalse(seebooleantype).
Example
varpassed:boolean:=true
varmark:int
fori:1..10
getmark
passed:=passedandmark>=60
endfor
ifpassed=truethen
put"Youpassedalltensubjects"
endif
DetailsThelineifpassed=truethencanbesimplifiedtoifpassedthenwithnochangetothemeaningoftheprogram.
type declaration
Syntax
AtypeDeclarationisoneof:
(a) typeid:typeSpec (b) typeid:forward
DescriptionAtypedeclarationgivesanametoatype.Thisnamecanbeusedinplaceofthetype.
Example
typenameType:string(30)
typerange:0..150
typeentry:
record
name:nameType
age:int
endrecord
Details
Thekeywordpervasivecanbeinsertedjustaftertype.Whenthisisdone,thetypeisvisibleinsideallsubconstructsofthetypescope.Withoutpervasive,thetypeisnotvisibleinsidemodules,monitorsandclassesunlessexplicitlyimported.Pervasivetypesneednotbeimported.Youcanabbreviatepervasiveasanasterisk(*).
Aforwardtypeallowspointerstobedeclaredtothetypebeforethetypeisresolved.Toresolveatype,youmustfollowaforwardwithadeclarationofthesamenameandinthesamescope.ThistypedeclarationmustincludeatypeSpec.
TypeConv
Description
ThisunitcontainsthepredefinedsubprogramsthatconvertbetweendifferentTuringstandardtypes.Therearealsosixroutinesthatarepartofthelanguage,ratherthanpartoftheunit,butareconceptuallypartofthisunit.
AllroutinesintheTypeConvunitareexportedunqualified.
DescriptionoftheroutinesintheTypeConvmodulecanbefoundinthischapter.
EntryPoints
intreal Convertsanintegertoareal.intstr* Convertsanintegertoastring.natreal Convertsanaturalnumbertoareal.natstr* Convertsanaturalnumbertoastring.round Convertsarealtoaninteger(rounding).floor Convertsarealtoaninteger(rounddown).ceil Convertsarealtoaninteger(roundup).realstr Convertsarealtoastring.erealstr Convertsarealtoastring(exponentialnotation).frealstr Convertsarealtoastring(noexponent).strint* Convertsastringtoaninteger.
strintok* Returnswhetherastringcanlegallybeconvertedtoaninteger.
strnat* Convertsastringtoanaturalnumber.
strnatok* Returnswhetherastringcanlegallybeconvertedtoanaturalnumber.
strreal Convertsastringtoareal.
strrealok Returnswhetherastringcanlegallybeconvertedtoareal.
chr* ReturnstheASCIIvalueofaspecifiedstringoflengthone.
ord* ReturnsastringoflengthonewiththeASCIIvaluespecified.
*Partofthelanguage,conceptuallypartoftheTypeConvunit.
typeSpec typespecification
Syntax
AtypeSpec(typespecification)isoneof:
(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:array1..150ofreal
(h) setType %Example:setof1..10
(i) recordType %Example:record…endrecord
(j) unionType %Example:union…endunion
(k) pointerType %Example:pointertocollectionVar
(l) namedType %Example:colorRange (m) nat %naturalnumber
(n) intn %n-byteinteger(n=1,2,4)
(o) natn %n-bytenatural(n=1,2,4)
(p) realn %n-bytereal(n=4,8) (q) char %singlecharacter (r) char(n) %ncharacters (s) subprogramType
Description
Atypespecificationdeterminestheallowedvaluesforavariableorconstant.Forexample,ifvariablexisaninteger(itstypeSpecisint),thepossiblevaluesforxarenumberssuchas-15,0,3and348207.Ifxisarealnumber(itstypeSpecisreal),thenitspossiblevaluesinclude7.8,-35.0,and15e12.Ifxisaboolean,itspossiblevaluesaretrueandfalse.Ifxisastring,itspossiblevaluesincludeHelloandGood-bye.
Example
varnumberOfSides:int
varx,y:real
typerange:0..150%ThetypeSpechereis0
typeentry:%HereisarecordtypeSpec
record
name:string(25)
age:range
endrecord
Seealso
int,real,boolean,string,subrangeType,enum,array,set,record,union,pointer,named,nat,intn,natn,realn,char,andchar(n)types.
unchecked compilerdirective
Dangerous
Description
OOTaddstheconceptof"unchecked"toTuring.Here,youcanrequestthatcertainruntimetests,whichtakeplacebydefault,canbeeliminated.Thismakestheprogrammoreefficientattheriskofunreliability.
Example
Declareptobeanuncheckedpointertoaninteger(seepointersfordetails).Pointerpwillbedangeroustouse,becausetheruntimesystemwillnotchecktoseeifitactuallylocatesaninteger,asopposedtoarbitrarycomputermemory.Inotherwords,uncheckedpointersarelikeClanguagepointers.
varp:unchecked^int
Example
DeclareCtobeanuncheckedcollectionofrecordsoftypeR(seecollectionsfordetails).PointerstoCwillbeunchecked.
varC:uncheckedcollectionofR
Example
Removecheckingfromthebodyofaloop.
fori:1..500
unchecked
ifa(i)=keythen
exit
endif
endfor
Details
Intheaboveexample,theuncheckedkeywordrequeststhatallchecking,inparticular,arrayboundscheckingforarraya,aretobeomitted.Thedisablinglastsfromtheoccurrenceofthekeyworduncheckedtotheendofthesurroundingconstruct,inthiscase,untilendfor.Inasimilarway,thecheckedkeywordwillrequestthatcheckingbere-enabledfromtheoccurenceofcheckedtotheendofthesurroundingconstruct.
Inthecurrent(1999)implementation,theuseofuncheckedto
turnoffcheckinginablockofstatementsisignored.Ingeneral,animplementationmaychoosetoignorerequeststodisablechecking.
union type
Syntax
AunionTypeis:
union[id]:indexTypeof
labellabelExpn{,labelExpn}:
{id{,id}:typeSpec}
{labellabelExpn{,labelExpn}:
{id{,id}:typeSpec}}
[label:{id{,id}:typeSpec}]
endunion
Description
Auniontype(alsocalledavariantrecord)islikearecordinwhichthereisaruntimechoiceamongsetsofaccessiblefields.Thischoiceismadebythetagstatement,whichdeletesthecurrentsetoffieldsandactivatesanewset.
Example
Thisuniontypekeepstrackofvariousinformationaboutavehicle,dependingonthekindofvehicle.
constpassenger:=0
constfarm:=1
constrecreational:=2
typevehicleInfo:
unionkind:passenger..recreationalof
labelpassenger:
cylinders:1..16
labelfarm:
farmClass:string(10)
label:%Nofieldsfor"otherwise"clause
endunion
varv:vehicleInfo
…
tagv,passenger%Activatepassengerpartv.cylinders
Theoptionalidentifierfollowingthekeywordunionisthenameofthetagoftheuniontype.Iftheidentifierisomitted,thetagisstillconsideredtoexist,althoughitsvaluecannotbeaccessed.Thetagmustbeofanindextype,forexample1..7.Youshouldlimittherangeofthisindextype,asthecompilermayhavealimit(atleast255)onthemaximumrangeitcanhandle.
Details
EachlabelExpnmustbeknownatcompiletimeandmustliewithintherangeofthetag'stype.Thefields,includingthetag,ofaunionvaluearereferencedusingthedotoperator,asinv.cylindersandthesecanbeusedasvariablesorconstants.Afieldcanbeaccessedonlywhenthetagmatchesoneofthelabelexpressionscorrespondingtothefield.Thetagcanbechangedbythetagstatementbutitcannotbeassignedto,passedtoavarparameter,orboundtousingvar.
Inaunion,id'soffields,includingthetag,mustbedistinct.However,theseneednotbedistinctfromidentifiersoutsidetheunion.Unionscanbeassignedasawhole(tounionsofanequivalenttype),buttheycannotbecompared.AsemicoloncanoptionallyfolloweachtypeSpec.
Anyarraycontainedinaunionmusthaveboundsthatareknownatcompiletime.
Thenotation>canbeusedtoaccessunionfields.Forexample,ifppointertovehicleRecord,p>farmClasslocatesthefarmClassfield.
Seealso pointer.
unit filecontainingmodule,monitor,orclass
Syntax
AcompilationUnitisoneof:
(a) [importList]mainProgram (b) unitmoduleDeclaration (c) unitmonitorDeclaration (d) unitclassDeclaration
Description
Aprogramcanbedividedupintounits,eachinaseparatefile.Allfilesexceptthemainprogrambeginwiththekeywordunit.Theunitcontainsthemainprogram,amodule,amonitororaclass.
Example
Hereisstackmodulethatisseparatedoutintoafilewhosenameis
unit%Thekeywordunitbeginseachseparatefile
modulestack
exportpush,pop
vartop:int:=0
varcontents:array1..100ofint
procedurepush(i:int)
top+=1
contents(top):=i
endpush
procedurepop(i:int)
i:=contents(top)
top-=1
endpop
endstack
Themainprogram,whichisinanotherfile,gainsaccesstothestackbyimportingit.Hereisthemainprogram:
importvarstack%Usethestack
varn:int
…
stack.push(n)
…
stack.pop(n)
Details
Inthisexample,thekeywordvarintheimportlistisrequiredbecausethemainprogramcausesachangeinthestack,bycallingpushandpopimportlistsofunitsthataremodules,monitorsandclassesareusedtogainaccesstofurtherunits.
Ifthestackwereinafilewithadifferentname,saystk.t,theimportlistwouldberewrittentouseaninclause,asfollows:
importvarstackin"stk.t"
AmainProgramissimplyaprogram.Seeprogram.
Seealsomodule,monitorandclass.Seealsoexportlist,importlist,inheritimplementlistandimplementbylist.
unqualified export
Description
Whenanidentifierxisexportedfromamodule,monitororclassMusingthekeywordunqualified,itcanbeusedoutsideofMwithoutthequalification"M.".Inotherwords,outsideofM,itcanbereferredtoassimplyx.Thekeywordunqualifiedcanbewritteninitsshortformas~.whichispronounced"notdot",asin:
export~.x
Seeals o exportlist.
upper bound
Syntax upper(reference[,dimension]):int
Description
Theupperattributeisusedtofindtheupperboundofanarray,string,char(n)ornon-opaquesubrangetype.(Seelowerforfindingthelowerbound.)
Example
Inaprocedure,seeiftheboundofarrayparameteraislargeenoughthatitcanbesubscriptedbyi.Ifitislargeenough,itisseta(i)tozero.
proceduretest(vara:array1..*ofreal)
ifi<=upper(a)then
a(i):=0.0
endif
endtest
Details
Inasimilarway,ifsisastring,itsupperbound(notlength!)isgivenbyupper(s).Ifanarrayhasmorethanonedimension,asinvarb:array1..10,1..60ofint,youmustspecifythedimension.Forexample,upper(b,2)returns60.
var declaration
Syntax
AvariableDeclarationisoneof:
(a) varid{,id}[:typeSpec][:=initializingValue] (b) collectionDeclaration
Description
Avariabledeclarationcreatesanewvariable(orvariables).Onlyform(a)willbeexplainedhere.SeecollectionDeclarationforexplanationofform(b).ThetypeSpecofform(a)canbeomittedonlyiftheinitializingvalueispresent.
Examplevarj,k:int:=1%jandkareassignedvalue1
vart:="Sample"%Thetypeoftisstring
varv:array1..3ofstring(6):=
init("George","Fred","Alice")
Details
Theinitializingvalue,ifpresent,mustbeanexpressionorelsealistofitemsseparatedbycommasinsideinit(…).ThesyntaxofinitializingValueisoneof:
(a) expn (b) init(initializingValue{,initializingValue})
Eachinit(…)correspondstoanarray,recordorunionvaluethatisbeinginitialized.Thesemustbenestedforinitializationofnestedtypes.
IfthetypeSpecisomitted,thevariable'stypeistakentobethe(root)typeoftheinitializingexpression,forexample,intorstring.ThetypeSpeccannotbeomittedfordynamicarraysorwhentheinitializingvalueisoftheforminit(…).Thevaluesinsideinit(…)mustbeknownatcompiletime.
Thekeywordpervasivecanbeinsertedjustaftervar.Whenthisisdone,thevariableisvisibleinsideallsubconstructsofthevariable'sscope.Withoutpervasive,thevariableisnotvisibleinsidemodulesunlessexplicitlyimported.Pervasivevariablesneednotbeimported.Youcanabbreviateanasterisk(*).
OOTextendsTuringinthefollowingway.OOTchangesform(a)toallowtheoptionaluseoftheregisterkeywordtorequestthatthevariablebeplacedinamachineregister.TheOOTsyntaxforform(a)isactually:
var[pervasive][register]id{,id}[:typeSpec
Inthecurrent(1994)OOTimplementation,programsareruninterpretivelyusingpseudo-code,whichhasnomachineregisters,andtheregisterkeywordisignored.Seeofregistervariables.
Seealsocollection,bind,procedureandfunctiondeclarations,parameterdeclarations,importlistsforotherusesofthekeywordvar.
variableReference useofavariable
Syntax
AvariableReferenceis:
variableId{componentSelector}
Description
InaTuringprogram,avariableisdeclaredandgivenaname(variableId)andthenused.Eachuseiscalledavariablereference.
Ifthevariableisanarray,collection,recordorunion,itsparts(components)canbeselectedusingsubscriptsandfieldnames(usingcomponentSelectors).TheformofacomponentSelectorisoneof:\
(a) (expn{,expn}) (b) .fieldId
Form(a)isusedforsubscripting(indexing)arraysandcollections.Thenumberofarraysubscriptsmustbethesameasinthearray'sdeclaration.Acollectionhasexactlyonesubscript,whichmustbeapointertothecollection.Form(b)isusedforselectingafieldofarecordorunion.
Example
Followingthedeclarationsofk,aandr,eachofk,a(k)andr.namearevariablereferences.
vark:int
vara:array1..100ofreal
varr:
record
name:string(20)
phone:string(8)
endrecord
…
k:=5
a(k):=3.14159
r.name:="SteveCook"
Avariablereferencecancontainmorethanonecomponent
Detailsselector,forexample,whenthevariableisanarrayofrecords.Foranexample,seetherecordtype.SeealsoconstantReferenceandvardeclaration.
View
Description
Thisunitcontainsthepredefinedsubprogramsthatdealwiththecurrentoutputsurface,whichisawindow.
AllroutinesintheViewunitareexportedqualified(andthusmustbeprefacedwith"View.")withtheexceptionofmaxx,maxy,maxcolorandmaxcolourwhichareexportedunqualified.
maxx
Returnsthemaximumxcoordinate(width1)(exportedunqualified).
maxy
Returnsthemaximumycoordinate(height1)(exportedunqualified).
maxcolor
Returnsthemaximumcolornumber(#colors1)(exportedunqualified).
maxcolour
Returnsthemaximumcolornumber(#colors1)(exportedunqualified).
Set Changestheconfigurationoftheoutputsurface.
ClipSet Clipsoutputtoaspecifiedrectangle.
ClipAdd
Addsanotherspecifiedrectangletotheclipping
EntryPoints
region.
ClipAddOval Addsanotherspecifiedovaltotheclippingregion.
ClipOff Stopsallclipping.
WhatDotColor
Getsthecolorofthepixelataspecifiedlocation.
WhatDotColour Getsthecolorofthepixelataspecifiedlocation.
Update
Updatestheonscreenwindowfromtheoffscreenbitmap.
UpdateArea
Updatespartoftheonscreenwindowfromtheoffscreenbitmap.
SetTransparentColor
SetsthetransparentcolortobeignoredwhenusingpicUnderMerge
mode.
SetTransparentColour
SetsthetransparentcolourtobeignoredwhenusingpicUnderMerge
mode.
View.ClipAdd PartofViewmodule
Syntax View.ClipAdd(x1,y1,x2,y2:int)
Description
TheView.ClipAddprocedureaddsanotherrectanglespecifiedby(x1,y1)-(x2,y2)totheclippingregion.Thisonlyworksonsystemsthatsupportcomplexclippingregions.Ifnoclippingregionhasbeenspecified,thentherectanglebecomesthecompleteclippingregion.
Aclippingregionistheregionthattheoutputwillappearin.Iftherectangleisspecifiedastheclippingregion,anydrawingdoneoutsidetherectanglewillnotappear.
Tosettheinitialclipping,orremovetheoldregionandreplaceitwithanewone,useView.ClipSet.Tosettheclippingregionbacktotheentirescreenorwindow,useView.ClipOff.
Thesecommandsonlyworkin"graphics"mode.
Example
Thisprogramsetstheclippingregiontofiverectanglesandthendrawsrandomcircles.Thecircleswillonlyappear(orpartiallyappear)intherectangles.
constmaxx13:int:=maxxdiv3
constmaxx23:int:=2*maxxdiv3
constmaxy13:int:=maxydiv3
constmaxy23:int:=2*maxydiv3
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)
%Drawtherandomovalsinthebox
varx,y,clr:int
loop
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
clr:=Rand.Int(0,maxcolor)%Randomcolor
Draw.FillOval(x,y,30,30,clr)
endloop
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.ClipAdd,notbycallingClipAdd.
Seealso View.ClipSetandView.ClipOfffunctions.
View.ClipAddOval PartofViewmodule
Syntax View.ClipAddOval(x,y,xradius,yradius:int)
Description
TheView.ClipAddOvalprocedureaddsanotherovalspecifiedby(x,y)andxradiusandyradius)totheclippingregion.Ifnoclippingregionhasbeenspecified,thentheovalbecomesthecompleteclippingregion.
Aclippingregionistheregionthattheoutputwillappearin.Iftherectangleisspecifiedastheclippingregion,anydrawingdoneoutsidetheovalwillnotappear.
Tosettheinitialclipping,orremovetheoldregionandreplaceitwithanewrectangle,useView.ClipSet.Tosettheclippingregionbacktotheentirescreenorwindow,useView.ClipOff.
Thesecommandsonlyworkin"graphics"mode.
Example
Thisprogramsetstheclippingregiontofivecirclesandthendrawsrandomsquares.Thesquareswillonlyappear(orpartiallyappear)intheovals.
constc1:int:=maxydiv4
constc2:int:=3*maxydiv4
constradius:int:=maxydiv4
View.ClipAddOval(c1,c1,radius,radius)
View.ClipAddOval(c1,c2,radius,radius)
View.ClipAddOval(c2,c1,radius,radius)
View.ClipAddOval(c2,c2,radius,radius)
%Drawtherandomsquaresinthebox
varx,y,clr:int
loop
x:=Rand.Int(0,maxx-30)%Randomx
y:=Rand.Int(0,maxy-30)%Randomy
clr:=Rand.Int(0,maxcolor)%Randomcolor
Draw.FillBox(x,y,x+30,y+30,clr)
endloop
Execute
Execute
BycombininganimationusingView.UpdateandView.ClipAddOval,youcanachieveamovingspotlighteffect.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.ClipAddOval,notbycallingClipAddOval.
Seealso View.ClipSet,View.ClipAddandView.ClipOfffunctions.
View.ClipOff PartofViewmodule
Syntax View.ClipOff
Description
TheView.ClipOffprocedureturnsoffclipping.Thismeansthatanydrawingcommandscanappearontheentiredrawingsurface(thescreenorthewindow,dependingonthesystem).
Thesecommandsonlyworkin"graphics"mode.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.ClipOff,notbycallingClipOff.
Seealso View.ClipAddandView.ClipSetfunctions.
View.ClipSet PartofViewmodule
Syntax View.ClipSet(x1,y1,x2,y2:int)
Description
TheView.ClipSetproceduresetstheclippingregiontotherectanglespecifiedby(x1,y1)-(x2,y2).Ifaclippingregionalreadyexist,itisreplacedbythespecifiedrectangle.
Aclippingregionistheregioninwhichtheoutputwillappear.Iftherectangleisspecifiedastheclippingregion,anydrawingdoneoutsidetherectanglewillnotappear.
Tosettheinitialclipping,orremovetheoldregionandreplaceitwithanewone,useView.ClipSet.Tosettheclippingregionbacktotheentirescreenorwindow,useView.ClipOff.
Thesecommandsonlyworkin"graphics"mode.
Example
Thisprogramsetstheclippingregiontofiverectanglesandthendrawsrandomcircles.Thecircleswillonlyappear(orpartiallyappear)intherectangles.
constmaxx13:int:=maxxdiv3
constmaxx23:int:=2*maxxdiv3
constmaxy13:int:=maxydiv3
constmaxy23:int:=2*maxydiv3
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)
%Drawtherandomovalsinthebox
varx,y,clr:int
loop
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
clr:=Rand.Int(0,maxcolor)%Randomcolor
Draw.FillOval(x,y,30,30,clr)
endloop
Exportedqualified.
Status ThismeansthatyoucanonlycallthefunctionbycallingView.ClipSet,notbycallingClipSet.
Seealso View.ClipAddandView.ClipOfffunctions.
View.maxcolor PartofViewmodule
Syntax View.maxcolor:int
Description
Themaxcolorfunctionisusedtodeterminethemaximumcolornumberforthecurrentmodeofthescreen.Thealternatespellingismaxcolour.
Example
Thisprogramoutputsthemaximumcolornumber.
setscreen("graphics")
…
put"Themaximumcolornumberis",View.maxcolor
Details
Thescreenshouldbeina"screen"or"graphics"mode.Ifitisnot,itwillautomaticallybesetto"screen"mode.SeeView.Setfordetails.
ForIBMPCcompatiblesin"screen"mode,maxcolor=15.ForthedefaultIBMPCcompatible"graphics"mode(VGA),maxcolor=15.
DetailsView.maxcolorisidenticaltoRGB.maxcolor.Itisplacedhereforconsistencywithotherscreeninformationroutines.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.maxcolor.NotethatRGB.maxcolorisexportedunqualified,sothatonecancallmaxcolor.
Seealso
Draw.Dotforexamplesoftheuseofmaxcolor.SeetheText.Colorprocedurewhichisusedforsettingthecurrently-activecolor.
View.maxx PartofViewmodule
Syntax maxx:int
DescriptionThemaxxfunctionisusedtodeterminethemaximumvalueofxforthecurrentgraphicsmode.
Example
Thisprogramoutputsthemaximumxvalue.
setscreen("graphics")
…
put"Themaximumxvalueis",maxx
Details
Thescreenshouldbeina"graphics"mode.Ifitisnot,itwillautomaticallybesetto"graphics"mode.Seesetscreenfordetails.
ForthedefaultIBMPCcompatiblegraphicsmode(CGA),maxx=319.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallingmaxxorbycallingView.maxx.
SeealsoDraw.Dotforanexampleoftheuseofmaxxandforadiagramillustratingxandypositions.
View.maxy PartofViewmodule
Syntax maxy:int
DescriptionThemaxyfunctionisusedtodeterminethemaximumvalueofyforthecurrentgraphicsmode.
Example
Thisprogramoutputsthemaximumyvalue.
setscreen("graphics")
…
put"Themaximumyvalueis",maxy
Details
Thescreenshouldbeina"graphics"mode.Ifitisnot,itwillautomaticallybesetto"graphics"mode.Seesetscreenfordetails.
ForthedefaultIBMPCcompatiblegraphicsmode(CGA),maxy=199.
Status
Exportedunqualified.
ThismeansthatyoucancallthefunctionbycallingmaxyorbycallingView.maxy.
SeealsoDraw.Dotforanexampleoftheuseofmaxyandforadiagramillustratingxandypositions.
View.Set PartofViewmodule
Syntax View.Set(s:string)
Example
HereareexampleusesoftheView.Setprocedure.Inmanycases,thesewillappearasthefirststatementoftheprogram.However,theycanappearanyplaceinaprogram.
View.Set("graphics")%Switchtographicsmode
View.Set("screen")%Switchtoscreenmode
View.Set("nocursor")%Turnoffcursor
View.Set("noecho")%Donotechokeystrokes
Description
TheView.Setstatementisusedtochangethemodeofthescreen,aswellasthewayinwhichTuringdoesinputandoutput.TheparametertoView.Setisastring,suchas"graphics".Thestringcontainsoneormoreoptionsseparatedbycommas,suchas"text,noecho".View.Setaffectstheactivewindow.
Details
Therearetwowindowmodes,textandgraphics.
textmodedoesnotallowanygraphicswhatsoever(includingcursorpositioning,etc.).Onlyputandgetareallowed.Anyoutputthatscrollsoffthetopofthewindowispreservedandcanviewedorprintedlater.
graphicsmodeallowscharactergraphicsandpixelgraphicscommandssuchandText.LocateandDraw.Box.
ThedefaultgraphicsmodeisdefinedintheTuringpreferences.Itisgoodpracticetosetthedesiredmodesothattheprogramwillfunctionproperlyregardlessofthedefaultgraphicsmode.Notethatiftheuserprintstheoutputwindow,intextmode,alloutputsenttothewindowisprinted.Ingraphicsmode,onlythecurrentoutputofthewindowisprinted.Iftheusersavestheoutputwindow,atextmodewindowwillproduceatextfilecontainingalltheoutputsenttothewindow.AgraphicswindowwillproduceaBMPgraphicsfilecontainingthecurrentcontentsofthewindow.
WheretheoptionstoView.Setaremutuallyexclusive,theyarelisted
Details
herewiththedefaultunderlined.Herearetheoptions:
"cursor","nocursor"-Causesthecursortobeshown(orhidden).Thecursorisonlydisplayedwhentheprogramisawaitinginput.
"echo","noecho"-Causes(orsuppresses)echoingofcharactersthataretyped.Echoingiscommonlyturnedoffininteractiveprogramstokeeptypedcharactersfrombeingechoedatinappropriateplacesonthescreen.
"noxor","xor"-noxormodemeansthatalldrawingisdonenormally.Inxormode,allpixelgraphicsaredrawnXOR'edonthebackground(withtheexceptionofthePicroutines,wherethedrawingmodeisspecified).ThemostimportantpropertyofanXOR'edobjectisthatitcanbeerasedandthebackgroundrestoredbyXOR'ingtheobjectontopofitself.
"msdos","nomsdos"-CausesthewindowtousetheMS-DOScharacterset(withlinedrawingcharacters)insteadoftheWindowsANSIcharacterset.The"nomsdos"optioncausesthewindowtousetheWindowsANSIcharacterset.Notethatthe"msdos"optiononlyworksiftheWindowsfont(usuallyCourierNew)supportsit.
"visible","invisible","popup"-Causestheactivewindowtobecomevisible(invisibleor,forpopup,invisibleuntilinputoroutputoccursinthewindow).
"title:<text>"-Causesthetitleoftheactivewindowtobesetto<text
"position:<x>;<y>"-Causesthepositionoftheupperleftcorneroftheactivewindowtobesetto(x,y).The<x>parametercanalsobeoneof:“left”,“center”,“center”or“right”,inwhichcasethewindowwillbeplacedontheleft,centerorrightsideofthescreen.The<y>parametercanalsobeoneof:“top”,“middle”,“truemiddle”,or“bottom”inwhichcasethewindowwillbeplacedatthetop,middleabout1/3fromthetop,middleorbottomofthescreen.Notethatwhenawindowissupposedtobecenteredinthemiddleofthescreen,“middle”usuallylooksbetterthan“truemiddle”.
"nooffscreenonly","offscreenonly"Causesor(suppresses)outputfrom
beingsenttothevisiblewindow.Whentheoffscreenonlyoptionisactive,anytextandgraphicsoutputisdrawntotheoffscreenbufferthatismaintainedforeveryRunwindowbutnotdrawntothescreen.View.UpdateisthenusedtocopytheentirecontentsoftheoffscreenbuffertotheRunwindow.Byallowingnumerousdrawingcommandstobesenttotheoffscreenbufferandthenupdatingthewindowatonetime,itispossibletogetsmootheranimation.
"buttonbar","nobuttonbar"Causesor(suppresses)thedisplayofabuttonbaratthetopoftheoutputwindowwhichallowstheusertoeasilystopprogramexecutionorsaveandprinttheoutputwindow.
"text","screen","graphics"-Setswindowtothegivenmodeandalwayserasesthescreen,evenwhenalreadyintherequestedmode.
Thetextmodecanhaveamodifierintheform"text:<rows>;<cols>".Thissetsthewindowtobe<rows>by<cols>oftextinsize.
Thescreenmodeactuallysetsthewindowtographicsmode.Itcanhaveamodifierintheform"screen:<rows>;<cols>".Thissetsthewindowtobe<rows>by<cols>oftextinsize.
Thegraphicsmodecanhaveamodifierintheform"graphics:<width<height>".Thissetsthewindowtobe<width>by<height>pixelsinsize.
Tosetawindowtothemaximumsizeavailableonthescreen,youcanuse“max”forthe<width>,<height>,<rows>or<columns>parameters.Ifthewindowrequestedislargerthanwillfitonthescreen,thewindowwillfilltheentirescreenandscrollbarswillbeaddedtotheoutputwindowtoallowthewindowusertoseetherestofthewindow.
Thisprogramcreatesagraphicswindowthatis300pixelsby100pixels.
View.Set("graphics:300;100")
Thisprogramoutputsthesquarerootsforthefirst200numbers.Theusercaninspectalltheoutputandprintthevaluesaftertheprogramhasfinishedexecution
Example
View.Set("text")
forvalue:1..200
putvalue:3,"",sqrt(value)
endfor
Thisprogramcreatesawindowwithoutabuttonbaratthetopthatissizedtofitthescreen.Itthendrawsan“X”inredinthewindow.
View.Set("graphics:max;max,nobuttonbar")
Draw.Line(0,0,maxx,maxy,red)
Draw.Line(maxx,0,0,maxy,red)
Thisprogramresizesthewindowto200x200,movestheoutputwindowtothebottom-leftofthescreenandhidesthebuttonbar.Itthensetsthewindowtitleto“BottomLeftWindow”andoutputstheword“Hello”.
View.Set("graphics:200;200,position:bottom;left,nobuttonbar")
View.Set("title:BottomLeftWindow")
put"Hello"
Seealso setscreenforfurtherinformation.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.Set,notbycallingSet.
View.SetTransparentColor PartofViewmodule
Syntax View.SetTransparentColor(colorNumber:int)
Description
TheView.SetTransparentColorproceduresetsthecolorintheRunwindowthatshouldbeconsideredtransparentwhenapictureisdrawnonthewindowusingthepicUnderMergemode.Ifnocolorisspecified,thenthedefaultbackgroundcolor(colorbg,usuallywhite)isusedasthetransparentcolor.YoucanchangethisbackgroundcolorusingRGB.SetColoroncolor0.
DetailsThiscallisoftenusedwhenyouwanttheRunwindowtohaveabackgroundcolorotherthancolor0.
Example
Thisprogramdisplaystwoimagesloadedfromthesamefile.Inthesecondimage,thetransparentcolorhasbeensettobrightred(thatis,thepartsoftheimagethataremeanttobetransparentareinbrightred).
constSIZE:int:=20
procedureDrawCheckerBoard
cls
forx:0..maxxbySIZE
fory:0..maxybySIZE
if((x+y)divSIZE)mod2=0then
Draw.FillBox(x,y,x+SIZE,y+
endif
endfor
endfor
endDrawCheckerBoard
varpic:int:=Pic.FileNew("datafiles/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
DetailsView.SetTransparentColourisanalternatespellingforView.SetTransparentColor.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.SetTransparentColor,notbycallingSetTransparentColor.
Seealso Pic.SetTransparentColor.
View.Update PartofViewmodule
Syntax View.Update
Description
TheView.UpdateprocedureupdatesaRunwindowfromanoffscreenbitmap.ItisusedwiththecommandView.Set("offscreenonly")whichpreventstheRunwindowfrombeingupdateduntiltheView.Updatecommandisgiven.
Example
Thisprogramdisplays30circlesbouncingaroundthescreen.ToseetheeffectwithoutView.Update,commentoutthelineView.Set("offscreenonly")
%Placesomecirclesaroundthescreen
constRADIUS:int:=30
constNUM_BALLS:int:=20
varx,y,dx,dy,clr:array1..NUM_BALLSofint
fori: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)
endfor
%Now,anydrawingtothescreenwon'tappearuntila
%View.Updateisgiven.
View.Set("offscreenonly")
loop
cls%Cleartheoffscreenwindow
fori:1..NUM_BALLS
ifx(i)+dx(i)<RADIUSor
x(i)+dx(i)>maxx-RADIUSthen
dx(i):=-dx(i)
endif
ify(i)+dy(i)<RADIUSor
y(i)+dy(i)>maxy-RADIUSthen
dy(i):=-dy(i)
endif
x(i):=x(i)+dx(i)
y(i):=y(i)+dy(i)
Draw.FillOval(x(i),y(i),RADIUS,RADIUS
endfor
%Allthecircleshavebeendrawn.Nowupdatethescreen.
View.Update
Time.Delay(5)
endloop
Execute
Details
AllTuringRunwindowshavebothanonscreenvisiblewindowandanoffscreenwindow.Wheneveranyoutputissenttothescreen,boththeonscreenwindowandtheoffscreenwindowareupdated.WhentheRunwindowneedstobeupdated(forexamplewhenanotherwindowismovedovertopofitandthenremoved),Turingcopiestheoffscreenwindowontotheonscreenwindow.
WhentheView.Set("offscreenonly")commandisgiven,Turingnolongerdrawstotheonscreenwindowwhenanydrawingcommandisgiven.However,itdoesupdatetheoffscreenwindow.WhentheView.Updatecommandisgiven,theentireoffscreenwindowiscopiedtotheonscreenwindow.
Thiscanbeusedtoprovidesmooth,flicker-freeanimation.Animatedobjectsflickerwhentheobjectbeinganimateddisappearsfromtheonscreenwindowforaperiodoftime.ByusingView.Set("offscreenonly")/View.Update,theonscreenwindowisneverblank.Instead,theoffscreenwindowdrawnovertopofftheonscreenwindow,replacingit.Thismeansthattheon-screenwindowisneverblankedout,eliminatingtheflickeringfoundintheanimation.
Details
It'sveryeasytoforgetthatnooutputwillappearintheRunwindowwhenusingView.Update.RemembertouseView.Set("nooffscreenonly")toturnoffthisfeaturesendingoutputfordebuggingpurposes.
Details
View.UpdateshouldnotbeusedinconjunctionwiththeSpritemodule.Spritescanbeconsideredalimitedversionofthistechnique.View.Updatealsoworkswellwhentheentirebackgroundis
changing.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.Update,notbycallingUpdate.
SeealsoView.Setforthe"offscreenonly"and"nooffscreenonly"options.
View.UpdateAreaforupdatingpartofthewindowatatime.
View.UpdateArea PartofViewmodule
Syntax View.UpdateArea(x1,y1,x2,y2)
Description
TheView.UpdateAreaprocedureupdatesarectanglularareaRunwindow,specifiedby(x1,y1)-(x2,y2)fromtheoffscreenbitmap.ItisusedwiththecommandView.Set("offscreenonly")whichpreventstheRunwindowfrombeingupdateduntiltheView.UpdateAreaorView.Updatecommandisgiven.
Becausetheentirescreenisnotupdatedeachtime,theanimationcanbemuchfaster,especiallyonslowmachines.ThisproceduredoestakemoreefforttousethanView.Updateasitrequirestheprogrammertocalculatewhichportionofthescreenmustbeupdated.
Example
Thisprogrammovesastarbackandforthacrossthescreen.TocomparethespeedupView.UpdateAreawithView.Update,replacethecallstoView.UpdateAreawithView.Update.
View.Set("offscreenonly")
varSIZE:int:=50
loop
forx:0..maxx-SIZE
Draw.FillStar(x,100,x+SIZE,100+SIZE
View.UpdateArea(x-1,100,x+SIZE,100+
Draw.FillStar(x,100,x+SIZE,100+SIZE
endfor
fordecreasingx:maxx-SIZE..0
Draw.FillStar(x,100,x+SIZE,100+SIZE
View.UpdateArea(x,100,x+SIZE+1,100+
Draw.FillStar(x,100,x+SIZE,100+SIZE
endfor
endloop
Execute
Details
Iftheentirescreenisbeingupdatedeachtimethroughtheanimationloop(forexampleifthebackgroundimageischanging),thenuseView.Updateinstead.
WhenusingView.UpdateArea,itisimportanttocorrectlycalculatetheregiontobeupdated.Thisregionmustnotonlycontaintheitembeingdrawn,butalsoanyareawherethebackgroundshouldbereplaced.Forexample,intheprogramabove,theareaupdatedincludedtheonepixeltotheleftofthestarwhenthestarwasmovingright-wardandonepixeltotherightofthestarwhenthestarwasmovingleft-ward.
Execute
HereisanexampleprogramthatallowsyoutocomparethespeedofanimationusingView.UpdatewithView.UpdateArea.Theprogramanimatesanobjectonabackgroundofstars.Pressinganykeyswitchesbetweenthetwocalls.
AllTuringRunwindowshavebothanonscreenvisiblewindowandanoffscreenwindow.Wheneveranyoutputissenttothescreen,boththeonscreenwindowandtheoffscreenwindowareupdated.WhentheRunwindowneedstobeupdated(forexamplewhenanotherwindowismovedovertopofitandthenremoved),Turingcopiestheoffscreenwindowontotheonscreenwindow.
Details
WhentheView.Set("offscreenonly")commandisgiven,Turingnolongerdrawstotheonscreenwindowwhenanydrawingcommandisgiven.However,itdoesupdatetheoffscreenwindow.WhentheView.Updatecommandisgiven,theentireoffscreenwindowiscopiedtotheonscreenwindow.
Thiscanbeusedtoprovidesmooth,flicker-freeanimation.Animatedobjectsflickerwhentheobjectbeinganimateddisappearsfromtheonscreenwindowforaperiodoftime.ByusingView.Set("offscreenonly")/View.Update,theonscreenwindowisneverblank.Instead,theoffscreenwindowdrawnovertopofftheonscreenwindow,replacingit.Thismeansthattheon-screenwindowisneverblankedout,eliminatingtheflickeringfoundintheanimation.
Details
It'sveryeasytoforgetthatnooutputwillappearintheRunwindowwhenusingView.UpdateArea.RemembertouseView.Set("nooffscreenonly")toturnoffthisfeaturesendingoutputfordebuggingpurposes.
Details
View.UpdateAreashouldnotbeusedinconjunctionwiththeSpritemodule.Spritescanbeconsideredalimitedversionofthistechnique.View.UpdateAreaalsoworkswellwhentheentirebackgroundischanging.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.UpdateArea,notbycallingUpdateArea.
SeealsoView.Setforthe"offscreenonly"and"nooffscreenonly"options.
View.Updateforproceduretoupdatetheentirescreenatonetime.
View.WhatDotColor PartofViewmodule
Syntax View.WhatDotColor(x,y:int):int
Description
TheView.WhatDotColorfunctionisusedtodeterminethecolornumberofthespecifiedpixel.ThealternatespellingisView.WhatDotColour.
Example
Thisprogramdrawsalinewhichbouncesofftheedgesofthescreenandmakesabeepwhenitfindsapixelthathasalreadybeencolored.
View.Set("graphics")
varx,y:int:=0
vardx,dx:int:=1
loop
ifView.WhatDotColor(x,y)not=0and
View.WhatDotColor(x,y)not=brightred
Draw.FillOval(x,y,10,10,brightred)
endif
Draw.Dot(x,y,1)
x:=x+dx
y:=y+dy
ifx=0orx=maxxthen
dx:=-dx
endif
ify=0ory=maxythen
dy:=-dy
endif
endloop
Execute
AnotherexampleillustratestheuseofView.WhatDotColortodeterminethecolorofpixelsinawindowpaintedwithmulti-colorblocks.Theactualcolornumberappearsintheblock.The
Example
colorofthedotunderthemousecursorappearsintheupper-leftcornerofthewindow.Notethatyoucanalsoplacethemousecursorovertheblacktextindicatingthecolornumber.
Details
Thescreenshouldbeina"graphics"mode.Ifisnotsetto"graphics"mode,itwillautomaticallybesetto"graphics"mode.SeeView.Setfordetails.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingView.WhatDotColor,notbycallingWhatDotColor.
Seealso
Draw.Dot,whichisusedforsettingthecolorofapixel.Seealsomaxxandmaxy,whichareusedtodeterminethenumberofpixelsonthescreen.
wait blockaprocessstatement
Syntax
AwaitStatementis:
waitvariableReference[,expn]
Description
Thewaitstatementisusedinaconcurrentprogramtocausetheexecutingprocesstobeblocked(togotosleep)untilitisawakenedbyasignalstatement.Thestatementcanonlybeusedinsideamonitor(aspecialkindofmodulethathandlesconcurrency).Awaitstatementoperatesonaconditionvariable(thevariableReference),whichisessentiallyaqueueofsleepingprocesses.Seeconditionforanexampleofawaitstatement.
Details
Awaitstatementforapriorityconditionmustincludetheoptionalexpn,.Thisexpressionmustbeanon-negativeintvaluewhichisusedtoorderprocesseswaitingforthecondition,lownumbersfirst.
Awaitstatementforatimeoutconditionmustincludetheoptionalexpn,whichmustbeanon-negativeintvaluewhichgivesthetimeoutinterval.Aprocesswaitingforatimeoutconditionisimplicitlyawakenedifitwaitslongerthanitstimeoutinterval.
Seealsoconditionandsignal.Seealsomonitorandfork.Seealsoempty.Seealsopause.
wallclock secondssince1/1/1970procedure
Syntax wallclock(varc:int)
DescriptionThewallclockstatementisusedtodeterminethetimeinsecondssince00:00:00GMT(GreenwichMeanTime)January1,1970.
Example
Thisprogramtellsyouhowmanysecondssince1970.
varseconds:string
wallclock(seconds)
put"Thenumberofsecondssince1970is",seconds
Details
BewarnedthatonsomecomputerssuchasIBMPCcompatiblesorAppleMacintoshes,thetimemaynotbesetcorrectlyintheoperatingsystem;inthatcase,thewallclockprocedurewillgiveincorrectresults.Also,onIBMPCcompatibles,thecallisdependentonhavingthetimezoneTZvariablecorrectlyset.OnanIBMPC,thedefaulttimezoneissettoPST(6hoursfromGMT).
OntheAppleMacintosh,thewallclockprocedurereturnsthenumberofsecondssince00:00:00localtimeJan.1,1970.
Seealsodelay,time,clock,sysclockanddatestatements.
SeealsopredefinedunitTime.
whatcol cursorpositionfunction
Syntax whatcol:int
DescriptionThewhatcolfunctionisusedtodeterminethecursorposition'scolumn.
Example
ThisprogramoutputsThecurrentrowis5,thecurrentcolumnis15.
locate(5,10)
put"12345"..
put"Thecurrentrowis",whatrow
put"Thecurrentcolumnis",whatcol
DetailsThescreenshouldbeina"screen"or"graphics"mode.whatcolfunctionsproperlyevenifthecursorisinvisible.
Seealso
thewhatrowfunction,whichisusedtosetthedeterminethecursorrow.Seealsothelocate,maxrowandmaxcolprocedure.
SeealsopredefinedunitText.
whatcolor textcolorgraphicsfunction
Syntax whatcolor:int
Description
Thewhatcolorfunctionisusedtodeterminethecurrent(foreground)color,ie.,thecolorusedforcharactersthatareoutputusingput.Thealternatespellingiswhatcolour.
Example
Thisprogramoutputsthecurrently-activecolornumber.Themessageisalsogiveninthecurrently-activecolor.
setscreen("graphics")
…
put"Thiswritingisincolornumber",whatcolor
DetailsThescreenshouldbeina"screen"or"graphics"mode.Seesetscreenfordetails.
Seealso
thecolorprocedure,whichisusedtosetthecolor.Seealsocolorbackandwhatcolorback.
SeealsopredefinedunitText.
whatcolorback colorofbackgroundfunction
Syntax whatcolorback:int
DescriptionThewhatcolorbackfunctionisusedtodeterminethecurrentbackgroundcolor.Thealternatespellingiswhatcolourback.
Example
Thisprogramoutputsthecurrently-activebackgroundcolornumber.Thebackgroundcolorofthemessageisdeterminedbythisnumber.
setscreen("screen")
…
put"Thebackgroundofthiswriting"
put"isincolornumber",whatcolorback
Details
Thescreenshouldbeina"screen"or"graphics"mode.Bewarethatthemeaningofbackgroundcolorisdifferentinthesetwomodes.Seecolorbackfordetails.
Seealsocolorandwhatcolor.
SeealsopredefinedunitText.
whatdotcolor graphicsfunction
Syntax whatdotcolor(x,y:int):int
DescriptionThewhatdotcolorfunctionisusedtodeterminethecolornumberofthespecifiedpixel.Thealternatespellingiswhatdotcolour.
Example
Thisprogramdrawsalinewhichbouncesofftheedgesofthescreenandmakesabeepwhenitfindsapixelthathasalreadybeencolored.
setscreen("graphics")
varx,y:int:=0
vardx,dx:int:=1
loop
ifwhatdotcolor(x,y)not=0then
sound(400,50)
endif
drawdot(x,y,1)
x:=x+dx
y:=y+dy
ifx=0orx=maxxthen
dx:=-dx
endif
ify=0ory=maxythen
dy:=-dy
endif
endloop
Details
Thescreenshouldbeina"graphics"mode.Ifisnotsetto"graphics"mode,itwillautomaticallybesetto"graphics"mode.Seesetscreenfordetails.
Seealso
drawdot,whichisusedforsettingthecolorofapixel.Seealsomaxxandmaxy,whichareusedtodeterminethenumberofpixelsonthescreen.Seealsosound,whichcausesthecomputertomakeasound.
SeealsopredefinedunitView.
whatrow cursorpositionfunction
Syntax whatrow:int
DescriptionThewhatrowfunctionisusedtodeterminethecursorposition'srow.
Example
ThisprogramoutputsThecurrentrowis5,thecurrentcolumnis15.
locate(5,10)
put"12345"..
put"Thecurrentrowis",whatrow
put"Thecurrentcolumnis",whatcol
DetailsThescreenshouldbeina"screen"or"graphics"mode.whatrowfunctionsproperlyevenifthecursorisinvisible.
Seealso
thewhatcolfunction,whichisusedtosetthedeterminethecursorcolumn.Seealsothelocate,maxrowandmaxcolprocedure.
SeealsopredefinedunitText.
Window
Description
Thisunitcontainsthepredefinedsubprogramsthathandlewindows.Thereareroutinestoopen,close,hide,showandselectwindows.
AllroutinesintheWindowunitareexportedqualified(andthusmustbeprefacedwith"Window.").
Details
ThepredefinedsubprogramsoftheWindowmoduleallusewindowidentifierstoindicatewhichwindowtoactupon.ThedefaultRunwindowcanbespecifiedbyusingdefWindID.Forexample,thefollowingcodecausesthemainRunwindowtoappearandthenblinkonandoffthreetimes.
%OutputsomedatatomaketheRunwindowappear.
put"Hello,World!"
fori:1..3
delay(1000)
Window.Hide(defWinID)
delay(1000)
Window.Show(defWinID)
endfor
put"Howareyou?"
EntryPoints
Open Opensanewexecutionwindow.Close Closesanexecutionwindow.Select Selectsanexecutionwindowforoutput.GetSelect Returnsthecurrently-selectedexecutionwindow.
SetActive Selectsandactivate(makefront-most)anexecutionwindow.
GetActive Getsthecurrentactivewindow.GetPosition Getthescreenpositionofanexecutionwindow.SetPosition Setthescreenpositionofanexecutionwindow.Hide Hidesanexecutionwindow.Show Showsthecurrentexecutionwindow.Set Setstheconfigurationoftheexecutionwindow.
Update Updatestheonscreenwindowfromtheoffscreenbitmap.
Window.Close PartofWindowmodule
Syntax Window.Close(windowID:int)
DescriptionTheWindow.CloseprocedureclosesthewindowspecifiedbythewindowIDparameter.
Example
Thefollowingprogramopensawindow,makesitactiveandthenclosesthewindowaftergettingakeystrokefromtheuser.
%Openthewindow
varwinID:int
winID:=Window.Open("position:300;300,graphics:200;200")
%Drawtherandomovalsinthebox
varx,y,clr:int
for:1..20
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
clr:=Rand.Int(0,maxcolor)%Randomcolor
Draw.FillOval(x,y,30,30,clr)
endfor
varch:char:=getchar%Waitforinput
Window.Close(winID)%Closethewindow
DetailsIfawindowisselected(i.e.outputisgoingtothatwindow)whenitisclosed,themainRunwindowbecomestheselectedwindow.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.Close,notbycallingClose.
Seealso Window.OpenandWindow.Select.
Window.GetActive PartofWindowmodule
Syntax Window.GetActive:int
Description
TheWindow.GetActivefunctionreturnsthewindowIDoftheactivewindow.IftheactivewindowisaTuringrunwindow,thenWindow.GetActivereturnsdefWinID(whichis-1)ifthewindowisthedefaultrunwindow,orwhatevernumberwasreturnedfromWindow.Openforanyotherrunwindow.Iftheactivewindowisnotarunwindow,thenitreturns-5andsetsError.LastandError.LastMsgtoindicatethefact.
Anactivewindowisdefinedasthewindowthathastheinputfocus.Thismeansthatanytypingwillbesenttotheactivewindow.Undermostsystemsanactivewindowisindicatedbyachangeintheappearanceofthewindow.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.GetActive,notbycallingGetActive.
Seealso Window.SetActive.
Window.GetPosition PartofWindowmodule
Syntax Window.GetPosition(windowID:int,varx,y:int)
Description
TheWindow.GetPositionprocedurereturnsthelocationofthespecifiedexecutionwindowonthescreenintheyparameters.Thexandyparametersspecifythelowerleftcornerofthewindowinscreencoordinates.(0,0)isthelowerleftcornerofthescreen.
Example
Thefollowingprogramoutputsthecurrentpositionoftherunwindow.
%Constantsforwindows
consttitleBarHeight:int:=21
constwindowEdgeSize:int:=13
%Calculatetheactualsizeofawindow
varwindowWidth:int:=maxx+windowEdgeSize
varwindowHeight:int:=maxy+windowEdgeSize+
%Getthescreensize
varscreenWidth:int:=Config.Display(cdScreenWidth
varscreenHeight:int:=Config.Display(cdScreenHeight
%Openthewindow
varwinID:int:=Window.Open("title:UpperRight")
Window.SetPosition(winID,screenWidthwindowWidth
%Returnthecurrentposition
varwindowXPosition,windowYPosition:int
Window.GetPosition(winID,windowXPosition,windowYPosition
put"Windowlocatedat",windowXPosition,",",
StatusExportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.GetPosition
Seealso Window.SetPositiontosetthecurrentwindowpositionandConfig.Display
Window.GetSelect PartofWindowmodule
Syntax Window.GetSelect:int
Description
TheWindow.GetSelectfunctionreturnsthewindowIDoftheselectedwindow.Iftheselectwindowisthemain(default)runwindow,thenitreturnsdefWinID(whichis-1).
Aselectedwindowisdefinedasthewindowthatoutputwillbesentto.Itcanbeinvisible.Whenaprogramstartsexecution,theselectedwindowisthemainRunwindow.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.GetSelect,notbycallingGetSelect.
Seealso Window.Select.
Window.Hide PartofWindowmodule
Syntax Window.Hide(windowID:int)
Description
TheWindow.Hideprocedurehidesthespecifiedwindow.Thismeansitdisappearsfromtheuser'sscreen.However,itisstillpossibletoselectanddrawthewindowwhileitremainshidden.Iftheuseractivatesit(usingWindow.GetActive)itwillautomaticallyappear.
Tomakeawindowappearafterit'shidden,youuseWindow.Show.
Details
Whenawindowishidden,outputtoitisfaster.Itisquitepossiblefortheyoutohideawindow,docomplicateddrawingtoitandthenmakeitappearinordertohavetheprogramexecutefaster.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.Hide,notbycallingHide.
Seealso Window.SelectandWindow.SetActive.
Window.Open PartofWindowmodule
Syntax Window.Open(setUpString:string):int
Description
TheWindow.Openfunctionisusedtocreateawindow.AwindowIDisreturnedifthewindowissuccessfullycreated.Ifthewindowisnotcreatedthenitreturns0.Error.LastandError.LastMsgcanthenbeusedtodeterminethecauseofthefailure.
ThesetUpStringparameterisidenticaltothatofView.Set.SeeView.Setforthelistofoptionsavailable.
Whenthewindowiscreated,itisautomaticallyselected(i.e.alloutputwillbesenttothatwindowunlessredirectedbyaWindow.Selectcommand).
Example
Thefollowingprogramopensawindow,makesitactiveandthenclosethewindowaftergettingakeystrokefromtheuser.
%Openthewindow
varwinID:int
winID:=Window.Open("position:top;center,graphics:200;200")
%Drawtherandomovalsinthebox
varx,y,clr:int
for:1..20
x:=Rand.Int(0,maxx)%Randomx
y:=Rand.Int(0,maxy)%Randomy
clr:=Rand.Int(0,maxcolor)%Randomcolor
Draw.FillOval(x,y,30,30,clr)
endfor
varch:char:=getchar%Waitforinput
Window.Close(winID)%Closethewindow
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.Open,notbycallingOpen.
SeealsoView.SetforthesyntaxofstartUpString.SeealsoWindow.SelectandWindow.SetActive.
Window.Select PartofWindowmodule
Syntax Window.Select(windowID:int)
Description
TheWindow.Selectselectsthewindowthatoutputistobesentto.
Aselectedwindowisdefinedasthewindowthatoutputwillbesentto.Itcanbeinvisible.Whenaprogramstartsexecution,theselectedwindowisthemainRunwindow.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.Select,notbycallingSelect.
Seealso Window.SelectandWindow.SetActive.
Window.Set PartofWindowmodule
Syntax Window.Set(windowID:int,setUpString:string)
Description
TheWindow.SetproceduresetstheconfigurationofthewindowspecifiedbythewindowIDparameter.SeeView.Setforacompletelistofavailableoptions.ThesetUpStringparametercanbeanycombinationoptions,separatedbycommas.Hereisaselectionoftheavailableoptions.
text:<rows>;<cols>-Setstheoutputwindowtotextmodeandchangesthewindowsizetobe<rows>rowsby<cols>columnsinsize.
graphics:<xsize>;<ysize>-Setstheoutputwindowtographicsmodeandchangesthewindowsizetobe<xsize>pixelsacrossand<ysize>pixelsinheight.
visible|invisible|popup-Setsthescreentobevisible,invisibleorpopup.Apopupwindowishiddenuntiloutputissenttothatwindow.ThemainRunwindowisapopupwindow.Ifyouneversendanyoutputtoit,itneverappears.
noxor|xor-SetswhetheralldrawingoperationsdrawusingXOR.
nocursor|cursor-Setswhetherthecursorisvisibleornot.
noecho|echo-Setswhethertheinputfromthekeyboardisechoedtothescreen.
title:<text>-Setsthewindowtitlebarto<text>.
position:<x>;<y>-Setsthepositionofthetopleftcornerofthewindowtobe(<x>,<y>).
offscreenonly|nooffscreenonly-Setswhetheroutputtothewindowgoestooffscreenwindowalone,orboththeonscreenandoffscreenwindow.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.Set,notbycallingSet.
Seealso
View.SetforacompletelistoftheoptionsavailablewithWindow.Set.SeeWindow.Openforhowtocreateanewwindow.
Window.SetActive PartofWindowmodule
Syntax Window.SetActive(windowID:int)
Description
TheWindow.SetActiveprocedureactivatesthewindowspecifiedbythewindowIDparameter.
Anactivewindowisdefinedasthewindowthathastheinputfocus.Thismeansthatanytypingwillbesenttotheactivewindow.Undermostsystemsanactivewindowisindicatedbyachangeintheappearanceofthewindow.
Details
Ingeneral,itisunwisetochangetheactivewindow.IftheuserisworkingonanotherprogramatthesametimetheprogramisrunningandtheprogramexecutestheWindow.SetActiveprocedure,sheorhewillsuddenlybereturnedtoOOTwithoutwarning.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.SetActive,notbycallingSetActive.
Seealso Window.GetActiveandWindow.Select.
Window.SetPosition PartofWindowmodule
Syntax Window.SetPosition(windowID:int,x,y:int)
DescriptionTheWindow.SetPositionproceduremovesthelocationofthespecifiedexecutionwindowonthescreen.specifythelowerleftcornerofthewindowinscreencoordinates.(0,0)isthelowerleftcornerofthescreen.
Example
Thefollowingprogramopensfourwindows,oneateachcornerofthescreen.
%Constantsforwindows
consttitleBarHeight:int:=21
constwindowEdgeSize:int:=13
%Calculatetheactualsizeofawindow
varwindowWidth:int:=maxx+windowEdgeSize
varwindowHeight:int:=maxy+windowEdgeSize+
%Getthescreensize
varscreenWidth:int:=Config.Display(cdScreenWidth
varscreenHeight:int:=Config.Display(cdScreenHeight
%Openthewindow
varwinID1:int:=Window.Open("title:UpperRight")
Window.SetPosition(winID1,screenWidthwindowWidth
varwinID2:int:=Window.Open("title:UpperLeft")
Window.SetPosition(winID2,0,screenHeightwindowHeight
varwinID3:int:=Window.Open("title:LowerLeft")
Window.SetPosition(winID3,0,0)
varwinID4:int:=Window.Open("title:LowerRight")
Window.SetPosition(winID4,screenWidthwindowWidth
StatusExportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.SetPosition
Seealso Window.GetPositiontogetthecurrentwindowpositionandConfig.Display
Window.Show PartofWindowmodule
Syntax Window.Show(windowID:int)
Description
TheWindow.Showproceduremakesthespecifiedwindowappearifitwasinvisible.
Tomakeawindowdisappearafterit'svisible,youuseWindow.Hide.
Details
Whenawindowishidden,outputtoitisfaster.Itisquitepossiblefortheyoutohideawindow,docomplicateddrawingtoitandthenmakeitappearinordertohavetheprogramexecutefaster.
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingWindow.Show,notbycallingShow.
Seealso Window.SelectandWindow.SetActive.
Window.Update PartofWindowmodule
Syntax Window.Update(windowID:int)
Description
TheWindow.UpdateprocedureupdatesaspecifiedRunwindowfromanoffscreenbitmap.ItisusedwiththecommandView.Set("offscreenonly")whichpreventstheRunwindowfrombeingupdateduntiltheWindow.Updatecommandisgiven.
ThiscommandisidenticaltotheView.Updatecommandexceptthatitupdatesthespecifiedwindow.Itshouldbeusedwhendoinganimationwithmorethanonewindow.
Seealso View.Updateforinformationonflicker-freeanimation.
write filestatement
Syntax
AwriteStatementis:
write:fileNumber[:status],writeItem{,writeItem}
Description
ThewritestatementoutputseachofthewriteItemstothespecifiedfile.Theseitemsareoutputdirectlyusingthebinaryformatthattheyhaveinthecomputer.Inotherwords,theitemsarenotinsource(ASCIIorEBCDIC)format.Inthecommoncase,theseitemswilllaterbeinputfromthefileusingthereadstatement.Bycontrast,thegetandputstatementsusesourceformat,whichapersoncanreadusingatexteditor.
Example
Thisexampleshowshowtooutputacompleteemployeerecordusingawritestatement.
varemployeeRecord:
record
name:string(30)
pay:int
dept:0..9
endrecord
varfileNo:int
open:fileNo,"payroll",write
…
write:fileNo,employeeRecord
Anarray,recordorunionmaybereadandwrittenasawhole.ThefileNumbermustspecifyafilethatisopenwithwritecapability(orelseaprogramargumentfilethatisimplicitlyopened).
Theoptionalstatusisanintvariablethatissettoimplementation-dependentinformationaboutthewrite.Ifstatusisreturnedaszero,thewritewassuccessful.Ifstatusisnotreturnedaszero,statusgivesinformationabouttheincompleteorfailedwrite(whichisnotdocumentedhere).Programmersoftenusestatuswhentheyarewritingarecordorarraytoafileandare
Details
notsureifthereisenoughroomonthedisktoholdtheitem.Ifthereisnotenoughroom,thewritewillfailpartwaythrough,buttheprogramcancontinueanddiagnosetheproblembyinspectingstatus.
AwriteItemis:
reference[:requestedSize[:actualSize]]
EachwriteItemisavariableorconstant,tobewrittenininternalform.TheoptionalrequestedSizeisanintegerexpressiongivingthenumberofbytesofdatatobewritten.TherequestedSizeshouldbelessthanorequaltothesizeoftheitem'sinternalforminmemory(ifitisnot,awarningmessageisissued).IfnorequestedSizeisgiven,thesizeoftheiteminmemoryisused.TheoptionalactualSizeissettothenumberofbytesactuallywritten.
Seealso write,open,close,seek,tell,getandputstatements.
xor exclusive"or"operator
Syntax AxorB
Description
Whenappliedtosetvalues,xor(symmetricdifference)yieldsasetwhichincludeselementeifandonlyifeiscontainedinexactlyoneoftheoperands.Whenappliedtonon-negativeintegervalues,xoryieldsanaturalnumberwhosebitsarethexorofthecorrespondingbitsoftheoperands.BothoperandsAandBareevaluated.
Example
Statuss3willcontainelementsthatareins1ors2butnotboth.Herexorisasetoperator.Seeenumandsettypesforexplanationsofthesetypes.
typestatus:enum(ready,sending,repeating)
typestatusSet:setofstatus
vars1,s2,s3:statusSet
s1:=statusSet(status.read,status.sending)
s2:=statusSet(status.read,status.repeating)
…
s3:=s1xors2%Sameas(s1+s2)-(s1*s2)
Example
Eachbitofnaturalnumbern3willbe1ifexactlyoneofthecorrespondingbitsofn1andn2are1.Forexample,ifn1=2#110(6)andn2=2#010(2),n3willbesetto2#100(4).Herexorisanintegeroperator.
varn1,n2,n3:nat
…
n3:=n1xorn2
Details
Thexoroperatorisnotashortcircuitoperator;inotherwords,bothofitsoperandsarealwaysevaluated.Theprecedenceofxoristhesameasthatofplus(+).
Seealsoset.SeealsoexplicitIntegerConstantwhichdescribesvaluessuchas2#110.
TuringLanguageElements#if-usedforconditionalcompilationaddressint-typeall-allmembersofasetand-operatoranyclass-theancestorofallclassesarray-typeassert-statementassignability-ofexpressiontovariableassignment-statementbegin-statementbind-declarationbody-declarationboolean-true-falsetypebreak-debuggerpausestatementcase-selectionstatementcatenation(+)-joiningtogetherstringschar-typechar(n)-typechecked-compilerdirectiveclass-declarationclose-filestatementcollection-declarationcomment-remarkstatementcomparisonOperatorcondition-declarationconst-constantdeclarationconstantReference-useofaconstantdeclaration-createavariabledeferred-subprogramdeclarationdiv-integertruncatingdivisionoperatorenum-enumeratedtypeenumeratedValue-enumeratedvalueequivalence-oftypesexit-statement
explicitCharConstant-characterliteralexplicitConstant-literalexplicitIntegerConstant-integerliteralexplicitRealConstant-realliteralexplicitStringConstant-stringliteralexplicitTrueFalseConstant-booleanliteralexpn-expressionexport-listexternal-declarationfalse-booleanvalue(nottrue)flexible-arrayinitializationfor-statementfork-statementforward-subprogramdeclarationfree-statementfunction-declarationfunctionCallget-filestatementhandler-exceptionhandlerid-(identifier)nameofaniteminaprogramif-statementimplement-clauseimplementby-clauseimport-listin-memberofasetinclude-sourcefilesindexTypeindirection-operator(@)infix-operatorinherit-inheritanceclauseinit-arrayinitializationint-integertypeintn-n-byteintegertypeinvariant-assertionloop-statementmod-modulooperatormodule-declarationmonitor-declarationnamed-type
nat-naturalnumbertypenatn-n-bytenaturalnumbertypenew-statementnil-pointertoacollectionnot-true/false(boolean)operatoropaque-typeopen-filestatementor-operatorparamDeclaration-parameterdeclarationpause-statementpervasive-declarationmodifierpointer-typepost-assertionpre-assertionprecedence-ofoperatorsprefix-operatorprocedure-declarationprocedureCall-statementprocess-declarationprogram-a(main)programput-statementquit-failstatementread-filestatementreal-therealnumbertyperealn-n-byterealnumbertyperecord-typeregister-usemachineregisterrem-remainderoperatorresult-statementreturn-statementscalar-typeseek-(file)statementseparator-betweentokensinaprogramset-typesetConstructorshl-shiftleftoperatorshr-shiftrightoperatorsignal-wakeupaprocessstatementskip-usedingetstatement
skip-usedinputstatementstandardTypestatementstatementsAndDeclarationsstring-typestring-comparisonsubprogramHeadersubprogramTypesubrangeTypesubstring-ofanotherstringtag-statementtell-filestatementtoken-ininputtrue-booleanvalue(notfalse)type-declarationtypeSpec-typespecificationunchecked-compilerdirectiveunion-typeunit-filecontainingmodule,monitor,orclassunqualified-exportvar-declarationvariableReference-useofavariablewait-blockaprocessstatementwrite-filestatementxor-exclusive"or"operator
BasicPredefinedSubprogramsTypeConversion
FromIntegerintreal-integer-to-realfunctionintstr-integer-to-stringfunction
FromRealceil-real-to-integerfunctionerealstr-real-to-stringfunctionfloor-real-to-integerfunctionfrealstr-real-to-stringfunctionrealstr-real-to-stringfunctionround-real-to-integerfunction
FromNatnatreal-naturalnumbertorealfunctionnatstr-natural-number-to-stringfunction
FromStringstrint-string-to-integer:functionstrintok-string-to-integer:functionstrnat-stringtonaturalnumberfunctionstrnatok-stringtonaturalnumberfunctionstrreal-string-to-realfunctionstrrealok-string-to-realfunction
To/FromASCIIchr-integer-to-characterfunctionord-character-to-integerfunction
MaximumNumbersmaxint-maximumintegerfunctionmaxnat-maximumnaturalnumberfunctionminint-minimumintegerfunctionminnat-minimumnaturalnumberfunction
Mathabs-absolutevaluefunctionarctan-arctangentfunction(radians)arctand-arctangentfunction(degrees)cos-cosinefunction(radians)
cosd-cosinefunction(degrees)exp-exponentiationfunctionln-naturallogarithmfunctionmax-maximumfunctionmin-minimumfunctionsign-functionsin-sinefunction(radians)sind-sinefunction(degrees)sqrt-squarerootfunction
Stringsindex-findpatterninstringfunctionlength-ofastringfunctionrepeat-makecopiesofstring:function
EnumeratedTypespred-predecessorfunctionsucc-successorfunction
Fileseof-end-of-filefunction
Arrayslower-boundupper-bound
RandomNumbersrand-randomrealnumberprocedurerandint-randomintegerprocedurerandnext-procedurerandomize-procedurerandseed-procedure
Timeclock-millisecsusedproceduredate-proceduresysclock-millisecsusedproceduretime-timeofdayasastringprocedurewallclock-secondssince1/1/1970procedure
Soundplay-procedureplaydone-functionsound-statement
Systemdelay-procedure
fetcharg-fetchargumentfunctiongetenv-getenvironmentfunctiongetpid-getprocessidfunctionnargs-numberofargumentssystem-statement
ParallelPortparallelget-parallelportfunctionparallelput-parallelportprocedure
Mousebuttonchoose-switchmousemodesbuttonmoved-hasamouseeventoccurredbuttonwait-getamouseeventproceduremousewhere
CharacterGraphicscls-clearscreengraphicsprocedurecolor-textcolorgraphicsprocedurecolorback-backgroundcolorprocedurecolour-textcolorgraphicsprocedurecolourback-backgroundcolorprocedurelocate-proceduremaxcol-maximumcolumnfunctionmaxcolor-graphicsfunctionmaxcolour-graphicsfunctionmaxrow-maximumrowfunctionsetscreen-graphicsprocedurewhatcol-cursorpositionfunctionwhatcolor-textcolorgraphicsfunctionwhatcolorback-colorofbackgroundfunctionwhatcolour-textcolorgraphicsfunctionwhatcolourback-colorofbackgroundfunctionwhatrow-cursorpositionfunction
PixelGraphicscls-clearscreengraphicsprocedurecolor-textcolorgraphicsprocedurecolorback-backgroundcolorprocedurecolour-textcolorgraphicsprocedurecolourback-backgroundcolorproceduredrawarc-graphicsproceduredrawbox-graphicsprocedure
drawdot-graphicsproceduredrawfill-graphicsproceduredrawfillarc-graphicsproceduredrawfillbox-graphicsproceduredrawfillmapleleaf-graphicsproceduredrawfilloval-graphicsproceduredrawfillpolygon-graphicsproceduredrawfillstar-graphicsproceduredrawline-graphicsproceduredrawmapleleaf-graphicsproceduredrawoval-graphicsproceduredrawpic-graphicsproceduredrawpolygon-graphicsproceduredrawstar-graphicsprocedurelocate-procedurelocatexy-graphicsproceduremaxcol-maximumcolumnfunctionmaxcolor-graphicsfunctionmaxcolour-graphicsfunctionmaxrow-maximumrowfunctionmaxx-graphicsfunctionmaxy-graphicsfunctionsetscreen-graphicsproceduresizepic-graphicsfunctiontakepic-graphicsprocedurewhatcol-cursorpositionfunctionwhatcolor-textcolorgraphicsfunctionwhatcolorback-colorofbackgroundfunctionwhatcolour-textcolorgraphicsfunctionwhatcolourback-colorofbackgroundfunctionwhatdotcolor-graphicsfunctionwhatdotcolour-graphicsfunctionwhatrow-cursorpositionfunction
CharacterInputgetch-getcharacterproceduregetchar-getcharacterfunctionhasch-hascharacterfunction
Concurrencyempty-conditionfunction
getpriority-functionsetpriority-proceduresimutime-simulatedtimefunction
AddressesandSizesaddr-addressofavariablesizeof-sizeofatype
BitManipulationbits-extraction
Classesobjectclass-ofapointerself-pointertocurrentobject
TypeCheatscheat-typecheating
PredefinedModulesConcurrency
Concurrency.emptyConcurrency.getpriorityConcurrency.setpriorityConcurrency.simutime
ConfigConfig.DisplayConfig.LangConfig.Machine
DirDir.ChangeDir.CloseDir.CreateDir.CurrentDir.DeleteDir.GetDir.GetLongDir.Open
DrawDraw.ArcDraw.BoxDraw.ClsDraw.DotDraw.FillDraw.FillArcDraw.FillBoxDraw.FillMapleLeafDraw.FillOvalDraw.FillPolygonDraw.FillStarDraw.LineDraw.MapleLeafDraw.OvalDraw.Polygon
Draw.StarDraw.Text
ErrorError.LastError.LastMsgError.LastStrError.MsgError.StrError.Trip
ErrorNumExceptionsFile
File.CopyFile.DeleteFile.DiskFreeFile.ExistsFile.RenameFile.Status
FontFont.DrawFont.FreeFont.GetNameFont.GetSizeFont.GetStyleFont.NameFont.NewFont.SizesFont.StartNameFont.StartSizeFont.Width
GUIGUI.AddLineGUI.AddTextGUI.AlertGUI.Alert2GUI.Alert3GUI.AlertFullGUI.ChooseGUI.ChooseFull
GUI.ClearTextGUI.CloseWindowGUI.CreateButtonGUI.CreateButtonFullGUI.CreateCanvasGUI.CreateCanvasFullGUI.CreateCheckBoxGUI.CreateCheckBoxFullGUI.CreateFrameGUI.CreateHorizontalScrollBarGUI.CreateHorizontalScrollBarFullGUI.CreateHorizontalSliderGUI.CreateLabelGUI.CreateLabelFullGUI.CreateLabelledFrameGUI.CreateLineGUI.CreateMenuGUI.CreateMenuItemGUI.CreateMenuItemFullGUI.CreatePictureGUI.CreatePictureButtonGUI.CreatePictureButtonFullGUI.CreatePictureRadioButtonGUI.CreatePictureRadioButtonFullGUI.CreateRadioButtonGUI.CreateRadioButtonFullGUI.CreateTextBoxGUI.CreateTextBoxFullGUI.CreateTextFieldGUI.CreateTextFieldFullGUI.CreateVerticalScrollBarGUI.CreateVerticalScrollBarFullGUI.CreateVerticalSliderGUI.DisableGUI.DisposeGUI.Draw...GUI.EnableGUI.FontDrawGUI.GetCheckBox
GUI.GetEventTimeGUI.GetEventWidgetIDGUI.GetEventWindowGUI.GetHeightGUI.GetMenuBarHeightGUI.GetScrollBarWidthGUI.GetSliderValueGUI.GetTextGUI.GetVersionGUI.GetWidthGUI.GetXGUI.GetYGUI.HideGUI.HideMenuBarGUI.OpenFileGUI.OpenFileFullGUI.Pic...GUI.ProcessEventGUI.QuitGUI.RefreshGUI.SaveFileGUI.SaveFileFullGUI.SelectRadioGUI.SetActiveGUI.SetBackgroundColorGUI.SetBackgroundColourGUI.SetCheckBoxGUI.SetDefaultGUI.SetDisplayWhenCreatedGUI.SetKeyEventHandlerGUI.SetLabelGUI.SetMouseEventHandlerGUI.SetNullEventHandlerGUI.SetPositionGUI.SetPositionAndSizeGUI.SetScrollAmountGUI.SetSelectionGUI.SetSizeGUI.SetSliderMinMax
GUI.SetSliderReverseGUI.SetSliderSizeGUI.SetSliderValueGUI.SetTextGUI.SetXORGUI.ShowGUI.ShowMenuBar
InputInput.KeyDown-getkeyboardstateInput.Pause-pauseforkeystrokeInput.getchInput.getcharInput.hasch
JoystickJoystick.GetInfo
KeyboardLimits
maxint-maximumintegerfunctionmaxnat-maximumnaturalnumberfunctionminint-minimumintegerfunctionminnat-minimumnaturalnumberfunction
Mathabs-absolutevaluefunctionarctan-arctangentfunction(radians)arctand-arctangentfunction(degrees)cos-cosinefunction(radians)cosd-cosinefunction(degrees)exp-exponentiationfunctionln-naturallogarithmfunctionmax-maximumfunctionmin-minimumfunctionsign-functionsin-sinefunction(radians)sind-sinefunction(degrees)sqrt-squarerootfunction
MouseMouse.ButtonChooseMouse.ButtonMovedMouse.ButtonWait
Mouse.WhereMusic
Music.PlayMusic.PlayFileMusic.PlayFileStopMusic.SoundMusic.SoundOff
NetNet.BytesAvailableNet.CharAvailableNet.CloseConnectionNet.HostAddressFromNameNet.HostNameFromAddressNet.LineAvailableNet.LocalAddressNet.LocalNameNet.OpenConnectionNet.OpenURLConnectionNet.TokenAvailableNet.WaitForConnection
PCPC.ParallelGetPC.ParallelPutparallelget-parallelportfunctionparallelput-parallelportprocedure
PicPic.BlendPic.BlurPic.DrawPic.DrawFramesPic.DrawFramesBackPic.DrawSpecialPic.DrawSpecialBackPic.FileNewPic.FileNewFramesPic.FlipPic.FramesPic.FreePic.Height
Pic.MirrorPic.NewPic.RotatePic.SavePic.ScalePic.ScreenLoadPic.ScreenSavePic.SetTransparentColorPic.SetTransparentColourPic.Width
RGBRGB.AddColorRGB.AddColourRGB.GetColorRGB.GetColourRGB.SetColorRGB.SetColourRGB.maxcolorRGB.maxcolour
RandRand.IntRand.NextRand.RealRand.ResetRand.SeedRand.Set
SpriteSprite.AnimateSprite.ChangePicSprite.FreeSprite.HideSprite.NewSprite.SetFrameRateSprite.SetHeightSprite.SetPositionSprite.Show
Strindex-findpatterninstringfunctionlength-ofastringfunction
repeat-makecopiesofstring:functionStream
Stream.FlushStream.FlushAllStream.eofeof-end-of-filefunction
SysSys.ExecSys.FetchArgSys.GetComputerNameSys.GetEnvSys.GetPidSys.GetUserNameSys.Nargsgetenv-getenvironmentfunctiongetpid-getprocessidfunction
TextText.ClsText.ColorText.ColorBackText.ColourText.ColourBackText.LocateText.LocateXYText.WhatColText.WhatColorText.WhatColorBackText.WhatColourText.WhatColourBackText.WhatRowText.maxcolText.maxrow
TimeTime.DateTime.DateSecTime.DelayTime.ElapsedTime.ElapsedCPUTime.PartsSec
Time.SecTime.SecDateTime.SecParts
TypeConvFromInteger
intreal-integer-to-realfunctionintstr-integer-to-stringfunction
FromNatnatreal-naturalnumbertorealfunctionnatstr-natural-number-to-stringfunction
FromRealceil-real-to-integerfunctionerealstr-real-to-stringfunctionfloor-real-to-integerfunctionfrealstr-real-to-stringfunctionrealstr-real-to-stringfunctionround-real-to-integerfunction
FromStringstrint-string-to-integer:functionstrintok-string-to-integer:functionstrnat-stringtonaturalnumberfunctionstrnatok-stringtonaturalnumberfunctionstrreal-string-to-realfunctionstrrealok-string-to-realfunction
To/FromASCIIchr-integer-to-characterfunctionord-character-to-integerfunction
ViewView.ClipAddView.ClipOffView.ClipSetView.SetView.Update-flicker-freeanimationView.WhatDotColorView.WhatDotColourView.maxcolorView.maxcolourView.maxxView.maxy
WindowWindow.CloseWindow.GetActiveWindow.GetPositionWindow.GetSelectWindow.HideWindow.OpenWindow.SelectWindow.SetWindow.SetActiveWindow.SetPositionWindow.ShowWindow.Update
MiscellaneousSubprogramsAddressesandSizes
addr-addressofavariablesizeof-sizeofatype
Arrayslower-boundupper-bound
BitManipulationbits-extraction
Classesobjectclass-ofapointerself-pointertocurrentobject
EnumeratedTypespred-predecessorfunctionsucc-successorfunction
TypeCheatscheat-typecheating
TheGUIModuleIntroduction
SincetheintroductionoftheMacintosh,graphicaluserinterfaces(GUI)havebeenbecomingmoreandmorecommon.MostcommercialprogramswrittenforeithertheMacintoshorMicrosoftWindowsmakeuseofGUIelementstomaketheirprogrameasiertouse.
Forsometime,studentshavebeenrequestingmethodsofputtingGUIelementssuchasbuttons,checkboxes,radiobuttons,etc,intotheirTuringprograms.TuringnowincludesanewsetofpredefinedsubprogramsthatallowstudentstoaddnumerousGUIelementstotheirprogramsquicklyandeasily.Thesesubprogramsallowstudentstocreate:buttons,checkboxes,radiobuttons,sliders,scrollbars,picturebuttons,radiopicturebuttons,textfields,lines,textlabels,andframes.
TheentireGUILibraryiswritteninTuringandthesourceisincludedwiththeTuringdistribution.TheGUIlibraryiscompletelyprocedure-oriented.Thismeansthatitisnotnecessarytoknowobject-orientedprogrammingorconceptsinordertobeabletousethelibrary.Advancedstudentsarewelcome(infact,encouraged)tolookattheprogramsasanexampleofalargeprojectwritteninTuring.WehopethattherewillbeenterprisingstudentswhowillbeinspiredtoaddnewwidgetstothelibraryandencouragethosewhodosotosubmitthemtoHoltSoftwareforpossibleinclusionintothenextversionofthelibrary.
Hereisawindowwithafewwidgets.
SomeGUIWidgets(OutputofExample.dem)
TheGUIlibraryisusablebystudentswhounderstandtheconceptofsubprograms.InordertousetheGUIlibrary,studentsmustwriteprocedures(althoughtheymaybeassimpleasthestudentdesires).WethereforesuggestthatteachersintroducestudentstotheGUIlibraryinaGrade11computersciencecourse.
Note:Turinghasnotchanged.Itisnotavisualbuildinglanguage.StudentswishingtousetheGUIlibrarywillbewritingprogramstocreateandusetheseGUIelement,notspendingtheirtimevisuallybuildinguserinterfaces(whichmaybefun,butteachesverylittle).InkeepingwiththetraditionofTuring,themorethestudentslearnaboutcomputerscience,themoreinterestingtheir
programswillbe,GUIornoGUI!
Terminology
Theterm"Widget"meansanygraphicaluserinterfaceelement.Abutton,acheckboxorradiobuttonareallexamplesofwidgets.
Theterm"Event"meanseitherakeystrokeoramousebuttonbeingpressedinawindow.
ExamplePrograms
Allexampleprogramsshownherearelocatedinthe[TuringDirectory]/Examples/GUIdirectory.(Inotherwords,startinthesamedirectoryastheTuringexecutable,movetotheExamplesfolderandthentheGUIfolder.)AlltheavailableGUIwidgetshaveexampleprogramstodemonstratetheiruse.
GeneralPrinciplesoftheGUILibrary
HerearesomegeneralinstructionsfortheuseoftheGUIlibrary.Readthissectionbeforelookingatthespecificsofvariousroutines.
AllthesubprogramsfortheGUIlibraryareplacedinamodulecalledGUI.Tocallanyofthesubprograms,prefacethenameofthesubprogramwithGUI..Forexample,theCreateLabelsubprogramwouldbecalledusingGUI.CreateLabel.Ingeneral,mostwidgetshaveaCreatesubprogram.Forexample,buttonshaveaCreateButtonsubprogram,radiobuttonshaveaCreateRadioButtonsubprogram,andsoon.TheCreatesubprogramtakesasparametersthingssuchasthelocation,thesizeoftheGUIelement,andthenameofaproceduretobecalledwhenthewidgetisclicked.ThisproceduremustbedeclaredbeforethecalltotheCreatesubprogram.Formostwidgets,therearetwoformsoftheCreatesubprogram.TheCreatesubprogramandtheCreateFullsubprogram.ThedifferencebetweenthetwoisthattheCreateFullsubprogramallowstheusertodefinemoreparametersthatareotherwisesettodefaultvalues.Forexample,theGUI.CreateButtonprocedureallowstheusertospecifythexandylocationofthebutton,thewidthofthebutton,thetextthatappearsinthebutton,andtheproceduretocallwhenthebuttonisclicked.TheGUI.CreateButtonFullroutinespecifiesthoseandalsoallowstheusertospecifytheheightofthebutton(otherwisesettoaheightthatwillfitthelabel),ashortcutkeyboardcharacterthatallowstheuserto"press"thebuttonusingakeyboardandaparametertoallowtheusertospecifyifthisbuttonisthe"default"button(theone"pressed"iftheuserpressestheEnterkey).AllCreatesubprogramsreturnaninteger.ThisnumberistheIDofthewidgetthathasbeencreated.YouneedtousethisIDifyouwanttodoanythingtothewidgetlater,suchasmoveit,changeitssize,hideit,andsoon.MostsimpleprogramscansafelyignorethewidgetID,althoughtheywillneedtohandlethereturnvaluefromthefunction.Afterallthewidgetshavebeencreated,theprogrammustrepeatedlycallGUI.ProcessEventuntilthefunctionreturnstrue.
%Nowprocesseventsuntiltheuserabortstheprogram.
loop
exitwhenGUI.ProcessEvent
endloop
GUI.ProcessEventchecksforuserinputfromthemouseorthekeyboardandthencheckstoseeiftheuserhasclickedonawidget.Iftheuserhas,thenitrespondsappropriately(togglingthecheckbox,pressingthebutton,etc.)andthenifappropriate,callstheproceduretheusersuppliedintheCreatesubprogram.GUI.ProcessEventreturnstruewhentheGUI.Quithasbeencalled,otherwiseitreturnsfalse.
Whenaprogramisfinishedexecution(forexampleiftheuserselected"Quit"or"Exit"fromthefilemenu),itshouldcalltheGUI.Quitprocedure.ThiswillcausetheGUI.ProcessEventlooptoexit.Theprogramshouldhaveanycleanupcodeplacedaftertheendloop.
Hereisaverysimpleexampleofaprogramthatputs"Hello"everytimeabuttonispressed.
%The"Hello"program.
importGUI
View.Set("graphics:200;200")%Shrinktherunwindow
%Theprocedurecalledwhenthebuttonispushed.
procedurePutHello
put"Hello"
endPutHello
%Createthebutton.ThenumberreturnedistheIDnumberofthebutton.
varb:int:=GUI.CreateButton(100,100,0,"SayHello",PutHello)
%Nowprocesseventsuntiltheuserabortstheprogram.
loop
exitwhenGUI.ProcessEvent
endloop
Hereistheoutputwindowaftertheuserhaspressedthebuttontwice.
OutputofHello.dem
ActiveandPassiveWidgets
Widgetscomeintwoforms.Activewidgetsareonesthatrespondtokeystrokesandbuttonclicks.Passivewidgetsdonotrespondtoanything.Examplesofpassivewidgetsarelines,frames,labels,labelledframesandpictures.Passivewidgetsaregenerallyusedtoorganizetheoutputwindow.
Hereisanexampleofasmallprogramthatshowsomepassivewidgets.
%The"Passive"program
%Thisdemonstratessomeofthepassivewidgetssuchas:
%Lines,Frames,LabelledFrames,LabelsandPictures.
importGUI
%We'llneedapictureforourPicturewidget.Mostlikely
%youwouldnormallyhaveitsavedinanexternalfileand
%usePic.FileNewtoreaditintoapicture.Fortheexample
%programwe'llconstructitbyhand.
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)
varpic:=Pic.New(0,0,100,100)
View.Set("graphics:310;335")
%Thebackgroundmustbegrayforindentedandexdented
%itemstobevisible.
GUI.SetBackgroundColor(gray)
%Nowplacethewidgets.
%Threelinesofthedifferenttypeswithlabels
varline1:=GUI.CreateLine(70,10,maxx-10,10,GUI.LINE)
varlabel1:=GUI.CreateLabelFull(60,10,"Line",0,0,
GUI.RIGHT+GUI.MIDDLE,0)
varline2:=GUI.CreateLine(70,30,maxx-10,30,GUI.INDENT)
varlabel2:=GUI.CreateLabelFull(60,30,"Indent",0,0,
GUI.RIGHT+GUI.MIDDLE,0)
varline3:=GUI.CreateLine(70,50,maxx-10,50,GUI.EXDENT)
varlabel3:=GUI.CreateLabelFull(60,50,"Exdent",0,0,
GUI.RIGHT+GUI.MIDDLE,0)
%Nowplacetheframes
varframe1:=GUI.CreateFrame(10,70,100,120,GUI.LINE)
varlabel4:=GUI.CreateLabelFull(10,70,"Line",90,50,
GUI.CENTER+GUI.MIDDLE,0)
varframe2:=GUI.CreateFrame(110,70,200,120,GUI.INDENT)
varlabel5:=GUI.CreateLabelFull(110,70,"Indent",90,50,
GUI.CENTER+GUI.MIDDLE,0)
varframe3:=GUI.CreateFrame(210,70,300,120,GUI.EXDENT)
varlabel6:=GUI.CreateLabelFull(210,70,"Exdent",90,50,
GUI.CENTER+GUI.MIDDLE,0)
%Nowplacethelabelledframes
varframe4:=GUI.CreateLabelledFrame(10,140,100,190,GUI.LINE,"Line")
varframe5:=GUI.CreateLabelledFrame(110,140,200,190,GUI.INDENT,
"Indent")
varframe6:=GUI.CreateLabelledFrame(210,140,300,190,GUI.EXDENT,
"Exdent")
%Placethepicture
varlabel7:=GUI.CreateLabel(30,315,"Picturewithoutmerge")
varpic1:=GUI.CreatePicture(30,210,pic,false)
varlabel8:=GUI.CreateLabel(maxx-130,315,"Picturewithmerge")
varpic2:=GUI.CreatePicture(maxx-130,210,pic,true)
%Thisloopdoesn'tdomuchsincenoneofthewidgetshaveanyactions.
loop
exitwhenGUI.ProcessEvent
endloop
Hereistheoutputwindowfromtheprogramwithsomelabels,aline,apicture,andalabelledframe.
OutputofPassive.dem
Whenanactivewidgetisinitialized,usuallyanactionproceduremustbespecified.Thisisthenameofaprocedurethatwillbecalledwhenthewidgetisselected.Forexample,intheHelloprogram,thePutHelloprocedurewasspecifiedastheactionprocedureofthebutton.Wheneverthebuttonwaspressed,thePutHelloprocedurewascalled.
Someactionprocedureshavearguments.Forexample,theactionprocedureforasliderhasaparameterofthecurrentvalue.ThisallowstheproceduretousethecurrentvaluewithouthavingtocallaGUIsubprogramtogetthecurrentslidervalue.
KeyboardShortcuts
Severaltypesofwidgetscanhave"shortcuts".Ashortcutissimplyakeystrokethathasthesameeffectasclickingonthewidget.WhenyouspecifyashortcuttoawidgetintheCreateFullprocedureforthewidget,youmustspecifyasinglecharacter.TheeasiestwaytodothisistousethechrfunctionwiththeASCIIvalueofthecharactertobeusedastheshortcut.Youcanalsospecifycontrolcharactersusingthe"^"notation.Forexample,thecharacterCtrl+Fcanbeexpressedas"^F"inTuring.
ThefollowingcharacterscannotbeusedasshortcutsbecausetheTuringenvironmentusesthemforvariouspurposes(stoppingorrerunningprograms,andsoon.):Ctrl+C,Ctrl+D,Ctrl+Z,F1,F11andF12.
BackgroundColor
Itiscommonforwindowstohaveadifferentbackgroundcolorfromthestandardwhite.Tochangethebackgroundcolorofawindow,usetheGUI.SetBackgroundColorprocedure.Thisproceduretakesoneparameter,thenewbackgroundcolor.Itredrawsthewindowinthebackgroundcolorandthenredrawsallthewidgets.Italsonotifiesthewidgetsaboutthenewbackgroundcolorsothatwhenthewidgetiserasedormoved,thelocationofthewidgetisfilledwiththenewbackgroundcolorinsteadofwhite.
NotethatMicrosoftWindowsdialogboxesoftenhaveabackgroundcolorofgray.Inordertosimulatethat,youshouldgivethecommandGUI.SetBackgroundColor(gray)beforecreatingwidgets.
Severalwidgets(Canvas,Frame,LabelledFrame,TextFieldandTextBox)canhavebordersofeithertypeINDENTorEXDENT.Thesebordersgiveasortof3-Dappearancetothewidget.However,theyrequirethatthebackgroundbesettogray.
HereisanexampleofasmallprogramthatcreatesaCanvaswitha3-Dappearanceandthendrawscirclesinthecorner.
%The"Canvas1"program.
%Createacanvasanddrawfourcirclesonit.
importGUI
View.Set("graphics:200;200")
%Necessaryfora3-Dlookforthecanvas
GUI.SetBackgroundColor(gray)
%ThisprocedureisneededasanargumenttoCreateCanvasFull.
procedureDoNothing(mx,my:int)
endDoNothing
%Createalabelforthecanvas.WecoulduseCreateLabelFullformore
%precisealignment.
varlabel1:=GUI.CreateLabel(70,182,"FourCircles")
%Createthecanvas.WeneedtouseCreateCanvasFullinorderto
%specifythetypeofborder.
varcanvas:=GUI.CreateCanvasFull(20,20,160,160,GUI.INDENT,
DoNothing,DoNothing,DoNothing)
%Drawthefourovals.Noticethattheydon'textendoffthecanvas
%andtheco-ordinatestheyusearerelativetothecanvas,notthewindow.
constradius:=70%Halfthewidth-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)
Hereistheoutputwindow.
OutputofCanvas1.dem
WidgetSizes
Thesizethatyouspecifyawidgettobeisnotnecessarilytheactualsizethatthewidgetwillappear.Infactformanywidgets,youcanspecifyawidthandheightof0forthewidgetandletstheinitializerdecidehowlargethewidgetshouldbe.Anotherexampleiswithcheckboxes,whereifyouspecifythecheckboxtoberightjustified,thexandycoordinatesindicatethelower-rightcornerinsteadofthelower-leftcornerasusual.Thismeansthatyoumayhavetodosomeexperimentationtodeterminewhereyouwantthewidgetstobeplaced.Readthepageoneachsubprogramthatyouusetofindoutexactlywhatyouarespecifyingwiththex,y,widthandheightparameters.
Ifyouaretryingtoalignwidgetstogether(forexamplealigningscrollbarswithacanvas),usetheGUI.GetX,GUI.GetY,GUI.GetWidth,andGUI.GetHeightfunctionstodeterminethesizeoftheobject.
PositioningTextLabels(AligningLabelswithWidgets)
Itisverycommontowanttoaligntextlabelswithwidgetsonthescreen.Thereareafewtipsandtrickstodoingsosuccessfully.Toalignatextlabelwithawidget,itissimplyamatterofusingtheGUI.CreateLabelFullfunctionwiththeappropriatex,y,width,heightandalignmentarguments.
Ifyouareleftorrightaligningalabel,thengenerallyyouwillwantthexcoordinatetospecifytheedgetobealignedfromandthewidthparametershouldbesetto0.Similarly,ifyouaretoporbottomaligningalabel,thentheycoordinateshouldspecifytheedgetobealignedfromandtheheightparametershouldbesetto0.
Toalignawidgethorizontallywithawidget,chooseGUI.CENTERforthehorizontalalignmentandtheusethexcoordinateandwidthofthewidgetasthelabel'sxcoordinateandwidth.YoucangetthexcoordinateandwidthofawidgetusingGUI.GetXandGUI.GetWidth.
Likewise,toalignawidgetverticallywithawidget,chooseGUI.MIDDLEfortheverticalalignmentandtheusetheycoordinateandheightofthewidgetasthelabel'sycoordinateandheight.YoucangettheycoordinateandheightofawidgetusingGUI.GetYandGUI.GetHeight.
Hereisanexampleillustratingtheplacementofalabelatthecenterofeachoffoursidesofawidgetcalledw:
importGUI
View.Set("graphics:200;50,nobuttonbar")
procedureDoNothing(text:string)
endDoNothing
varw:int:=GUI.CreateTextField(50,15,100,"",DoNothing)
%Thesefollowinglinesaretheimportantpartoftheprogram.
varleft:=GUI.CreateLabelFull(GUI.GetX(w)-2,GUI.GetY(w),
"Left",0,GUI.GetHeight(w),GUI.RIGHT+GUI.MIDDLE,0)
varabove:=GUI.CreateLabelFull(GUI.GetX(w),
GUI.GetY(w)+GUI.GetHeight(w)+2,"Above",GUI.GetWidth(w),0,
GUI.CENTER+GUI.BOTTOM,0)
varright:=GUI.CreateLabelFull(GUI.GetX(w)+GUI.GetWidth(w)+2,
GUI.GetY(w),"Right",0,GUI.GetHeight(w),GUI.LEFT+GUI.MIDDLE,0)
varbelow:=GUI.CreateLabelFull(GUI.GetX(w),GUI.GetY(w)-2,
"Below",GUI.GetWidth(w),0,GUI.CENTER+GUI.TOP,0)
Here'stheresult.Notethattheformulaforaligningalabelwithawidgetisthesameforanytypeofwidget.
TextBoxAlignedwithFourLabels
Here'sanexampleillustratingaligningawidgetwiththetopofthewindow.Noticethatthelabeliscenteralignedwithxof0andwidthofmaxx,andtopalignedwithayofmaxyandaheightof0.
vartitle:=GUI.CreateLabelFull(0,maxy,"Title",maxx,0,
GUI.CENTER+GUI.TOP,0)
Finally,here'sanexampleillustratingtheplacementofalabelinthecenterofthescreen.Noticethatthelabeliscenteralignedwithxof0andwidthofmaxx,andmiddlealignedwithayof0andaheightofmaxy.
vartitle:=GUI.CreateLabelFull(0,0,"Title",maxx,maxy,
GUI.CENTER+GUI.MIDDLE,0)
Notethatifalabel'spositionorsizeischangedwithGUI.SetPosition,GUI.SetSizeorGUI.SetPositionAndSize,itstillretainsitsalignmentwithrespecttoitsnewx,y,width,andheightvalues.
Canvases
Thecanvasisaratheruniquewidget.Itisessentiallyadrawingsurfacethatyouplaceinthewindow.TherearecallsusingacanvaswidgetthatessentiallyduplicateallthestandardDrawmodulecalls,alongwithcallscorrespondingtoFont.DrawandvariousPicmodulecalls.
ThedifferenceisthatthecallsusingtheCanvaswidgetuse(0,0)tomeanthebottomleftcornerofthecanvas(notthewindow)andalldrawingisclippedtothecanvas(meaningthatifyouaccidentallydrawoffthecanvas,thepartofthepictureoutsidetheboundsofthecanvaswillnotappear).OneofthemostcommonbugsistoaccidentallyusetheactualDrawmoduleroutinesinsteadoftheGUI.Drawroutineswhendrawinginacanvas.IfthedrawingisgoesoutsidetheboundsoftheCanvas,youhavemadethismistake.
AnotherfeatureoftheCanvaswidgetisthatyoucanspecifyaprocedurestobecalledwheneverauserclicksintheCanvaswidget,dragsthemousewiththemousebuttondownandthenletsgoofthemousebutton.Theseproceduresallowyourprogramtorespondtomouseactivitytakingplaceinthecanvaswidget.
HereisaprogramthatusesaCanvastoallowtheusertodrawandabuttontoallowtheusertoerasethedrawing.
%The"Draw"program
importGUI
View.Set("graphics:300;300")
varoldx,oldy:int
varcanvas:int%Thedrawingcanvas.
varclear:int%Theclearbutton.
%Calledwhentheuserpressesthemousebuttoninthecanvas.
%Setstheinitialmouseposition.
procedureMouseDown(mx,my:int)
oldx:=mx
oldy:=my
endMouseDown
%Calledastheuserdragsthemousewiththebuttondowninthecanvas.
%Drawsalinefromthepreviousmousepositiontothecurrentposition.
procedureMouseDrag(mx,my:int)
GUI.DrawLine(canvas,oldx,oldy,mx,my,colorfg)
oldx:=mx
oldy:=my
endMouseDrag
%Calledwhenthemousebuttonisreleased.
procedureDoNothing(mx,my:int)
endDoNothing
%Calledwhentheclearbuttonispressed.
procedureClear
GUI.DrawCls(canvas)
endClear
%Createthecanvas
canvas:=GUI.CreateCanvasFull(10,30,maxx-20,maxy-40,0,
MouseDown,MouseDrag,DoNothing)
%Createtheclearbutton
clear:=GUI.CreateButton(maxxdiv2-20,0,40,"Clear",Clear)
loop
exitwhenGUI.ProcessEvent
endloop
Hereistheoutputwindowaftertheuserhasdrawnsomelines.
OutputofDraw.dem
MultipleWindows
Turingallowsformultiplerunwindows.Thiscanbeusedtoaddextrafunctionalitytoprograms,howeverthereareafewissuesthatmustbeunderstoodbeforemultiplewindowscanbesuccessfullyused.
Turingusestheconceptofselectedwindowsandactivewindows.AselectedwindowisdeterminedbytheprogramandischangedbyWindow.Select.Theselectedwindowisthewindowinwhichalloutputappears.Whenawidgetiscreated,itisautomaticallycreatedintheselectedwindow.
Anactivewindowislastwindowonwhichtheuserclicked.Theactivewindowisshownbyhavingitstitlebarhighlighted.Whenausertypes,allkeystrokesaresenttotheactivewindow.
Itisentirelypossibletohavetheselectedwindowandtheactivewindowbetodifferentwindows.
Whenyoucallgetch,Mouse.ButtonWait,oranyotherinputroutine,Turingchecksonlytheselectedwindow.TheGUILibraryworksaroundthisbyselectingallthewindowsthathavewidgetsinthem(oneatatime,startingwiththeactivewindow)andcheckingeachforevents.
Ifyouareprocessinganeventfromoneofseveralwindows,makecertainthatthecorrectwindowisselectedbeforeyououtputyourresults.Notethatthewidgetsautomaticallyselectthecorrectwindow,sothereisnoneedtochangetheselectedwindowbeforemakinganycallstotheGUImodule.
Ifyoucloseawindowwithwidgetsinit,useGUI.CloseWindowtoclosethewindow.Thisremovesallthewidgetsinthewindowbeforeclosingit.Ifyouhaveseveralwindowswithwidgetsandwantsomewindowstobehiddenandthenshownlater,usetheGUI.ShowWindowandGUI.HideWindowtoshowandhidethewindowswithwidgetsinthem.
TheGUILibraryInternals
WhileitisnotnecessarytoknowtheinternalsoftheGUILibrarytouseit,weprovidethisbriefoverviewforthosewhowishtounderstandtheinnerworkingsofthelibrary.
TheGUILibraryconsistsoffourparts.TheonlypartvisibletotheuseristheGUImodule.Thisislocatedin"%oot/lib/GUI",where%ootisthedirectoryinwhichtheOOTexecutableislocated.TheGUImoduleisessentiallyaseriesofproceduresthatprovideafrontendtotheWidgetModuleandtheWidgetClassLibrary.
TheWidgetModuleisamodulecalledWidgetModulethatconsistsofaseriesofsubprogramsthatcoveralltheaspectsofGUI'sthatdonotpertaintoaparticularwidget.Forexample,theproceduretochangethebackgroundcolorishere,aswellastheproceduretoprocessanevent.Itislocatedin"%oot/lib/GuiClass/wdgtmod.tu"
TheGUIClassLibraryconsistsofaseriesofclassesarrangedinahierarchyillustratedinthefollowingfigure.MostoftheactualTuringcodefortheGUILibraryislocatedintheWidgetClassLibrary.Eachdifferenttypeofwidgethasitsownclass.Widgetsthatsharecommonbehaviorhavethesameparent.Forexample,boththeverticalandhorizontalsliderhaveasliderclassasaparent.ThoseclasseswhosenamesstartwithGenericareabstractclasses.Theyshouldnotbeinstantiatedthemselves.Theyareusedtodefinecommonbehavioramongtheirsubclasses.TheTuringsourcefortheclassescanbefoundinthedirectory"%oot/lib/GuiClass"
ThefourthpartistheWidgetGlobalsmodule.ThismodulethatconsistsmostlyofglobalvariablesusedbytheGUIClassLibraryandtheWidgetmodule.Itislocatedin"%oot/lib/GuiClass/wdgtglob.tu"
HereisanexampleofhowtheGUImoduleworks:whenyoucreateabuttonusingGUI.CreateButton,theCreateButtonfunctionintheGUImodulecreatesanobjectoftypeButtonClass.(ButtonClassisfoundintheWidgetClassLibrarydiscussedfurtherdown).ItthencallstheInitializeprocedureoftheButtonClasstoinitializethebuttonwiththespecifiedparameters.FinallyitassignsanIDnumbertothewidgetandarrangesitinatableforfuturereference.Hereis
anotherexample:whenyoucallaprocedurelikeGUI.Show,theShowproceduretakesthewidgetID,looksuptheobjectthatitrepresents,andthencallstheShowprocedureoftheobject.
StudentswhowishtoaddnewwidgetstotheGUIlibrarywillhavetounderstandtheprinciplesofobjectorientedprogramming,astheywillbeaddinganewclasstotheGUIClassLibraryandthenaddingnewsubprogramsintheGUImodulethatwillcalltheirnewclasses.(Attheveryleast,aCreatesubprogramwillberequiredforthenewwidget.)
AsuggestedprojectwouldbetocreatenewversionsoftheButtonClass,CheckBoxClassandRadioButtonClassclassesthatarebuttons,checkboxesandradiobuttonswiththenewWindows95/NTappearance.TheycouldbecalledtheButton95Class,CheckBox95ClassandRadioButton95Class.Properlywritten,thesenewclassesshouldinheritfromButtonClass,etc.andcontainonlythoseproceduresthatdifferfromthebaseclass(presumablytheproceduresthatdisplaythewidget).
TheGUIClassLibraryHierarchy
GUIModuleRoutinesSummary
TheroutinesintheGUImodulearedividedintoseveraldifferenttypes.Therearetheroutinestocreatevariouswidgets,theroutinestocreatemenusandmenuitems,theroutinestodogeneralactivities(suchasprocessinganevent,changingthebackgroundcolor,etc.)andtheroutinesthatactonvarioustypesofwidgets.
Hereisthelistoftheroutinesthatcreatewidgets:
GUI.CreateButton,GUI.CreateButtonFull Createabutton.GUI.CreateCheckBox,GUI.CreateCheckBoxFull Createacheckbox.GUI.CreateRadioButton,GUI.CreateRadioButtonFull Createaradiobutton.GUI.CreatePictureButton,GUI.CreatePictureButtonFull Createapicturebutton.
GUI.CreatePictureRadioButton,GUI.CreatePictureRadioButtonFull
Createapictureradiobutton.
GUI.CreateHorizontalSlider Createahorizontalslider.
GUI.CreateVerticalSlider Createaverticalslider.GUI.CreateHorizontalScrollBar,GUI.CreateHorizontalScrollBarFull
Createahorizontalscrollbar.
GUI.CreateVerticalScrollBar,GUI.CreateVerticalScrollBarFull
Createaverticalscrollbar.
GUI.CreateCanvas,GUI.CreateCanvasFull Createacanvas.GUI.CreateTextField,GUI.CreateTextFieldFull Createatextfield.GUI.CreateTextBoxFull,GUI.CreateTextBoxFull Createatextbox.
GUI.CreateTextBoxChoice Createamulti-lineselector.
GUI.CreateLine Createaline.GUI.CreateFrame Createaframe.GUI.CreateLabelledFrame Createalabelledframe.GUI.CreateLabel,GUI.CreateLabelFull Createalabel.GUI.CreatePicture Createapicture.
Hereisthelistofroutinesthatcreatemenusandmenuitems:
GUI.CreateMenu Createamenu.GUI.CreateMenuItem,GUI.CreateMenuItemFull Createamenuitem.
Hereisthelistofgeneralroutines:
GUI.ProcessEvent Processasinglekeyboardormousedownevent.GUI.Quit Telltheprogramtoexittheeventloop.
GUI.ResetQuit Resetthe"quit"flagsoaprogramcanreentertheeventloop.
GUI.Refresh Redrawallthewidgetsonthescreen.GUI.SetBackgroundColor Changethewindow'sbackgroundcolour.GUI.SetNullEventHandler Setthenulleventhandler.GUI.SetKeyEventHandler Setthekeystrokeeventhandler.GUI.SetMouseEventHandler Setthemouseeventhandler.GUI.HideMenuBar Hidethemenubarinthewindow.GUI.ShowMenuBar Showthemenubarinthewindow.
GUI.GetEventWidgetID Gettheselectedwidget'sID(usedinawidget'sactionprocedure).
GUI.GetEventWindow Getthewindowthattheeventtookplacein(usedinawidget'sactionprocedure).
GUI.GetEventTime Getthetime(inmilliseconds)thattheeventtookplace(usedinawidget'sactionprocedure).
GUI.GetScrollBarWidth Returnthewidthofascrollbar.GUI.GetMenuBarHeight Returntheheightofamenubar.
GUI.GetVersion ReturnthecurrentversionnumberoftheGUImodule.
Hereisalistofroutinesthatactonthewidgetsandthesortofwidgetstheyacton.
GUI.Show Displaythewidget. All
GUI.Hide Hidethewidget. All
GUI.GetXReturnthexcoordinateofthewidget'sleftedge.
All
GUI.GetY
Returntheycoordinateofthewidget'sbottomedge.
All
GUI.GetWidthReturnthewidget'sactualwidth.
All
GUI.GetHeightReturnthewidget'sactualheight.
All
GUI.Dispose Disposeofthewidget. All
GUI.SetPosition Setthewidget'sposition. All
GUI.SetSize Setthewidget'ssize. All
GUI.SetPositionAndSize Setthewidget'spositionandsize. All
GUI.EnableEnablethewidgettorespondtoevents.
ActiveWidgets
GUI.Disable
Disablethewidgetfromrespondingtoevents.
ActiveWidgets
GUI.SetLabel Setthewidget'stextlabel.
Button,CheckBox,RadioButton,Label,LabelledFrame
Setthebutton's
GUI.SetColor color. Button
GUI.SetDefault Makethebuttonthedefaultbutton. Button
GUI.GetCheckBoxGetwhetheracheckboxisfilled.
CheckBox
GUI.SetCheckBox Setacheckboxtobefilledornot. CheckBox
GUI.SelectRadio Selectaradiobutton.
RadioButton,PictureRadioButton
GUI.GetSliderValue Returnthecurrentvalueoftheslider.
Slider,ScrollBar
GUI.SetSliderValue Setthevalueoftheslider.
Slider,ScrollBar
GUI.SetSliderMinMaxSettheslider'sminimumandmaximum.
Slider,ScrollBar
GUI.SetSliderSize Settheslider'slength(orheight).
Slider,ScrollBar
GUI.SetSliderReverseReversethedirectionoftheslider.
Slider,ScrollBar
GUI.SetScrollAmount
Setthescrollbar'sthumbsizeandthescrollamountforarrows/pageupanddown.
ScrollBar
DrawArc,DrawBox,DrawCls,DrawDot,DrawFill,DrawFillArc,DrawFillBox,DrawFillMapleLeaf,DrawFillOval,DrawFillPolygon,DrawFillStar,DrawLine,DrawMapleLeaf,DrawOval,DrawPolygon,
RoutinesthatperformthesamefunctionastheDrawmodulefortheCanvas
Canvas
DrawStar,DrawText widget.
GUI.FontDraw"Font.Draw"fortheCanvaswidget.
Canvas
PicDraw,PicNew,PicScreenLoad,PicScreenSave
RoutinesthatperformthesamefunctionasthePicmodulefortheCanvaswidget.
Canvas
GUI.SetXOR
PerformsView.Set("xor")fortheCanvasWidget.
Canvas
GUI.SetText Setthetextofatextfield. TextField
GUI.SetEchoChar
Setthecharacterthatappearswhenuserentersakeystroke.
TextField
GUI.SetSelection Settheselectioninthetextfield. TextField
GUI.SetActive
Makethetextfieldtheactiveone(wherekeystrokeswillgoandwherethecursorblinks).
TextField
GUI.ClearText Clearatextbox. TextBox
GUI.AddText Addtexttoatextbox. TextBox
GUI.AddLine Addalineoftexttoatextbox. TextBox
GUI.SetTopLineScrollstextboxtomakelineappearattop.
TextBox
GUI.SetScrollOnAdd Setswhethertextboxscrollswhentextadded.
TextBox
Widgets-CommonRoutines
Alloftheproceduresinthissectioncanbeusedwithanywidget,althoughsomemayhavenoeffect(forexampleGUI.GetXonamenuitemismeaningless).
GUI.ShowDisplaysawidget.UsedinconjunctionwithHidetohideandshowwidgets.Hiddenwidgetscannotgetevents(i.e.respondtokeystrokesormouseclicks).
GUI.Hide
Hidesawidget.UsedinconjunctionwithShowtohideandshowwidgets.Hiddenwidgetscannotgetevents(i.e.respondtokeystrokesormouseclicks).Ifanactivetextfield(seetextfield)ishidden,thenanykeystrokesinthewindowwillbeignored.
GUI.GetXGUI.GetY
Returnsthex(y)coordinateoftheleftedgeofawidget.Notethatthismaybedifferentfromthexcoordinatespecifiedinthewidget'sCreatecall.Forexample,ifaradiobuttoniscreatedwithrightjustification,thexcoordinateintheCreatemethodspecifiestherightedge.
Hereisasmallsubprogramthatshoulddrawarectangleentirelyaroundawidget(i.e.nopartofthewidgetshouldstickout).
procedureWidgetRect(widgetID:int)
constx:int:=GUI.GetX(widgetID)
consty:int:=GUI.GetY(widgetID)
constwidth:int:=GUI.GetWidth(widgetID)
constheight:int:=GUI.GetHeight(widgetID)
Draw.Box(x,y,x+width-1,y+height-1,black)
endWidgetRect
GUI.GetWidthGUI.GetHeight
Returnstheactualwidth(height)ofawidget.NotethatthismaybedifferentfromthewidthspecifiedintheCreatecall(especiallysincemanywidgetsallowyoutospecify0forthewidthandlettheGUImoduledeterminethenecessarywidth).
GUI.Dispose
Eliminatesawidget.Itshouldbecalledinordertofreeupanymemorythatthewidgetmighthaveallocated.Notethatyoucannotusethewidgetafterithasbeendisposedof.Ifyouwishtotemporarilygetridofawidget,considerusingtheHidemethodandthentheShowmethodwhenyouwanttouseitagain.
GUI.SetPosition
Movesawidgettothespecifiedlocation.Ifthewidgetisvisible,itismovedimmediatelytothenewlocation.Ifthewidgetishidden,itwillappearatthenewlocationwhentheShowprocedureiscalled.NotethatthelocationspecifiedinGUI.SetPositionarethesameasintheCreatemethod.Forexample,ifyouhadspecifiedacheckboxtoberightjustifiedintheCreateCheckBoxFullfunction,thenthelocationinacalltoSetPositionwouldspecifythelower-rightcornerasopposedtothelower-leftcorner.
GUI.SetSize
Changesthesizeofawidget.Ifthewidgetisvisible,itssizeischangedimmediately,otherwisethewidgetwillappearinitsnewsizewhenthewidgetisnextmadevisible.Notethatthewidthandheightparametersarenotnecessarilytheactualwidthandheightofthewidget.Forexample,theTextFieldwidgetignorestheheightparameter,calculatingthewidget'sactualheightfromtheheightofthetextintheTextField.
GUI.SetPositionAndSize Changesthepositionandsizeofthewidgetsimultaneously.ItworksthesamewayastheSetPositionandSetSizeprocedures.
Widgets-Buttons
OutputofButtons.dem
Thebuttonwidgetisusedtoimplementatextualbutton.Whenyouclickonabutton,thebutton'sactionprocedureiscalled.Ifabuttonisgivenashortcut,thenenteringthekeystrokewillcausetheactionproceduretobecalled.Itwillnotvisiblycausethebuttontodepress.
Ifabutton'swidthorheightissettozero(ornotspecifiedatall),thenthebuttonisshapedtofitthetext.
Abuttoncanbethedefaultbuttonforawindow.Ifthatisthecase,thenthebuttonwillbedrawnwithatickerborderarounditandiftheuserpressesENTER,thenthebutton'sactionprocedurewillbecalled.
Whenabuttonisnotenabled,thetextinthebuttonisgrayedoutandthebuttonnolongerrespondstoanymouseclicksorkeystrokesuntilthebuttonisenabledagain.
GUI.CreateButtonCreatesanddisplaysabutton.GUI.CreateButtonspecifiesthelocation,width,textandactionprocedureofthebutton.
GUI.CreateButtonFullCreatesanddisplaysabutton.GUI.CreateButtonFullalsospecifiestheheight,keyboardshortcutanddefaultstatusofthebutton.
GUI.EnableGUI.Disable
Enables(disables)abutton.Disabledbuttonshavetheirtextgrayedoutandcannotgetevents(i.e.respondtokeystrokesormouseclicks).
GUI.SetLabel Changesthetextofabutton.
GUI.SetDefault
Setsthe"defaultstatus"ofabutton.Ifabuttonisthedefaultbutton,thenitisdrawnwithaheavyoutlineanditisactivatedwhentheuserpressesENTER(RETURNonaMacintosh).
Widgets-CheckBoxes
OutputofCheckBoxes.dem
Thecheckboxwidgetisusedtoimplementacheckboxthatcanbesetorunset.Whenyouclickonacheckbox,thestatusofthecheckboxflipsfromsettounsetandbackagainandthecheckbox'sactionprocedureiscalledwiththenewstatusasaparameter.Ifacheckboxisgivenashortcut,thenenteringthekeystrokewillcausethecheckboxtochangestatusandtheactionproceduretobecalled.Thenewstatuswillbedisplayedimmediately.
Acheckbox'ssizeisnotspecifiedduringcreation.Itisdeterminedbasedonthesizeofthetext.Insteadtheuserspecifiesthelower-leftcornerofthecheckbox(orthelower-rightifthecheckboxisrightjustified).
Whenacheckboxisnotenabled,thelabelbesidethecheckboxisgrayedout
andthecheckboxnolongerrespondstoanymouseclicksorkeystrokesuntilthecheckboxisenabledagain.
GUI.CreateCheckBox
Createsanddisplaysaleftaligned(checkboxtotheleftofthelabel)checkbox.GUI.CreateCheckBoxspecifiesthelocation,textandactionprocedureofthecheckbox.
GUI.CreateCheckBoxFull
Createsanddisplaysacheckbox.GUI.CreateCheckBoxFullalsospecifiesthealignmentofthecheckbox(whetherthecheckboxistherightorleftofthetext)andthecheckbox'skeyboardshortcut.
GUI.EnableGUI.Disable
Enables(disables)acheckbox.Disabledcheckboxeshavetheirtextgrayedoutandcannotgetevents(i.e.respondtokeystrokesormouseclicks).
GUI.SetLabel Changesthetextofacheckbox.
GUI.GetCheckBoxReturnsacheckbox'sstatus.Ifthecheckboxisset(hasanXinit),GUI.GetCheckBoxreturnstrue,otherwiseitreturnsfalse.
GUI.SetCheckBoxSetsthestatusofacheckbox.Itcallsthecheckbox'sactionprocedurewiththenewstatusandredrawsthewidgetwiththenewstatus.
Widgets-RadioButtons
OutputofRadioButtons.dem
Theradiobuttonwidgetisusedtoimplementasetofbuttonsofwhichoneandonlyonebuttonmustbeselectedatalltimes.(Thinkold-styleradiostationbutton.Selectingone"deselects"thepreviously-selectedstation.)Whenyouclickonaradiobutton,anyotherradiobuttonthatispartofthesetisdeselectedandtheradiobutton'sactionprocedureiscalled.Ifaradiobuttonisgivenashortcut,thenenteringthekeystrokewillcausetheradiobuttontobeselected(andanyotherradiobuttoninthegrouptobede-selected)andtheactionproceduretobecalled.Thenewly-selectedordeselectedradiobuttonswillbedisplayedimmediately.
Whenaradiobuttoniscreated,thewidgetIDofanotherradiobuttonmustbesupplied.AvalueofzeroforthewidgetIDindicatesthatthisradiobuttonispart
ofanewgroup.ThewidgetIDmustbetheIDofthelastradiobuttonaddedtothegroup.Becauseradiobuttonsarealmostalwaysplacedingroupsyoucanspecify-1forthexandycoordinatesandtheradiobuttonwillbeplacedjustbelowthepreviousradiobuttonandretainthesamealignment.Whenagroupofradiobuttonsisselected,thefirstradiobuttoncreatedinthegroupwillbetheselectedone.YoucanchangethisbyusingtheGUI.SelectRadioproceduretoselectadifferentone.
Aradiobutton'ssizeisnotspecifiedduringcreation.Itisdeterminedbasedonthesizeofthetext.Theuserspecifiesthelower-leftcorneroftheradiobutton(orthelower-rightiftheradiobuttonisrightjustified).
Whenaradiobuttonisnotenabled,thelabelbesidetheradiobuttonisgrayedoutandtheradiobuttonnolongerrespondstoanymouseclicksorkeystrokesuntiltheradiobuttonisenabledagain.
GUI.CreateRadioButton
Createsanddisplaysaleftaligned(circletotheleftofthelabel)radiobutton.GUI.CreateRadioButtonspecifiesthelocation,text,theradiobuttontobejoinedtoandtheactionprocedureoftheradiobutton.
GUI.CreateRadioButtonFull
Createsanddisplaysaradiobutton.GUI.CreateRadioButtonFullalsospecifiesthealignmentoftheradiobutton(whetherthecircleistherightorleftofthetext)andtheradiobutton'skeyboardshortcut.
GUI.EnableGUI.Disable
Enables(disables)aradiobutton.Disabledradiobuttonshavetheirtextgrayedoutandcannotgetevents(i.e.respondtokeystrokesormouseclicks).
GUI.SetLabel Changesthetextofaradiobutton.
GUI.SelectRadioSelectsaradiobutton.Thepreviously-selectedradiobuttonis"de-selected".Theactionprocedureoftheradiobuttoniscalled.
Widgets-PictureButtons
OutputofPictureButtons.dem
Thepicturebuttonwidget(hereaftersimplycalledabutton)issimplyabuttonwithapictureonitinsteadoftext.ThepicturemustbecreatedbytheprogrambeforehandusingPic.NeworPic.FileNew.TheresultingpicturecanthenbeusedasaparametertoGUI.CreatePictureButton.Ingeneral,picturesshouldbeamaximumofabout30pixelshighandwide,althoughthereisnobuiltinlimitintheGUIlibrary.
Whenyouclickonapicturebutton,thepicturebutton'sactionprocedureiscalled.Ifapicturebuttonisgivenashortcut,thenenteringthekeystrokewillcausetheactionproceduretobecalled.Itwillnotvisiblycausethebuttontodepress.
Ifabutton'swidthorheightissettozero(ornotspecifiedatall),thenthebutton
isshapedtofitthepicture.
Whenapicturebuttonisnotenabled,thepicturebuttonisgrayedoutandthepicturebuttonnolongerrespondstoanymouseclicksorkeystrokesuntilthebuttonisenabledagain.
GUI.CreatePictureButton
Createsanddisplaysapicturebutton.Thebuttonisautomaticallysizedtofitthepicture.Ifyouneedtoknowtheprecisesizeofthebutton,usetheGUI.GetWidthandGUI.GetHeightfunctions.GUI.CreatePictureButtonspecifiesthelocation,pictureidandactionprocedureofthebutton.
GUI.CreatePictureButtonFull
Createsanddisplaysapicturebutton.GUI.CreatePictureButtonFullalsospecifiesthewidth,heightandkeyboardshortcutofthebutton.Italsospecifieswhetherthebuttonpictureshouldbemergedwiththebackgroundcolorornot.
GUI.EnableGUI.Disable
Enables(disables)apicturebutton.Disabledpicturebuttonsaregrayedoutandcannotgetevents(i.e.respondtokeystrokesormouseclicks).
Widgets-PictureRadioButtons
OutputofPictureRadioButtons.dem
Thepictureradiobuttonwidget(hereaftersimplycalledabutton)issimplyapicturebutton(seeWidget-PictureButton)thathasthebehaviorofaradiobutton.Thismeansthatoneandonlyonepictureradiobuttonofagroupisselectedatanytime.Aselectedpictureradiobuttonisdisplayedasbeingpressed.
Whenyouclickonapicturebutton,thepreviously-selectedpictureradiobuttonwillbede-selectedandthenewpicturebutton'sactionprocedureiscalled.Ifapicturebuttonisgivenashortcut,thenenteringthekeystrokewillcausetheactionproceduretobecalledandthepictureradiobuttonwillbedrawnselected.
Createsanddisplaysapictureradiobutton.Thebuttonisautomaticallysizedtofitthe
GUI.CreatePictureRadioButton
picture.Ifyouneedtoknowtheprecisesizeofthebutton,usetheGUI.GetWidthandGUI.GetHeightfunctions.GUI.CreatePictureRadioButtonspecifiesthelocation,pictureidandactionprocedureofthebuttonaswellastheradiopicturebuttontobejoinedto.
GUI.CreatePictureRadioButtonFull
Createsanddisplaysapictureradiobutton.GUI.CreatePictureRadioButtonFullalsospecifiesthewidth,heightandkeyboardshortcutofthebutton.Italsospecifieswhetherthebuttonpictureshouldbemergedwiththebackgroundcolorornot.
GUI.EnableGUI.Disable
Enables(disables)apictureradiobutton.Disabledpicturebuttonsaregrayedoutandcannotgetevents(i.e.respondtokeystrokesormouseclicks).
Widgets-Sliders
OutputofSliders.dem
Slidersaretheequivalentofavolumecontrolonastereo.Tocontrolaslider,theusersimplyclicksonthecontrolknobandslidesthecontrolleftandright(upanddownforaverticalslider).Whenevertheuserslidesthecontrolknob,theactionprocedureofthewidgetiscalledwiththecurrentvalueasaparameter.
TherangeofvaluesthatthesliderwillgiveisdeterminedbytheminandmaxparametersintheCreatecall.Theleftsideoftheslider(bottomforverticalsliders)representstheminimumvalue,whiletheright(top)representsthemaximumvalue.
Insomeinstances,youwillwantthereversetobetrue(right/topisminimum).Inthatcase,calltheGUI.SetSliderReverseproceduretoflipthevaluesoftheslider.
Slidersalwayshaveafixedheight(forhorizontalsliders)orwidth(forverticalsliders).ThelengthparameterintheCreatecallspecifieshowlongtheslidershouldbe.
GUI.CreateHorizontalSlider
Createsanddisplaysahorizontal(left-right)slider.GUI.CreateHorizontalSliderspecifiesthelocation,length,minimumandmaximumvaluesfortheslider,theinitialvalueoftheslider,andtheactionprocedureoftheslider.
GUI.CreateVerticalSlider
Createsanddisplaysavertical(up-down)slider.GUI.CreateVerticalSliderspecifiesthelocation,length,minimumandmaximumvaluesfortheslider,theinitialvalueoftheslider,andtheactionprocedureoftheslider.
GUI.EnableGUI.Disable
Enables(disables)aslider.Disabledsliderscannotgetevents(i.e.respondtomouseclicks).
GUI.GetSliderValue Returnsthecurrentvalueofaslider.
GUI.SetSliderValueSetsthevalueofaslider.Itmovesthecontrolknobontheslidertotheappropriatelocationandcallstheslider'sactionprocedurewiththenewvalue.
GUI.SetSliderMinMax
Setstheminimumandmaximumvaluesofaslider.Itredrawsthecontrolknobtotakeintoaccountthenewminimumandmaximum.Ifthecurrentvalueofthesliderisoutsidethenewmin/max,thenthevalueisadjustedappropriately.
GUI.SetSliderSizeChangesthelengthofaslider.Redrawsthesliderandchangesthepositionofthecontrolknobtotakeintoaccountthenewsizeoftheslider.
GUI.SetSliderReverse
Setsasliderinto(oroutof,ifalreadyinto)"reversemode".Normally,asliderisatitsminimumvaluewhenthecontrolknobisontheleftside(bottomforaverticalslider).Thisreversesit,sotheminimumvalueiswhenthesliderisattherightside(topforverticalsliders)ofthetrack.Callingthisroutineasecondtimereversesitbacktonormal.Thisprocedureredrawstheslidertomovethecontrolknobtoitsnewlocation.
Widgets-ScrollBars
OutputofScrollBars.dem
Scrollbarsareusuallyusedtoallowausertoseeapieceofadocumentthatcannotbedisplayedonthescreeninitsentirety.Thepictureaboveshowsthescrollbarsappearance.Tocontrolascrollbar,thereareafewchoices:theusercanclickonthethumb(theboxinthescrollbar)andslideitupanddown,ortheusercanclickinthescrollbaritselfaboveorbelowthethumb(inwhichcasethethumbismovedupordownone"page"),ortheusercanclickontheupordownarrowsattheendsofthescrollbar(inwhichcasethethumbismovedupone"line").Theprogrammerdefinesapageoraline.Whenthevalueofthescrollbarchanges,theactionprocedureofthescrollbariscalledwiththenewvalueasaparameter.
Therangeofvaluesthatthescrollbarwillgiveisdeterminedbytheminand
maxparametersintheCreatecall.Theleftsideofthescrollbar(bottomforverticalscrollbars)representstheminimumvalue,whiletheright(top)representsthemaximumvalue.Thereisalsothe"thumbsize".Thisrepresentstherangeofvaluesthatcanbeseenatonceonthescreen.
Forexample,ifyouhaveawindowthatcandisplay20linesoftextatonceandthereare100linesoftext,youwouldsetminto1,maxto100,andthumbSizeto20.Thevaluereturnedbythescrollbarwouldthenbethelinenumberofthefirstlineonthescreentobedisplayed.Whenthescrollbarwasatitsmaximumvalue,itwouldreturn81,sincebydoingso,lines81-100wouldbedisplayed.
Whenascrollbarisdisabledorthescrollbar'sthumbsizeisgreaterthanthedifferencebetweentheminimumandmaximumvalues(i.e.theitembeingscrolledfitsinthewindow),thescrollbarisdeactivated.Thebarisdrawninwhiteratherthangrayandthearrowsaregrayedout.Thescrollbardoesnotrespondtomouseclicks.
Insomeinstances,youwillwanttheminimumandmaximumvaluesofthescrollbartobereversed(right/topisminimum).Inthatcase,calltheGUI.SetSliderReverseproceduretoflipthevaluesofthescrollbar.
Scrollbarsalwayshaveafixedheight(forhorizontalscrollbars)orwidth(forverticalscrollbars).Togetthescrollbar'swidth,usetheGUI.GetScrollBarWidthfunction.ThelengthparameterintheCreatecallspecifieshowlongthescrollbarshouldbe.
GUI.CreateHorizontalScrollBar
Createsanddisplaysahorizontal(left-right)scrollbar.GUI.CreateHorizontalScrollBarspecifiesthelocation,length,minimumandmaximumvaluesforthescrollbar,theinitialvalueofthescrollbar,andthescrollbar'sactionprocedure.
Bydefault,thearrowincrement(theamountthevalueischangedwhenthescrollingarrowsarepressed)issettoone.Thepageup/downincrement(theamountthevalueischangedwhentheuserclicksin
thebartotherightorleftofthethumb)issettoonequarterthedifferencebetweentheminimumandthemaximum.The"thumbsize"issettozero(seethedescriptionofscrollbarsforanexplanationofthethumbsize).
GUI.CreateVerticalScrollBar
Createsanddisplaysavertical(up-down)scrollbar.GUI.CreateVerticalScrollBarspecifiesthelocation,length,minimumandmaximumvaluesforthescrollbar,theinitialvalueofthescrollbar,andthescrollbar'sactionprocedure.
Bydefault,thearrowincrement(theamountthevalueischangedwhenthescrollingarrowsarepressed)issettoone.Thepageup/downincrement(theamountthevalueischangedwhentheuserclicksinthebartotherightorleftofthethumb)issettoonequarterthedifferencebetweentheminimumandthemaximum.The"thumbsize"issettozero(seethedescriptionofscrollbarsforanexplanationofthethumbsize).
GUI.CreateHorizontalScrollBarFull
Createsanddisplaysahorizontal(left-right)scrollbar.GUI.CreateHorizontalScrollBarFullalsospecifiesthearrowincrement,pageincrement,andthumbsizeforthescrollbar.
GUI.CreateVerticalScrollBarFull
Createsanddisplaysahorizontal(left-right)scrollbar.GUI.CreateVerticalScrollBarFullalsospecifiesthearrowincrement,pageincrementandthumbsizeforthescrollbar.
GUI.EnableGUI.Disable
Enables(disables)ascrollbar.Disabledscrollbarscannotgetevents(i.e.respondto
mouseclicks).GUI.GetSliderValue Returnsthecurrentvalueofascrollbar.
GUI.SetSliderValue
Setsthevalueofascrollbar.Itmovesthecontrolknobonthescrollbartotheappropriatelocationandcallsthescrollbar'sactionprocedurewiththenewvalue.
GUI.SetSliderMinMax
Setstheminimumandmaximumvaluesofascrollbar.Itredrawsthecontrolknobtotakeintoaccountthenewminimumandmaximum.Ifthecurrentvalueofthescrollbarisoutsidethenewmin/max,thenthevalueisadjustedappropriately.
GUI.SetSliderSize
Changesthelengthofascrollbar.Redrawsthescrollbarandchangesthepositionofthecontrolknobtotakeintoaccountthenewsizeofthescrollbar.
GUI.SetSliderReverse
Setsascrollbarinto(oroutof,ifalreadyinto)"reversemode".Normally,ascrollbarisatitsminimumvaluewhenthecontrolknobisontheleftside(bottomforaverticalscrollbar).Thisreversesit,sotheminimumvalueiswhenthescrollbarisattherightside(topforverticalscrollbars)ofthetrack.Callingthisroutineasecondtimereversesitbacktonormal.Thisprocedureredrawsthescrollbartomovethecontrolknobtoitsnewlocation.
GUI.SetScrollAmount
Setsascrollbar'sarrowincrement,pageincrement,andthumbsize.Redrawsthescrollbartotakeintoaccountthenewthumbsize.
Widgets-Canvases
OutputofCanvases.dem
Acanvasisadrawingsurfaceforusebytheprogram.Itdiffersfromjustusingthewindowsurfacetodrawoninthat(0,0)representsthelower-leftcornerofthecanvasandalldrawingisclippedtothecanvas.(Thismeansthatifyouaccidentallyattempttodrawoutsideofthecanvas,itwillnotactuallydrawbeyondtheborderofthecanvas.)
CanvaseshaveproceduresthatemulatealltheproceduresintheDrawmoduleaswellasaproceduretoemulateFont.Draw,Pic.Draw,Pic.New,Pic.ScreenLoad,andPic.ScreenSave.
Youcangetmousefeedbackfromacanvas.UsingtheGUI.CreateCanvasFullmethod,youcanspecifythreeroutinesthatarecalledwhenthemousebuttonisdepressedwhilepointinginacanvas.Oneroutinewillbecalledwhentheuserpressesthemousebuttondowninacanvas.Anotherroutinewillbecalledwhiletheuserdragsthemousewiththemousebuttondown.Thisroutineisrepeatedlycalledwheneverthemousechangespositionwhilethemousebuttonisdown.Thelastroutineiscalledwhenthemousebuttonisreleased.Allthreeroutines
takeanxandyparameter,whichisthelocationofthemousewithrespecttothecanvas(i.e.(0,0)isthelower-leftcornerofthecanvas).
GUI.CreateCanvasCreatesanddisplaysacanvas.GUI.CreateCanvasspecifiesthelocationandsizeofthecanvas.Thecanvaswillhavealineborderaroundit.
GUI.CreateCanvasFull
Createsanddisplaysacanvas.GUI.CreateCanvasFullalsospecifiesthetypeofborderandthreeprocedurestobecalledwhenamouseispressed,draggedorreleasedonthecanvas.
GUI.EnableGUI.Disable
Enables(disables)acanvas.Disabledcanvasescannotgetevents(i.e.respondtomouseclicks).Ifnomouseroutineswerespecified(i.e.thecanvaswascreatedwithGUI.CreateCanvasandnotGUI.CreateCanvasFull)thisroutineessentiallydoesnothing.
GUI.DrawArcGUI.DrawBoxGUI.DrawClsGUI.DrawDotGUI.DrawFillGUI.DrawFillArcGUI.DrawFillBoxGUI.DrawFillMapleLeafGUI.DrawFillOvalGUI.DrawFillPolygonGUI.DrawFillStarGUI.DrawLineGUI.DrawBoxGUI.DrawMapleLeafGUI.DrawOvalGUI.DrawPolygonGUI.DrawStarGUI.DrawTextGUI.FontDrawGUI.PicDrawGUI.PicNewGUI.PicScreenLoad
AlltheseroutinesdrawtoacanvasinthesamemannerasthesimilarlynamedDraw�,Pic�andFont.Drawsubprograms.Allcoordinatesarebasedonthecanvasandalldrawingisclippedtothecanvasdrawingsurface.Ifthecanvasisin"xormode",allthedrawingwillbedonewith"xor"set.(SeeView.Setformoreinformationabout"xor".)
GUI.PicScreenSave
GUI.SetXOR
Setsthe"xormode"ofacanvas.Whenin"xormode",alltheDraw...proceduresofacanvasaretreatedasiftheView.Set("xor")statementhadbeenexecutedbeforetheDrawprocedure.
Widgets-TextFields
OutputofTextFields.dem
Atextfieldisaboxforenteringonelineoftext.WhentheuserpressesENTER,thetextfield'sactionprocedureiscalled.
Onlyonetextfieldisactiveatatime.Theactivetextfieldhasablinkingcursor(oritsselectionhighlighted).Ifakeystrokeoccurswhenawindowhasanactivetextfieldinit,thekeystrokewillbedirectedtotheactivetextfield.YoucanchangewhichtextfieldisactivewiththeGUI.SetActiveprocedureorbysimplyclickingonanothertextfieldwiththemouse.
Whenmultipletextfieldsarecreatedinawindow,thefirsttextfieldcreatedisactivewhentheprogrambegins.
Thecurrentversionofthetextfielddoesnotsupportcutandpasteorkeyboardcommandstoextendtheselection.
Becausestringsareamaximumof255characters,thisisthemaximumnumberofcharactersinatextfield.
TheTABcharactercyclesbetweendifferenttextfieldsinawindow.Itcyclesthroughthetextfieldsintheorderinwhichtheywerecreated.BACKTAB(shift+TAB)cyclesthroughthefieldsinreverseorder.
GUI.CreateTextField
Createsanddisplaysatextfield.GUI.CreateTextFieldspecifiesthelocation,width,initialtextstring,andactionprocedureofthetextfield.Theheightofthetextfieldisdeterminedbytheheightofthefontusedbythetextfield.Thetextfieldwillhavealineborderaroundit.
GUI.CreateTextFieldFull
Createsanddisplaysatextfield.GUI.CreateTextFieldFullalsospecifiesthetypeofborder,fontforenteredtext,andkindofinputrestriction(integeronly,etc.)
GUI.EnableGUI.Disable
Enables(disables)atextfield.Disabledpicturebuttonsaregrayedoutandcannotgetevents(i.e.respondtokeystrokesormouseclicks).
GUI.SetText Setsthetextofatextfield.Thecursorissetthebeginningofthetext.
GUI.GetText Returnsthecurrenttextofatextfield.GUI.SetSelection Setstheselection(theselectedtext)inatextfield.GUI.SetActive Makesatextfieldactive.
Widgets-TextBoxes
OutputofTextBoxes.dem
Atextboxisaboxusedfordisplayinglargerquantitiesoftext.Ithasbothverticalandhorizontalscrollbarstoallowtheusertoscrollthroughallthetextinthebox.
GUI.CreateTextBoxCreatesanddisplaysatextbox.GUI.CreateTextBoxspecifiesthelocationandsizeofthetextbox.Thetextboxwillhavealineborderaroundit.
GUI.CreateTextBoxFullCreatesanddisplaysatextbox.GUI.CreateTextBoxFullalsospecifiesthetypeofborderandthefontfordisplayedtext.
GUI.ClearText Clearsallthetextinatextbox.Addstexttothecurrentlineofthetextbox.Doesnot
GUI.AddTextaddanewlineafterthetext.Equivalenttoputtext...Thisscrollsthetextbox(ifnecessary)sothattheaddedtextisnowvisible.Tomovethecursortotheendofthetextwithoutaddinganyextratext,callGUI.AddTextwith""forthetextparameter.
GUI.AddLineAddstexttothecurrentlineofthetextboxfollowedbyanewline.Equivalenttoputtext.Thisscrollsthetextbox(ifnecessary)sothattheaddedtextisnowvisible.
Widgets-Lines
OutputofLines.dem
LinesareorganizationalelementsthatmakethewindowlookbetterandhelporganizetheGUIelements.
GUI.CreateLineCreatesanddisplaysaline.GUI.CreateLinespecifiestheendpointsoftheline(whichmustbeeitherverticalorhorizontal)andthetypeofline.
Widgets-Frames
OutputofFrames.dem
FramesareorganizationalelementsthatmakethewindowlookbetterandhelporganizetheGUIelements.Framesandlabelledframesaretheonlywidgetsinwhichotherwidgetscanbeplaced.
GUI.CreateFrameCreatesanddisplaysaframe.GUI.CreateFramespecifiesthecoordinatesofthelower-leftandupper-rightcorneroftheframeandthetypeofborderoftheframe.
Widgets-LabelledFrames
OutputofLabelledFrames.dem
LabelledframesareorganizationalelementsthatmakethewindowlookbetterandhelporganizetheGUIelements.Framesandlabelledframesaretheonlywidgetsinwhichotherwidgetscanbeplaced.
GUI.CreateLabelledFrame
Createsanddisplaysalabelledframe.GUI.CreateLabelledFramespecifiesthecoordinatesofthelower-leftandupper-rightcorneroftheframe,thetypeofborderoftheframe,andthetextoftheframe'slabel.
GUI.SetLabel Changesthetextofalabelledframe.
Widgets-Labels
OutputofLabels.dem
LabelsareorganizationalelementsthatmakethewindowlookbetterandhelporganizetheGUIelements.Theyaresimplytextplacedinawindow.Toaidinaligningtextwithvariouswidgets,itispossibletoaligntextinalargerregion(asshowninthefigure).
GUI.CreateLabelCreatesanddisplaysalabel.GUI.CreateLabelspecifiesthelower-leftcornerofthetextandthetextitself.Thesystemfontisusedtodisplaythelabel.
GUI.CreateLabelFull
Createsanddisplaysalabel.GUI.CreateLabelFullalsospecifiesthewidth,height,alignment,andfontforthelabel.Thewidthandheightarespecifiedforalignment
purposes.GUI.SetLabel Changesthetextofalabel.
Widgets-Pictures
OutputofPictures.dem
PicturesareorganizationalelementsthatmakethewindowlookbetterandhelporganizetheGUIelements.Theyaresimplyapictureplacedinawindow.ThepicturesarespecifiedusingapictureIDfromanyofthePic�subprograms.
GUI.CreatePictureCreatesanddisplaysapicture.GUI.CreatePicturespecifiesthelocation,pictureID,andwhetherthepictureshouldbemergedwiththebackground.
Widgets-Menus
OutputofMenus.dem
Menusareusedinmostmoderninterfaces.Inordertocreateafullsetofmenus,youmustcreatethemenuandthencreatethemenuitemsinthatmenu.Themenusareautomaticallyaddedtothemenubaroftheselectedmenu.
Menuitemsaretheindividualentriesofamenu.Tocreatemenusforawindow,youmustcreateamenu,thencreatethemenuitemsforthatmenu,thencreatethenextmenu,thentheitemsforthatmenu,etc.Allmenuitemsareautomaticallyaddedtothelastmenuandafterthelastmenuitemofthecurrentlyselected(notactive!)window.
Whenyouselectaniteminamenu,theactionprocedureoftheitemiscalled.Theactionprocedurehasnoparameters.
Asofthev1.0releaseoftheGUILibrary,itisanerrortocreateamenuitemwithouthavingcreatedamenufirst.Infuturereleasesitwillbepossibletocreatemenusandattachandremovethemfrommenubarswhendesired.
Menusandmenuitemscanbeenabledanddisabled.Adisabledmenuitemisgrayedout.Whentheuserselectsthemenu,allitemsinthemenuappeardisabledandcannotbeselected.Adisabledmenuitemisgrayedoutwhenthemenuisdisplayed.Theusercannotselectthemenuitem.
Separatorsinamenuappearasasolidlineacrossthemenu.Thesearecreatedbycreatingamenuitemwhosetextisthreedashes"---".
GUI.CreateMenu
Createsanddisplaysamenu.Themenuwillbeaddedaftertheothermenusinthemenubar.Iftherearenopreviousmenus,thenamenubarisautomaticallycreatedandthemenuadded.GUI.CreateMenuspecifiesthetextthatwillappearinthemenubar.Itissuggestedthatthetextnothaveanyspacesinit.
GUI.EnableGUI.Disable
Enables(disables)amenu.Disabledmenusaregrayedoutinthemenubar.Ifselected,allthemenuitemsinthemenubarappeardisabledandcannotbeselected.
GUI.CreateMenuItem
Createsamenuitem.GUI.CreateMenuItemspecifiesthetextofthemenuitemandtheactionproceduretobecalledwhenthemenuitemisselected.Themenuitemwillbeaddedtothelastmenuaftertheothermenuitemsinthemenu.Iftherearenomenusdefined,anerrorresults.
GUI.CreateMenuItemFull Createsamenuitem.GUI.CreateMenuItemFullalsospecifiesashortcutkeystroke.
GUI.EnableGUI.Disable
Enables(disables)amenuitem.Disabledmenuitemsaregrayedoutwhenthemenuisdisplayedandcannotbeselectedbytheuser.
Widgets-GeneralRoutines
ThefollowingproceduresareincludedintheGUImodulebutdonotrelatetoaspecificwidget.
GUI.ProcessEvent
Thisfunctionprocessesasingleevent(amousebuttonpressorakeystroke).Iftheeventactivatesawidget,thentheactionprocedureofthewidgetiscalled.Tofindoutwhichwidgetwasactivatedandcalledtheactionprocedure(necessaryifseveralwidgetshavethesameactionprocedure),youcancallGUI.GetEventWidgetID.Togettheexacttimethattheeventoccurred,youcancallGUI.GetEventTime.Togetthewindowinwhichtheeventtookplace,youcancallGUI.GetEventWindow.Ifamouseclickoccurred,butdidnotactivateanywidget,thenthedefaultmouseeventhandleriscalled.Bydefault,thisdoesnothing.However,ifyouwantyourprogramtorespondtomouseeventsthatdonotaffectawidget,callGUI.SetMouseEventHandlertospecifyyourowndefaultmouseeventhandler.Ifakeystrokeoccurred,butdidnotactivateanywidget(i.e.itwasn'tashortcutforawidgetandtherearenotextfieldsinthewindow)thenthedefaultkeystrokehandleriscalled.Bydefault,thisdoesnothing.However,ifyouwantyourprogramtorespondtokeystrokeeventsthatdonotaffectawidget,callGUI.SetKeyEventHandlertospecifyyourowndefaultkeyeventhandler.Ifnoeventoccurred,thenthenulleventhandleriscalled.Bydefault,thisdoesnothing.However,ifyouwantyourprogramtoperformsomeactionrepetitivelywhenitisnotdoinganythingelse,thencallGUI.SetNullEventHandlertospecifyyourownnulleventhandler.Thenullevent
handlerisoftenusedforsuchthingsasupdatingaclockandmakingcertainthatmusicisplayinginthebackground.
GUI.Quit
ThisprocedurecausesGUI.ProcessEventtoreturntrue.Iftheprogramisstructuredproperlywitha
loop
exitwhenGUI.ProcessEvent
endloop
attheendoftheprogram,thentheprogramwillexittheloopafterfinishingthecurrentactionprocedure.ThisprocedureisusuallycalledfromtheactionprocedureofaQuitbuttonorExitmenuitem.
GUI.Refresh
Thisroutineredrawsallthewidgetsinthecurrently-selectedwindow.Thisisusedwhensomeformofdrawingmayhaveoverwrittenthewidgetsinawindow.ItisusedbytheGUILibrarytoredrawallthewidgetswhenthebackgroundcolorofawindowhaschanged.
GUI.SetBackgroundColorGUI.SetBackgroundColour
Changesthebackgroundcolorofthecurrently-selectedwindow.(Bothspellingsofcolorareacceptable.)Thisdoesnotchangethevalueofcolor0inthewindow.Insteaditfillstheentirewindowwiththenewbackgroundcolorandthenredrawsallthewidgets.Theusualbackgroundcoloroutsideofwhiteisgray.
GUI.SetNullEventHandler
Setsthenewnulleventhandler.ThespecifiedprocedurewillbecalledeverytimeGUI.ProcessEventiscalledandthereisnokeystrokeormousebuttonpressed.
GUI.SetMouseEventHandler
Setsthenewdefaultmouseeventhandler.ThespecifiedprocedurewillbecalledeverytimeGUI.ProcessEventiscalledandthereisamousebuttonpressedwhichisnothandledbyanywidget.
GUI.SetKeyEventHandler
Setsthenewdefaultkeystrokeeventhandler.ThespecifiedprocedurewillbecalledeverytimeGUI.ProcessEventiscalledandthereisakeystrokewhichisnothandledbyanywidget.
GUI.HideMenuBar
Hidesthemenubarintheselectedwindow.Nomenuitemscanbeselectedwhenthemenubarishidden.(Menuitemshortcutswillbeignoredwhenthemenubarishidden.)
GUI.ShowMenuBar Showsthemenubarintheselectedwindow.
GUI.GetEventWidgetID
ReturnsthewidgetIDofthewidgetthatwasactivatedbythemousebuttonpressorthekeystroke.Thisfunctionshouldonlybecalledinanactionprocedure,asitwillreturn-1whenthereisnoeventthatactivatedawidgetbeingprocessed.
GUI.GetEventWindow
ReturnsthewindowIDofthewindowinwhichtheevent(mousebuttonorkeystroke)tookplace.Thisfunctionshouldonlybecalledinanactionprocedureorinadefaultmouseorkeystrokeeventhandler,asitwillreturn-1whenthereisnoeventbeingprocessed.
GUI.GetEventTime
Returnsthetimeinmillisecondswhentheevent(mousebuttonorkeystroke)tookplace.ThisvalueisthesamevaluethatTime.Elapsedreturnsifcalledwhentheeventwasprocessed.Thisfunctionshouldonlybecalledinanactionprocedureorinadefaultmouseorkeystrokeornulleventhandler,asitwillreturn-1whenthereisnoeventbeingprocessed.
GUI.SetDisplayWhenCreated
Setswhetherwidgetsareautomaticallydisplayedwhencreated,orwhetherGUI.Showmustbecalledfirst.Bydefault,thisissettotrue(widgetsaredisplayedwhencreated).However,theremaybetimeswhenyouwanttocreateawidgetandthenmakeseveraladditionalcallsbeforedisplayingthewidget.Closesawindowwithwidgetsinit.This
GUI.CloseWindow
procedureautomaticallydisposesofanywidgetsinthewindowandmakescertainthattheGUILibraryrecognizesthatthewindownolongerexists.ThisprocedurewillcallWindow.Close,sothereisnoneedfortheusertodoso.
GUI.ShowWindow
Showsahiddenwindowwithwidgetsinit.ThisproceduremakescertainthattheGUILibraryrecognizesthatthewindowisvisible.ThisprocedurewillcallWindow.Show,sothereisnoneedfortheusertodoso.
GUI.HideWindow
Hidesavisiblewindowwithwidgetsinit.ThisproceduremakescertainthattheGUILibraryrecognizesthatthewindowisnolongervisible.ThisprocedurewillcallWindow.Hide,sothereisnoneedfortheusertodoso.
GUI.GetScrollBarWidthReturnsthewidthofascrollbar.Usefulwhenplacingascrollbarwidgetbeneathanotherobject.
GUI.GetMenuBarHeightReturnstheheightofthemenubar.Usefulwhenplacingwidgetstomakecertainthattheydonotoverlapthemenu.
GUI.GetVersion
ReturnsthecurrentversionoftheGUImodule.BecausetheGUImoduleisexpectedtogrow,newversionswillprobablybemadeavailableatHoltSoftware'swebsitelocatedathttp://www.holtsoft.com/turing.Ifyouwishtousefeaturesthatdonotappearinearlierversionsofthelibrary,youcanhaveyourprogramcheckthatthecurrentavailableversionmeetstheprogramsneeds.GUI.GetVersionreturnsanintegerfrom100-999andisreadas1.00to9.99.
PredefinedFunctionsandProceduresabs addr arctan arctand anyclassbreak buttonchoose buttonmoved buttonwait ceilchr clock cls color colorbackcolour colourback cos cosd datedelay drawarc drawbox drawdot drawfilldrawfillarc drawfillbox drawfillmapleleaf drawfilloval drawfillpolygondrawfillstar drawline drawmapleleaf drawoval drawpicdrawpolygon drawstar empty eof erealstrexp fetcharg floor frealstr getchgetchar getenv getpid getpriority haschindex intreal intstr length lnlocate locatexy lower max maxcolmaxcolor maxcolour maxint maxnat maxrowmaxx maxy min minint minnatmousehide mouseshow mousewhere nargs natrealnatstr nil ord palette playplaydone pred rand randint randnextrandomize randseed realstr repeat roundsetpriority setscreen sign simutime sinsind sizeof sizepic sound sqrtstrint strintok strnat strnatok strrealstrrealok succ sysclock sysexit systemtakepic time upper wallclock whatcolwhatcolor whatcolorback whatcolour whatcolourback whatdotcolorwhatdotcolour whatpalette whatrow whattextchar whattextcolorwhattextcolorback whattextcolour whattextcolourback
PredefinedModulesBrush Button CheckBox Comm ConcurrencyConfig Dir Draw DropBox EditBoxError ErrorNum Event File FontGUI Input Joytick Keyboard LimitsListBox Math Menu Mouse MusicNet Obsolete PC Pen PicPrint RadioButton Rand RGB SoundSprite Str Stream Student SysText Time TypeConv Video ViewWindow
PredefinedOOTConstants(...meansseveralconstantswiththeprefix,seethemoduleforacompletelist)
black blue brightblue brightcyanbrightmagenta brightpurple brightred brightwhitebrushErrorBase cdMaxNumColors cdMaxNumColours cdMaxNumPagescdScreenWidth clLanguageVersion clMaxNumDirStreams clMaxNumRunTimeArgsclRelease cmFPU cmOS cmProcessorcolourbg colorfg colourfg configErrorBasedarkgray darkgrey defFontID defWinIDe...(ErrorNum) errWinID excp...(Exceptions) fileErrorBasefontErrorBase fsysErrorBase generalErrorBase graygrey guiErrorBase joystick1 joystick2magenta mouseErrorBase musicErrorBase ootAttr...(File)penErrorBase pic...(Pic) picXorplaceCenterDisplay placeCentreWindow printerErrorBase purplered rgbErrorBase spriteErrorBase streamErrorBasetimeErrorBase unixSignalToException viewErrorBase whiteyellow
Keywordsaddressint all and array asmassert begin bind bits bodyboolean break by case charcheat checked class close collectioncondition const decreasing def deferreddiv else elseif elsif endendfor endif endloop enum exitexport external false fcn flexiblefor fork forward free functionget handler if implement importin include inherit init intint1 int2 int4 invariant labelloop mod module monitor natnat1 nat2 nat4 new notobjectclass of opaque open orpacked pause pervasive pointer postpre priority proc procedure processput quit read real real4real8 record register rem resultreturn seek self set shlshr signal skip string tagtell then timeout to truetype unchecked union unqualified varwait when write xor
OperatorsMathematicalOperators
Operator Operation ResultTypePrefix+ Identity AsOperandsPrefix- Negative AsOperands+ Addition AsOperands- Subtraction AsOperands* Multiplication AsOperands/ Division AsOperandsdiv IntegerDivision intmod Modulo intrem Remainder int** Exponentiation AsOperands< LessThan boolean> GreaterThan boolean= Equals boolean<= LessThanorEqual boolean>= GreaterThanorEqual booleannot= NotEqual boolean
BooleanOperators
Operator Operation ResultTypePrefixnot Negation booleanand And booleanor Or booleanxor ExclusiveOr boolean=> Implication boolean
SetOperators
Operator Operation ResultType+ Union set- SetSubtraction set* Intersection set= Equality booleannot= Inequality boolean<= Subset boolean< Strict(Proper)Subset boolean>= Superset boolean> Strict(Proper)Superset boolean
OperatorsonMembersandSets
Operator Operation ResultTypein MemberofSet booleannotin NotMemberofSet booleanxor ExclusiveOr set
BitManipulationOperators
Operator Operation ResultTypeshl Shiftleft natshr Shiftright natand Bit-wiseAnd nator Bit-wiseOr natxor Bit-wiseExclusiveOr nat
PointerOperators
Operator Operation ResultType^ Followpointer Targettype
TypeCheats
Operator Operation ResultType# Typecheat nat
OperatorShortForms
Thesecanbeusedinplaceoftheabovenotation.not ~not= ~=notin ~inand &or |
OperatorPrecedence
Highestprecedenceoperatorsfirst.
1. **,^,#2. prefix+and-3. *,/,div,mod,rem,shl,shr4. +,-,xor5. <,>,=,<=,>=,not=,in,notin6. not7. and8. or9. =>
FileStatementsFileCommands
open openafile close closeafile put writealphanumerictexttoafile get readalphanumerictextfromafile write binarywritetoafile read binaryreadfromafile seek movetoaspecifiedpositioninafile tell reportthecurrentfileposition eof checkforendoffile
FileCommandSyntaxopen:streamNo,fileName,ioCapability{,ioCapability}
ioCapabilityisoneofget,put,read,write,seek,mod
putorwritecapabilitywillcauseanyexistingfiletobetruncatedtozerolengthunlessthemodcapabilityisalsospecified.
seekcapabilityisneededtouseseekortellcommands.
close:streamNo
get:streamNo,getItem{,getItem}
put:streamNo,putItem{,putItem}
read:streamNo[:fileStatus],readItem{,readItem}
write:streamNo[:fileStatus],writeItem{,writeItem}
seek:streamNo,filePositionorseek:streamNo,*
tell:streamNo,filePositionVar
eof(streamNo):boolean(Thisisafunction)
AppendingtoaTextFile%Openthefileforput,butdonoteraseit
open:streamNo,fileName,put{,get},mod
%Movethefilepointertotheendofthefile
seek:streamNo,*
ControlConstructs
FOR
for[decreasing]variable:startValue..endValue...statements...exitwhenexpn...statements...
endfor
LOOP
loop...statements...exitwhenexpn...statements...
endloop
IF
ifconditionthen...statements...{elsifconditionthen...statements...}[else...statements...]
endif
CASE
caseexpnof...statements...{labelexpn{,expn...statements...}[label:...statements...]
endcase
Anynumberofexitandexitwhenstatementscanappearatanyplaceinsidefor..endforconstructsandloop..endloopconstructs.
KeyCodesOrdinalvaluesofkeystrokesreturnedbygetchandgetchar.
0
(space) 32
@ 64
` 96Ctrl-A 1 ! 33 A 65 a 97Ctrl-B 2 " 34 B 66 b 98Ctrl-C 3 # 35 C 67 c 99Ctrl-D 4 $ 36 D 68 d 100Ctrl-E 5 % 37 E 69 e 101Ctrl-F 6 & 38 F 70 f 102Ctrl-G 7 ' 39 G 71 g 103
Ctrl-H/BS 8 ( 40 H 72 h 104Ctrl-I/Tab 9 ) 41 I 73 i 105Ctrl-J/Enter 10 * 42 J 74 j 106
Ctrl-K 11 + 43 K 75 k 107Ctrl-L 12 , 44 L 76 l 108Ctrl-M 13 - 45 M 77 m 109Ctrl-N 14 . 46 N 78 n 110Ctrl-O 15 / 47 O 79 o 111Ctrl-P 16 0 48 P 80 p 112Ctrl-Q 17 1 49 Q 81 q 113Ctrl-R 18 2 50 R 82 r 114Ctrl-S 19 3 51 S 83 s 115Ctrl-T 20 4 52 T 84 t 116Ctrl-U 21 5 53 U 85 u 117Ctrl-V 22 6 54 V 86 v 118Ctrl-W 23 7 55 W 87 w 119
Ctrl-X 24 8 56 X 88 x 120Ctrl-Y 25 9 57 Y 89 y 121Ctrl-Z 26 : 58 Z 90 z 122
Ctrl-[/Esc 27 ; 59 [ 91 { 123Ctrl-\ 28 < 60 \ 92 | 124Ctrl-] 29 = 61 ] 93 } 125Ctrl-^ 30 > 62 ^ 94 ~ 126Ctrl-_ 31 ? 63 _ 95 Ctrl-BS 127
Alt-9 128
Alt-D 160
F6 192
Ctrl-F3 224Alt-0 129 Alt-F 161 F7 193 Ctrl-F4 225Alt-- 130 Alt-G 162 F8 194 Ctrl-F5 226Alt-= 131 Alt-H 163 F9 195 Ctrl-F6 227
Ctrl-PgUp 132 Alt-J 164 F10 196 Ctrl-F7 228F11 133 Alt-K 165 197 Ctrl-F8 229F12 134 Alt-L 166 198 Ctrl-F9 230
Shift-F11 135 167 Home 199 Ctrl-F10 231Shift-F12 136 168 UpArrow 200 Alt-F1 232Ctrl-F11 137 169 PgUp 201 Alt-F2 233Ctrl-F12 138 170 202 Alt-F3 234
Alt-F11 139 171 LeftArrow 203 Alt-F4 235
Alt-F12 140 Alt-Z 172 204 Alt-F5 236
Ctrl-UpArrow 141 Alt-X 173 RightArrow 205 Alt-F6 237
142 Alt-C 174 206 Alt-F7 238BackTab 143 Alt-V 175 End 207 Alt-F8 239
Alt-Q 144 Alt-B 176 DownArrow 208 Alt-F9 240
Ctrl-DownArrow 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-LeftArrow 243
Alt-T 148 180 Shift-F1 212 Ctrl-RightArrow 244
Alt-Y 149 181 Shift-F2 213 Ctrl-End 245Alt-U 150 182 Shift-F3 214 Ctrl-PgDn 246Alt-I 151 183 Shift-F4 215 Ctrl-Home 247Alt-O 152 184 Shift-F5 216 Alt-1 248Alt-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 254Alt-S 159 F5 191 Ctrl-F2 223 Alt-8 225
OrdinalvaluesofcharactersthataresetbyInput.KeyDown.
Backspace 8
(space) 32
@ 64
` 96Tab 9 ! 33 A 65 a 97Enter 10 ! 34 B 66 b 98Escape 27 # 35 C 67 c 99
$ 36 D 68 d 100F11 133 % 37 E 69 e 101F12 134 & 38 F 70 f 102Shift 180 ' 39 G 71 g 103Control 181 ( 40 H 72 h 104Alt 182 ) 41 I 73 i 105
Keypad5 183 * 42 J 74 j 106F1 187 + 43 K 75 k 107F2 188 , 44 L 76 l 108F3 189 - 45 M 77 m 109F4 190 . 46 N 78 n 110F5 191 / 47 O 79 o 111F6 192 0 48 P 80 p 112F7 193 1 49 Q 81 q 113F8 194 2 50 R 82 r 114F9 195 3 51 S 83 s 115F10 196 4 52 T 84 t 116
5 53 U 85 u 117Home 199 6 54 V 86 v 118
UpArrow 200 7 55 W 87 w 119PgUp 201 8 56 X 88 x 120
LeftArrow 203 9 57 Y 89 y 121RightArrow 205 : 58 Z 90 z 122
End 207 ; 59 [ 91 { 123DownArrow 208 < 60 \ 92 | 124
PgDn 209 = 61 ] 93 } 125Insert 210 > 62 ^ 94 ~ 126Delete 211 ? 63 _ 95
RunWindowCharacterSetTheTuringcharactersetandtheirASCIIvalues
chr(8)=backspacechr(9)=tabchar(10)=newline
Youcanalsoget(onmostsystems),theMS-DOScharactersetbyusingthecommandsetscreen("msdos").Thisisthecharactersetafterthesetscreen("msdos")commandwasgiven.
ClickthebuttontolaunchtheprogramtodisplaythecharactersetinTuring.
TuringTeacher/AdministratorQuickStartGuideThisguideisdesignedtobetheminimalinformationthatyoushouldreadifyouareteachingcoursesusingTuring4.0orareinchargeofadministeringTuring4.0
ThisguideprovidesinformationontheTuringenvironment(theeditor,therunwindows,etc.)ItdoesnotprovideanyinformationontheTuringprogramminglanguageitself.
Note,ifyouhaveanyquestionsnotansweredhere,pleasecheckwiththeTuringTeacher/Administrator'sCompleteGuideformoreinformation.
TableofContents
1. MakingCertainYouHavetheLastestVersion2. MandatoryAdministrationIssues3. UsingtheParallelPortsinTuring44. StudentDistribution5. TechnicalSupport
1.MakingCertainYouHavetheLastestVersion
Turing4.0isupdatedregularly.Tofindoutwhatversionyouarecurrentlyrunning,clicktheAboutTuringmenuitemintheHelpmenu.TofindoutthecurrentversionofTuring,gotohttp://www.holtsoft.com/turing/support/#currentversion.Thisliststhecurrentversionofthesoftware.
Thispagealsolistswhichbugshavebeenfixedandwhennewfeatureshavebeenadded.Thepagealsocontainsasection(http://www.holtsoft.com/turing/support/#turing4patches)whereafilecanbedownloadedthatwillupdatemostversionsofTuringtothelatestversion.
Ifyouareateacheroranadministratorataschoolandrequireacompleteinstallationfile(asopposedtothepublicallyavailablepatch),contactTomWestat(416)978-8363.
2.MandatoryAdministrationIssues
Turing4.0hasbeendesignedtorunoneitheranetworkorinstalledonindividualstand-alonemachines.Runningonanetworkisoftenpreferredbecauseofeaseofadministration.However,Turing,likeanyotherapplicationwillloadsomewhatfasterwhenitislaunchedifitisstoredlocally.
ThereareonlytwoadministrationissuesthatmustbeaddressedtoconfigureTuringproperly.
1. Setthestart-in(oftencalledthe"working")directoryproperly.
Itisimportantthatthestart-indirectoryforTuringbesettothestudent'shomedirectory.Thisisdonebysettingthestart-in(orworking)directoryoftheshortcutormenuitemusedtolaunchTuringtothedrivemappedtothestudent'shomedirectory.
Theshortcut'sworkingdirectorycanbemodifiedbychangingit'sstart-inorworkingdirectoryproperty.(TodisplaythePropertiesdialogbox,rightclickontheshortcutormenuitemandselectPropertiesfromthepop-upmenu.)
PropertiesforaShortcutunderWindows2000
Thisrequiresthatyouhavewriteaccesstotheshortcut.Notethatcommercialmenufront-endshavetheirownwayofsettingthestart-indirectoryofapplications.
Ifthereisnodrivemappedtothestudent'shomedirectory,orthismethodisnotapplicabletoyoursystemsetup,pleasecheckwiththeTuringTeacher/Administrator'sCompleteGuideformoreinformation.
2. SeteitherBeginnerorRegularModeforStudents.
TuringcanbesettoBeginnermode,inwhichcaseonlyonefileisopenatatime.Openingupanotherfileclosesthefirstone.Whentheprogramisrunning,theEditorwindowminimizes.Inthisway,onlyonewindowisusuallyvisibleatatime.Inthisfashion,BeginnermodeissimilartotheoldDOSTuring.
InRegularmode,anynumberoffilescanbeopenedandeachappearsinitsowneditorwindow.
Ingeneral,wesuggestBeginnermodeforgrade9and10andRegularmodeforallothers.IfyouareusingBeginnermode,wesuggestthatyoupointouttothestudentsthattheycanusethePrefencestochangetoRegularmodewhentheyfeelcomfortablewiththeenvironment.
Tochangethemode(ortomakeanyotherchangetothesystempreferences),youmustopenaDOSwindow,cdtothedirectoryinwhichtheTuringexecutable(turing.exe)islocatedandissuethecommand:
turing-admin
ThiswillcauseTuringtostartinAdministratormode,displayingthefollowingdialogbox:
AdministrationModeNotification
SelectingPreferencesfromtheFilemenuwilldisplayatabbeddialogboxofalltheTuringpreferences.
PreferencesinAdministratorMode
Set(orunset)theBeginnerModepreference,clicktheOKbuttonandquitTuring.Ofcourse,youcanchangeanyotherpreferencesthatyouwouldlike.AnychangesthatyoumakeherewillaffectallthoseusingTuring.
3.UsingtheParallelPortsinTuring4
Turing4.0supportstheparallelputandparallelgetcommandstoallowyoutosetthepinsontheparallelportlowandhigh.IfyouarerunningunderWindowsNT,2000orXP,youwillneedtoinstalladevicedriveroneachmachine.Instructionsfordoingsocanbefoundhere.Ifparallelputandparallelgetdonotseemtofunction,youmayneedtochangetheirBIOSsettings.Youcangetinformationonhowtodothathere.
4.StudentDistributionofTuring4.0
TheOntarioMinistrylicensedoesnotincludetherighttoredistributethesoftwaretostudents.Ifyouwishtogivethesoftwaretostudents,aseparatelicensemustbeobtaineddirectlyfromHoltSoftware.
Ifyourschooldoesnothavesuchalicense,studentscanpurchasethesoftwareforhomeusebyprintingandthenmailinganorderformfoundhttp://www.holtsoft.com/studentbuy.Thisorderformcanalsobeusedtoallowinterestedstudentstopurchasetextbooks.
Ifyourschoolhaspurchasedaredistributionlicense(almost200schoolshavedoneso),thenyoumayredistributetheTuringsoftwaretoyourstudents.YoucaneitherburncopiesoftheCDtodistributetostudentsorplacetheTuringinstallerfileontoyourschoolInternetserverandgiveyourstudentstheURL.
Ifyouplacethisfileonyourschoolinternetserver,youmustnotmakeanylinksfromyourwebpagestothesoftware.
Thiswillpreventotherusersofthewebfromdownloadingyoursoftware.Ifyouplacelinksfromyourschool'swebsite,thenatsomepointawebsearchenginewillfindthesoftwareandpostitslocationtotheinternetatlarge,allowingforlargescalepiracy(andaveryoverloadedschoolwebserver).Iftherearenolinkstothesoftware,thenonlythosewhohavebeentoldtheexactURLwillbeabletodownloadthesoftware.
NotethatifyouarecopyinganumberofdifferentprogramsontoasingleCDforredistribution,youmayrenametheTuringinstallerprogramtosomethingmoredescriptive.
Permanentstudentredistributionlicensescanbepurchasedfor$500-$750formostschools.Ifyouareinterestedinpurchasingastudentredistributionlicense,contactChrisStephensonat(416)[email protected]
5.TechnicalSupport
Ifyouhaveproblems,questionsorsuggestionsabouttheTuringsoftware,contacttechnicalsupportat:Telephone: (416)978-8363Tollfree: 1-800-361-8324Fax: (416)978-1509E-mail: [email protected]
TuringTeacher/AdministratorGuideThisistheTuringTeacher/Administratorguide.ItcontainsmostoftheinformationthatyouwillneedtoadministertheTuring4.0software.ItshouldbereadbythosewhoareteachingcoursesusingTuring4.0orareinchargeofadministeringTuring4.0
ThisguideprovidesinformationontheTuringenvironment(theeditor,therunwindows,etc.)ItdoesnotprovideanyinformationontheTuringprogramminglanguageitself.
NotethatthereissomeoverlapwiththeTuringTeacher/AdministratorQuickStartGuide.
TableofContents
1. MakingCertainYouHavetheLastestVersion2. MandatoryAdministrationIssues3. ChangingSystemPreferences4. TuringPreferences5. ParallelPortandTuring46. MissingFeaturesfromTuring47. TheTuringDebugger8. StudentDistribution9. TechnicalSupport
1.MakingCertainYouHavetheLastestVersion
Turing4.0isupdatedregularly.Tofindoutwhatversionyouarecurrentlyrunning,clicktheAboutTuringmenuitemintheHelpmenu.TofindoutthecurrentversionofTuring,gotohttp://www.holtsoft.com/turing/support/#currentversion.Thisliststhecurrentversionofthesoftware.
Thispagealsolistswhichbugshavebeenfixedandwhennewfeatureshavebeenadded.Thepagealsocontainsasection(http://www.holtsoft.com/turing/support/#turing4patches)whereafilecanbedownloadedthatwillupdatemostversionsofTuringtothelatestversion.
Ifyouareateacheroranadministratorataschoolandrequireacompleteinstallationfile(asopposedtothepublicallyavailablepatch),contactTomWestat(416)978-8363.
2.MandatoryAdministrationIssues
Turing4.0hasbeendesignedtorunoneitheranetworkorinstalledonindividualstand-alonemachines.Runningonanetworkisoftenpreferredbecauseofeachofinstallation,however,Turingwillloadsomewhatfasterwhenitislaunchedifitisstoredlocally.
Turing4.0hasbeendesignedtorunoneitheranetworkorinstalledonindividualstand-alonemachines.Runningonanetworkisoftenpreferredbecauseofeaseofadministration.However,Turing,likeanyotherapplicationwillloadsomewhatfasterwhenitislaunchedifitisstoredlocally.
ThereareafewadministrationissuesthatmustbeaddressedtoconfigureTuringproperly.
1. Setthestart-in(oftencalledthe"working")directoryproperly.
Itisimportantthatthestart-indirectoryforTuringbesettothestudent'shomedirectory.Thiscanbedoneinavarietyofways,fromleasttomostcomplicated.
1. Manyschoolshavethestudent'shomedirectorymappedtoadrive(oftenH:\).Ifthisisthecase,thensetthestart-in(orworking)directoryoftheshortcutormenuitemusedtolaunchTuringtothemappeddrive.
Theshortcut'sworkingdirectorycanbemodifiedbychangingit'sstart-inorworkingdirectoryproperty.(TodisplaythePropertiesdialogbox,rightclickontheshortcutormenuitemandselectPropertiesfromthepop-upmenu.)
PropertiesforaShortcutunderWindows2000
Thisrequireschangingtheshortcut'spropertiesrequireswriteaccesstotheshortcut.Notethatcommercialmenufront-endshavetheirownwayofsettingthestart-indirectoryofapplications.
2. Ifthe"MyDocuments"folderismappedtothestudentshomedirectory,youcansetthepreferencestomakeTuringusethe"MyDocuments"folderasthestart-infolder.Notethatthisoptionisthepreferredoptionforhomeusers,wherethe"MyDocuments"folderisthehomedirectory.
TheUse"MyDocuments"FolderintheAdminPane
Tochangethepreference,enterAdministratormode(seeChangingSystemPreferencesbelow)andsettheUse"MyDocuments"FoldercheckboxintheAdminpaneoftheTuringPreferences(seeTuringPreferencesbelow).
3. Ifeachstudent'shomedirectoryisspecifieddifferently(i.e.thereisnomappingofthehomedirectorytoadrive),thenyoumayneedtouseenvironmentvariablestocreateauseablepath.Forexample,ifstudentsfilesarestoreding:\class108\[StudentName]andthereisanenvironmentvariablesUSERNAMEthatcontainsthestudent'sname,thenthethestart-indirectoryfortheshortcutshouldbesettog:\class108\%USERNAME%.
4. Occasionallyusershavereportedsituationslikethepreviouscase,exceptthatWindowsseemsunabletosetthestart-indirectoryproperlyusingenvironmentvariables.
TheStartupDirectoryTextFieldintheAdminPane
Tosetthestart-indirectory,enterAdministratormode(seeChangingSystemPreferencesbelow)andsettheStartupDirectorytextfieldintheAdminpaneoftheTuringPreferencesappropriately(seeTuringPreferencesbelow)includingspecifyingthedirectoryusingtheenvironmentvariables.
2. SeteitherBeginnerorRegularModeforStudents.
TuringcanbesettoBeginnermode,inwhichcaseonlyonefileisopenatatime.Openingupanotherfileclosesthefirstone.Whentheprogramisrunning,theEditorwindowminimizes.Inthisway,onlyonewindowisusuallyvisibleatatime.Inthisfashion,BeginnermodeissimilartotheoldDOSTuring.
InRegularmode,anynumberoffilescanbeopenedandeachappearsinitsowneditorwindow.
Ingeneral,wesuggestBeginnermodeforgrade9and10andRegularmodeforallothers.IfyouareusingBeginnermode,wesuggestthatyoupointouttothestudentsthattheycanusethePrefencestochangetoRegularmodewhentheyfeelcomfortablewiththeenvironment.
Tochangethepreference,youwillneedtoenterAdministratormode(seeChangingSystemPreferencesbelow)andchangetheBeginnerModepreferenceintheGeneralpaneappropriately(seeTuringPreferencesbelow).
3. Windows95andtheTuringNetmodule
IfyouareusingWindows95(notWindows98/Me/NT/2000/XP)andyouwishtousetheTuringNetmoduleinordertowriteprogramsthatcommunicatewithothercomputers,thenyoumayneedupdatetheWindow95networkingcode.
Thiscanbedonebyrunningtheprogramlocatedat:
[Turingdirectory]\support\Microsoft\W95ws2setup.exe
ThisprogramfromMicrosoftpatchesWindows95networkingcode.ItmustberunoneverycomputerrunningWindows95unlessthemachinesbootfromaserver.
4. ParallelPortUsageIfyouareintendtouseTuringtocontroldevicesattachedtotheparallelport(usingtheparallelputandparallelget,andarerunningunderWindowsNT/XP/2000,youwillneedtoinstalladevicedriver.(WindowsNT/XP/2000donotallowdirectaccesstothesystemhardware.).Thedevicedrivercanbeinstalledbyrunningtheprogramlocatedat:
[Turingdirectory]\support\dlportio_install.exe
FurtherinformationcanbefoundinParallelPortandTuring4.
3.ChangingSystemPreferences
Turingusesatwolevelpreferencemodel.Thereisacentralsetofpreferencesthatarekeptin
[TuringDirectory]\Support\Ini\turing_admin.ini
ThesepreferencesarethesameforallusersandarecalledtheSystemPreferences.Asecondsetofpreferencesisstoredineachstudent'shomedirectoryinafilecalledturing.ini.ThesepreferencesoverridethecentralpreferencesandallowstudentstoindividuallymodifythebehaviourofTuring.
Whenastudentmodifiesthepreferences,theturing.inifileinthestudent'shomedirectoryischanged.TochangetheSystempreferences(i.e.thecontentsoftheturing_admin.inifile),Turingmustbestartedupwiththecommandline
turing-admin
ThiscanbedonebystartingupaDOSwindow,doingacdtothedirectoryinwhichturing.exeisstoredandthentypingturing-admin.Theusermusthavewriteaccesstothedirectoryinwhichtheturing_admin.inifileisstored.
WhenTuringislaunched,itwilldisplayamessageboxonstart-upindicatingthatitisinAdministratormodeandwherethepreferenceswillbestored.
AdministrationModeNotification
SelectingPreferencesfromtheFilemenuwilldisplayatabbeddialogboxofalltheTuringpreferences.IfyouareinAdministratormode,thenanextratablabeledAdminwillappearwithextrapreferencesthatcanonlybesetbytheAdministrator.NotethatindividualstudentscannotoverridethepreferencesthatappearontheAdminpane.
PreferencesinAdministratorMode
OncethePreferenceshavebeenset,theAdministratorcanexitTuring.
4.TuringPreferences
ThissectionlistsallthepreferencesavailableinTuringsortedbythepane
"General"Pane
The"General"Pane
BeginnerModeWhenBeginnermodeisset,onlyonefilecanbecanbeloadedintotheTuringenvironmentatatime.TheEditorwindowisminimizedeverytimetheRunwindowisactiveandvice-versa.Thedebuggercannotbedisplayedorused.Ifthisboxisnotset,thenTuringisinRegularmodeandmultiplefilescanbeopensimultaneously.BeginnermodeisrecommendedforstudentswhoareoverwhelmedorconfusedbytoomanyTuringwindows(especiallystudentsingrades9and10).OneWindowModeThisoptionisnotavailableinTuring4.0.ItwillbeusedtoswitchbetweenMDIandSDImodesinafutureversionofthesoftware.DisplayFullPathnames
ThefullpathnameandnotjustthefilenamearedisplayedintheEditorwindow'stitlebarandrecentfilessubmenu.SavePreviousFileas".BAK"Whenafileissavedovertopofanolderfile,theolderfileisrenamedwitha.BAKsuffix(i.e.test.ttotest.bak)ConfirmonQuitWhentheuserclosesthelasteditorwindow,TuringdisplaysadialogboxaskingwhethertheuserwishestoQuit.Onsystemswhereloadingisslow(usuallyoveranetwork),thiscanstoptheusersfromaccidentallyquittingTuring.SkipSplashScreenWhenTuringstartsup,itnormallydisplaysa"Splash"screenwiththeversionnumber.TheSplashscreendisappearswhentheuserclicksabuttonorafter3seconds.TurningthisoptionoffcausestheSplashscreennottobedisplayed.Add".t"toFileNamesWhenaSaveFiledialogboxappearsandtheuserspecifiesafilenamewithoutafilesuffix,Turingadds".t".Thiscanberemovedbytheuser.ConvertLeadingSpacesintoTabsWhenTuringsavesafile,itnormallyconvertsgroupsofleadingspacesintoTABcharacters,savingdiskspace.ThenumberofspacespertabisspecifiedbytheSpacesperTabtextfield.Ifthischeckboxisnotselected,thenthespacesarenotconverted.Don'tSaveRecentFilesMenuNormallyTuringliststhelastseveralfilesopened.However,ifstudentsdonothaveindividualaccounts,thenthisfeaturemaynotbeusefulandcanbeturnedoff.FindUsesSelectedTextBydefault,TuringusestheWindowsbehaviourthatwhenaFindcommandisgivenandthereisselectedtext,theselectedtextiscopiedtotheFinddialogbox.Ifyoudon'tlikethisbehaviour,thenunsettingthisoptionwillstopthisbehaviour.Ifitisnotset,thenanadditionalmenuitemisplacedintheSearchmenuthatfindsthenextoccuranceofthecurrentlyselectedtext.StartinLastActiveDirectoryIfstudentsarewritinglargeprojectsinmanysubdirectories,thenthisoptioncanbeenabledtoautomaticallystartTuringinthelastdirectoryinwhichafilewasloadedorsaved.TheTuringpreferencesfileisstillstoredinthestudent'shomedirectory.SpacesperTab
ThisspecifiesthenumberofspacesthataTabisconvertedtoandfrom.WhenTuringreadsatextfileintotheeditor,alltabsareconvertedontospaces.IfyoucreatedtheTuringfileonaneditorwhereTabsareadifferentnumberofspaces,thenchangethisvalueappropriately.IndentSizeWhenTabispressedintheTuringeditor,itisconvertedintospaces.ThenumberintheIndentSizetextfielddetermineshowmanyspacestheTabkeyisconvertedto.NotetheSpacesperTabisusedwhenTuringreads/writesfiles.TheIndentSizefieldisusedwhenTuringrespondstotheTabkey.FileAssociationMicrosoftWindowshastheabilitytoassociatefileswithaparticularsuffixwithspecificprograms.TheTuringenvironmentcanbeassociatedwiththefollowingfilesuffixes:.t,.tur,.dem,.tiand.tu.ToassociatethesefilesuffixeswithTuring,clicktheAssociate".t"fileswithTuringbutton.Toresetthefileassociationsbacktowhattheywerebefore,clicktheReset".t"FileAssociation.
"EditorWindow"Pane
The"EditorWindow"Pane
EditorFontYoucanchangethefontsizeandtypefaceusedintheeditorwindow.Ifyouchangethetypeface,youmustchooseamonospacedfontwhereboldandnon-boldlettersarethesamesize.Manymonospacedfontshavedifferentsizesforboldandnon-boldletters.FullScreenforBeginnerModeIfinbeginnermode,editorwindowsareautomaticallyinfullscreenmode.Youcanchangethisbehaviourbuyunsettingthischeckbox.FullScreenforRegularModeEditorwindowsarenormally25x80columns(orthesizespecifiedbytheEditorWindowRows/Columnstextfields).Ifthischeckboxisset,editorwindowsareautomaticallymaximizedtofillthescreen.Thisoptionissuggestedforsystemswith640x480screenresolution.Userscanchangethewindowsizebyclickingthefullscreen/normalwindowbuttoninthewindow'stitlebar.EditorWindowRows/ColumnsThesetextfieldscontrolthesizeofeditorwindowswhenfirstcreated.SyntaxColoringWhenselected,partsofTuringprogramsappearindifferentcolors:commentsappearingreen,stringsinred,keywordsinboldface,predefinedidentifiersinblack,anduseridentifiersinblue.AlwaysShow'Debugger'MenuIntheinterestofkeepingtheinterfaceassimpleaspossible,andbecausemoststudentsdonotusethedebuggingfeatures,TuringdoesnotdisplaytheDebuggermenubydefault.Instead,theuserselectsShowDebuggerMenufromtheRunmenu.SettingthischeckboxcausestheDebuggermenutoalwaysbedisplayed.TextCursorWidthBydefault,thecursor(correctlycalledthecaret)is2pixelswide,allowingittobeseeneasilyintheEditorwindow.However,someuserspreferthecarettobe1pixelwideandsomepreferthecarettooverlayanentirecharacter(inasimilarmannertoDOSeditors).Legalvaluesare1(whichrepresenta1pixelthickcaret),2(whichrepresenta2pixelthickcaret),and3(whichrepresentsatextcursorthatcoverstheentirecharacter.
"RunWindow"Pane
The"RunWindow"Pane
DefaultRunWindowFontYoucanchangethefontsizeandtypefaceusedintheTuringrunwindow.Ifyouchangethetypeface,youmustchooseamonospacedfont.NotethatchangingthesizeoftherunwindowfontmaycauseoddoutputinTuringprogramsthatwerewrittenassumingaparticularcharactersize.StartinGraphicsModeThismakestheinitialrunwindowagraphicswindow.Theusercanusegraphicswithoutthesetscreen("graphics")commandintheprogram.Outputthatscrollsoffthetopofthescreenislost.Intextmode,graphicsarenotallowed,butalltextoutputiskeptandcanbescrolled,saved,andprintedatanytime.FullScreenRunWindowThiscausesthedefaultrunwindowtooccupytheentirescreen.RunWindowRows/ColumnsThissetsthesizeofthedefaultrunwindow.Changingthesizemaycauseprogramsthatassumea25x80windowtomalfunction.UseSmallFontson640x480ScreenAstandard25x80windowdoesnotquitefitona640x480screenwithastandardsizetaskbar.Asaresult,withoutthisoption,thedefaultgraphicsmoderunwindowappearswithscrollbars.ThisoptioncausesTuringtouse
aslightlysmallerfontfor640x480runwindowssotheentirewindowfitsonthescreen.ThisoptionmaycauseoddoutputinTuringprogramsthatwerewrittenassumingaparticularcharactersize.
"Printing"Pane
The"Printing"Pane
Notethattheoptionsmarkedwithanasterisk(*)canbesetintheprintingdialog.
PrintingFont/PrintingHeaderFontYoucanchangethefontsizeandtypefaceusedinprinting.Ifyouchangethetypeface,youmustchooseamonospacedfontwhereboldandnon-boldlettersarethesamesize.Manymonospacedfontshavedifferentsizesforboldandnon-boldletters.BoldKeywords/ItalicizeIdentifiers*Thisallowsfor"syntaxcoloring"ofprintouts.Keywordscanbeplacedinboldandidentifiersitalicized.PrintPageHeaderOnsomesystems,aheaderpageisautomaticallyprintedoutandthereislittlereasonforapageheader.Unsettingthischeckboxwillcauseprintouts
nottohaveanyheaderontheprintedprograms.UserNameinHeaderNormallytheusernameisdisplayedintheheader.However,onsomesystemstheusernameisnon-descriptiveornon-existent.Thisallowsyoutodisabletheprintingoftheusernameonsuchsystems.Two-UpPrinting*Thisisapapersavingmeasure.Textisprintedinlandscapemodewithtwo"pages"perpieceofpaper.Thismeansthatlistingsusehalftheamountofpaper.Ofcourse,thefontismuchsmaller.LineNumbers*Thisprintsoutlinenumbersinfrontofeachlineoftheprogram.Thisisusefulifyouareprintingoutalistingtohandouttotheclass.BorderAroundTextSomeusersliketohaveathinborderprintedaroundthetextforeaseofdeterminingthemargins,etc.SettingthischeckboxcausesTuringtodisplayahairlineborderaroundprogramprintouts.MarginsIfyouneedtochangethemarginsonprintouts(forexample,tofacilitatetheinsertionofprogramlistingsinto3-ringbinders),thenyoucandobychangingthevaluesinthetextfields.Marginsareexpressedininches.UserNameOnsystemswheretheusernameisnon-descriptiveornon-existent,theusercanenteranamethatwillappearontheprintoutallowingittobeidentified.Ifstudentsarechoosinginappropriateusernames,thispreferencecanbedisabledintheAdmintabpreferencedialog.
"Admin"Pane
The"Admin"Pane
Note,theAdminpaneisonlyavailableinadministratormode.StudentsstartingTuringwillnothaveaccesstothisdialogbox.
StartupDirectoryUserswillstartinthedirectorylistedinthistextfield.Ifleftblank,TuringwillusetheworkingdirectoryoftheshortcutusedtostartTuring.Ifnoworkingdirectoryfortheshortcutisspecified,thedirectorywhereTuringisinstalledisused.Environmentvariablesprefixedandsuffixedwith%signscanbeusedhere(example:g:\students\%username%).Notethatinmostcases,thistextfieldshouldbeblank.Use"MyDocuments"folderThe"MyDocuments"foldercanbeusedasthestartupdirectoryinsteadofthecontentsoftheStartupDirectorytextfield.Thisismostcommonlyusedinsingleusersystems.CanSetUserNameAllowstheusertospecifytheusernametoappearontopofprintouts.Thischeckboxcanbeunsetifstudentsarechoosinginappropriateusernames.CanEnterRegularModeAllowstheusertoturnoffthebeginnermodepreference.Thischeckboxcanbeunsetifitisdesirabletohaveallstudentsworkinginbeginnermode.
DebuggerAvailableThischeckboxcanbeunsetinordertostopstudentsgettingaccesstothedebugger.CannotAlterPreferencesWhenset,thisstopsstudentsfromaccessingthePreferencesdialog.ItalsostopsTuringfromreadingthestudent'sturing.inifile.Thiscanbesetwhenitisimportanttohaveauniformsetofpreferencesonallstudentmachines,orwhenthereisnolog-onprocedureandstudentsaresharingmachines.Prohibituseof'Sys.Exec'Whenset,theSys.Execandsystemproceduresdonothing.Thiscanbesetifthereisasystemsecurityconcernaboutstudentsstartingarbitraryprograms.NoSoundorMusicWhenset,theTuringsoundandmusiccommandsdonothing.UseonlyStartupDirectoryandBelowCAUTION!Thisoptiononlyprovidesrudimentarysecurityandistobeusedonlyonsystemswheretheoperatingsystemcannotprovidepropersecurity.Thisoptionwillnotallowstudentstosaveorloadtoanydirectoryotherthattheirstartupdirectoryordirectoriescreatedinthestartupdirectory.Thisoptiondoesnotstopstudentsfrombrowsingthenamesoffilesinotherdirectories,onlyfromloadingorsavingfilesinthem.UseOnlyAllowedDrivesCAUTION!Thisoptiononlyprovidesrudimentarysecurityandistobeusedonlyonsystemswheretheoperatingsystemcannotprovidepropersecurity.Thisoptionallowsstudentstoloadfilesonlyfromthesetofdrivesspecifiedinthetextfield.The'*'representsnetworkdrives.ForbidUseofCertainDrivesCAUTION!Thisoptiononlyprovidesrudimentarysecurityandistobeusedonlyonsystemswheretheoperatingsystemcannotprovidepropersecurity.Thisoptionpreventsstudentsfromloadingfilesfromthesetofdrivesspecifiedinthetextfield.The'*'representsnetworkdrives.
5.UsingtheParallelPortsinTuring4
UnderTuring4.0and,itispossibletoaccesstheIBMPC'sparallelportforreadingandwriting.Thisisnormallydoneusingtheparallelputandparallelgetcommands.(InTuring4.0,youcanusePC.ParallelPutandPC.ParallelGettoaccessportsotherthanLPT1.)
UnderWindows95/98andMe,theoperatingsystemallowsdirectaccesstotheparallelport.UnderWindowsNT,2000andXP,accesstotheparallelportisrestrictedbytheoperatingsystem.Inordertoaccesstheport,underWindowsNT,2000andXP,itisnecessarytoinstalladevicedriveroneachmachinethatwillbeaccessingtheparallelport.Theneededdevicedriverinstallerislocatedat:
[Turingdirectory]\support\dlportio_install.exe
where[Turingdirectory]isthedirectoryinwhichTuringwasinstalled.ExecutingthisprogramwillinstallthedevicedriverintheWindowsSystemdirectoryofthemachineuponwhichitisexecuted.
Lastly,beforeaccessingtheparallelport,checkthattheparallelportisinnormalmodeandnotinbi-directional,PS/2,EPPorECPmode.YoucandeterminewhichmodetheparallelportisinusingtheDeviceManager.InthelistofdevicesintheDeviceManagerwindow,doubleclickPorts(COMandLPT),andthentheLPT(orPRN)port.Thisdisplaysapropertysheetabouttheparallelport.Takealookatwhatitsaysaboutit.Ifitisinanon-originalmode(i.e.mentionsbi-directional,PS/2,EPPorECPmode),thenyouwillprobablyneedtoadjustthesystemsBIOSsettings.
(UnderWindows2000theDeviceManagercanbedisplayedbyselectingtheSystemControlPanelfromSettingsintheStartmenu.SelecttheHardwaretabandthenclicktheDeviceManagerbutton.)
Ifthesettingfortheparallelportneedstobechanged,restartthemachine,andpresstheappropriatekeytoentertheBIOSSetUpProgram(thekeyvariesbetweenmachines,butisusuallynotedonthescreen).OftentheparallelportsettingsarefoundinAdvancedSettingsoftheprogram.TheparallelportshouldbesettoNormal,Standard,ATorUnidirectionalmode.(Allfour
namesaredifferentdescriptionsofthesamemode.)Oncethisisdoneandthenewsettingsaresaved,thenstartthemachineintoWindows.OnceinWindows,selectShutDownandturnthemachinecompletelyoff.Oncethemachineisoff,waitatleast10secondsinthepowered-offstate.Thenrestartthemachine.(Whileshuttingdownthemachineshouldnotbenecessary,wehavehadseveralcaseswherethechangeonlytookwhenthemachinehadbeenpowered-downandrestarted.)
6.MissingFeaturesfromTuring4
Turing4.0doesnotyetincorporateallthefeaturesthatcurrentlyexistinObjectOrientedTuring3.1.1andareintendedforfutureTuringreleases.Overthenextfewmonths,newfeatureswillbeaddedandupdatestoTuringwillbemadeavailableonourwebsite.Thefeaturestobeaddedare:
ViewVariablesTheSpritemodule
Ifyouhaveimmediateneedofanyofthesefeatures,pleasecontinuetousetheObjectOrientedTuring3.1.1software.OntariouserscanobtainthesoftwarethroughtheirOESSsoftwarerepresentative.
TodeterminethecurrentreleaseofTuring,checktheTuringwebsiteat
http://www.holtsoft.com/turing/support
7.TheTuringDebugger
ThecurrentversionofTuringhasaDebuggerfacilitiesthatallowstudentstofollowexecutionofaprogrameitherpausingaftereachlineofexecutionorexecutingslowlywhilehighlightingeachlineofexecution.Becauseoftheconfusingnatureofthedebuggerformanystudents,thedefaultconfigurationofTuringdoesnotdisplaythedebuggermenuuntilthestudentrequestsitbyselectingtheShowDebuggerMenufromtheRunmenu.
AlwaysShow'Debugger'MenuintheEditorWindowPane
IfyouwishstudentstohaveamoreregularexposuretotheDebugger,youcansetaSystempreferencetocauseTuringtoalwaysdisplaytheDebuggermenu.Tosetthethispreference,enterAdministratormode(seeChangingSystemPreferencesbelow)andsettheAlwaysShow'Debugger'MenucheckboxintheEditorWindowpaneoftheTuringPreferences.
8.StudentDistributionofTuring4.0
TheOntarioMinistrylicensedoesnotincludetherighttoredistributethesoftwaretostudents.Ifyouwishtogivethesoftwaretostudents,aseparatelicensemustbeobtaineddirectlyfromHoltSoftware.
Ifyourschooldoesnothavesuchalicense,studentscanpurchasethesoftwareforhomeusebyprintingandthenmailinganorderformfoundhttp://www.holtsoft.com/studentbuy.Thisorderformcanalsobeusedtoallowinterestedstudentstopurchasetextbooks.
Ifyourschoolhaspurchasedaredistributionlicense(almost200schoolshavedoneso),thenyoumayredistributetheTuringsoftwaretoyourstudents.YoucaneitherburncopiesoftheCDtodistributetostudentsorplacetheTuringinstallerfileontoyourschoolInternetserverandgiveyourstudentstheURL.
Ifyouplacethisfileonyourschoolinternetserver,youmustnotmakeanylinksfromyourwebpagestothesoftware.
Thiswillpreventotherusersofthewebfromdownloadingyoursoftware.Ifyouplacelinksfromyourschool'swebsite,thenatsomepointawebsearchenginewillfindthesoftwareandpostitslocationtotheinternetatlarge,allowingforlargescalepiracy(andaveryoverloadedschoolwebserver).Iftherearenolinkstothesoftware,thenonlythosewhohavebeentoldtheexactURLwillbeabletodownloadthesoftware.
NotethatifyouarecopyinganumberofdifferentprogramsontoasingleCDforredistribution,youmayrenametheTuringinstallerprogramtosomethingmoredescriptive.
Permanentstudentredistributionlicensescanbepurchasedfor$500-$750formostschools.Ifyouareinterestedinpurchasingastudentredistributionlicense,contactChrisStephensonat(416)[email protected]
9.TechnicalSupport
Ifyouhaveproblems,questionsorsuggestionsabouttheTuringsoftware,contacttechnicalsupportat:Telephone: (416)978-8363Tollfree: 1-800-361-8324Fax: (416)978-1509E-mail: [email protected]
TuringDebuggerGuideIntroduction
Turingsupportsanumberoftoolstoenableuserstodebugtheirprogramsandexamineprogramexecution.Someoftheavailabletoolsare:
Steppingexecutionalineatatime.TracingexecutionwithasetpausebetweenlinesofexecutionSettingbreakpointstopauseexecutionatspecifiedpointsintheprogram.Viewingallopenresourcesofaprogramincludingfiles,fonts,pictures,etc.
AsofMay2002,theTuring4.1softwaredoesnotcontainthefollowingfeature:
Viewvariables.
Thisfeaturewillbeimplementedastimeanddeveloperresourcespermit.
DisplayingTheDebuggerMenu
Inordertouseanyofthedebuggercommands,youneedtohavetheDebuggermenushowingintheEditorwindow.Bydefault,theDebuggermenuishiddeninordertosimplifytheTuringenvironmentforthemajorityofstudentsnotusingthedebugger.
TherearetwowaysthattheDebuggermenucanbedisplayed.YoucanselecttheShowDebuggerMenucommandintheRunmenu.
ShowDebuggerMenucommandintheRunmenu
Ifyouareconsistenlyusingthedebugger,thenyoushouldchangethePreferencessothattheDebuggermenuisalwaysdisplayed.ThiscanbedonebybringinguptheEditorWindowpaneofthePreferencesdialogboxandsettingtheAlwaysShow'Debugger'Menucheckbox.
AlwaysShow'Debugger'MenuintheEditorWindowPane
UsingTheDebuggerMenu
ShowDebuggerMenucommandintheRunmenu
TheDebuggermenugivesyouaccesstoallthedebuggingfeaturesinTuring4.0.Thefollowingmenuoptionsareavailable:
ShowDebuggerControlsThiscommandcauseseachEditorwindowtodisplayasecondrowofcontrolsatthetopofthewindow(calledtheDebuggercontrols)thatallowtheusertostepthroughaprogramandtraceexecutionoftheprogram.WhentheDebuggercontrolsarevisible,thenthismenuitemchangestoHideDebuggerControls.
WindowwithDebuggerControlsVisible
ShowBreakpointsThiscommandcauseseachEditorwindowtodislayanareaontheleftwherebreakpointscanbeplaced.Abreakpointisamarkerthatcausestheprogramtopausewhenexecutionreachesthemarkedline.
WindowwithBreakpointVisible
ClearBreakpointsThiscommandquicklyeliminatesallbreakpointsthathavebeensetinanyEditorwindow.ShowAllocatedObjectsThiscommandshowsallthefiles,fonts,pictures,etcthathavebeenopenedorcreatedbytheprogrambuthavenotbeenclosed.Astheprogramexecutes,thiswindowupdateseverytimearesourceisallocatedorfreed.
AllocatedObjectsWindow
TuringExecution
Therestofthisdocumentwillusesometermsthatmustbeunderstoodproperly.
Running-ATuringprogramisrunningwhenstatementsarebeingcontinuouslyexecutedwithouthumanintervention.However,runningmaybestalledwhiletheprogramiswaitingforkeyboardinput,executingadelaystatement,etc.Paused-ATuringprogramispausedwhenexecutionistemporarilyhalted.Noinputisacceptedbytheprogramwhileitispaused.Aprogramcanbecomepausedinavarietyofwaysincluding:
TheuserpressingthePausebutton.TheuserpressingaStep,StepOverorStepReturnbutton.Executionreachingabreakpoint.Executionreachingthebreakstatementinaprogram.
WhenaTuringprogramispaused,thelineinthesourcecodeonwhichtheTuringprogramwasabouttoexecuteishighlighted.Ineachcase,theprogramcanresumerunningbyclickingtheResumebutton.TheprogramcanalsotemporarilyresumerunningbytheuserpressingtheStep,StepOverorStepReturnbutton.Oncethestatementorstatementsarefinishedrunning,theprogramispausedagain.Executing-AprogramisexecutingwhenitiseitherRunningorPaused.Halted-ATuringprogramishaltedwhenitcannolongerexecuting.Itcannotberesumedandmustbestartedfromthebeginninginordertorunitagain.Aprogramcanbehaltedby:
TheuserpressingtheStopbutton.Arun-timeerror.TheuserclosingaRunwindow.
SteppingaProgram
SteppingaprogramconsistsofexecutingaTuringprogramalineatatime.Aftereachstepcommand,executionpauses,highlightingthenextlinetobeexecuted.Tostepaprogram,theprogrammustnotberunning.TheDebuggercontrolsintheEditorwindowmustbevisible.Tosteptheprogram,theuserclicksoneofthethreebuttonsintheDebuggerControls:
Step-Iftheprogramishalted,thisexecutestheveryfirstlineofcodeandthenpauses.Iftheprogramispaused,itexecutesthehighlightedlineofcodeandthenpauses.Ifitlineofcodetobeexecutedisasubprogramcall,thenitentersthesubprogramandpausesatthefirstlineofcodeinthesubprogram.Ifitisattheendofthesubprogram,thenitleavesthesubprogramandpausesatthesubprogramcall.ThiscommandissometimescalledStepInto.StepOver-Thisexecutesasinglelineofcode.However,iftheprogramispausedatasubprogramcall,thentheentiresubprogramisexecutedandexecutionispausedatthenextlineafterthesubprogramcall.StepReturn-Thisresumesexecutionuntiltheexecutionreturnsfromasubprogram.Thenextlineafterthesubprogramcall.Notethatifthiscommandisgiveninthemainprogram,thenexecutionwillcontinueuntiltheprogramterminates.
TracingaProgram
Tracingaprogramissimplyexecutingaprogramslowlywitheachlineofcodeintheprogrambeinghighlightedasitisexecuted.Tracingallowsuserstoseehowcontrolconstructsoperate.Unlikestepping,withtracing,executioncontinuesuntilitispausedorhaltedinsomeotherfashion.
Tostartaprogramtracing,theDebuggerControlsmustbevisible.TheuserthenclickstheTraceExecutioncheckbox.Whentheprogramisnextrunning,eachtimeastatementisexecuted,thelineinthesourcecodewillbehighlighted.ThespeedatwhichthetracingoccursiscontrolledbytheTraceSpeedsliderfoundintheDebuggerControls.Whenthesliderisontheleft,thereisessentiallynodelaybetweenexecutionofstatements.(Notethatexecutionwillstillbemuchslowerthannottracingduetothetimetakentohighlighteachexecutingstatement.)Whenthesliderisontheright,eachstatementwillwaitforabout5secondsafterexecutingbeforethenextstatementisexecuted.
SettingBreakpoints
Oftenonlyaparticularsectionofcodeisofinteresttotheuser.Breakpointsprovideamechanismforpausingaprogramonlywhenexecutionreachesaspecifiedstatement.Tosetbreakpoints,theyneedtobedisplayedintheEditorwindow.ThisisdonewiththeShowBreakpointscommandintheDebuggermenu.Oncebreakpointsarevisible,theycanbeset(andremoved)bysimplyclickingthemouseinthebreakpointarea.Whenthemouseisoverthebreakpointarea,itturnsintoadiamond.Whenthebreakpointisset,areddiamondappearsinthebreakpointarea.Toremovethebreakpoint,simplyclickthereddiamondandthebreakpointdisappears.
WindowwithTwoBreakpointsSet
Whenexecutionreachesalinewithabreakpointonit,theprogrampausesand
thelineishighlighted.Theprogramcanthenberesumedorsteppedasdesired.Notethatitispossibletosetabreakpointonalinethatisnotexecuted.Ifyouplaceabreakpointonablankline,itisquitelikelythatexecutionwillnotstop.Likewise,inlinesbrokenovermultiplelines,itisbesttoputthebreakpointonthelastlineinthestatement.
Toclearallthebreakpoints,selectClearBreakpointsfromtheDebuggermenu.
ViewingOpenFiles/Pictures/Fonts,etc.
AcommonerrorinTuringprogramsistoneglecttocloseopenfiles(usingtheClosestatement)orfreepicturesorfonts(usingthePic.FreeorFont.Freeprocedures).TheAllocatedObjectswindowdisplaysallallocatedresourcesuntiltheyarefreed.ThiswindowisdisplayedbyselectingtheShowAllocatedObjectscommandfromtheDebuggermenu.Thecommandcanbegivenevenafteraprogramhashalted.Itisausefulcommandtousewhenamopen,Pic.NeworFont.Newhasfailedbecauseoftoomanyopenfiles,picturesorfonts.
Thewindowwillalsodisplayjusthowmuchmemoryeachpicturetakesup.
AllocatedObjectsWindow
Clickingonthelinecontainingtheallocatedobjectwillhighlightthelineinthecodewheretheobjectwasallocated.TheheadingsoneachofthecolumnscanbeclickedallowingtheobjectstobesortedeitherbytheirID,orbywhereintheprogramtheywereallocated.
Error.TripMsg PartofErrormodule
Syntax Error.TripMsg(errorCode:int,errorMessage:string)
Description
Error.TripMsgisaprocedurethatsetstheerrornumberanderrormessagethatisreturnedbyError.LastandError.LastMsg.Itdoesnothalttheprogram.
YoucanfindalistofconstantsforthelegalerrorcodesinthemoduleErrorNum.AnycalltoError.TripMsgshoulduseaconstantfoundintheErrorNummoduleorzero,iftheerrorcodeisnotrelevant(i.e.onlytheerrormessageisrelevant).
Example
Thisprogramsetsanerrorcode.Theprogramoutputs201fortheerrorand"File*really*notfound"forthemessage.
Error.TripMsg(eFsysFileNotFound,"File*really*notfound")
put"Errorcode=",Error.Last
put"Errormessage=",Error.LastMsg
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingError.TripMsgcallingTripMsg.
Error.Halt PartofErrormodule
Syntax Error.Halt(errorMessage:string)
Description
Error.HaltisaprocedurethatimmediatelyhaltsexecutionoftheprogramandshowsthespecifiederrormessageonthelineintheprogramthatcallsError.Halt.
Thisprocedureisusefulforallowingaquickhalttoaprogramwhileindicatinganerrorcondition.
Example
Thisprogramhaltsonthefirstlinewithanerrormessagestating"Executionterminatedbytheprogram."
Error.Halt("Executionterminatedbytheprogram.")
Execute
Status
Exportedqualified.
ThismeansthatyoucanonlycallthefunctionbycallingError.HaltnotbycallingHalt.