xHarbour Language Reference Guide

November 24, 2016 | Author: Luiz Uberti | Category: N/A
Share Embed Donate


Short Description

Download xHarbour Language Reference Guide...

Description

Copyright

© 2006 xHarbour.com Inc. All rights reserved. xHarbour Language Reference Guide version 1.0. If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of xHarbour.com Inc. Please note that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user license agreement. The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by xHarbour.com Inc. xHarbour.com Inc. assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational content contained in this guide. xHarbour.com Inc. 10624 S. Eastern Avenue, Henderson, Nevada 89052, USA.

Read Me First!

Read Me First! Welcome to the First Version of the xHarbour Language Reference Guide. This page informs you about what you can expect from the First Edition and what is not yet included. First, we'd like to thank you for patience and ongoing support while we were preparing this xHarbour Language Reference Guide. It is a huge documentation project and while not yet finished, we are confident that the large amount of quality information will prove valuable for every xHarbour programmer.

First stage (completed) We have started this First Edition with collecting most information about xHarbour's roots: the Clipper programming language. The topics covering Clipper are entirely re-written.

Second stage (completed) At the second stage, we focused on documenting all xHarbour's extensions to the Clipper language. There is a wealth of new features added to xHarbour that do not exist in Clipper (see "Notes for Clipper programmers" below). For example, a complete OOP model with new classes exists. New data types and operators are added. Additional preprocessor directives are available, plus numerous new functions and statements. As a matter of fact, the core documentation of xHarbour is about twice as much as the original Clipper Norton Guides. It is structured into the following sections: 1.

Operator Reference

2.

Statement Reference

3.

Command Reference

4.

Class Reference (textmode)

5.

Function Reference

6.

Preprocessor Reference

These sections should aid you in finding information on core features of xHarbour easily. In addition, a comprehensive Index and Full Text Search capabilities, plus a sophisticated Cross Reference Link System are all included. Please try these features for searching and finding the information you need in the xHarbour Documentation.

Third stage (ongoing) We are now entering the third documentation stage right after the release of this book. The result of this third stage will be provided as a free update to Version 1.0 of the xHarbour Language Reference Guide. We are commited to supply you with this free update promptly. However, there is still a bunch of work ahead and we hope you enjoy reading this Version 1.0 in the meantime. A list of items we will cover in the next version can be found on this page.

xHarbour Language Reference Guide

1

Read Me First!

Notes for Clipper programmers The xHarbour programming language has its roots in CA-Clipper, a powerful xBase dialect, and is modelled around Clipper. xHarbour extends Clipper and has received many new features, which can be detected very easily: Extended function arguments are highlighted in yellow. Refer to function AIns() for an example. All topics that do not exist in Clipper, but are added by xHarbour, are listed in the category xHarbour extensions.

Copyright Please read the Copyright note carefully before using this guide.

Your contributions This Version 1.0 of the xHarbour Language Reference Guide can only reflect the current stage of xHarbour and its documentation, as of Dec 2006. We are constantly adding new features to xHarbour and new information to the documentation. If you miss something particular, please let us know. This file should give you a clear idea of xHarbour.com commitment to the xHarbour programming language. We are grateful for any suggestion you may have to improve xHarbour. Thank you for your support.

2

xHarbour Language Reference Guide

Table of Contents

Table of Contents R EAD M E F IRST!........................................................... 1 TABLE OF CONTENTS .................................................. I OPERATOR REFERENCE.............................................. 9 $......................................................................... 10 %........................................................................ 11 & (bitwise AND) ................................................. 12 & (macro operator)............................................ 14 ( )........................................................................ 19 * ......................................................................... 21 ** ....................................................................... 22 + ......................................................................... 23 ++ ....................................................................... 25 -.......................................................................... 26 -- ........................................................................ 28 ->........................................................................ 29 .AND................................................................... 31 .NOT................................................................... 32 .OR. .................................................................... 33 :.......................................................................... 35 :=........................................................................ 37 < ......................................................................... 38 = ....................................................................... 56 >> ....................................................................... 58 @ ....................................................................... 59 @() ..................................................................... 60 HAS .................................................................... 62 IN ....................................................................... 64 LIKE .................................................................... 66 [ ] (array)............................................................ 68 [ ] (string) ........................................................... 69 ^^ ....................................................................... 71 { } ....................................................................... 73 {=>} .................................................................... 74 {|| }.................................................................... 76 | (bitwise OR)..................................................... 78 STATEMENT REFERENCE.......................................... 80 (struct) ............................................................... 81 ACCESS............................................................... 82 ANNOUNCE........................................................ 84 ASSIGN............................................................... 85 ASSOCIATE CLASS............................................... 88

BEGIN SEQUENCE ...............................................92 CLASS ..................................................................94 CLASSDATA .........................................................99 CLASSMETHOD .................................................102 DATA.................................................................103 DELEGATE .........................................................106 DESTRUCTOR ....................................................108 DO CASE............................................................110 DO WHILE .........................................................112 ENABLE TYPE CLASS..........................................114 ERROR HANDLER ..............................................116 EXIT PROCEDURE ..............................................118 EXPORTED: .......................................................120 EXTEND CLASS...WITH DATA ............................121 EXTEND CLASS...WITH METHOD.......................123 EXTERNAL .........................................................125 FIELD.................................................................126 FOR ...................................................................128 FOR EACH .........................................................130 FUNCTION ........................................................132 GLOBAL.............................................................135 HIDDEN:............................................................137 IF.......................................................................139 INIT PROCEDURE ..............................................141 INLINE METHOD ...............................................143 LOCAL ...............................................................145 MEMVAR ..........................................................147 MESSAGE ..........................................................148 METHOD (declaration) .....................................150 METHOD (implementation)..............................153 METHOD...OPERATOR ......................................156 METHOD...VIRTUAL ..........................................158 OPERATOR ........................................................159 OVERRIDE METHOD .........................................161 PARAMETERS....................................................163 pragma pack() ..................................................164 PRIVATE ............................................................165 PROCEDURE ......................................................167 PROTECTED: .....................................................169 PUBLIC ..............................................................170 REQUEST...........................................................172 RETURN ............................................................173 STATIC...............................................................174 SWITCH.............................................................176 TRY...CATCH ......................................................178 typedef struct ...................................................180 WITH OBJECT ....................................................183 COMMAND REFERENCE ......................................... 185 ? | ?? ................................................................186 @...BOX ............................................................188 @...CLEAR .........................................................190 @...GET.............................................................192 @...PROMPT.....................................................196 @...SAY .............................................................197 @...TO ..............................................................200 I

Table of Contents ACCEPT.............................................................202 APPEND BLANK................................................. 203 APPEND FROM ................................................. 205 AVERAGE ..........................................................208 CANCEL.............................................................210 CLEAR ALL......................................................... 211 CLEAR MEMORY ............................................... 212 CLEAR SCREEN..................................................213 CLEAR TYPEAHEAD ........................................... 214 CLOSE ...............................................................215 COMMIT...........................................................217 CONTINUE ........................................................218 COPY FILE ......................................................... 219 COPY STRUCTURE ............................................. 220 COPY STRUCTURE EXTENDED...........................221 COPY TO ...........................................................223 COUNT..............................................................227 CREATE .............................................................229 CREATE FROM ..................................................231 DO ....................................................................233 DEFAULT TO ..................................................... 234 DELETE..............................................................235 DELETE FILE ......................................................237 DELETE TAG......................................................238 EJECT ................................................................ 240 ERASE ...............................................................241 FIND..................................................................242 GO ....................................................................243 INDEX ...............................................................245 INPUT ...............................................................249 JOIN ..................................................................250 KEYBOARD........................................................252 LOCATE.............................................................254 MENU TO..........................................................256 PACK.................................................................258 QUIT .................................................................259 READ.................................................................260 RECALL..............................................................262 REINDEX ...........................................................264 RELEASE............................................................265 RENAME ...........................................................267 REPLACE ...........................................................269 RESTORE...........................................................271 RUN ..................................................................273 SAVE .................................................................274 SEEK..................................................................275 SELECT ..............................................................277 SET ALTERNATE ................................................279 SET AUTOPEN ................................................... 281 SET AUTORDER ................................................. 283 SET AUTOSHARE ............................................... 284 SET BACKGROUND TASKS.................................285 SET BACKGROUNDTICK ....................................286 SET BELL ...........................................................287 SET CENTURY....................................................288 SET COLOR........................................................289 II

SET CONFIRM ................................................... 290 SET CONSOLE ................................................... 291 SET CURSOR ..................................................... 292 SET DATE .......................................................... 293 SET DBFLOCKSCHEME ......................................295 SET DECIMALS .................................................. 297 SET DEFAULT .................................................... 298 SET DELETED .................................................... 299 SET DELIMITERS ............................................... 301 SET DESCENDING ............................................. 302 SET DEVICE ....................................................... 303 SET DIRCASE ..................................................... 305 SET DIRSEPARATOR .......................................... 306 SET EOL ............................................................ 307 SET EPOCH ....................................................... 308 SET ERRORLOG................................................. 309 SET ERRORLOOP............................................... 310 SET ESCAPE....................................................... 311 SET EVENTMASK .............................................. 312 SET EXACT ........................................................ 314 SET EXCLUSIVE ................................................. 316 SET FILECASE .................................................... 317 SET FILTER ........................................................ 318 SET FIXED ......................................................... 320 SET FUNCTION.................................................. 321 SET INDEX......................................................... 323 SET INTENSITY .................................................. 325 SET KEY.............................................................326 SET MARGIN..................................................... 327 SET MEMOBLOCK............................................. 328 SET MESSAGE ................................................... 330 SET OPTIMIZE................................................... 331 SET ORDER ....................................................... 332 SET PATH .......................................................... 334 SET PRINTER..................................................... 335 SET RELATION .................................................. 337 SET SCOPE ........................................................ 339 SET SCOPEBOTTOM.......................................... 341 SET SCOPETOP.................................................. 342 SET SCOREBOARD ............................................ 343 SET SOFTSEEK................................................... 344 SET STRICTREAD............................................... 346 SET TRACE ........................................................ 347 SET TYPEAHEAD ............................................... 348 SET UNIQUE ..................................................... 349 SET VIDEOMODE .............................................. 350 SET WRAP......................................................... 351 SKIP ..................................................................352 SORT................................................................. 354 STORE...............................................................356 SUM ................................................................. 357 TEXT ................................................................. 359 TOTAL...............................................................360 UNLOCK............................................................ 362 UPDATE............................................................ 363 USE ................................................................... 365

Table of Contents WAIT ................................................................ 367 ZAP................................................................... 368 FUNCTION REFERENCE .......................................... 369 AAdd().............................................................. 370 Abs()................................................................. 371 AChoice().......................................................... 372 AClone() ........................................................... 377 ACopy() ............................................................ 379 ADel() ............................................................... 381 ADir() ............................................................... 383 AEval() ............................................................. 385 AFields() ........................................................... 387 AFill()................................................................ 389 AIns()................................................................ 391 ALenAlloc()....................................................... 393 Alert()............................................................... 394 Alias()............................................................... 396 AllTrim() ........................................................... 397 AltD() ............................................................... 398 AmPm() ............................................................ 400 Array().............................................................. 401 Asc() ................................................................. 402 AScan()............................................................. 403 ASize().............................................................. 405 ASizeAlloc() ...................................................... 406 ASort().............................................................. 407 At()................................................................... 409 ATail() .............................................................. 411 Bin2I() .............................................................. 412 Bin2L().............................................................. 413 Bin2U()............................................................. 414 Bin2W() ............................................................ 415 BlobDirectExport() ........................................... 416 BlobDirectGet() ................................................ 419 BlobDirectImport()........................................... 421 BlobDirectPut() ................................................ 423 BlobExport()..................................................... 425 BlobGet().......................................................... 427 BlobImport() .................................................... 428 BlobRootDelete() ............................................. 430 BlobRootGet() .................................................. 431 BlobRootLock()................................................. 432 BlobRootPut() .................................................. 433 BlobRootUnlock()............................................. 435 BoF() ................................................................ 436 Break() ............................................................. 438 Browse()........................................................... 440 CDoW() ............................................................ 442 Chr() ................................................................. 443 CMonth().......................................................... 445 Col() ................................................................. 447 ColorSelect()..................................................... 448 ConvToAnsiCP()................................................ 450 ConvToOemCP()............................................... 451 CStr()................................................................ 452

CtoD() ...............................................................454 CurDir() .............................................................455 CurDrive() .........................................................456 Date() ...............................................................457 Day() .................................................................458 Days() ...............................................................459 DbAppend() ......................................................460 DbClearFilter() ..................................................462 DbClearIndex()..................................................463 DbClearRelation() .............................................464 DbCloseAll() ......................................................465 DbCloseArea()...................................................466 DbCommit() ......................................................467 DbCommitAll()..................................................468 DbCopyExtStruct() ............................................469 DbCopyStruct() .................................................470 DbCreate() ........................................................472 DbCreateIndex() ...............................................475 DbDelete() ........................................................477 DbEdit() ............................................................478 DbEval() ............................................................483 Dbf() .................................................................485 DbFieldInfo().....................................................486 DbFileGet() .......................................................488 DbFilePut() ........................................................489 DbFilter() ..........................................................490 DbGoBottom() ..................................................492 DbGoto()...........................................................493 DbGoTop() ........................................................495 DbInfo() ............................................................496 DbOrderInfo() ...................................................503 DbRecall() .........................................................510 DbRecordInfo() .................................................511 DbReindex() ......................................................513 DbRelation() .....................................................514 DbRLock() .........................................................516 DbRLockList() ....................................................518 DbRSelect() .......................................................519 DbRUnlock()......................................................521 DbSeek() ...........................................................522 DbSelectArea()..................................................524 DbSetDriver() ....................................................526 DbSetFilter() .....................................................527 DbSetIndex() .....................................................529 DbSetOrder() ....................................................530 DbSetRelation() ................................................531 DbSkip() ............................................................533 DbSkipper().......................................................535 DbStruct() .........................................................537 DbTableExt().....................................................539 DbUnlock()........................................................540 DbUnlockAll()....................................................541 DbUseArea() .....................................................542 DefPath() ..........................................................544 Deleted()...........................................................545 Descend()..........................................................547 III

Table of Contents DevOut()...........................................................549 DevOutPict() ..................................................... 550 DevPos() ...........................................................551 DirChange() ......................................................552 Directory() ........................................................553 DirectoryRecurse()............................................555 DirRemove() ..................................................... 557 DiskChange() ....................................................558 DiskName()....................................................... 560 DiskSpace() ....................................................... 561 DispBegin() ....................................................... 563 DispBox() ..........................................................565 DispCount()....................................................... 567 DispEnd() ..........................................................568 DispOut() ..........................................................569 DispOutAt()....................................................... 570 DispOutAtSetPos()............................................572 DllCall().............................................................573 DllExecuteCall() ................................................576 DllLoad()...........................................................578 DllPrepareCall() ................................................579 DllUnload() ....................................................... 581 DosError()......................................................... 582 DoW()...............................................................585 DtoC() ...............................................................586 DtoS() ...............................................................587 ElapTime() ........................................................589 Empty().............................................................590 Eof()..................................................................592 ErrorBlock() ......................................................594 ErrorLevel() ....................................................... 597 ErrorNew()........................................................599 ErrorSys()..........................................................601 Eval() ................................................................ 602 Exp() .................................................................604 FCharCount() ....................................................605 FClose().............................................................606 FCount()............................................................608 FCreate()...........................................................609 FErase() ............................................................611 FError() .............................................................612 FieldBlock() ....................................................... 613 FieldDec()..........................................................615 FieldGet()..........................................................616 FieldLen()..........................................................617 FieldName()......................................................618 FieldPos()..........................................................619 FieldPut() ..........................................................620 FieldType()........................................................622 FieldWBlock() ................................................... 623 File()..................................................................625 FileStats() ......................................................... 627 FkLabel()...........................................................629 FkMax() ............................................................630 FLineCount() ..................................................... 631 FLock() ..............................................................632 IV

FOpen() ............................................................ 634 Found().............................................................636 FParse()............................................................ 638 FParseEx() ........................................................ 640 FParseLine()...................................................... 641 FRead().............................................................643 FReadStr() ........................................................ 645 FreeLibrary()..................................................... 647 FRename() ........................................................ 648 FSeek().............................................................. 650 FWordCount() .................................................. 652 FWrite()............................................................ 653 GetCurrentThread().......................................... 655 GetDefaultPrinter() .......................................... 656 GetEnv() ...........................................................657 GetLastError() .................................................. 658 GetNew() .......................................................... 659 GetPrinters()..................................................... 661 GetProcAddress() ............................................. 663 GetRegistry() .................................................... 665 GetSystemThreadID()....................................... 667 GetThreadID() .................................................. 668 HaaDelAt() ....................................................... 670 HaaGetKeyAt() ................................................. 672 HaaGetPos()..................................................... 674 HaaGetRealPos() .............................................. 676 HaaGetValueAt().............................................. 678 HaaSetValueAt() .............................................. 680 HAllocate() ....................................................... 682 HardCR()...........................................................683 Hash()...............................................................684 HB_AExpressions() ........................................... 686 HB_AnsiToOem().............................................. 688 HB_AParams().................................................. 690 HB_ArgC() ........................................................ 691 HB_ArgCheck() ................................................. 692 HB_ArgString() ................................................. 693 HB_ArgV() ........................................................ 694 HB_ArrayId() .................................................... 696 HB_ArrayToStructure()..................................... 697 HB_ATokens()................................................... 699 HB_AtX() .......................................................... 701 HB_BackGroundActive()................................... 703 HB_BackGroundAdd() ......................................704 HB_BackGroundDel() ....................................... 706 HB_BackGroundReset()....................................707 HB_BackGroundRun() ......................................708 HB_BackGroundTime()..................................... 709 HB_BitAnd() ..................................................... 710 HB_BitIsSet() .................................................... 711 HB_BitNot() ...................................................... 713 HB_BitOr() ........................................................ 714 HB_BitReset() ................................................... 715 HB_BitSet()....................................................... 717 HB_BitShift() .................................................... 719 HB_BitXOr() ...................................................... 721

Table of Contents HB_BuildDate() ................................................ 722 HB_BuildInfo() ................................................. 723 HB_CheckSum() ............................................... 725 HB_CmdArgArgV()........................................... 726 HB_Compiler() ................................................. 727 Hb_CRC32()...................................................... 728 HB_Crypt() ....................................................... 729 HB_Decrypt() ................................................... 730 HB_DeSerialize() .............................................. 731 HB_EnumIndex() .............................................. 732 HB_Exec()......................................................... 734 HB_ExecFromArray() ....................................... 736 HB_FNameMerge().......................................... 740 HB_FNameSplit() ............................................. 741 HB_FReadLine() ............................................... 743 HB_FSize() ........................................................ 745 HB_FTempCreate() .......................................... 746 HB_FuncPtr().................................................... 748 HB_GCAll() ....................................................... 749 HB_GCStep() .................................................... 750 HB_IdleAdd().................................................... 751 HB_IdleDel()..................................................... 753 HB_IdleReset() ................................................. 754 HB_IdleSleep() ................................................. 755 HB_IdleSleepMSec()......................................... 756 HB_IdleState().................................................. 757 HB_IsArray() .................................................... 758 HB_IsBlock()..................................................... 759 HB_IsByRef....................................................... 760 HB_IsDate()...................................................... 762 HB_IsHash() ..................................................... 763 HB_IsLogical() .................................................. 764 HB_IsMemo()................................................... 765 HB_IsNIL() ........................................................ 766 HB_IsNull()....................................................... 767 HB_IsNumeric()................................................ 768 HB_IsObject()................................................... 769 HB_IsPointer().................................................. 770 HB_IsRegExString() .......................................... 771 HB_IsString().................................................... 772 HB_KeyPut()..................................................... 773 HB_LangSelect()............................................... 774 HB_LibDo()....................................................... 777 HB_MacroCompile() ........................................ 779 HB_MD5() ........................................................ 780 HB_MD5File() .................................................. 781 HB_MultiThread() ............................................ 782 HB_MutexCreate()........................................... 783 HB_MutexLock() .............................................. 786 HB_MutexTimeoutLock() ................................. 787 HB_MutexTryLock() ......................................... 788 HB_MutexUnlock() .......................................... 789 HB_ObjMsgPtr()............................................... 790 HB_OemToAnsi() ............................................. 792 HB_OsNewLine() .............................................. 793 HB_QSelf() ....................................................... 794

HB_QWith() ......................................................795 HB_Random() ...................................................796 HB_RandomInt()...............................................798 HB_RandomSeed() ...........................................800 HB_ReadIni() ....................................................802 HB_RegEx().......................................................804 HB_RegExAll()...................................................807 HB_RegExComp()..............................................811 HB_RegExMatch() ............................................812 HB_RegExSplit() ................................................814 HB_ResetWith() ................................................816 HB_RestoreBlock()............................................818 HB_SaveBlock() ................................................819 HB_Serialize() ...................................................820 HB_SetCodePage() ...........................................822 HB_SetIniComment() ........................................824 HB_SetMacro() .................................................825 HB_SetWith() ....................................................826 HB_SizeofCStructure() ......................................828 HB_StructureToArray() .....................................830 HB_ThisArray() .................................................832 HB_VMExecute() ..............................................833 HB_VMMode()..................................................834 HB_WithObjectCounter()..................................835 HB_WriteIni()....................................................836 HB_XmlErrorDesc()...........................................838 HClone() ............................................................839 HCopy().............................................................841 HDel() ...............................................................844 HDelAt() ............................................................845 Header() ...........................................................846 HEval() ..............................................................847 HexToNum() .....................................................849 HexToStr().........................................................850 HFill() ................................................................851 HGet() ...............................................................852 HGetAACompatibility() .....................................853 HGetAutoAdd().................................................854 HGetCaseMatch() .............................................855 HGetKeyAt()......................................................857 HGetKeys()........................................................858 HGetPairAt() .....................................................859 HGetPartition() .................................................860 HGetPos() .........................................................861 HGetVaaPos() ...................................................863 HGetValueAt() ..................................................865 HGetValues() ....................................................866 HHasKey() .........................................................867 HMerge() ..........................................................868 HScan() .............................................................869 HSet() ................................................................871 HSetAACompatibility()......................................873 HSetAutoAdd()..................................................875 HSetCaseMatch()..............................................877 HSetPartition()..................................................879 HSetValueAt()...................................................881 V

Table of Contents I2Bin()...............................................................883 If() | IIf()............................................................885 IndexExt() ......................................................... 887 IndexKey()......................................................... 888 IndexOrd() ........................................................890 Inkey()...............................................................891 Int()...................................................................893 IsAlNum()..........................................................894 IsAlpha() ...........................................................895 IsAscii() .............................................................896 IsCntrl().............................................................897 IsColor() ............................................................898 IsDigit().............................................................899 IsDirectory()......................................................900 IsDisk()..............................................................901 IsGraph()...........................................................903 IsLower()...........................................................904 IsPrint().............................................................905 IsPrinter()..........................................................906 IsPunct() ...........................................................908 IsSameThread() ................................................909 IsSpace()...........................................................911 IsUpper()...........................................................912 IsValidThread() ................................................. 913 IsXDigit()...........................................................915 JoinThread()......................................................916 KillAllThreads() ................................................. 918 KillThread() ....................................................... 919 L2bin() ..............................................................920 LastKey()...........................................................922 LastRec()...........................................................924 Left().................................................................925 Len() .................................................................926 LenNum()..........................................................928 LibFree() ...........................................................929 LibLoad()...........................................................930 LoadLibrary() ....................................................931 Log() .................................................................933 Lower() .............................................................934 LTrim() ..............................................................935 LUpdate()..........................................................936 MakeDir() ......................................................... 937 Max()................................................................ 939 MaxCol()...........................................................940 MaxRow()......................................................... 941 MCol()...............................................................942 MDblClk() ......................................................... 943 MemoEdit() ......................................................944 MemoLine() ......................................................951 MemoRead() ....................................................954 Memory() ......................................................... 955 MemoTran() ..................................................... 957 MemoWrit() ..................................................... 958 MemVarBlock() ................................................959 MenuModal() ................................................... 960 MHide() ............................................................962 VI

Min() ................................................................ 963 MLCount() ........................................................ 964 MLCToPos() ...................................................... 966 MLeftDown() .................................................... 968 MlPos() .............................................................969 Mod() ...............................................................971 Month()............................................................ 972 MPosToLC() ...................................................... 973 MPresent() ....................................................... 975 MRestState() .................................................... 976 MRightDown().................................................. 977 MRow() ............................................................ 978 MSaveState().................................................... 979 MSetBounds()................................................... 980 MSetCursor() .................................................... 981 MSetPos()......................................................... 982 MShow()...........................................................983 NetErr() ............................................................ 984 NetName() ....................................................... 986 NextKey().......................................................... 987 Notify() .............................................................989 NotifyAll()......................................................... 990 NumButtons()................................................... 992 NumToHex() ..................................................... 993 OrdBagExt()...................................................... 994 OrdBagName()................................................. 995 OrdCondSet().................................................... 997 OrdCount() ..................................................... 1000 OrdCreate() .................................................... 1002 OrdCustom()................................................... 1004 OrdDescend() ................................................. 1005 OrdDestroy() .................................................. 1007 OrdFindRec() .................................................. 1008 OrdFor().......................................................... 1010 OrdIsUnique()................................................. 1011 OrdKey() ......................................................... 1012 OrdKeyAdd()................................................... 1014 OrdKeyCount()................................................ 1016 OrdKeyDel() .................................................... 1018 OrdKeyGoTo()................................................. 1020 OrdKeyNo() .................................................... 1022 OrdKeyRelPos() .............................................. 1024 OrdKeyVal() .................................................... 1026 OrdListAdd() ................................................... 1027 OrdListClear() ................................................. 1029 OrdListRebuild() ............................................. 1030 OrdName() ..................................................... 1031 OrdNumber() .................................................. 1033 OrdScope() ..................................................... 1035 OrdSetFocus()................................................. 1037 OrdSetRelation() ............................................ 1039 OrdSkipRaw() ................................................. 1040 OrdSkipUnique()............................................. 1042 OrdWildSeek() ................................................ 1044 Os()................................................................. 1046 Os_IsWin2000().............................................. 1047

Table of Contents Os_IsWin2000_Or_Later() ............................. 1048 Os_IsWin2003() ............................................. 1049 Os_IsWin95() ................................................. 1050 Os_IsWin98() ................................................. 1051 Os_IsWin9X() ................................................. 1052 Os_IsWinME() ................................................ 1053 Os_IsWinNT()................................................. 1054 Os_IsWinNT351()........................................... 1055 Os_IsWinNT4()............................................... 1056 Os_IsWinVista() ............................................. 1057 Os_IsWinXP() ................................................. 1058 Os_IsWtsClient() ............................................ 1059 Os_VersionInfo() ............................................ 1060 OutErr() .......................................................... 1062 OutStd() ......................................................... 1063 PadC() | PadL() | PadR() ................................ 1064 PCol() ............................................................. 1066 PCount()......................................................... 1068 PrinterExists()................................................. 1069 PrinterPortToName() ..................................... 1070 PrintFileRaw() ................................................ 1071 ProcFile() ........................................................ 1073 ProcLine()....................................................... 1074 ProcName().................................................... 1075 PRow() ........................................................... 1076 PValue() ......................................................... 1078 QOut() | QQOut()........................................... 1079 QueryRegistry().............................................. 1081 RAscan()......................................................... 1084 RAt()............................................................... 1086 RddInfo() ........................................................ 1088 RddList()......................................................... 1091 RddName()..................................................... 1093 RddSetDefault() ............................................. 1094 ReadModal() .................................................. 1096 RecCount() ..................................................... 1098 RecNo() .......................................................... 1099 RecSize()......................................................... 1100 Replicate()...................................................... 1101 RestScreen()................................................... 1102 Right()............................................................ 1104 RLock() ........................................................... 1105 Round() .......................................................... 1107 Row() ............................................................. 1109 RTrim() ........................................................... 1110 SaveScreen() .................................................. 1112 Scroll()............................................................ 1114 Seconds() ....................................................... 1116 SecondsSleep()............................................... 1117 Secs().............................................................. 1118 Select()........................................................... 1119 Set() ............................................................... 1120 SetBlink()........................................................ 1127 SetCancel()..................................................... 1128 SetColor() ....................................................... 1130 SetCursor() ..................................................... 1132

SetErrorMode()...............................................1134 SetKey() ..........................................................1135 SetLastError()..................................................1138 SetMode().......................................................1139 SetMouse() .....................................................1141 SetPos()...........................................................1142 SetPrc() ...........................................................1143 SetRegistry() ...................................................1145 SoundEx()........................................................1147 Space() ............................................................1148 Sqrt()...............................................................1149 StartThread() ..................................................1150 StoD()..............................................................1153 StopThread()...................................................1154 Str().................................................................1155 StrToHex().......................................................1157 StrTran() .........................................................1158 StrZero()..........................................................1160 Stuff()..............................................................1162 Subscribe() ......................................................1164 SubscribeNow() ..............................................1166 SubStr()...........................................................1167 TBMouse() ......................................................1169 TBrowseDB()...................................................1170 TBrowseNew() ................................................1172 ThreadSleep() .................................................1173 Throw() ...........................................................1174 Time() .............................................................1175 Tone() .............................................................1176 TraceLog().......................................................1177 Transform() ....................................................1178 Trim() ..............................................................1180 TString() ..........................................................1182 Type()..............................................................1183 U2bin()............................................................1185 Upper() ...........................................................1187 Used() .............................................................1188 Val()................................................................1189 ValToPrg().......................................................1191 ValToPrgExp().................................................1193 Valtype() .........................................................1195 Version() .........................................................1197 W2bin()...........................................................1198 WaitForThreads() ...........................................1199 WildMatch() ...................................................1200 Word() ............................................................1202 Year() ..............................................................1203 CLASS REFERENCE (TEXTMODE) ...........................1204 C Structure class .............................................1205 Error() .............................................................1211 Get() ...............................................................1219 HBObject() ......................................................1237 HBPersistent().................................................1243 MenuItem() ....................................................1246 Popup() ...........................................................1250 VII

Table of Contents TBColumn()..................................................... 1260 TBrowse() ....................................................... 1265 TopBarMenu() ................................................1288 TXmlDocument() ............................................1299 TXmlIterator()................................................. 1309 TXmlIteratorRegEx() ....................................... 1312 TXmlIteratorScan() ......................................... 1315 TXmlNode() ....................................................1318 PREPROCESSOR REFERENCE ................................ 1330 #command | #translate .................................1331 #define............................................................1338 #error .............................................................1341 #if ...................................................................1342 #ifdef .............................................................. 1344 #ifndef ............................................................1346 #include ..........................................................1347 #pragma......................................................... 1349 #stdout ...........................................................1351 #uncommand | #untranslate ......................... 1352 #undef ............................................................1353 #xcommand | #xtranslate.............................. 1354 #xuncommand | #xuntranslate......................1355 NOT INCLUDED IN THIS EDITION .......................... 1356 U NDOCUMENTED FUNCTIONS ....................................1357 U NDOCUMENTED CGI FUNCTIONS .............................1358 U NDOCUMENTED CT FUNCTIONS ...............................1359 U NDOCUMENTED M ISC F UNCTIONS ............................1361 U NDOCUMENTED RDD F UNCTIONS ............................1362 U NDOCUMENTED RTL F UNCTIONS .............................1363 U NDOCUMENTED TIP F UNCTIONS .............................. 1365 U NDOCUMENTED VM F UNCTIONS .............................1366 CATEGORIES ........................................................ 1367 Array functions ............................................... 1367 Assignment operators ....................................1367 Associative arrays........................................... 1367 Background processing ..................................1367 Binary functions ............................................. 1368 Bitwise functions ............................................1368 Bitwise operators ........................................... 1368 Blob functions................................................. 1368 C Structure support ........................................1369 Character functions........................................1369 Character operators ....................................... 1370 Checksum functions........................................1370 Class declaration ............................................1370 Code block functions ......................................1371 Comparison operators....................................1371 Console commands ........................................1371 Control structures........................................... 1371 Conversion functions......................................1372 Database commands......................................1373 Database drivers ............................................1374 VIII

Database functions ........................................ 1374 Date and time ................................................ 1376 Debug functions............................................. 1376 Declaration..................................................... 1377 Directory functions......................................... 1378 DLL functions.................................................. 1378 Environment commands ................................ 1378 Environment functions................................... 1379 Error functions ............................................... 1379 Field functions ................................................ 1380 File commands ............................................... 1380 File functions .................................................. 1380 Get system ..................................................... 1381 Hash functions ............................................... 1381 Index commands ............................................ 1382 Index functions............................................... 1382 Indirect execution........................................... 1383 Info functions ................................................. 1383 Input commands ............................................ 1383 Keyboard functions ........................................ 1384 Language specific........................................... 1384 Logical functions ............................................ 1384 Logical operators ........................................... 1384 Low level file functions................................... 1384 Mathematical functions................................. 1385 Mathematical operators ................................ 1385 Memo functions............................................. 1385 Memory commands....................................... 1385 Mouse functions............................................. 1385 Multi-threading functions.............................. 1386 Mutex functions ............................................. 1386 Network functions.......................................... 1387 Numeric functions .......................................... 1387 Object functions............................................. 1387 Operators ....................................................... 1388 Output commands ......................................... 1388 Output functions ............................................ 1389 Pointer functions ............................................ 1389 Preprocessor directives ..................................1389 Printer commands.......................................... 1389 Printer functions............................................. 1390 Random generator......................................... 1390 Registry functions .......................................... 1390 Regular expressions ....................................... 1390 Screen functions............................................. 1390 SET commands............................................... 1391 Special operators ........................................... 1392 Statements..................................................... 1392 UI functions .................................................... 1392 xHarbour extensions ......................................1393 INDEX ...................................................................1399

Operator Reference

Operator Reference

9

$

$ Substring operator (binary): search substring in string.

Syntax $ $

Arguments

is a character value that is searched for in .

is a character value where is searched in.

is the expression of any type to search.

is the array to scan for a matching in.

Description The substring operator performs a case-sensitive search and returns .T. (true) when is found in , otherwise the result is .F. (false). The $ operator can also be used to search for a given value within any Array.

Info See also: Category: DLL:

=, IN, HAS, LIKE Character operators, Comparison operators, Operators xhbdll.dll

Example // The example demonstrates a case-sensitive search. PROCEDURE Main() LOCAL cString := "xHarbour" ? "X" $ cString ? "arb" $ cString ? 1 $ { 3, 2, 1 } RETURN

10

// result: .F. // result: .T. // result: .T.

Operator Reference

%

% Modulus operator (binary): calculates the remainder of a division.

Syntax %

Arguments

is the dividend of the division.

is the divisor of the division.

Description The modulus operator returns the remainder of dividing by .

Info See also: Category: LIB: DLL:

*, **, +, -, /, = (compound assignment), SET FIXED Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example calculates the remainder of a division // between two numbers. PROCEDURE Main ? 5 % 0 ? 3 % 2 ? -2 % 3 ? 4 % 2 ? 5.4 % 2.3 RETURN

Operator Reference

// // // //

result: 0 result: 1 result: -2 result: 0

// result: 0.8

11

& (bitwise AND)

& (bitwise AND) Bitwise AND operator (binary): performs a logical AND operation.

Syntax & | --> cCharacter & | --> nNumeric

Arguments

A character expression of which all bits of each character are processed in a logical AND operation.

A numeric value all bits of which are processed. Numbers are always treated as integer values. If a number has a decimal fraction, it is truncated. |

The right operand of the bitwise AND operator can be specified as a character or a numeric value.

Description The bitwise AND operator performs a logical AND operation with the individual bits of both operands. The left operand is the value to process while the right operand provides the bit mask for the operation. The return value of the &-operator has the same data type as the left operand. Bits at identical positions in both operands are compared. The bit at the same position is set in the return value, when both operands have the bit set at the same position. If either operand has a bit not set, the corresponding bit in the return value is also not set. The bit mask to apply to the left operand can be specified as a numeric or as a character value. Depending on the left operand, bitwise AND operations are performed according to the following rules:

cString & cMask When both operands are character values, the bits of individual characters of both operands are compared. If the right operand has less characters, it is repeatedly applied until all characters of the left operand are processed. The return value has the same number of characters as the left operand.

cString & nMask When the left operand is a character value and the right operand is numeric, the bits set in the numeric value are compared with the bits of each character in the left operand.

nNumber & cMask When the left operand is numeric and the right operand is a character value, the bits set in the numeric value are compared consecutively with the bits of each character in the right operand.

12

Operator Reference

& (bitwise AND)

nNumber & nMask When both operands are numeric values, the bits of both values are compared. Note: Numeric operands are always treated as integer values. If a number has a decimal fraction, it is ignored.

Info See also: Category: LIB: DLL:

^^ (bitwise XOR), | (bitwise OR), .AND., .NOT., .OR. Bitwise operators, Operators, xHarbour extensions xhb.lib xhbdll.dll

Example // The example demonstrates bitwise AND operations using // operands of different data types. #define #define #define #define

STAT_OFF STAT_INIT STAT_IDLE STAT_ON

0 1 2 4

PROCEDURE Main LOCAL nStatus := STAT_INIT + STAT_IDLE ? 2 & 3

// result: 2

? "A" & 64

// result: "@"

? 64 & "A"

// result: 64

? "Z" & "A"

// result: "@"

? nStatus & STAT_IDLE

// result: 2

? nStatus & STAT_ON

// result: 0

? "One" & "Two" RETURN

Operator Reference

// result: "Dfe"

13

& (macro operator)

& (macro operator) Macro operator (unary): compiles a character string at runtime.

Syntax a) & b) "Text &. substitution" c) & d) :& [:= ] :&([]) e) &([])

Arguments

This is a character string indicating the name of a variable whose symbolic name is known at runtime. This applies to variables of type PRIVATE, PUBLIC or FIELD.

A character string holding a valid xHarbour expression to compile at runtime.

This is a variable holding a reference to an object value (Valtype() == "O") to which a message is sent.

A character string indicating the name of an instance variable of the object. If no assignment operator is used in the expression, the value of the instance variable is retrieved by the macro operator. Otherwise, the value is assigned to the instance variable.

A character string indicating the name of a method of the object to execute. Calling a method with the macro operator requires the parentheses () be added to the expression. Optionally, a list of parameters can be specified within the parentheses. The list of is passed to the method.

A character string indicating the name of a function or procedure to execute. Calling a function with the macro operator requires the parentheses () be added to the expression. Optionally, a list of parameters can be specified within the parentheses. The list of is passed to the function or procedure.

Description One extremely powerful feature of xHarbour is the Macro operator (&). It allows for compiling and executing program code at runtime of an application. The program code is supplied in form of a character string and can be as simple as a variable name or may include very complex expressions. 14

Operator Reference

& (macro operator)

Despite its power, there are some limitations a programmer must be aware of when using the Macro operator. As a first rule, no white space characters may follow the macro operator. This is required to distinguish the & sign from the bitwise AND operator. The macro expression must follow the & operator immediately. All entities that do not have a symbolic name at runtime of an application cannot be accessed by the Macro operator. This applies to memory variables of type GLOBAL, LOCAL and STATIC, to STATIC declared functions and procedures, as well as commands and statements. Also, the Macro operator cannot resolve multiple line expressions, it can only compile expressions programmed within one line of code. As indicated in the syntax description, there are some typical scenarios where the Macro operator is used. Examples for these scenarios follow: a)

Acessing and creating variables The values of PRIVATE, PUBLIC and FIELD variables can be retrieved by using a character string indicating the symbolic name of a variable. LOCAL LOCAL LOCAL LOCAL

cPrivate := "myPrivate" cPublic := "myPublic" cField := "LastName" x, y, z

PUBLIC myPublic := "A public variable" PRIVATE myPrivate := 10 USE Customer x := &cPrivate y := &cPublic z := &cField ? x, y, z // result: 10 A public variable Miller

The macro operator is used in this example as the right-hand-side expression of the assignments. As a result, the values of the variables whose names are stored in LOCAL variables are retrieved and assigned to the LOCAL variables x, y and z. When the macro operator is used on the left-hand-side of an assignment, a value is assigned to the corresponding variable. If the variable does not exist prior to the assignment, it is created as a PRIVATE variable: LOCAL cPrivate := "myPrivate" LOCAL cPublic := "myPublic" LOCAL cField := "LastName" PUBLIC

myPublic

:= "A public variable"

USE Customer &cPrivate := 10

// creates a PRIVATE variable // named myPrivate

&cPublic := "New text" FIELD->&cField := "McBride" ? &cPrivate, &cPublic, &cField // result: 10 New text McBride

Operator Reference

15

& (macro operator)

Note that PUBLIC variables cannot be created using this technique while field variables must be aliased to assign a value. b)

Text substitution Text substitution is a special situation where the macro operator appears within a character string. LOCAL cText PRIVATE cMacro := "xHarbour" cText := "This is a &cMacro. test." ? cText // result: This is a xHarbour test." cMacro := CDoW(Date()) cText := "Today is &cMacro.!" ? cText // result: Today is Tuesday!"

When a character string contains a macro variable, the macro is substituted with the contents of the macro variable. Note that the end of the macro variable within the text string is indicated with a period. This period does not appear in the result string but serves as "end-of-macro" marker. c)

Runtime compilation The most common situation for using the Macro operator is the compilation of expressions at runtime. Expressions must be syntactically correct and may only refer to entities whose symbolic names are known at runtime. If, for example, a function is called only within a Macro expression and nowhere else in the program code, the function symbol must be declared with the REQUEST statement so that it is linked to the executable file. PROCEDURE Main REQUEST CDoW, Date LOCAL cExpr := "CDoW(Date())" ? &cExpr // result: Tuesday RETURN

The creation of code blocks as complex data types is also a very common usage scenario for the Macro operator. PROCEDURE Main LOCAL i, cExpr, cFPos REQUEST FieldGet, FieldPut USE Customer aBlocks := Array( FCount() ) FOR i:=1 TO FCount() cFPos := LTrim( Str(i) ) cExpr := "{|x| IIf(x==NIL,FieldGet(" + cFPos + ")," + ; "FieldPut(" + cFPos + ",x)) }" aBlocks[i] := &cExpr NEXT AEval( aBlocks, {|b| QOut(Eval(b)) } ) USE RETURN

16

Operator Reference

& (macro operator)

Within the FOR..NEXT loop, the syntax for code blocks accessing different field variables is created as character strings. Each string differs by the value of the loop counter variable which identifies individual field variables by theri ordinal position. The character strings are compiled to code blocks and stored in an array. d)

Sending messages to objects The possibility of sending messages to objects is another field of Macro operator usage that allows for highly dynmic application development. Messages are encoded as character strings: #include "hbclass.ch" PROCEDURE Main LOCAL obj := TestClass():new( "Text to display" ) LOCAL cMsg := "display" obj:&cMsg()

// displays: Text to display

cMsg := "cValue" obj:&cMsg := "New text" obj:display() RETURN

// displays: New text

CLASS TestClass EXPORTED: DATA cValue METHOD new( cString ) CONSTRUCTOR METHOD display ENDCLASS METHOD new( cString ) CLASS TestClass ::cValue := cString RETURN self METHOD display() CLASS TestClass ? ::cValue RETURN self

When the send operator (:) is followed by the Macro operator, the contents of the variable following the Macro operator is interpreted as message to send to the object. Note that calling an object's method requires the parentheses be added to the expression. e)

Calling functions There are two possibilities for calling functions using the macro operator: one is to encode a complete function call as a macro expression, the other is to use only the function name. The difference between both possibilities lies in the type of variables that can be passed to a Macro operator called function. PROCEDURE Main LOCAL cMacro LOCAL nValue := 2 PRIVATE nNumber := 3 cMacro := "TestFunc( nNumber )"

// result: 30

? &cMacro cMacro := "TestFunc"

Operator Reference

17

& (macro operator) ? &cMacro( nValue ) RETURN

// result: 20

FUNCTION TestFunc( n ) RETURN 10 * n

When the macro expression includes parentheses for the function call, only PRIVATE, PUBLIC or FIELD variables can be passed as parameters, since the variable names appear in the macro string. LOCAL variables, in contrast, can be passed when the parentheses are "hard coded", i.e. the macro string contains only the name of the function to call.

Info See also: Category: LIB: DLL:

18

@(), ( ), {|| }, HB_MacroCompile(), HB_SetMacro() Indirect execution, Special operators, Operators xhb.lib xhbdll.dll

Operator Reference

()

() Execution or grouping operator.

Syntax () ([]) :([])

Arguments

One or more expressions to execute, separated with commas.

This is the symbolic name of a function, method or procedure to execute.

An optional comma separated list of parameters to pass to the called function, method or procedure

This is a variable holding a reference to an object value (Valtype() == "O") that should execute a method.

Description Parentheses are used to execute functions, procedures or methods, and to group expressions and define their order of execution. When using the parentheses as a grouping operator, all items appearing inside the parentheses must be valid expressions. The grouping operator can be nested to any depth. The nesting level influences execution order of expressions, i.e. expressions on a deeper nesting level are evaluated first while expressions with the same nesting level are evaluated from left to right. When the parantheses are used as execution operator, expressions between the parentheses are passed as arguments to the called function, method or procedure. Multiple expressions must be separated with commas. When no expression appears within the parentheses, no argument is passed.

Info See also: Category: LIB: DLL:

& (macro operator) Special operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates different scenarios for using // the () operator. PROCEDURE Main LOCAL x

Operator Reference

19

() // changing precedence of operations ? 5 + 2 * 2 // result: ? (5 + 2)* 2 // result: ? 5 + 2 * 2 - 1 // result: ? 5 +(2 *(2 - 1)) // result: x := "

xHarbour

"

// one function call ? AllTrim( x ) // list of function calls ? ( x := Date(), CDow(x) ) RETURN

20

9 14 8 7

// result: "xHarbour"

// result: "Wednesday"

Operator Reference

*

* Multiplication operator (binary): multiplys numeric values.

Syntax *

Arguments

is numeric expression to multiply with .

is numeric expression to multiply with .

Description This operator multiplies the value of with the value of and returns the result.

Info See also: Category: LIB: DLL:

%, **, +, -, /, = (compound assignment), SET DECIMALS, SET FIXED Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example shows the behavior of the "*" operand in different // situations. PROCEDURE Main ? 3 * 1 ? 3 * -1 ? -4 * -2 RETURN

Operator Reference

// result: 3 // result: -1 // result: 8

21

**

** Exponentiation (binary): raises a number to the power of an exponent.

Syntax ** ^

Arguments

is numeric value to raise to the power defined by .

is the power to raise .

Description This operator is a binary operator that raises to the power of .

Info See also: Category: LIB: DLL:

%, *, +, -, /, = (compound assignment), SET DECIMALS, SET FIXED Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example shows some results of the "**" operator. PROCEDURE Main ? 5 ** 0 ? 5 ** 1 ? 5 ** 2 ? 5 ** -2 ? -5 ** 2 ? 5 ^ 0 ? 5 ^ 1 ? 5 ^ 2 ? 5 ^ -2 ? -5 ^ 2 RETURN

22

// // // // //

result: result: result: result: result:

1.00 5.00 25.00 0.04 25.00

// // // // //

result: result: result: result: result:

1.00 5.00 25.00 0.04 25.00

Operator Reference

+

+ Plus operator: add values, concatenate values and unary positive.

Syntax + + + +

Arguments

is a numeric value to which the value of is added.

is a date value to which days are added.

is a character string to concatenate with .

Description Depending on the data types of the operands, the Plus operator performs different operations.

Unary positive sign A numeric expression preceeded by the "+" operator performs no operation on the operand.

Numeric addition When both operands are numeric values, the right operand is added to the left operand and the result is a numeric value.

Date addition When eigher operand is a date value and the other is a numeric, the value of is added as days to . The returned value is a date.

String concatenation If both operands are character strings, the value of is joined to the end of . The result is a character string containing both operands.

Hash operation If both operands are hashes, a set-oriented operation is performed so that the resulting hash value contains unique keys of both operands (refer to the hash operator ).

Operator Reference

23

+

Info See also: Category: LIB: DLL:

%, *, **, ++, -, /, = (compound assignment), {=>} Character operators, Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates variations with the + operator: PROCEDURE Main // Unary positive sign (also included is the ? 1 + + 1 // result: ? 1 + - 1 // result: ? 1 -- 1 // result: // Addition ? 10 + 2 ? CtoD("01/01/2005") + 5 ? 31 + CtoD("01/01/2005") // String concatenation ? "Visit" + " " + "xHarbour.com" RETURN

24

negative sign) 2 0 2

// result: 12 // result: 01/06/2005 // result: 02/01/2005

// result: "Visit xHarbour.com"

Operator Reference

++

++ Increment operator (unary): prefix / postfix increment.

Syntax ++ ++

Arguments

is the name of a memory or field variable of Numeric or Date data type. When is a field variable, it must be specified with an alias name or must be declared as field variable using the FIELD statement.

Description The increment operator increases the value of its operand by one. When used in an expression, the position of the operator is important for the result of the expression. When the operator appears to the left of the operand (prefix notation), the operand's value is first incremented and then used in the expression. When the operator appears to the right of the operand (postfix notation), the operand's value is first used in the expression and then incremented.

Info See also: Category: LIB: DLL:

+, --, :=, = (compound assignment) Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates the use of the ++ operator and // outlines the importance of prefix and postfix notation. PROCEDURE Main LOCAL nValue1 := 0 LOCAL nValue2 ? nValue1 ++ ? nValue1

// result: 0 // result: 1

? ++ nValue1 ? nValue1

// result: 2 // result: 2

nValue2 := ++ nValue1 ? nValue1 ? nvalue2

// result: 3 // result: 3

nValue2 := nValue1 ++ ? nValue1 ? nvalue2 RETURN

Operator Reference

// result: 4 // result: 3

25

-

Minus operator: add values, concatenate values and unary negative.

Syntax - - - - -

Arguments

is a numeric value from which the value of is subtracted.

is a date value from which the date value is subtracted.

is a date value from which days are subtracted.

is a character string to add to the end of after all trailing blanks from are removed.

Description Depending on the data types of the operands, the Minus operator performs the following operations:

Unary negative sign when the Minus operator precedes a numeric operand, it performs the equivalent of multiplying the operand by -1. This changes the operand's sign from plus to minus and vice versa.

Numeric subtraction When both operands are numeric values, the right operand is subtracted from the left operand and the result is a numeric value.

Date subtraction When the left operand is a date value and the right operand is a numeric, the value of is subtracted as number of days from . The returned value is a date. When both operands are of Date data type, the operator calculates the difference in days between left and right operand and returns a numeric value. When the left operand is a Numeric value and the right operand is a Date, a runtime error is raised sine this is not allowed.

26

Operator Reference

-

String concatenation If both operands are character data types, the value of is joined to , returning a character string. Trailing blanks in are removed and appended to the end of the result string.

Hash operation If both operands are hashes, a set-oriented operation is performed so that the resulting hash value contains unique keys of the left operand which are not contained in the right operand (refer to the hash operator ).

Info See also: Category: LIB: DLL:

%, *, **, +, --, /, = (compound assignment) Character operators, Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates variations with the - operator: PROCEDURE Main // Unary negative sign (also included is the positive sign) ? 1 - -1 // result: 2 ? 1 + -1 // result: 0 ? 1 + + 1 // result: 2 // Subtraction ? CtoD("01/20/2005") - 5 ? 10 - 2 // String concatenation ? "A " + "B " + "C " ? "A " - "B " - "C " RETURN

Operator Reference

// result: 01/15/2005 // result: 8

// result: "A B C " // result: "ABC "

27

--

-Decrement operator (unary): Prefix / postfix decrement

Syntax -- --

Arguments

is the name of a memory or field variable of Numeric or Date data type. When is a field variable, it must be specified with an alias name or must be declared as field variable using the FIELD statement.

Description The decrement operator decreases the value of its operand by one. When used in an expression, the position of the operator is important for the result of the expression. When the operator appears to the left of the operand (prefix notation), the operand's value is first decremented and then used in the expression. When the operator appears to the right of the operand (postfix notation), the operand's value is first used in the expression and then decremented.

Info See also: Category: LIB: DLL:

++, -, :=, = (compound assignment) Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates the use of the -- operator and // outlines the importance of prefix and postfix notation. PROCEDURE Main LOCAL nValue1 := 0 LOCAL nValue2 ? nValue1 -? nValue1

// result: 0 // result: -1

? -- nValue1 ? nValue1

// result: -2 // result: -2

nValue2 := -- nValue1 ? nValue1 ? nvalue2

// result: -3 // result: -3

nValue2 := nValue1 -? nValue1 ? nvalue2 RETURN

28

// result: -4 // result: -3

Operator Reference

->

-> Alias operator (binary): identifies a work area.

Syntax -> () -> -> ( ) () -> ( ) FIELD -> MEMVAR ->

Arguments

This is the symbolic alias name of a work area as specified with the ALIAS option of the USE command.

The field name whose value is retrieved from the work area specified with .

Instead of using a symbolic name, a work area can be identified by its numeric ordinal position . This value can be obtained by calling the Select() function. The numeric work area must be enclosed in parentheses () when using it with the alias operator.

One or more comma separated expressions to execute in the work area identified with or . FIELD

The FIELD keyword is a reserved alias name that identifies a field variable in the current work area. MEMVAR

The MEMVAR keyword is a reserved alias name that identifies a memory variable of type PRIVATE or PUBLIC. An abbreviation of this alias is M->.

Description The alias operator "points" to an unselected work area identified with its symbolic name or its ordinal number . This allows for retrieving values of field variables from unselected work areas or executing expressions in the specified work area. The alias operator implicitly selects the work area specified with the left operand and then executes the instructions of the right operand. When the operation is complete, the original work area becomes current again. FIELD and MEMVAR are reserved alias names that allow for resolving name conflicts between memory and field variables. If memory and field variables with the same symbolic name exist, unaliased variables are resolved as field variables. This behaviour is influenced by the compiler switch Operator Reference

29

->

/v. It is, however, strongly recommended to avoid identical variable names for memory and field vraiables, and to use the alias operator to identify a variable unambiguously.

Info See also: Category: LIB: DLL:

DbSelectArea(), FIELD, FieldName(), FieldPos(), FieldGet(), MEMVAR, Select(), USE Special operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates usage of the alias operator. // The last aliased expression generates a runtime error. PROCEDURE Main LOCAL nArea USE Customer ALIAS Cust ? FIELD->Lastname

// current work area // result: Miller

nArea := Select() SELECT 100 ? Used()

// work area number // select free work area // result: .F.

? Cust->Lastname ? Cust->(Recno())

// result: Miller // result: 1

? (nArea)->Lastname ? (nArea)->(LastRec())

// result: Miller // result: 1576

? FIELD->Lastname USE RETURN

30

// runtime error

Operator Reference

.AND.

.AND. Logical AND operator (binary).

Syntax .AND.

Arguments

and are logical expressions to AND.

Description The logical .AND. operator yields the result of a logical AND operation with left and right operand. The result is only .T. (true) when the value of both operands is also .T. (true), in all other cases the result is .F. (false). When multiple .AND. operators appear in an expression, the result is already determined when one operand has the value .F. (false). In this case, remaining .AND. operators are not evaluated for optimization reasons. This so called shortcut optimization can be switched off using the compiler switch /z.

Info See also: Category: LIB: DLL:

& (bitwise AND), .OR., .NOT. Logical operators, Operators xhb.lib xhbdll.dll

Example // This example shows results of .AND. operations // using different operands: PROCEDURE Main ? .T. .AND. ? .T. .AND. ? .F. .AND. ? .F. .AND. RETURN

Operator Reference

.T. .F. .T. .F.

// // // //

result: result: result: result:

.T. .F. .F. .F.

31

.NOT.

.NOT. Logical NOT operator (unary).

Syntax ! .NOT.

Arguments

is a logical expression to logically negate.

Description The .NOT. operator (alternatively "!" as an abbreviation) is a unary logical operator that negates the value of its operand. This yields the logical inverse of .

Info See also: Category: LIB: DLL:

.AND., .OR. Logical operators, Operators xhb.lib xhbdll.dll

Example // The example shows the logical inverse of the operands: PROCEDURE Main ? .NOT. (.T.) ? .NOT. (.F.) ? ! 1 > 2 RETURN

32

// result: .F. // result: .T. // result: .T.

Operator Reference

.OR.

.OR. Logical OR operator (binary).

Syntax .OR.

Arguments

and are logical expressions.

Description The logical .OR. operator yields the result of a logical OR operation with left and right operand. The result is only .T. (true) when the value of one operand is also .T. (true), in all other cases the result is .F. (false). When multiple .OR. operators appear in an expression, the result is already determined when one operand has the value .T. (true). In this case, remaining .OR. operators are not evaluated for optimization reasons. This so called shortcut optimization can be switched off using the compiler switch /z.

Info See also: Category: LIB: DLL:

.AND., .NOT., | (bitwise OR) Logical operators, Operators xhb.lib xhbdll.dll

Example // This example shows results of .OR. operations // using different operands: PROCEDURE Main ? .T. .OR. .T. ? .T. .OR. .F. ? .F. .OR. .T. ? .F. .OR. .F. RETURN

Operator Reference

// // // //

result: result: result: result:

.T. .T. .T. .F.

33

/

/ Division operator (binary): divides numeric values.

Syntax /

Arguments

is the dividend.

is the divisor.

Description This operator returns the division of by as a numeric value.

Info See also: Category: LIB: DLL:

% Mathematical operators, Operators xhb.lib xhbdll.dll

Example // The example shows the use of the "/" operator: PROCEDURE Main ? 3 / 3 ? 3 /-2 ? -3 / 2 ? -3 /-2 ? 3 / 0 RETURN

34

// // // // //

result: result: result: result: result:

1 -1.50 -1.50 1.50 0

Operator Reference

:

: Send operator (unary): sends a message to an object.

Syntax :[ ( [] ) ]

Arguments

is a variable holding an object to which the message is sent.

is the name of an instance variable or method. When a method is called on the object, the message name must be followed with parentheses.

is an optional comma separated list of parameters passed to a method.

Description A class defines instance variables and methods for its objects. Accessing an object's instance variable or executing one of its methods requires the object to receive a corresponding message. This is the task of the Send operator (:). To access an instance variable, the message is sent without following parentheses. As a result, the object returns the value of the instance variable that corresponds to the message. Methods, in contrast, are invoked by adding parentheses to the message and passing an optional list of parameters to the method. Parameters are listed inside the parentheses. The double send operator :: has a special meaning within the context of the program code of methods. It is an abbreviation for self:, i.e. :: sends messages to the object that executes a method. Note that only messages are understood by an object that are declared in the object's class. In addition, only those instance variables and methods are accessible that are visible in the current program context. If either an instance variable/method is not declared or currently not visible, the message is not understood by the object and a runtime error is generated.

Info See also: Category: Header: LIB: DLL:

CLASS, DATA, METHOD (Implementation) Special operators, Operators hbclass.ch xhb.lib xhbdll.dll

Example // The example demonstrates the use of the single and // double send operator. Note that the double send operator // is only used within the program code of a method. #include "hbclass.ch"

Operator Reference

35

: PROCEDURE Main LOCAL obj := MyClass():new( "Hello World" ) obj:display()

// shows: Hello World

obj:value := "Hi there" obj:display() RETURN

// shows: Hi there

CLASS MyClass EXPORTED: DATA value METHOD new( cString ) CONSTRUCTOR METHOD display ENDCLASS METHOD new( cString ) CLASS MyClass ::value := cString RETURN self METHOD display CLASS MyClass ? ::value RETURN self

36

Operator Reference

:=

:= Inline assignment to a variable.

Syntax :=

Arguments

is the name of a variable of any type.

is any valid expression whose result is assigned to .

Description The := operator assigns the value of to a variable. It is the preferred assignment operator since it can be used to initialize variables within their declaration statements. This is not permitted with the simple assignment operator "=". If the variable does not exist when the assignment operation is processed, a PRIVATE variable is automatically created and gets assigned the value of .

Info See also: Category: LIB: DLL:

++, --, = (assignment), = (compound assignment) Assignment operators xhb.lib xhbdll.dll

Example // The example demonstrates the use of the inline assignment // operator in various situations: PROCEDURE Main LOCAL dDate := StoD("20050701") // initializes variables LOCAL nMonth := Month( dDate ) // in declaration statement nDay := 12 nYear := nPreviousYear := 2000

// creates // PRIVATE variables

// assignment within expression IF (nMonth := Month(dDate)) == 7 ? "July" ENDIF ? nMonth // result: 7 // note the removed parentheses and // different return value of the expression IF nMonth := Month(dDate) == 7 ? "July" ENDIF ? nMonth // result: .T. RETURN

Operator Reference

37

<

< Less than operator (binary): compares the size of two values.

Syntax <

Arguments

The values of and must have the same data type and are compared.

Description The "less than" operator compares two values of the same data type. It returns .T. (true) when the left operand is smaller than the right operand, otherwise the return value is .F. (false). Only the simple data types Character, Date, Logic, Memo and Numeric can be compared. The complex data types Array, Code block, Hash, Object and the value NIL cannot be used with the "less than" operator.

Comparison rules Data type

Comparison

Character Date Logical Memo Numeric

The comparison is based on the ASCII value of the characters. The comparison is based on the underlying date value. False (.F.) is smaller than true (.T.). Same as Character data type. Comparison is based on the value of the numerics.

SET EXACT For character comparisons, the less than operator takes the SET EXACT setting into account. With SET EXACT OFF, characters are compared up to the length of the right operand. With SET EXACT ON, characters are compared up to the length of the left operand and trailing blank spaces are ignored.

Info See also: Category: LIB: DLL:

$, >, =, SET EXACT Comparison operators, Operators xhb.lib xhbdll.dll

Example // The example demonstrates the result of the "" operator. PROCEDURE Main ? "A" > "Z" ? "a" > "Z"

// result: .F. // result: .T.

? CToD("12/28/2005") > CToD("12/31/2005") // result: .F. ? .T. > .F. // result: .T.

54

Operator Reference

> ? 2 > 1

// result: .T.

SET EXACT OFF ? "ab" > "a"

// result: .F.

SET EXACT ON ? "ab" > "a" RETURN

Operator Reference

// result: .T.

55

>=

>= Greater than or equal operator (binary): compares the size of two values.

Syntax >=

Arguments

The values of and must have the same data type and are compared.

Description The "greater than or equal" operator compares two values of the same data type. It returns .T. (true) when the left operand is greater than or equal to the right operand, otherwise the return value is .F. (false). Only the simple data types Character, Data, Logic, Memo and Numeric can be compared. The complex data types Array, Code block, Hash, Object and the value NIL cannot be used with the "greater than or equal" operator.

Comparison rules Data type

Comparison

Character Date Logical Memo Numeric

The comparison is based on the ASCII value of the characters. The comparison is based on the underlying date value. False (.F.) is smaller than true (.T.). Same as Character data type. Comparison is based on the value of the numerics.

SET EXACT For character comparisons, the "greater than or equal" operator takes the SET EXACT setting into account. With SET EXACT OFF, characters are compared up to the length of the right operand. With SET EXACT ON, characters are compared up to the length of the left operand and trailing blank spaces are ignored.

Info See also: Category: LIB: DLL:

$, = "Z" ? "a" >= "Z"

// result: .F. // result: .T.

? CToD("12/28/2005") >= CToD("12/31/2005")

56

Operator Reference

>= ? .T. >= .F.

// result: .F. // result: .T.

? 2 >= 1

// result: .T.

SET EXACT ? "a" >= ? "a" >= ? "" >= ? "a" >=

OFF "a "ab" "a" ""

SET EXACT ? "a" >= ? "a" >= ? "" >= ? "a" >= RETURN

ON "a "ab" "a" ""

Operator Reference

"

// // // //

result: result: result: result:

.F. .F. .F. .T.

"

// // // //

result: result: result: result:

.T. .F. .F. .T.

57

>>

>> Right-shift operator (binary): shifts bits to the right.

Syntax >>

Arguments

is a numeric value whose bits are shifted to the right.

is a number indicating how many places the bits are shifted to the right.

Description The >> operator accesses individual bits in the left operand and shifts them to the right as many times as specified with the right operand. Both operands are always treated as integer values. If an operand has a decimal fraction, it is truncated prior to the operation. A shift operation involves all bits of the left operand. When the bits are shifted one place to the right, the lowest bit is discarded and the highest bit is set to 0. A numeric value has 32 bits on a 32 bit operating system. Shifting a nonnegative value to the right is equivalent with dividing by 2 raised to the power of .

Info See also: Category: LIB: DLL:

2 ? 52 / 2 ^ 2 RETURN

58

// binary: 00110100 // binary: 00001101 (value = 13) // result: 13

Operator Reference

@

@ Pass-by-reference operator (unary): passes variables by reference.

Syntax @

Arguments

is the name of any valid memory variable. Field variables cannot be passed by reference.

Description When a variable is passed by reference to a subroutine, any changes made to the variable are reflected in the calling routine once the called routine has returned. Normally, variables are passed by value. This means that the called routine receives a copy of the passed value so that the variable's value in the calling routine remains unaffected by assignment operations in the called routine. When a variable is prefixed with the @ operator in a function call, the called function receives a reference to the variable. The variable can then be assigned a new value in the called function. The changed value is reflected in the calling routine when the called function has finished. Passing variables by reference is usually required when a subroutine must deliver more than one return value.

Info See also: Category: LIB: DLL:

FUNCTION, METHOD (Declaration), PROCEDURE Operators, Special operators xhb.lib xhbdll.dll

Example // The example shows the difference between a function call with // and without the @ operator: PROCEDURE Main() LOCAL cMsg := "Hello World" ? GetMsg( cMsg ) ? cMsg ? GetMsg( @cMsg ) ? cMsg RETURN NIL

// result: Ok // result: Hello World // result: Ok // result: Hi there

FUNCTION GetMsg( cString ) cString := "Hi there" RETURN "Ok"

Operator Reference

59

@()

@() Function-reference operator (unary): obtains a function pointer.

Syntax ( @() )

-->

pFuncPointer

Arguments

is the symbolic name of a function or procedure to obtain the function pointer from. Note that the function-reference operator can only be used within parentheses. If this syntactical rule is not complied with, a syntax error is reported by the compiler.

Description The function-reference operator retrieves the pointer to a function or procedure. The resulting value is of Valtype()=="P". A function pointer can be used with function HB_Exec() or HB_ExecFromArray() to execute the function indirectly. This type of indirect execution is similar to using within a macroexpression, or embedding the call within a code block which is then passed to the Eval() function. If a function is to be called indirectly for multiple times, however, the usage of the function-pointer along with HB_Exec() or HB_ExecFromArray() has a considerable performance advantage. Note: The function-reference operator can resolve FUNCTIONs or PROCEDUREs declared as STATIC only if the referenced is declared in the same PRG file where the operator is used. Pointers to methods of objects can only be obtained using function HB_ObjMsgPtr().

Info See also: Category: LIB: DLL:

{|| }, ( ), FUNCTION, HB_Exec(), HB_ExecFromArray(), HB_FuncPtr(), HB_ObjMsgPtr(), METHOD (Declaration), PROCEDURE Operators, Indirect execution, Special operators, xHarbour extensions xhb.lib xhbdll.dll

Example // The example shows the difference of indirect execution using a // code block and a function pointer PROCEDURE Main LOCAL pFunc := ( @Test() ) LOCAL bBlock := {|x,y| Test( x, y ) } ? Valtype( bBlock ) ? Valtype( pFunc ) EVal( bBlock,

// result: B // result: P

"Hello", "World" )

HB_Exec( pFunc, NIL, "Hello", "World" ) RETURN

PROCEDURE Test( ... )

60

Operator Reference

@() LOCAL xVal ? PCount() FOR EACH xVal IN HB_AParams() ?? xVal NEXT RETURN

Operator Reference

61

HAS

HAS Searches a character string for a matching regular expression.

Syntax HAS

Arguments

This is the character string being searched.

This is a character string holding the search pattern as a literal regular expression. Alternatively, the return value of HB_RegExComp() can be used.

Description The HAS operator searches the character string for a substring based on the regular expression . If the string contains a substring that matches the search pattern, the result of the operator is .T. (true). When no match is found, the result is .F. (false). If the HAS operator is applied often in a search routine with the same regular expression, a literal regular expression can be compiled with HB_RexExComp() to speed up operations.

Info See also: Category: LIB: DLL:

$, AScan(), IN, LIKE, HB_RegEx(), HB_RegExComp(), HScan() Character operators, Comparison operators, Operators, Regular expressions, xHarbour extensions xhb.lib xhbdll.dll

Example // // // //

The example uses two regular expressions to detect if a character string contains a number or a Hex number. Note that one regular expression is a literal string while the second is compiled. PROCEDURE Main LOCAL aExpr := { "0xEA", "3.14", "aChar", DtoC( Date() ), "0x0d" } LOCAL cHex := HB_RegExComp( "0[xX][A-Fa-f0-9]+" ) LOCAL cString

FOR EACH cString IN aExpr ? cString, "" IF cString HAS "[0-9].?[0-9]*" IF cString HAS cHex ?? "contains a Hex number" ELSE ?? "contains a number" ENDIF

62

Operator Reference

HAS ELSEIF cString HAS cHex ?? "contains a Hex number" ELSE ?? "contains no number" ENDIF NEXT ** // // // // //

Output: 0xEA contains a Hex number 3.14 contains a number aChar contains no number 09/21/06 contains a number 0x0d contains a Hex number

RETURN

Operator Reference

63

IN

IN Searches a value in another value.

Syntax IN IN IN

Arguments

is a character or other value that is searched for in .

is an array with random values.

is a value to search in a hash.

is a hash value whose keys are searched for .

Description The IN operator searches the left operand in the right operand and returns .T. (true) if the value of the left operand is contained in the value of the right operand, otherwise .F. (false) is returned.

Substring search When both operands are character strings, the IN operator performs a case-sensitive substring search and returns .T. (true) if is found in , otherwise .F. (false). This is the same search as with the $ operator, but IN is much faster.

Array search If the right operand is an array, the IN operator scans the elements of in the first dimension and returns .T. (true) if an element contains the value of the left operand. may be of any data type.

Hash key search If the right operand is a hash, the IN operator scans the keys of (which is similar to the first column of a two column array) and returns .T. (true) if the hash has the key . may be of any data type.

64

Operator Reference

IN

Info See also: Category: LIB: DLL:

$, AScan(), HAS, LIKE, HScan() Character operators, Comparison operators, Operators, xHarbour extensions xhb.lib xhbdll.dll

Example // The example demonstrates results of the IN operator with values // of different data types. PROCEDURE Main LOCAL cString LOCAL hHash LOCAL aSub LOCAL aArray

:= := := :=

"xHarbour" { "A" => Date(), 1 => "B" } { 1, 2 } { 1, Date(), aSub }

? "A" IN cString ? "arb" IN cString

// result: .F. // result: .T.

? ? ?

// result: .T. // result: .F. // result: .T.

"A" "B" 1

IN hHash IN hHash IN hHash

? "A" IN aArray ? Date() IN aArray ? aSub IN aArray RETURN

Operator Reference

// result: .F. // result: .T. // result: .T.

65

LIKE

LIKE Compares a character string with a regular expression.

Syntax LIKE

Arguments

This is the character string being compared.

This is a character string holding the comparison rule as a literal regular expression. Alternatively, the return value of HB_RegExComp() can be used.

Description The LIKE operator compares the character string with the regular expression . If the string matches the regular expression, the result of the operator is .T. (true). When no match is given, the result is .F. (false). If the LIKE operator is applied often in a search routine with the same regular expression, a literal regular expression can be compiled with HB_RexExComp() to speed up operations.

Info See also: Category: LIB: DLL:

$, AScan(), IN, HAS, HB_RegEx(), HB_RegExComp(), HScan() Character operators, Comparison operators, Operators, Regular expressions, xHarbour extensions xhb.lib xhbdll.dll

Example // The example uses a regular expression to detect if a character // string is a valid eMail address. PROCEDURE Main LOCAL cRegEx := "^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$" LOCAL aString LOCAL cEMail aString := { "[email protected]" , "info_xHarbour.com" , "info@xHarbour,com" , "Mail to [email protected]"

; ; ; }

FOR EACH cEMail IN aString IF cEMail LIKE cRegEx ? cEMail, "is valid" ELSE ? cEMail, "is not valid" ENDIF NEXT

66

Operator Reference

LIKE ** Output: // [email protected] is valid // info_xHarbour.com is not valid // info@xHarbour,com is not valid // Mail to [email protected] is not valid RETURN

Operator Reference

67

[ ] (array)

[ ] (array) Array element operator (unary): retrieves array elements.

Syntax [] [][nSubScript2][]

Arguments

is an expression which returns a reference to an array. This can be a memory variable, an instance variable or a function call that returns an array.

is a numeric expression which indicates the ordinal position of the array element to retrieve. One subscript must be passed for each dimension of the array.

Description The array element operator retrieves a value stored in an array element. The ordinal position of the desired element must be specified as a numeric value. Elements of multi-dimensional arrays are specified using one subscript value per array dimension. Note: if is a negative value, the operator retrieves the element Abs() from the end of the array.

Info See also: Category: LIB: DLL:

[ ] (string), { }, Array() Operators, Special operators xhb.lib xhbdll.dll

Example // The example shows some variations of the use of the subscript operator. PROCEDURE Main LOCAL aArray := { "One", "Two", "Three" } // one dimensional array ? aArray[1] // result: One ? aArray[2] // result: Two ? aArray[3] // result: Three ? aArray[-1] ? aArray[-3]

// result: Three // result: One

USE Customer

// two dimensional array // combined with function call // result: FIRSTNAME

? DbStruct()[1,1] RETURN

68

Operator Reference

[ ] (string)

[ ] (string) Character operator (unary): retrieves a character from a string.

Syntax []

Arguments

is a character string containing at least one character.

is a numeric expression which indicates the ordinal position of the character to retrieve.

Description The character retrieves a single character at position from the string . The value for mus be in the range of 1 to Len(). Note: if is a negative value, the operator retrieves the character Abs() from the end of the the string.

Info See also: Category: LIB: DLL:

[ ] (array), SubStr() Character operators, Operators, Special operators, xHarbour extensions xhb.lib xhbdll.dll

Example // The example shows how to access and change characters in a string. // Two functiosn are programmed which convert a numeric value to/from // a string containing only "1" and "0". PROCEDURE Main LOCAL cStr cStr := "xHarbour" ? cStr[5] // result: b cStr[5] := "B" ? cStr

// result: xHarBour

cStr[-1] := "B" ? cStr

// result: xHarBouB

? cStr := Num2Bin( 52 ) // result: 00000000000000000000000000110100 ? Bin2Num( cStr ) // result: 52.00 RETURN FUNCTION Num2Bin( n ) LOCAL i, cBin := Padr("", 32, "0" )

Operator Reference

69

[ ] (string) FOR i:=1 TO 32 IF IsBit( n, i ) cBin[33-i] := "1" ENDIF NEXT RETURN cBin FUNCTION Bin2Num( cBin ) LOCAL n := 0 LOCAL i, imax := Len(cBin) FOR i:=1 TO imax IF cBin[imax+1-i]=="1" n += 2^(i-1) ENDIF NEXT RETURN n

70

Operator Reference

^^

^^ Bitwise XOR operator (binary): performs a logical XOR operation.

Syntax ^^ | --> cCharacter ^^ | --> nNumeric

Arguments

A character expression of which all bits of each character are processed in a logical XOR operation.

A numeric value all bits of which are processed. Numbers are always treated as integer values. If a number has a decimal fraction, it is truncated. |

The right operand of the bitwise XOR operator can be specified as a character or a numeric value.

Description The bitwise XOR operator performs a logical XOR operation with the individual bits of both operands. The left operand is the value to process while the right operand provides the bit mask for the operation. The return value of the &-operator has the same data type as the left operand. Bits at identical positions in both operands are compared. The bit at the same position is set in the return value, when both operands have the bit set differently at the same position. If both operands have the same bit set or not set, i.e. when both bits are the same, the corresponding bit in the return value is not set. A special feature of a logical XOR operation is that the left operand can be recovered from the result value when the result value is XORed with the right operand in a second operation. The bit mask to apply to the left operand can be specified as a numeric or as a character value. Depending on the left operand, bitwise XOR operations are performed according to the following rules:

cString ^^ cMask When both operands are character values, the bits of individual characters of both operands are compared. If the right operand has less characters, it is repeatedly applied until all characters of the left operand are processed. The return value has the same number of characters as the left operand.

cString ^^ nMask When the left operand is a character value and the right operand is numeric, the bits set in the numeric value are compared with the bits of each character in the left operand.

Operator Reference

71

^^

nNumber ^^ cMask When the left operand is numeric and the right operand is a character value, the bits set in the numeric value are compared consecutively with the bits of each character in the right operand.

nNumber ^^ nMask When both operands are numeric values, the bits of both values are compared. Note: Numeric operands are always treated as integer values. If a number has a decimal fraction, it is ignored.

Info See also: Category: LIB: DLL:

& (bitwise AND), | (bitwise OR), .AND., .NOT., .OR., HB_BitXOr() Bitwise operators, Operators, xHarbour extensions xhb.lib xhbdll.dll

Example // This example encrypts and decrypts the value 'Secure sentence.' // with a key 'Secret password'. PROCEDURE MAIN() LOCAL cEncrypted := "Secure sentence." ^^ "Secret password" LOCAL cDecrypted := cEncrypted ^^ "Secret password" ? cEncrypted ? cDecrypted RETURN NIL

72

Operator Reference

{}

{} Literal array.

Syntax {[]}

Arguments

is a comma separated list of expressions that may yield any data type, including arrays. When an expression evaluates to an array, or when another literal array is specified, a nested, or multi-dimensional array is created.

Description This operator is used as a delimiter for creating references to literal arrays. Expressions listed within the curly braces are evaluated and their return value is stored in the elements of the newly created array. Note: When a variable is declared as STATIC, the expressions may only be constant values that can be resolved at compile time.

Info See also: Category: LIB: DLL:

[ ] (array), {=>}, Array(), Hash() Operators, Special operators xhb.lib xhbdll.dll

Example // The example creates arrays of different dimensions. PROCEDURE Main LOCAL aAge := {12, 15, 11, LOCAL aUsers := { {"John", {"Marc", {"Bill",

9, 11, 14} // one dimensional 31}, ; // two dimensional 28}, ; 33} }

LOCAL aVal := { Date(), ; // three dimensional { 1, 2, {.T., "Ok"} }, ; "Third Element" } ? aAge[3] ? aUsers[2][1] ? aVal[2,3,2] ? aVal[3] RETURN

Operator Reference

// // // //

result: result: result: result:

11 Marc Ok Third Element

73

{=>}

{=>} Literal hash.

Syntax {[] => [][, => ]}

Arguments ..

is one or more key values to initialize the Hash with. Key values may be of data type Character, Date or Numeric. Other data types are not allowed for . ..

is one or more values of any data type associated with when the Hash is initialized. Multiple key/value pairs are separated with commas.

Description An empty literal Hash is created with the characters {=>}. The Hash can be initialized with key => value pairs upon creation. A Hash is similar to a two column array where the keys are stored in the left and the associated values in the right column. For this reason, a Hash is often referred to as "associative array". A Hash, however, is a genuine data type in xHarbour and allows for different operations than with the Array data type. The most significant difference between Hash and Array is that while values stored in an array are retrieved using a numeric ordinal position of an array element, a Hash value is retrieved by its associated key, and not by its ordinal position. For this reason, data types for keys must be orderable. This restricts keys to the data types Character, Date and Numeric. A key, however, can be associated with a value of any data type, including Hash. The most common data type for keys is Character. This makes a Hash to a kind of "lightweight object" that has only data and no methods. Since the key strings are used to retrieve the associated values, a key string can be understood like a message sent to an object. The "dual" nature of the Hash data type, being partly similar to arrays and partly to objects, finds its expression also in the syntactical notation that can be used for retrieving a value from a Hash. Both operators are supported, the array element operator [ ] and the : send message operator. The latter, however, requires keys to be of data type Character. Important: when using the : send message operator to create or retrieve a value from a Hash, the message is case-sensitive unless HSetCaseMatch() is set to .F. (false) for the Hash.

Info See also: Category: LIB: DLL:

{ }, Array(), CLASS, Hash() Operators, Special operators, xHarbour extensions xhb.lib xhbdll.dll

Examples // The example demonstrates how to create and populate hash values.

74

Operator Reference

{=>} PROCEDURE Main // literal hash LOCAL hHash := { "COM1" => 1, "COM2" => 2 } // object notation ? hHash:COM1

// result: 1

// array notation ? hHash["COM2"]

// result: 2

// adding a new key/value pair using object notation hHash:COM3 := 3 ? hHash:COM3

// result: 3

? hHash:COM4 RETURN

// runtime error

// The example demonstrates comparison operators with hashes PROCEDURE Main LOCAL hHash1 := { "A" => 1, "B" => 2, "C" => 3, "D" => 4 } LOCAL hHash2 := { "B" => 5, "C" => 6, "E" => 7, "F" => 8 } LOCAL hHash3 := hHash1 ? hHash1 == hHash2 ? hHash1 hHash2

// result: .F. // result: .T.

? hHash1 == hHash3 ? hHash1 hHash3 RETURN

// result: .T. // result: .F.

// The example demonstrates set-oriented operations with hashes // using Plus and Minus operators PROCEDURE Main LOCAL hHash1 := { "A" => 1, "B" => 2, "C" => 3, "D" => 4 } LOCAL hHash2 := { "B" => 5, "C" => 6, "E" => 7, "F" => 8 } LOCAL hHash3 hHash3 := hHash1 + hHash2 ? ValToPrg( hHash3 ) // { "A" => 1, "B" => 5, "C" => 6, "D" => 4, "E" => 7, "F" => 8 } hHash3 := hHash1 - hHash2 ? ValToPrg( hHash3 ) // { "A" => 1, "D" => 4 } RETURN

Operator Reference

75

{|| }

{|| } Literal code block.

Syntax {|[]| }

Arguments

This is an optional comma separated list of parameter names declared for use inside the code block. Code block parameters are only visible within the code block and must be placed between the || delimiters.

is a list of comma separated expressions to execute in the code block. The return value of the code block is the return value of the last expression in the list.

Description Literal code blocks are created in program code using the {|| } characters. A code block is an extremely powerful instrument since it allows a programmer to separate the definition of program code from its execution time. A code block is a piece of executable code that can be assigned to a variable. This makes a code block similar to a macro expression but in contrast to a macro, a code block is resolved at compile time. This makes code blocks considerably faster than macro expressions that are compiled at runtime. The program code, embedded within a code block, is executed by passing the code block to the Eval() function. Arguments passed to this function are passed on to the code block and are received by the code block parameters. The expressions in the code block are then executed from left to right. The return value of the last expression is finally returned from the code block. When LOCAL variables exist at the time of code block creation and are included in the expression list, they are embedded in the code block. This has a far reaching consequence: normally, LOCAL variables cease to exist when the function returns in which the LOCALs are declared. If, however, the function returns a code block with embedded LOCAL variables, they continue to exist inside the code block and for the lifetime of it. This way, LOCAL variables can become detached from the declaring function context.

Info See also: Category: LIB: DLL:

, AEval(), AScan(), ASort(), DbEval(), Eval(), HEval(), LOCAL Indirect execution, Operators, Special operators xhb.lib xhbdll.dll

Example // // // //

The example demonstrates two basic techniques for using code blocks. The first code block receives parameters from outside (the Eval() function), while the second code block uses embedded LOCAL variables that are detached from function MyDispbox(). PROCEDURE Main LOCAL nTop

76

:=

5

Operator Reference

{|| } LOCAL LOCAL LOCAL LOCAL

nLeft nBot nRight bBlock

:= := := :=

10 20 70 {|t,l,b,r| DispBox(t,l,b,r) }

CLS // draw a box at screen Eval( bBlock, nTop, nLeft, nBot, nRight ) @ MaxRow()-1, 0 WAIT "press key to clear screen" CLS @ MaxRow()-1, 0 WAIT "press key to redraw box" bBlock := MyDispBox( nTop, nLeft, nBot, nRight ) @ MaxRow()-1, 0 WAIT "press key to restore screen" Eval( bBlock ) @ MaxRow()-1, 0 WAIT "press key to end RETURN

"

// this function creates a code block with detached LOCALs FUNCTION MyDispBox( nT, nL, nB, nR ) LOCAL cScreen := SaveScreen( nT, nL, nB, nR ) Dispbox( nT, nL, nB, nR ) RETURN {|| RestScreen( nT, nL, nB, nR, cScreen ) }

Operator Reference

77

| (bitwise OR)

| (bitwise OR) Bitwise OR operator (binary): performs a logical OR operation.

Syntax

| | | |



--> --> --> -->

Character Character Numeric Numeric

Arguments

A character expression of which all bits of each character are processed in a logical OR operation.

A numeric value all bits of which are processed. Numbers are always treated as integer values. If a number has a decimal fraction, it is truncated. |

The right operand of the bitwise OR operator can be specified as a character or a numeric value.

Description The bitwise OR operator performs a logical OR operation with the individual bits of both operands. The left operand is the value to process while the right operand provides the bit mask for the operation. The return value of the | operator has the same data type as the left operand. Bits at identical positions in both operands are compared. The bit at the same position is set in the return value, when one of both operands have the bit set at the same position. If either operand has a bit not set, the corresponding bit in the return value is also not set. The bit mask to apply to the left operand can be specified as a numeric or as a character value. Depending on the left operand, bitwise OR operations are performed according to the following rules:

cString | cMask When both operands are character values, the bits of individual characters of both operands are compared. If the right operand has less characters, it is repeatedly applied until all characters of the left operand are processed. The return value has the same number of characters as the left operand.

cString | nMask When the left operand is a character value and the right operand is numeric, the bits set in the numeric value are compared with the bits of each character i n the left operand.

nNumber | cMask When the left operand is numeric and the right operand is a character value, the bits set in the numeric value are compared consecutively with the bits of each character in the right operand.

78

Operator Reference

| (bitwise OR)

nNumber | nMask When both operands are numeric values, the bits of both values are compared. Note: Numeric operands are always treated as integer values. If a number has a decimal fraction, it is ignored.

Info See also: Category: LIB: DLL:

& (bitwise AND), ^^ (bitwise XOR), .AND., .NOT., .OR., HB_BitOr() Bitwise operators, Operators, xHarbour extensions xhb.lib xhbdll.dll

Example // The example sets all characters in lower case and performs a bitwise // OR operation between 123 as character/numeric and 3. PROCEDURE Main() ? "MiXeD CaSe StRiNg" | 32

// result: mixed case string

? "123" | 3 // result: 333 // "1" binary: 00110001 | 00000011 => 00110011 "3" // "2" binary: 00110010 | 00000011 => 00110011 "3" // "3" binary: 00110011 | 00000011 => 00110011 "3" ? 123 | 3 // 123 binary: 01111011 | 00000011

// result: 123 => 01111011

RETURN NIL

Operator Reference

79

Statement Reference

80

Statement Reference

(struct)

(struct) Creates a new structure object

Syntax := (struct ) or := (struct *)

Arguments

This is the name of a memory variable to assign the structure object to.

This is the symbolic name of a structure declared with typedef struct.

This is the name of a memory variable holding a pointer. The pointer holds the memory address of the structure. The resulting structure object is initialized with the structure data pointed to by .

Description The (struct) statement provides the most convenient way of creating a structure object of a declared C structure. (struct) is not a statement in its strongest definition, since it is used on the right side of the assignment operator and produces a return value: a new C Structure object. The name of a declared structure must be provided with the (struct) statement. A corresponding structure object is then instantiated and assigned to the memory variable . This structure object maintains an uninitialized C structure. When the (struct) statement is coded with an asterisk, an additional memory variable must follow the closing brace. This variable must be of Valtype()=="P", i.e. it is a pointer holding the memory address of structure data. The created structure object is then initialized with the structure data stored at the memory address of . This is required in the special case when an external function called via DllCall() produces a pointer to a new structure. Data pointed to by is then transferred into a new xHarbour structure object. Note: refer to the typedef struct statement for a usage example of (struct).

Info See also: Category: Header: Source: LIB: DLL:

C Structure class, DllCall(), pragma pack(), typedef struct C Structure support, xHarbour extensions cstruct.ch, winapi.ch, wintypes.ch rtl\cstruct.prg xhb.lib xhbdll.dll

Statement Reference

81

ACCESS

ACCESS Declares an ACCESS method of a class.

Syntax ACCESS [ INLINE | VIRTUAL ]

Arguments

This is the symbolic name of the access method to implement. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. INLINE

Normally, access methods are implemented outside the class declaration, using a regular METHOD (implementation). When an access method is implemented as INLINE method, is executed when the access method is invoked. must be one line of code. The code cannot contain commands but only function and method calls. VIRTUAL

An access method can be declared as VIRTUAL method. The VIRTUAL and INLINE clauses are mutually exclusive.

Description An ACCESS method is a special method since it is invoked when an object receives a message "as if" an instance variable is queried. Sending without including parentheses to an object results in the method call. ACCESS methods "simulate" an instance variable for the calling context. An object can have "computed" instance variables whose values are the result of a method call. An ACCESS method "hides" the method call from the calling context. Another special method type can be declared with ASSIGN which "simulates" the write access to an instance variable via a method call.

Info See also: Category: Header: Source: LIB: DLL:

ASSIGN, CLASS, DATA, EXPORTED:, METHOD (declaration), METHOD...VIRTUAL Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example implements a class that uses ACCESS methods // for simulating instance variables. #include "hbclass.ch" PROCEDURE Main

82

Statement Reference

ACCESS LOCAL obj := Someday():new() // real instance variable ? obj:date // result: 08/31/06 // "simulated" instance variables ? obj:yesterday // result: Wednesday ? obj:today // result: Thursday ? obj:tomorrow // result: Friday ? obj:nextWeek RETURN

// result: 09/04/06

CLASS Someday EXPORTED: DATA date INIT Date() ACCESS ACCESS ACCESS ACCESS ENDCLASS

today tomorrow yesterday nextWeek

METHOD today RETURN CDoW( ::date ) METHOD tomorrow RETURN CDoW( ::date + 1 ) METHOD yesterday RETURN CDoW( ::date - 1 ) METHOD nextWeek LOCAL nDays := -1 // find next Monday DO WHILE DoW( ++nDays + ::date ) 2 ENDDO RETURN ::date + nDays

Statement Reference

83

ANNOUNCE

ANNOUNCE Declaration of a module identifier name.

Syntax ANNOUNCE

Arguments

is the symbolic name of a module.

Description The ANNOUNCE statement declares a symbolic name for the linker which is not declared as FUNCTION, PROCEDURE or CLASS in the PRG code of an xHarbour project. This way, an entire module can be assigned a symbolic name that is later resolved by the linker. ANNOUNCE must appear prior to any executable statement in a PRG source code file. The identifier must be unique for the entire xHarbour project.

Info See also: Category:

#include, EXTERNAL, REQUEST Declaration, Statements

Examples // The example shows how the default replaceable database driver // is linked into an application. ANNOUNCE RDDSYS REQUEST _DBF REQUEST DBFNTX REQUEST DBFFPT PROCEDURE Main ? "This program has the default RDD linked in" RETURN // The example demonstrates how to produce an executable that does not // require/use a replaceable database driver. ANNOUNCE RDDSYS PROCEDURE Main ? "This program has no RDD linked in" RETURN

84

Statement Reference

ASSIGN

ASSIGN Declares an ASSIGN method of a class.

Syntax ASSIGN ( ) INLINE

Arguments

This is the symbolic name of the assign method to implement. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. ( )

An access method receives exactly one parameter which must be declared in parentheses. INLINE

ACCESS methods must be declared and implemented as INLINE methods. is executed when the access method is invoked. It must be one line of code which cannot contain commands but only function and method calls.

Description An ASSIGN method is a special method since it is invoked when a value is assigned to an instance variable of an object. Instead of the assignment operation, the access method is invoked and the assigned value is passed as parameter to the method where it is processed. ASSIGN methods "simulate" the assignment of a value to an instance variable for the calling context. Another special method type can be declared with ACCESS which "simulates" the read access to an instance variable via a method call.

Info See also: Category: Header: Source: LIB: DLL:

ACCESS, CLASS, DATA, EXPORTED:, METHOD (declaration) Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example implements a class whose instances have three states // represented as numeric -1, 0 and 1. The state can be changed by // assigning values of different data types. #include "Hbclass.ch" #include "Error.ch" PROCEDURE Main LOCAL obj := ThreeState():new() ? obj:state

Statement Reference

// result: -1

85

ASSIGN obj:state := "ON" ? obj:state

// result: 1

obj:state := "OFF" ? obj:state

// result:

obj:state := "UNDEF" ? obj:state

// result: -1

obj:state := .T. ? obj:state

// result:

obj:state := NIL ? obj:state

// result: -1

obj:state := 1 ? obj:state

// result:

obj:state := 3

// runtime error

0

1

1

RETURN CLASS ThreeState PROTECTED: DATA _value INIT

-1

EXPORTED: ACCESS state ASSIGN state( x ) INLINE ::state( x ) ENDCLASS

METHOD state( xState ) CLASS ThreeState LOCAL lError := .F. IF PCount() == 0 RETURN ::_value ENDIF IF Valtype( xState ) == "N" IF xState IN { -1, 0, 1 } ::_value := xState ELSE lError := .T. ENDIF ELSEIF Valtype( xState ) == "C" DO CASE CASE Upper( xState ) == "ON" ::_value := 1 CASE Upper( xState ) == "OFF" ::_value := 0 CASE Upper( xState ) == "UNDEF" ::_value := -1 OTHERWISE lError := .T. ENDCASE ELSEIF Valtype( xState ) == "L" ::_value := IIF( xState, 1, 0 )

86

Statement Reference

ASSIGN ELSEIF Valtype( xState ) == "U" ::_value := -1 ELSE lError := .T. ENDIF IF lError RETURN ::error( "illegal data assigned", ; ::className(), "state" , ; EG_ARG, {xState} ) ENDIF RETURN ::_value

Statement Reference

87

ASSOCIATE CLASS

ASSOCIATE CLASS Defines a scalar class for a native data type.

Syntax ASSOCIATE CLASS WITH TYPE

Arguments

This is the symbolic name of the user-defined class to associate with a native data type. WITH TYPE

The following keywords are recognized for : ARRAY, BLOCK, CHARACTER, DATE, HASH, LOGICAL, NIL, NUMERIC and POINTER.

Description The ASSOCIATE CLASS statement associates a user defined scalar class with a native data type. Objects of such class are used in place of the data type . A scalar class can have only CLASSDATA and METHODs but no DATA, since a scalar object itself is the data. A scalar class must be declared and implemented following the CLASS statement. Default implementations of scalar classes can be enabled with the ENABLE TYPE CLASS. Note, however, that ASSOCIATE CLASS and ENABLE TYPE CLASS are mutually exclusive statements.

Info See also: Category: Header: Source: LIB: DLL:

ENABLE TYPE CLASS, CLASS, EXTEND CLASS...WITH METHOD Class declaration, Declaration, xHarbour extensions hbclass.ch rtl\tclass.prg xhb.lib xhbdll.dll

Example // // // // // // // // // // // // // // // // // //

88

The example implements a class that extends the data type Date with advanced date and time formatting capabilities. It distinguishes upper and lower case letters for the Day, Month and time. A formatting template is built with the following characters: d dd ddd D DD DDD DDDD M MM MMM MMMM yy

-

numeric day without leading zero numeric day with leading zero numeric day without leading zero and postfix (st, nd, rd, th) first letter of weekday name of weekday abbreviated to two characters name of weekday abbreviated to three characters complete name of weekday numeric month without leading zero numeric month with leading zero month name abbreviated to three letters complete month name year without century

Statement Reference

ASSOCIATE CLASS // // // // // // // //

yyyy h hh m mm s ss \

-

year with century hour without leading zero hour with leading zero minute without leading zero minute with leading zero second without leading zero second with leading zero escape character for d, D, m, M, y, h, m, s

#include "HbClass.ch" PROCEDURE Main LOCAL dDate ASSOCIATE CLASS DateFormatter WITH TYPE DATE dDate := Ctod( "09/01/2006" ) ? dDate // result: 09/01/06 ? dDate:shortDay() // result: Fri ? dDate:shortMonth() // result: Sep ? dDate:format( "dd MMM. yyyy" ) // result: 01 Sep. 2006 ? dDate:format( "dd-MM-yy hh:mm\h", Time() ) // result: 01-09-06 18:07h dDate += 2 ? dDate:format( "DDDD, MMMM ddd, at h \hour\s an\d m \minute\s" ) // result: Sunday, September 3rd, at 18 hours and 7 minutes ? dDate:httpDate() // result: Sun, 03 Sep 2006 18:07:45 RETURN

CLASS DateFormatter EXPORTED: METHOD shortDay METHOD shortMonth METHOD time METHOD asString METHOD httpDate METHOD format ENDCLASS

INLINE INLINE INLINE INLINE

Left( CDow(self), 3 ) Left( CMonth(self), 3 ) Time() DtoS(self)

METHOD httpDate( cTime ) CLASS DateFormatter RETURN ::format( "DDD, dd MMM yyyy hh:mm:ss", cTime )

METHOD format( cFormat, cTime ) CLASS DateFormatter LOCAL aToken := {} LOCAL cToken := "" LOCAL cChar

Statement Reference

89

ASSOCIATE CLASS IF cTime == NIL cTime := ::time() ENDIf FOR EACH cChar IN cFormat IF .NOT. cChar IN "DdMyhms" IF Len( cToken ) > 0 AAdd( aToken, cToken ) ENDIF IF cChar == "\" cToken := cChar ELSE AAdd( aToken, cChar ) cToken := "" ENDIF ELSE cToken += cChar ENDIF NEXT AAdd( aToken, cToken ) cFormat := "" FOR EACH cToken IN aToken IF cToken == "" LOOP ENDIF SWITCH cToken[1] CASE "y" IF Len( cToken ) == 4 cFormat += Left( ::asString(), 4 ) ELSE cFormat += SubStr( ::asString(), 3, 2 ) ENDIF EXIT CASE "M" SWITCH Len( cToken ) CASE 1 cToken := SubStr( ::asString(), 5, 2 ) IF cToken[1] == "0" cFormat += cToken[2] ELSE cFormat += cToken ENDIF EXIT CASE 2 cFormat += SubStr( ::asString(), 5, 2 ) EXIT CASE 3 cFormat += ::shortMonth() EXIT DEFAULT cFormat += CMonth(self) END EXIT CASE "D" IF Len( cToken ) alias name, or the one specified with the IN clause. The FIELD statement does not verify if the field variables exist at runtime or if a database is open with as name. When the declared field variable does not exist at runtime, an error is generated. The scope of the FIELD variable depends on the place of declaration: 1.

When the FIELD declaration appears at the top of a PRG file before any other executable statement, the declaration has file wide scope, i.e. it is valid throughout the entire PRG file.

2.

When the FIELD declaration follows a FUNCTION, METHOD or PROCEDURE declaration, the variable is treated as FIELD variable only in the routine that declares the FIELD.

The lines in PRG source code preceding the FIELD declaration may not call executable code. They can only contain declaration statements, i.e. only the FUNCTION, METHOD, PROCEDURE statements, and the LOCAL, MEMVAR, PARAMETERS, or STATIC variable declarations are allowed to precede the FIELD statement.

Info See also: Category:

FUNCTION, GLOBAL, LOCAL, MEMVAR, PROCEDURE, STATIC Declaration, Statements

Example PROCEDURE Main FIELD InvoiceNo, AmountDue, Payment IN Inv FIELD CustNo , FirstName, LastName IN Cust USE Customer ALIAS Cust SHARED INDEX ON CustNo TO CustA USE Invoice ALIAS Inv SHARED NEW SET RELATION TO CustNo INTO Cust

126

Statement Reference

FIELD GO TOP SET ALTERNATE TO NotPaid.txt SET ALTERNATE ON DO WHILE .NOT. Eof() IF Payment == 0 ? CustNo, Lastname, FirstName, InvoiceNo, AmountDue ENDIF SKIP ENDDO SET ALTERNATE TO DbCloseAll() RETURN

Statement Reference

127

FOR

FOR Executes a block of statements a specific number of times.

Syntax FOR := TO [STEP ] [EXIT] [LOOP] NEXT

Arguments FOR :=

is the name of the variable that holds a counter value used to control the number of iterations of the FOR...NEXT loop. If does not exist when the loop is entered, it is created as a PRIVATE variable. The value is a numeric start value to initialize with when the FOR statement is executed for the first time. TO

is a numeric value that controls the termination of the FOR...NEXT loop. As soon as is greater than or equal to , the statements between FOR and NEXT are no longer executed. STEP

is a numeric value is incremented with for each iteration of the loop. If not specified, it defaults to 1. When is a negative value, the loop ends when is smaller than or equal to . EXIT

The EXIT statement unconditionally terminates a FOR...NEXT loop. Program flow branches to the first statement following the NEXT statement. LOOP

The LOOP statement branches control unconditionally to the FOR statement, i.e. to the begin of the loop.

Description The FOR...NEXT statements form a control structure that executes a block of statements for a specific number of times. This is controlled by the counter variable which gets assigned the value when the loop is entered for the first time. The loop iterates the statements between FOR and NEXT and adds the value to each time the NEXT statement is reached or a LOOP statement is executed. The value identifies the largest value for ( is positive) or its smallest value ( is negative) after which the FOR...NEXT loop terminates. Note: The expressions in the FOR statement are evaluated each time a new iteration begins. As a consequence, new values can be assigned to or while the loop executes.

128

Statement Reference

FOR

Info See also: Category:

AEval(), FOR EACH, DO CASE, DO WHILE, IF, SWITCH, WITH OBJECT Control structures, Statements

Example // This example shows a typical scenario for a FOR..NEXT loop // where an array is filled with data, and stored data is output. PROCEDURE Main LOCAL aFields, i USE Customer aFields := Array( FCount() ) // fill array in regular order FOR i:=1 TO FCount() aArray[i] := FieldName(i) NEXT USE // output data in reverse order FOR i:=Len( aArray ) TO 1 STEP -1 ? aArray[i] NEXT RETURN

Statement Reference

129

FOR EACH

FOR EACH Iterates elements of data types that can be seen as a collection.

Syntax FOR EACH IN || [LOOP] [EXIT] NEXT

Arguments

The name of a variable that gets assigned a new value on each iteration. IN

This is a value of data type Array. The FOR EACH loop iterates all array elements in the first dimension and assigns their values to . IN

This is a value of data type Object. The FOR EACH loop iterates all instance variables of the object and assigns their values to . IN

This is a value of data type Character string. The FOR EACH loop iterates all individual characters of the string and assigns them to . LOOP

The LOOP statement unconditionally branches to the FOR EACH statement, i.e. to the begin of the loop, where the next value is assigned to . EXIT

The EXIT statement unconditionally terminates the FOR EACH loop and branches to the statement following NEXT.

Description The FOR EACH statement forms a control structure that executes a block of statements for a data type containing multiple elements. This can be data of type Array, Object or Character string. The loop iterates all elements contained in the data and assigns the value of the next element to on each iteration. FOR EACH is similar to the regular FOR loop. But it completes considerably faster than a FOR loop, since there is no explicit loop counter. In contrast, FOR EACH uses an implicit loop counter whose value can be queried using the function HB_EnumIndex(). Other than this, LOOP and EXIT statements within the loop are treated the same as in a FOR loop. When FOR EACH statements are nested, each loop maintains its own counter, i.e. HB_EnumIndex() retrieves the counter of the loop that is currently executed. When the FOR EACH loop is finished, its loop counter is set to 0. 130

Statement Reference

FOR EACH

Info See also: Category:

AEval(), HB_EnumIndex(), FOR, DO CASE, DO WHILE, IF, SWITCH, WITH OBJECT Control structures, Statements, xHarbour extensions

Example // The example demonstrates the FOR EACH statement using two // nested loops. The outer loop iterates an array while the // inner loop iterates character strings. PROCEDURE Main() LOCAL aArray := { "Hello", "World" } LOCAL cString, cChar FOR EACH cString IN aArray ? "----- Outer loop -----" ? HB_EnumIndex(), cString ? "----- Inner loop -----" FOR EACH cChar IN cSTring ? HB_EnumIndex(), cChar NEXT NEXT ? "-------- End ---------" ? HB_EnumIndex() RETURN /* Output of example: ----- Outer loop ----1 Hello ----- Inner loop ----1 H 2 e 3 l 4 l 5 o ----- Outer loop ----2 World ----- Inner loop ----1 W 2 o 3 r 4 l 5 d -------- End --------0 */

Statement Reference

131

FUNCTION

FUNCTION Declares a function along with its formal parameters.

Syntax [STATIC] FUNCTION [FIELD [MEMVAR [LOCAL [STATIC

( [] ) [IN ]] ] [:= ] ,... ] [:= ] ,... ]

RETURN

Arguments FUNCTION ( [] )

This is the symbolic name of the declared function. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. Optionally, the names of parameters accepted by the function can be specified as a comma separated list. These function parameters have LOCAL scope within the function. When the function is declared as STATIC FUNCTION, it is only visible within the PRG file that contains the function declaration and cannot be invoked from elsewhere. FIELD

An optional list of field variables to use within the FUNCTION can be declared with the FIELD statement. MEMVAR

If dynamic memory variables, i.e. PRIVATE or PUBLIC variables, are used in the function, they are declared with the MEMVAR statement. LOCAL [:= ]

Local variables are declared and optionally initialized using the LOCAL statement. STATIC [:= ]

Static variables are declared and optionally initialized using the STATIC statement. RETURN

The RETURN statement terminates a function and branches control back to the calling routine, returning the value to it.

Description The FUNCTION statement declares a function along with an optional list of parameters accepted by the function. Statements programmed in the function body form a self-contained part of a program that is executed when a function is called. Thus, tasks of a program can be split into several functions, each of which performs a sub-task when invoked. 132

Statement Reference

FUNCTION

The body of a function ends with the next FUNCTION, PROCEDURE or CLASS declaration, or at the end of file, which implies that function declarations cannot be nested. The execution of a function ends when a RETURN statement is encountered in the function body, which must return a value to the calling routine. This value is mandatory for functions and can be of any data type. The RETURN value is the only difference between functions and procedures. When a function is declared with the STATIC modifier, its visibility is restricted to the PRG file that contains the STATIC FUNCTION declaration. The names of STATIC functions are resolved by the compiler and do not exist at runtime of a program. The names of non-STATIC functions, also referred to as public functions, are resolved by the linker and do exist at runtime. Thus, public functions can be accessed by the Macro operator (&) while STATIC functions cannot. It is possible to declare STATIC functions with the same symbolic name in different PRG files. A name conflict to a public function with the same name declared in another PRG file does not arise. However, the symbolic names of public functions, procedures or classes must always be unique. When a function is invoked with values being passed to it, they are assigned to the formal parameters declared with . All variables declared in this list are LOCAL variables and their visibility is restricted to the statements programmed in the function body. The number of values passed to a function does not need to match the number of parameters declared. When fewer values are passed, the corresponding parameters are initialized with NIL. When more values are passed, the additional values are not asssigned to parameters but can be retrieved using function HB_AParams(). Undefined parameter list a function can be declared with an undefined parameter list using the ellipsis sign (...) as a placeholder for the parameter list. A function declared in such way can receive an unknown number of parameters.

Info See also: Category:

FIELD, HB_AParams(), LOCAL, MEMVAR, METHOD (declaration), PARAMETERS, PCount(), PRIVATE, PROCEDURE, PUBLIC, RETURN, STATIC Declaration, Statements

Examples // The example shows two functions used to calculate the number of // days for a month. PROCEDURE Main ? DaysOfMonth( ? DaysOfMonth( ? DaysOfMonth( ? DaysOfMonth( ? DaysOfMonth( RETURN

StoD( StoD( StoD( StoD( StoD(

"20000201" "20010201" "20040201" "20050301" "20051101"

) ) ) ) )

) ) ) ) )

// // // // //

Result: Result: Result: Result: Result:

29 28 29 31 30

FUNCTION DaysOfMonth( dDate ) LOCAL nMonth IF Valtype( dDate ) "D" dDate := Date() ENDIF nMonth := Month( dDate ) IF nMonth == 2

Statement Reference

133

FUNCTION RETURN IIf( IsLeapYear( dDate ), 29, 28 ) ELSEIF nMonth $ {4,6,9,11} RETURN 30 ENDIF RETURN 31

STATIC FUNCTION IsLeapYear( dDate ) LOCAL nYear := Year( dDate ) RETURN ( nYear % 4 == 0 ) .OR. ( nYear % 400 == 0 ) // The example demonstrates how an unknown number of command line // arguments passed to an xHarbour application can be processed. PROCEDURE Main( ... ) LOCAL aArg := HB_AParams() LOCAL cArg FOR EACH cArg IN aArg DO CASE CASE Upper( cArg ) IN ("-H/H-?/?") ? "Help requested" CASE .NOT. cArg[1] IN ( "-/" ) ?? " argument:", cArg CASE Upper( cArg ) IN ("-X/X") ? "Execution requested" OTHERWISE ? "Unknown:", cArg ENDCASE NEXT RETURN

134

Statement Reference

GLOBAL

GLOBAL Declares and optionally initializes a GLOBAL memory variable.

Syntax GLOBAL [:= ] GLOBAL EXTERNAL

Arguments GLOBAL

is the symbolic name of the global variable to declare.

is an optional value to assign to the GLOBAL variable after being declared. To assign a value, the inline assignment operator (:=) must be used. The simple assignment operator (=) cannot be used. Only literal values are allowed for when declaring GLOBAL variables. GLOBAL EXTERNAL

This is the name of a GLOBAL variable that is declared in another PRG file and must be referred to in the current PRG file.

Description The GLOBAL statement declares a memory variable that has GLOBAL scope. Global variables are resolved by the compiler, i.e. their symbolic name cannot be retrieved during runtime. This makes access to GLOBAL variables much faster than to memory variables of PRIVATE or PUBLIC scope, whose symbolic variable names exist at runtime. The names of GLOBAL variables cannot be included in macro-expressions since they cannot be resolved by the macro operator (&). This operator requires the symbolic name of a variable to exist at runtime. The lifetime of GLOBAL variables is identical with the lifetime of a program. They are visible and accessible throughout the functions and procedures of all PRG files that declare or refer to global variables. Variable of other types cannot have the same symbolic name as a GLOBAL variable since a global variable's name must be unique for all modules accessing such a variable. In addition, a GLOBAL can only be declared in one PRG file using the GLOBAL statement. When a global variable must be accessed in another PRG file, it must be referred to using the GLOBAL EXTERNAL statement.

Info See also: Category:

LOCAL, MEMVAR, PRIVATE, PUBLIC, STATIC Declaration, Statements, xHarbour extensions

Example // The example demonstrates how to declare/initialize a global variable // in one file, while it is referred to in a second file. ** Global1.prg

Statement Reference

135

GLOBAL GLOBAL gName := "My Global" PROCEDURE Main ? gName Test() ? gName RETURN

// result: My Global // result: New Name

** Global2.prg GLOBAL EXTERNAL gName PROCEDURE Test gName := "New Name" RETURN

136

Statement Reference

HIDDEN:

HIDDEN: Declares the HIDDEN attribute for a group of member variables and/or methods.

Syntax HIDDEN:

Description The HIDDEN: attribute restricts access to member variables and methods of a class. Hidden members can only be accessed in the methods of the class(es) declared in a PRG module. It is the most restrictive attribute. Hidden members cannot be accessed in the context of a FUNCTION or PROCEDURE, only in the context of a METHOD implemented in the declaring PRG module. A less restrictive visibility attribute is PROTECTED:.

Info See also: Category: Header: Source: LIB: DLL:

CLASS, DATA, EXPORTED:, METHOD (declaration), PROTECTED: Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example uses two files to demonstrate the protection // of a hidden member variable outside the declaring PRG module. ** MAIN.PRG uses the class PROCEDURE Main LOCAL obj obj := Test():new( "Hello", "World" ) obj:print() // result: Hello World ? obj:varTwo ? obj:varOne RETURN

// result: World // Scope Violation : VARONE

** TEST.PRG declares the class #include "Hbclass.ch" CLASS Test HIDDEN: DATA varOne EXPORTED: DATA varTwo METHOD init METHOD print ENDCLASS METHOD init( p1, p2 ) CLASS Test

Statement Reference

137

HIDDEN: ::varOne := p1 ::varTwo := p2 RETURN self METHOD print CLASS Test ? ::varOne, ::varTwo RETURN self

138

Statement Reference

IF

IF Executes a block of statements based on one or more conditions.

Syntax IF [ ELSEIF ] [ ELSE ] END[IF]

Arguments IF [ELSEIF ]

to are logical expressions. The statements following the first expression that yields the value .T. (true) are executed. ELSE

If no condition results in the value .T. (true), the statements following the ELSE statement, if present, are executed.

Description This statement executes a block of statements if the condition, related to the block, evaluates to true. If a condition evaluates to true, the following statements are executed until the next ELSEIF, ELSE or END[IF] statement is encountered. If no condition in the entire IF...ELSEIF structure evaluates to true, control is passed to the first statement following the ELSE statement. It is possible to include other control structures like DO WHILE and FOR within a single IF...ELSE structure. Note: The IF...ELSEIF...ENDIF statement is equal to the DO CASE...ENDCASE statement.

Info See also: Category:

BEGIN SEQUENCE, DO CASE, DO WHILE, FOR, If() | IIf(), SWITCH Control structures, Statements

Example // The example shows different forms of the IF END[IF] statement. PROCEDURE Main LOCAL nSalary := 1600 IF .F. ? "This will never be executed" END IF .T. ? "This will always be executed" ENDIF

Statement Reference

139

IF IF nSalary < 1000 ? "Start looking for another job!" ELSEIF nSalary < 1500 ? "That's pretty good" ELSEIF nSalary < 2000 ? "You should be happy" ELSE ? "You should be very happy" ENDIF RETURN

140

Statement Reference

INIT PROCEDURE

INIT PROCEDURE Declares a procedure to execeute when a program starts.

Syntax INIT PROCEDURE [FIELD [IN ]] [MEMVAR ] [LOCAL [:= ] ,... ] [RETURN]

Arguments INIT PROCEDURE

This is the symbolic name of the declared procedure. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. FIELD

An optional list of field variables to use within the INIT procedure can be declared with the FIELD statement. MEMVAR

If dynamic memory variables, i.e. PRIVATE or PUBLIC variables, are used in the INIT procedure, they are declared with the MEMVAR statement. LOCAL [:= ]

Local variables are declared and optionally initialized using the LOCAL statement. RETURN

The RETURN statement terminates an INIT procedure and branches control to the next INIT procedure. After the last INIT procedure has returned, control goes to the main, or root, procedure of an application.

Description The INIT PROCEDURE statement declares a procedure that is automatically called when a program is started. There is one implicit INIT procedure named ErrorSys() that is invoked in all xHarbour applications. It installs the default error codeblock and is programmed in ERRORSYS.PRG. INIT procedures do not have a list of arguments and no parameters are passed on program start. The execution order of INIT procedures is undetermined. It is only guaranteed that they are called when a program starts. An INIT procedure cannot be called explicitely during the start sequence of a program since its symbolic name is resolved at compile time and does not exist at runtime.

Statement Reference

141

INIT PROCEDURE

Info See also: Category:

EXIT PROCEDURE, PROCEDURE Declaration, Statements

Example // See the example for EXIT PROCEDURE

142

Statement Reference

INLINE METHOD

INLINE METHOD Declares and implements an inline method that spans across multiple lines.

Syntax INLINE METHOD ( [] ) ENDMETHOD

Arguments

This is the symbolic name of the method to implement. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters.

This is a acomma separated list of formal parameters accepted by the method. ENDMETHOD

This ends the implementation of an INLINE METHOD that spans across multiple lines.

Description Methods are declared within the class declaration. When a method is also implemented between CLASS and ENDCLASS, it is called an INLINE method. The INLINE METHOD declaration declares an inline method whose implementation spans across multiple lines. The end of this implementation must be indicated with the ENDMETHOD statement. INLINE METHOD exists for compatibility reasons. It is recommended to declare a method with METHOD (declaration) and implement it separately with METHOD (implementation). Note: if a method can be implemeted with one line of code, the INLINE option of the METHOD (declaration) can be used.

Info See also: Category: Header: Source: LIB: DLL:

CLASS, METHOD (declaration), METHOD (implementation) Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example implements a class whose methods are entirely implemented // INLINE. Objects of the class extract subsequent lines of an ASCII text // until no more text lines are available. #include "hbclass.ch" PROCEDURE Main LOCAL obj := LineParser():new( Memoread( "Test.prg" ) ) DO WHILE .NOT. obj:eof()

Statement Reference

143

INLINE METHOD ? obj:line obj:nextLine() ENDDO RETURN

CLASS LineParser PROTECTED: DATA text INLINE METHOD extract LOCAL i := At( Chr(13)+Chr(10), ::text ) IF i == 0 ::line ::text ELSE ::line ::text ENDIF

:= ::text := "" := SubStr( ::text, 1, i-1 ) := SubStr( ::text, i+2 )

RETURN self ENDMETHOD

EXPORTED: DATA line

INIT

""

READONLY

METHOD init( cText ) INLINE ( ::text := cText, ::extract(), self ) METHOD eof INLINE ( Len( ::text + ::line ) == 0 ) INLINE METHOD nextLine ::extract() RETURN ::line ENDMETHOD ENDCLASS

144

Statement Reference

LOCAL

LOCAL Declares and optionally initializes a local memory variable.

Syntax LOCAL [:= ]

Arguments LOCAL

is the symbolic name of the local variable to declare.

is an optional value to assign to the LOCAL variable after being declared. To assign a value, the inline assignment operator (:=) must be used. The simple assignment operator (=) cannot be used.

Description The LOCAL statement declares a lexical memory variable that has LOCAL scope. Local variables are resolved by the compiler, i.e. their symbolic name cannot be retrieved during runtime. This makes access to LOCAL variables much faster than to dynamic memory variables of PRIVATE or PUBLIC scope, whose symbolic variable names exist at runtime. The names of LOCAL variables cannot be included in macro-expressions since they cannot be resolved by the macro operator (&). This operator requires the symbolic name of a variable to exist at runtime. The visibility and lifetime of LOCAL variables is restricted to the function, procedure or method that declares a LOCAL variable. Unlike PRIVATE or PUBLIC variables, LOCAL variables cannot be seen in a subroutine. To make the value of a LOCAL variable visible in a subroutine, it must be passed as a parameter to the subroutine. When a routine executes the RETURN statement, all LOCAL variables declared in that routine are discarded and their values become subject to garbage collection. The lines in PRG source code preceding the LOCAL statement may not call executable code. They can only contain declaration statements, i.e. only the FUNCTION, METHOD, PROCEDURE statements, and the FIELD, MEMVAR, PARAMETERS, PRIVATE, PUBLIC, STATIC variable declarations are allowed to precede the LOCAL statement. It is possible to initialize a local variable already in the LOCAL statement. To accomplish this, the inline-assignment operator must be used. The value of any valid expression can be assigned. This includes literal values and the return values of functions. Note: If a PRIVATE or PUBLIC variable exists that has the same symbolic name as a LOCAL variable, only the LOCAL variable is visible. PRIVATE or PUBLIC variables with the same name become visible again, when the LOCAL variable gets out of scope, i.e. when the routine that declareS the LOCAL variable returns or calls a subroutine.

Statement Reference

145

LOCAL

Info See also: Category:

FUNCTION, GLOBAL, PARAMETERS, PRIVATE, PROCEDURE, PUBLIC, STATIC Declaration, Statements

Example // The example demonstrates the visibility of LOCAL and PRIVATE // memory variables PROCEDURE Main PRIVATE myVar := "Private Var" ? Procname(), myVar Test1() RETURN

PROCEDURE Test1 LOCAL myVar := "Local Var" // PRIVATE myVar is unvisible ? Procname(), myVar Test2() RETURN

PROCEDURE Test2 // PRIVATE myVar is visible ? Procname(), myVar RETURN

146

Statement Reference

MEMVAR

MEMVAR Declares PRIVATE or PUBLIC variables.

Syntax MEMVAR

Arguments MEMVAR

This is a comma separated list of symbolic names identifying field variables.

Description The MEMVAR statement declares symbolic names of dynamic memory variables of PRIVATE or PUBLIC scope. This instructs the compiler to resolve unaliased variable names to memory variables, not field. All variables listed in that appear in program code without alias name and alias operator, are treated as if they are listed with the M-> alias name. The scope of the MEMVAR statement depends on the place of declaration: 1.

When the MEMVAR declaration appears at the top of a PRG file before any other executable statement, the declaration has file wide scope, i.e. it is valid throughout the entire PRG file.

2.

When the MEMVAR declaration follows a FUNCTION, METHOD or PROCEDURE declaration, the variable is treated as memory variable only in the routine that declares the MEMVAR.

The lines in PRG source code preceding the MEMVAR declaration may not call executable code. They can only contain declaration statements, i.e. only the FUNCTION, METHOD, PROCEDURE statements, and the FIELD, LOCAL, PARAMETERS, or STATIC variable declarations are allowed to precede the MEMVAR statement.

Info See also: Category:

FIELD, GLOBAL, LOCAL, PRIVATE, PUBLIC, STATIC Declaration, Statements

Example // The example demonstrates the difference of a declared and // undeclared memory variable of PRIVATE scope. MEMVAR myVar PROCEDURE Main x := "myVar" myVar := "Hello World"

// compiler warning // no compiler warning

? x ? &x RETURN

Statement Reference

147

MESSAGE

MESSAGE Declares a message name for a method.

Syntax MESSAGE METHOD MESSAGE IN MESSAGE IS IN

Arguments

This is the symbolic name of a message to declare for a class. METHOD

This is the symbolic name of the method to execute when an object receives as a message. IN

Optionally, the name of the super class can be specified to which the message should be sent. This requires the class to inherit one or more other classes. IS

When a message should be directed to a super class, the method to invoke in the super class can be specified with .

Description The MESSAGE statement can only be used within the class declaration between CLASS and ENDCLASS. It declares a message that invokes a method of a different name in the declared class or its super class. MESSAGE is used to resolve ambiguities when a class inherits from one or more super classes which have the same method names. The statement can also be used to invoke a method via an alternative name.

Info See also: Category: Header: Source: LIB: DLL:

ACCESS, ASSIGN, CLASS, DATA, DELEGATE, METHOD (declaration) Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // In the example a Subclass uses the method implementation // of a Super class but redefines the message to send to // an object. Message :print() invokes method :show(). #include "Hbclass.ch" PROCEDURE Main

148

Statement Reference

MESSAGE LOCAL obj := TextFile():new( "Text.prg" ) obj:open() obj:print() obj:close() RETURN

CLASS Text EXPORTED: DATA string METHOD init(c) METHOD show ENDCLASS

INLINE ( ::string := c, self ) INLINE QOut( ::string )

CLASS TextFile FROM Text EXPORTED: DATA fileName METHOD init METHOD open METHOD close MESSAGE print IS show IN Text ENDCLASS METHOD init( cFile, cText ) CLASS TextFile ::fileName := cFile IF Valtype( cText ) == "C" ::text:init( cText ) ELSE ::text:init( Memoread(::fileName ) ) ENDIF RETURN self METHOD open CLASS TextFile SET ALTERNATE ON SET ALTERNATE TO (::fileName) RETURN METHOD close CLASS TextFile SET ALTERNATE TO SET ALTERNATE OFF RETURN

Statement Reference

149

METHOD (declaration)

METHOD (declaration) Declares the symbolic name of a method.

Syntax METHOD [(] )] [INLINE ] [SYNC]

Arguments

This is the symbolic name of a single method to declare. It must begin with a letter or underscore followed by digits, letters or underscores. A symbolic name can contain up to 63 characters. ()

A declaration of formal parameters enclosed in parentheses is required when the method is declared as INLINE. If INLINE is not used, the method can be declared without parameters. INLINE

This is the expression which is executed when an INLINE method is invoked. must be one line of code. The code cannot contain commands but only function and method calls. SYNC

The SYNC option declares a "synchronized" method. This is only required in multi-threaded applications when a method must be protected against simultaneous access by multiple-threads. Methods declared with the SYNC attribute can be executed only by one thread at a time. Refer to function StartThread() for more information on multiple threads.

Description When the METHOD statement occurs in the class declaration between CLASS and ENDCLASS, it declares the symbolic name of a method. This name must be sent to an object to invoke the method. The program code for a declared method must be implemented with a separate METHOD declaration that follows the ENDCLASS statement. If, however, the method code can be programmed in one line, method declaration and implementation can be coded within the class declaration using the INLINE option. INLINE methods are not implemented separately from the class declaration. When a method is invoked, the object executing the method is accessible in the code with the reserved variable name self. This can be abbreviated with two colons (::).

150

Statement Reference

METHOD (declaration)

Info See also: Category: Header: Source: LIB: DLL:

ACCESS, ASSIGN, CLASS, CLASSMETHOD, DATA, DELEGATE, EXPORTED:, HIDDEN:, INLINE METHOD, MESSAGE, METHOD (implementation), METHOD...OPERATOR, METHOD...VIRTUAL, PROTECTED:, StartThread() Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Examples METHOD declaration // // // // //

The example declares a simple class with a regular and INLINE method. Note that the INLINE method consists of expressions. The first is an assignment and the second return value of the method. Both expressions are comma and enclosed in parentheses.

an two is the separated

#include "Hbclass.ch" PROCEDURE Main LOCAL obj CLS obj := Test():new( "xharbour" ) obj:print() RETURN

CLASS Test HIDDEN: VAR name EXPORTED: METHOD init( cName ) INLINE ( ::name := cName, self ) METHOD print ENDCLASS METHOD print CLASS Test ? ::name RETURN self

SYNC method // // // // // // // //

The example implements a Queue class that adds a value to a queue with method :put(). Method :get() retrieves the last value added to the queue. The queue itself is an array. Both methods are declared with the SYNC attribute to protect the queue array from simultaneous access by multiple threads. The Main thread puts values into the queue, while four other threads retrieve values from the queue. #include "hbclass.ch" PROCEDURE Main

Statement Reference

151

METHOD (declaration) LOCAL i, aT[4], oQueue := Queue():new() CLS FOR i:=1 TO 4 aT[i] := StartThread( @Test(), oQueue ) NEXT FOR i:=1 TO 4000 oQueue:put(i) NEXT WaitForThreads() RETURN

// Write values // to queue

// Wait until all threads // have terminated

** This code runs simultaneously in 4 threads PROCEDURE Test( oQueue ) LOCAL i, nRow, nCol nRow := GetThreadID() + 10 nCol := 0 // Read values FOR i:=1 TO 1000 // from queue DispOutAt( nRow, nCol+20, oQueue:nCount ) DispOutAt( nRow, nCol+40, oQueue:get() NEXT RETURN

)

** class with SYNC methods protecting the :aQueue array CLASS Queue PROTECTED: VAR aQueue INIT {} EXPORTED: VAR nCount INIT 0 READONLY METHOD put() SYNC METHOD get() SYNC ENDCLASS

METHOD put( xValue ) CLASS Queue AAdd( ::aQueue, xValue ) ::nCount ++ RETURN self

METHOD get() CLASS Queue LOCAL xReturn IF ::nCount > 0 ::nCount -xReturn := ::aQueue[1] ADel ( ::aQueue, 1 ) ASize( ::aQueue, ::nCount ) ENDIF RETURN xReturn

152

Statement Reference

METHOD (implementation)

METHOD (implementation) Declares the implementation code of a method.

Syntax METHOD [( )] CLASS RETURN

Arguments

This is the symbolic name of the method to implement. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. ()

If a method accepts parameters, they must be declared as a comma separated list within parameters. CLASS

This is the symbolic name of the class where the method is declared. RETURN

The RETURN statement terminates a method and branches control back to the calling routine, returning the value to it.

Description When the METHOD statement occurs outside the class declaration after ENDCLASS, it declares the implementation part of a method. A method is implemented like a FUNCTION, including formal parameter list, if required. There is one important difference to functions: a special variable self exists in all methods. self is the object executing the method. Via self instance variables of an object can be accessed and other methods of the class can be invoked. The name of the class where the method is declared must be specified with the method implementation. Without the class name, it would not be possible to implement multiple classes having the same method names in one PRG module. When a method does not require a particular return value, it is quite common to return the self object. This way, method calls can be "chained" in one line of code.

Statement Reference

153

METHOD (implementation)

Info See also: Category: Header: Source: LIB: DLL:

CLASS, FUNCTION, INLINE METHOD, METHOD (declaration), PROCEDURE Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example implements a class with nine methods that can be // used for database access which is independent of the current // workarea. #include "HbClass.ch" PROCEDURE Main LOCAL oWorkArea // method "chaining" oWorkArea := WorkArea():new( "Customer.dbf" ):open() ? Alias()

// result: Customer

SELECT 0 ? Alias()

// result: empty string ("")

// method "chaining" oWorkArea:goBottom():skip(-5) DO WHILE .NOT. oWorkArea:eof() ? Customer->LastName oWorkArea:skip() ENDDO oWorkArea:close() ? Alias()

// result: empty string ("")

oWorkArea:open() ? Alias()

// result: Customer

oWorkArea:close() RETURN CLASS WorkArea PROTECTED: VAR fileName EXPORTED: VAR area READONLY METHOD METHOD METHOD METHOD METHOD METHOD METHOD METHOD METHOD ENDCLASS

154

init open close bof eof found skip goTop goBottom

Statement Reference

METHOD (implementation) METHOD init( cFileName ) CLASS WorkArea ::fileName := cFileName ::area := 0 RETURN self METHOD open() CLASS WorkArea IF ::area == 0 USE ( ::fileName ) NEW SHARED ::area := Select() ELSE DbSelectArea( ::area ) ENDIF RETURN self METHOD close() CLASS WorkArea IF ::area 0 (::area)->(DbCloseArea()) ::area := 0 ENDIF RETURN self METHOD bof CLASS WorkArea RETURN IIf( ::area == 0, .T., (::area)->(Bof()) ) METHOD eof CLASS WorkArea RETURN IIf( ::area == 0, .T., (::area)->(Eof()) ) METHOD found CLASS WorkArea RETURN IIf( ::area == 0, .F., (::area)->(Found()) ) METHOD skip( nSkip ) CLASS WorkArea IF PCount() == 0 nSkip := 1 ENDIF IF ::area > 0 (::area)->(DbSkip(nSkip)) ENDIF RETURN self METHOD goTop CLASS WorkArea IF ::area > 0 (::area)->(DbGotop()) ENDIF RETURN self METHOD goBottom CLASS WorkArea IF ::area > 0 (::area)->(DbGoBottom()) ENDIF RETURN self

Statement Reference

155

METHOD...OPERATOR

METHOD...OPERATOR Declares a method to be executed with an operator.

Syntax METHOD OPERATOR

Arguments

This is the symbolic name of the method to declare. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. OPERATOR

This is the operator which invokes the method.

Description The OPERATOR option of the METHOD statement defines an operator that can be used with an object. When the object is an operand of , the method is invoked. Unary operators invoke the method without an argument while binary operators pass the second operand as argument to the method. Note: only regular operators can be used for . Special operators are not supported. When is a binary operator, the object must be the left operand for invoking the method .

Info See also: Category: Header: Source: LIB: DLL:

CLASS, EXTEND CLASS...WITH METHOD, METHOD (implementation), OPERATOR Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example demonstrates how basic numeric operations can // be implemented with objects. The example support two unary // and two binary operators. #include "Hbclass.ch" PROCEDURE Main LOCAL oNumA := Number():new( 10 ) LOCAL oNumB := NUmber():new( 2 )

156

? oNumA + 100

// result: 110

? oNumA + oNumB ++

// result: 13

? oNumA - oNumB

// result: 7

Statement Reference

METHOD...OPERATOR ? -- oNumA RETURN

CLASS Number PROTECTED: DATA nNumber

// result: 9

INIT 0

EXPORTED: METHOD init(n)

INLINE (IIf(Valtype(n)=="N",::nNumber:=n,) , self)

METHOD METHOD

add subtract

OPERATOR + OPERATOR -

METHOD METHOD

increment decrement

OPERATOR ++ OPERATOR --

value value(n)

INLINE ::nNumber INLINE ::nNumber := n

ACCESS ASSIGN ENDCLASS

METHOD add(x) CLASS Number IF HB_IsObject(x) RETURN ::nNumber + x:value ENDIF RETURN ::nNumber + x METHOD subtract(x) CLASS Number IF HB_IsObject(x) RETURN ::nNumber - x:value ENDIF RETURN ::nNumber - x METHOD increment CLASS Number RETURN ++ ::nNumber METHOD decrement CLASS Number RETURN -- ::nNumber

Statement Reference

157

METHOD...VIRTUAL

METHOD...VIRTUAL Declares a method as virtual.

Syntax METHOD VIRTUAL|DEFERRED

Arguments

This is the symbolic name of the method to declare. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. DEFERRED

This is a synonym for VIRTUAL.

Description The METHOD...VIRTUAL statement can only be used in the class declaration between CLASS and ENDCLASS. It declares the symbolic name of a virtual method. A virtual method is a method that is declared in a class but not implemented. The implementation of such method is deferred to a sub-class. Consequently, virtual methods are only used with inheritance where sub-classes are derived from super classes. By means of virual methods a programmer can define the "message profile" within a class hierarchy at a very early point of the development cycle. An object having virtual methods understands the corresponding message but does not execute code.

Info See also: Category: Header: Source: LIB: DLL:

158

CLASS, DELEGATE Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Statement Reference

OPERATOR

OPERATOR Overloads an operator and declares a method to be invoked for it.

Syntax OPERATOR [ARG ] INLINE

Arguments

This is the operator which executes . The operator must be enclosed in quotes. ARG

When a binary operator is overloaded, is the name of a variable which receives the value of the second operand of the operator. Unary operators do not require be declared. INLINE

This is the expression which is executed when the object is an operand of . must be one line of code. The code cannot contain commands but only function and method calls.

Description The OPERATOR statement can only be used in the class declaration between CLASS and ENDCLASS. It is the inline version of the METHOD...OPERATOR statement. Note: only regular operators can be used for . Special operators are not supported. when is a binary operator, the object must be the left operand for being executed.

Info See also: Category: Header: Source: LIB: DLL:

METHOD...OPERATOR Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example declares a String class and displays the // results of operations with a String object. #include "HbClass.ch" PROCEDURE Main LOCAL obj := String():New( "Hello ? ? ? ?

obj obj obj obj

= == !=

Statement Reference

"Hello" "Hello" "Hello" "Hello"

// // // //

" )

result: result: result: result:

.T. .F. .F. .F.

159

OPERATOR ? obj # ? obj $

"Hello" "Hello"

// result: .F. // result: .F.

? ? ? ?

"hello" "hello" "hello" "hello"

// // // //

"World" "World"

// result: Hello World // result: HelloWorld

obj obj obj obj

< >=

? obj + ? obj RETURN

CLASS String EXPORTED: DATA value

result: result: result: result:

.T. .T. .F. .F.

INIT ""

METHOD init( c ) INLINE ( IIf(valtype(c)=="C", ::value := c, ), self ) OPERATOR OPERATOR OPERATOR OPERATOR OPERATOR OPERATOR OPERATOR OPERATOR OPERATOR OPERATOR ENDCLASS

160

"=" "==" "!=" "=" "+" "-" "$"

ARG ARG ARG ARG ARG ARG ARG ARG ARG ARG

c c c c c c c c c c

INLINE INLINE INLINE INLINE INLINE INLINE INLINE INLINE INLINE INLINE

::value ::value ::value ::value ::value ::value ::value ::value ::value ::value

= == != < >= + $

c c c c c c c c c c

Statement Reference

OVERRIDE METHOD

OVERRIDE METHOD Replaces a method in an existing class.

Syntax OVERRIDE METHOD ; IN CLASS WITH

Arguments

This is the symbolic name of the method to replace. IN CLASS

This is the symbolic name of the class in which the method is replaced. WITH

This is the symbolic name of the function implementing the code for the replaced method.

Description The OVERRIDE METHOD statement replaces the implementation of a method in an existing class. When an object receives the message , the code implemented in is executed and the previous implementation is no longer accessible. is usually implemented as a STATIC FUNCTION where the self object is retrieved with HB_QSelf(). OVERRIDE METHOD can be used to replace the method implementation in a higher level of a class tree. This is especially useful when the source code of the classes is not available. However, great care must be taken in order not to break existing class inheritance. An alternative is the declaration of a sub-class using the FROM option in the class declaration and implement the new method in the sub-class.

Info See also: Category: Header: Source: LIB: DLL:

ASSOCIATE CLASS, DELEGATE, EXTEND CLASS...WITH METHOD, METHOD (implementation), OPERATOR Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Example // The example outlines how a method can be replaced in existing // classes and how the self object is retrieved in the implementation // of a replacement method. #include "hbclass.ch" PROCEDURE Main() LOCAL cVar := "Hello", GetList := {}

Statement Reference

161

OVERRIDE METHOD CLS OVERRIDE METHOD Display IN CLASS GET WITH MyGetDisplay OVERRIDE METHOD AsString IN CLASS ARRAY WITH MyArrayString @ 10,10 GET cVar ? GetList:AsString() RETURN STATIC FUNCTION MyGetDisplay LOCAl Self := HB_QSelf() Alert( ::VarGet() ) RETURN Self STATIC FUNCTION MyArrayString() LOCAl Self := HB_QSelf() RETURN "{ ... }"

162

Statement Reference

PARAMETERS

PARAMETERS Declares PRIVATE function parameters.

Syntax PARAMETERS

Arguments

This is a comma separated list of symbolic names for the parameters to declare.

Description The PARAMETERS statement declares the formal list of parameters for functions and procedures. The parameters are created as PRIVATE variables when the function or procedure is invoked. Note: It is recommended to list formal parameters within parentheses in the FUNCTION or PROCEDURE declaration. This results in the formal parameters being created as LOCAL variables. Access to LOCAL variables is faster than to PRIVATE variables.

Info See also: Category:

FUNCTION, LOCAL, PCount(), PRIVATE, PROCEDURE, PUBLIC, STATIC Declaration, Statements

Example // The example demonstrates two possible forms of declaring // parameters. The declaration shown with Sum2() is recommended. PROCEDURE Main ? Sum1( 10, 20 ) ? Sum2( 100, 200 ) RETURN FUNCTION Sum1 PARAMETERS n1, n2 RETURN n1 + n2 FUNCTION Sum2( n1, n2 ) RETURN n1 + n2

Statement Reference

163

pragma pack()

pragma pack() Defines the byte alignment for the next structure declaration.

Syntax pragma pack( [] )

Arguments

This is a numeric value specifying the byte alignment for the next typedef struct declaration. If is omitted, the byte alignment is set to 8 bytes.

Description xHarbour supports C structures with its typedef struct statement. Structure data is held in a contiguous block of memory which stores the values of all structure members. For efficient memory management, the values of structure members are aligned at an byte boundary. The default alignment is an 8 byte boundary.

Windows API structures All structures used with 32-bit Windows API functions must be aligned on a 4 byte boundary. That is, pragma pack(4) must be called before typedef struct. Otherwise, structure data is not correctly processed.

Info See also: Category: Header: LIB: DLL:

164

C Structure class, (struct), typedef struct C Structure support, xHarbour extensions cstruct.ch xhb.lib xhbdll.dll

Statement Reference

PRIVATE

PRIVATE Creates and optionally initializes a PRIVATE memory variable.

Syntax PRIVATE [:= ]

Arguments PRIVATE

is the symbolic name of the PRIVATE variable to createe.

is an optional value to assign to the PRIVATE variable after being created. To assign a value, the inline assignment operator (:=) must be used. The simple assignment operator (=) cannot be used.

Description The PRIVATE statement creates a dynamic memory variable that has PRIVATE scope. Private variables are resolved at runtime, i.e. their symbolic name exist while a program is being executed. This makes PRIVATE variables accessible for the Macro operator (&) at the expense of execution speed. The access to LOCAL variables is faster than to PRIVATE variables. Private variables are visible from the time of creation until the declaring routine returns, or until they are explicitely released. Visibility of PRIVATEs extends to all subroutines called after variable creation. A private variable can become temporarily hidden when a subroutine declares a variable having the same symbolic name. This can lead to subtle programming error, so that the use of PRIVATEs is discouraged unless there is good reason to use a PRIVATE variable. This is the case, for example, when it must be resolved within a macro expression. It is possible to initialize a private variable already in the PRIVATE statement. To accomplish this, the inline-assignment operator must be used. The value of any valid expression can be assigned. This includes literal values and the return values of functions. Note: PIVATE variables are declared with the MEMVAR statement and created with the PRIVATE statement. That means, PRIVATE is an executable statement that must follow all declaration statements. All undeclared variables that are assigned a value with the inline assignemnt operator, are created as PRIVATE variables.

Info See also: Category:

FIELD, GLOBAL, LOCAL, MEMVAR, PUBLIC, RELEASE, STATIC Declaration, Statements

Example // These examples show different initializations of PRIVATE variables. PROCDEURE Main PRIVATE nNumber := 5 PRIVATE aUsers[10]

Statement Reference

// initialized as numeric // array with 10 empty elements

165

PRIVATE PRIVATE nAge, cName dDate := Date() RETURN

166

// uninitialized // undeclared but initialized

Statement Reference

PROCEDURE

PROCEDURE Declares a procedure along with its formal parameters.

Syntax [STATIC] FUNCTION [FIELD [MEMVAR [LOCAL [STATIC

( [] ) [IN ]] ] [:= ] ,... ] [:= ] ,... ]

RETURN

Arguments PROCEDUR ( [] )

This is the symbolic name of the declared procedure. It must begin with a letter or underscore followed by digits, letters or underscores. The symbolic name can contain up to 63 characters. Optionally, the names of parameters accepted by the procedure can be specified as a comma separated list. These parameters have LOCAL scope within the procedure. When the procedure is declared as STATIC PROCEDURE, it is only visible within the PRG file that contains the procedure declaration and cannot be invoked from elsewhere. FIELD

An optional list of field variables to use within the PROCEDURE can be declared with the FIELD statement. MEMVAR

If dynamic memory variables, i.e. PRIVATE or PUBLIC variables, are used in the procedure, they are declared with the MEMVAR statement. LOCAL [:= ]

Local variables are declared and optionally initialized using the LOCAL statement. STATIC [:= ]

Static variables are declared and optionally initialized using the STATIC statement. RETURN

The RETURN statement terminates a procedure and branches control back to the calling routine. A procedure has no return value.

Description The PROCEDURE statement declares a procedure along with an optional list of parameters accepted by the function. Statements programmed in the procedure body form a self-contained part of a program that is executed when a procedure is called. Thus, tasks of a program can be split into several procedures, each of which performs a sub-task when invoked. Statement Reference

167

PROCEDURE

The body of a procedure ends with the next FUNCTION, PROCEDURE or CLASS declaration, or at the end of file, which implies that procedure declarations cannot be nested. The execution of a procedure ends when a RETURN statement is encountered in the procedure body. A procedure does not return a value to the calling routine, only functions have a return value. The RETURN value is the only difference between functions and procedures. When a procedure is declared with the STATIC modifier, its visibility is restricted to the PRG file that contains the STATIC PROCEDURE declaration. The names of STATIC procedures are resolved by the compiler and do not exist at runtime of a program. The names of non-STATIC procedures, also referred to as public procedures, are resolved by the linker and do exist at runtime. Thus, public procedures can be accessed by the Macro operator (&) while STATIC procedures cannot. It is possible to declare STATIC procedures with the same symbolic name in different PRG files. A name conflict to a public procedure with the same name declared in another PRG file does not arise. However, the symbolic names of public functions, procedures or classes must always be unique. When a procedure is invoked with values being passed to it, they are assigned to the formal parameters declared with . All variables declared in this list are LOCAL variables and their visibility is restricted to the statements programmed in the procedure body. The number of values passed to a procedure does not need to match the number of parameters declared. When fewer values are passed, the corresponding parameters are initialized with NIL. When more values are passed, the additional values are not asssigned to parameters but can be retrieved using function HB_AParams().

Info See also: Category:

FIELD, FUNCTION, HB_AParams(), LOCAL, MEMVAR, METHOD (declaration), PARAMETERS, PCount(), PRIVATE, PUBLIC, RETURN, STATIC Declaration, Statements

Example // The PROCEDURE statement is used in may other examples of // this documentation. See there.

168

Statement Reference

PROTECTED:

PROTECTED: Declares the PROTECTED attribute for a group of member variables and methods.

Syntax PROTECTED:

Description Protected member variables and methods are accessible in the class(es) declared in the PRG module and all subclasses. Subclasses are all classes that inherit directly or indirectly from the declared class. A protected member is accessible within the context of a METHOD implemented in the declaring PRG module or in the PRG module of a subclass. Protected members are not accessible within the context of FUNCTION and PROCEDURE.

Info See also: Category: Header: Source: LIB: DLL:

CLASS, DATA, EXPORTED:, HIDDEN:, METHOD (declaration) Class declaration, Declaration, xHarbour extensions hbclass.ch vm\classes.c xhb.lib xhbdll.dll

Statement Reference

169

PUBLIC

PUBLIC Creates and optionally initializes a PUBLIC memory variab le.

Syntax PUBLIC [:= ]

Arguments PUBLIC

is the symbolic name of the PUBLIC variable to createe.

is an optional value to assign to the PUBLIC variable after being created. To assign a value, the inline assignment operator (:=) must be used. The simple assignment operator (=) cannot be used. When a PUBLIC variable is not assigned a value upon creation, it is initialized with .F. (false). This is different to all other variable types, which are initialized with NIL, by default.

Description The PUBLIC statement creates a dynamic memory variable that has PUBLIC scope. Public variables are resolved at runtime, i.e. their symbolic name exist while a program is being executed. This makes PUBLIC variables accessible for the Macro operator (&) at the expense of execution speed. The access to GLOBAL variables is faster than to PUBLIC variables. Public variables are visible from the time of creation until they are explicitely released. Visibility of PUBLICs extends to the entire program, even if a PUBLIC variable is created in a sub -routine which has returned. A public variable can become temporarily hidden when a subroutine declares a variable having the same symbolic name. It is possible to initialize a public variable already in the PUBLIC statement. To accomplish this, the inline-assignment operator must be used. The value of any valid expression can be assigned. This includes literal values and the return values of functions. Note: PUBLIC variables are declared with the MEMVAR statement and created with the PUBLIC statement. That means, PUBLIC is an executable statement that must follow all declaration statements.

Info See also: Category:

FIELD, GLOBAL, LOCAL, MEMVAR, PRIVATE, RELEASE, STATIC Declaration, Statements

Example // This example creates PUBLIC variables in a sub-routine called from // the Main routine PROCEDURE Main ? Type( "dataPath" ) ? Type( "tempPath" )

// result: U // result: U

MakeConfig()

170

Statement Reference

PUBLIC ? dataPath ? tempPath RETURN

// result: C:\xhb\apps\data // result: C:\xhb\apps\temp

PROCEDURE MakeConfig() PUBLIC dataPath := "C:\xhb\apps\data" PUBLIC tempPath := "C:\xhb\apps\temp" RETURN

Statement Reference

171

REQUEST

REQUEST Declares the symbolic name of an external function or procedure for the linker.

Syntax REQUEST [,]

Arguments REQUEST

This is the symbolic name of a function or procedure to declare for the linker. When multiple names are declared, they must be separated with commas.

Description The REQUEST statement declares a symbolic name of a function or procedure for the linker. This is usually required when there is no direct call of a function or procedure in PRG code, for example when a function is only called within a macro-expression using the macro-operator. By requesting the symbolic name of a function, the linker is forced to link the corresponding function to the executable file.

Info See also: Category:

#include, EXTERNAL Declaration

Example // This example demonstrates a possible header file with some REQUEST // statements. The file can the be #included in PRG files that may // need the requested functions. ** File: Requests.ch REQUEST _ADS REQUEST HBObject // EOF

172

Statement Reference

RETURN

RETURN Branches program control to the calling routine.

Syntax RETURN []

Arguments

is an expression of arbitrary data type that is passed from methods or functions to the calling routine. Procedures do not have a return value.

Description The RETURN statement branches program control to the calling routine, eventually passing a value back. Before the called routine returns, all LOCAL and PRIVATE variables declared in this routine are discarded. When the RETURN statement is executed by the main, or root, routine of an application, control goes back to the operating system. Note: The RETURN statement is not the end of a FUNCTION or PROCEDURE declaration, it terminates execution of a called routine. It is possible to have multiple RETURN statements in the body of a FUNCTION or PROCEDURE declaration.

Info See also: Category:

BEGIN SEQUENCE, ErrorLevel(), FUNCTION, LOCAL, PRIVATE, PROCEDURE, PUBLIC, QUIT Control structures, Statements

Statement Reference

173

STATIC

STATIC Declares and optionally initializes a STATIC memory variable.

Syntax STATIC [:= ]

Arguments

is the symbolic name of the static variable to declare.

is an optional value to assign to the STATIC variable after being declared. To assign a value, the inline assignment operator (:=) must be used. The simple assignment operator (=) cannot be used. Only literal values are allowed for when declaring STATIC variables.

Description The STATIC statement declares a memory variable that has STATIC scope. Static variables are resolved by the compiler, i.e. their symbolic name cannot be retrieved during runtime. This makes acces to STATIC variables much faster than to memory variables of PRIVATE or PUBLIC scope, whose symbolic variable names exist at runtime. The names of STATIC variables cannot be included in macro-expressions since they cannot be resolved by the macro operator (&). This operator requires the symbolic name of a variable to exist at runtime. The lifetime of STATIC variables is identical with the lifetime of a program. Unlike LOCAL variables, whose values are discarded when the declaring routine executes the RETURN statement, STATIC variables keep their values during the entire execution cycle of a program. The value assigned to a STATIC variable is stored in this variable until it gets assigned a new value. The visibility of STATIC variables depends on the place of declaration: 1.

When the STATIC declaration appears at the top of a PRG file before any other executable statement, the STATIC variable has file wide scope, i.e. it can be seen by all routines programmed in that PRG file.

2.

When the STATIC declaration follows a FUNCTION, METHOD or PROCEDURE declaration, the variable can be seen only in the routine that declares the STATIC variable.

3.

STATIC variables cannot be seen outside the PRG file that contains the STATIC declaration.

When a routine executes the RETURN statement, all STATIC variables declared in that routine keep their values. The lines in PRG source code preceding the STATIC statement may not call executable code. They can only contain declaration statements, i.e. only the FUNCTION, METHOD, PROCEDURE statements, and the FIELD, LOCAL, MEMVAR or PARAMETERS variable declarations are allowed to precede the STATIC statement. It is possible to initialize a static variable already in the STATIC statement. To accomplish this, the inline-assignment operator must be used. The values assigned to STATIC variables must be programmed as literal values, i.e. the compiler must be able to resolve values assigned to STATIC 174

Statement Reference

STATIC

variables. It is not possible, for example, to initialize a STATIC variable with the RETURN value of a function, since this can only be resolved at runtime of a program. Note: symbolic name as a STATIC variable, only the STATIC variable is visible. PRIVATE or PUBLIC variables with the same name become visible again, when the STATIC variable gets out of scope, i.e. when the routine that declares the STATIC variable returns or calls a subroutine.

Info See also: Category:

FUNCTION, GLOBAL, LOCAL, PARAMETERS, PRIVATE, PROCEDURE, PUBLIC Declaration, Statements

Example // The example uses one PRIVATE variable and two STATIC variables to // demonstrate lifetime and visibility of STATIC variables. STATIC snFileWide := 100 PROCEDURE Main PRIVATE myVar := 10 ? ProcName(), snFileWide, myVar

// output: MAIN

100

10

Test1() Test2()

// output: TEST1 // output: TEST2

100 110

3 12

// output: TEST1

100

3

// output: TEST2

110

12

? snFileWide ? myVar RETURN

// output: 120 // output: 12

PROCEDURE Test1() STATIC myVar := 1 ? ProcName(), snFileWide, myVar += 2 snFileWide += 10 RETURN

PROCEDURE Test2() ? ProcName(), snFileWide, myVar += 2 snFileWide += 10 RETURN

Statement Reference

175

SWITCH

SWITCH Executes one or more blocks of statements.

Syntax SWITCH CASE [EXIT] [CASE [EXIT] ] [DEFAULT ] END

Arguments SWITCH

The value of must be of data type Character or Numeric. When it is of type Character, it must be a single character, not a character string. Numeric values must be integer values. CASE ..

is a constant value of the same data type as . It must be a singlecharacter or an integer numeric value.

Description The SWITCH statement compares a constant value against a series of constant values. It is similar to the DO CASE statement but outperforms it to a great extent due to the restrictions introduced with values permitted for comparison. As a general rule, only literal values in form of single characters or integer constants may follow the CASE clauses. The SWITCH statement evaluates and then searches for a first match between the resulting value and . When a match is found, the statements following the corresponding CASE clause are executed down to the END statement. To suppress execution of statements of the next CASE clause, the EXIT statement must be explicitely used. This is a major difference to the DO CASE statement where subsequent CASE clauses are skipped once a first match is found. If no initial match is found with the CASE clauses, the statements following DEFAULT are executed, if present.

Info See also: Category:

BEGIN SEQUENCE, DO CASE, FOR, FOR EACH, IF, TRY...CATCH Control structures, Statements, xHarbour extensions

Examples // The example demonstrates the SWITCH control structure with // EXIT statement PROCEDURE Main LOCAL nMonth := Month( Date() )

176

Statement Reference

SWITCH SWITCH nMonth CASE 1 CASE 2 CASE 3 ? "First Quarter" EXIT CASE 4 CASE 5 CASE 6 ? "Second Quarter" EXIT CASE 7 CASE 8 CASE 9 ? "Third Quarter" EXIT DEFAULT ? "Fourth quarter" END RETURN // The example demonstrates the SWITCH control structure without // EXIT statement PROCEDURE Main LOCAL x := "D" SWITCH x CASE "A" ? "A" CASE "B" ? "B" CASE "D" ? "DEF" CASE "H" ? "HIJ" DEFAULT ? "Default" END RETURN ** // // //

Output: DEF HIJ Default

Statement Reference

177

TRY...CATCH

TRY...CATCH Declares a control structure for error handling.

Syntax TRY [THROW( )] [CATCH [] [FINALLY ] END

Arguments

These are the regular programming statements to execute in the TRY...CATCH control structure. THROW

When an unexpected situation is detected in , a new Error object can be created explicitly and passed to the Throw() function. If is omitted and an error is detected by the xHarbour runtime, the Error object is created automatically. CATCH

This is an optionally declared variable that receives the error object passed to the Throw() function in the TRY section of the control structure. The statements following the CATCH clause are used for error handling. FINALLY

The finally section is guaranteed to be executed, no matter if an error was handled or not.

Description Any code that might throw an exception is placed inside of the try block. If an exception is thrown, the catch block is entered and the program can perform the appropriate operation to recover or alert the user. If FINALLY is specified, code within the FINALLY section is guranteed to be executed after the TRY section has been executed and the CATCH section is activated, unless the CATCH section throws an UNHANDLED Error. This means that the FINALLY section will be executed even if the CATCH section re-throws the error or attempts to RETURN. In such cases, the requested operation which forces out of the TRY section will be deferred until after the FINALLY section has been completed. Important: although CATCH and FINALLY are both marked as optional, at least one of these options must be used within a TRY...END control block.

178

Statement Reference

TRY...CATCH

Info See also: Category:

BEGIN SEQUENCE, Error(), ErrorBlock(), ErrorNew(), Throw() Control structures, Statements, xHarbour extensions

Example // The example demonstrates program flow for a TRY..CATCH sequence PROCEDURE Main() LOCAL oErr TRY ? "Trying" ? "Throwing" Throw( ErrorNew( "Finalize Test", 0, 0, "Forced Error" ) ) CATCH oErr ? "Caught:", oErr:Operation ? "Throwing to outer, should be deferred" Throw( oErr ) FINALLY ? "Finalized" END ? "Oops, should have Re-Thrown, after the FINALLY." RETURN

Statement Reference

179

typedef struct

typedef struct Declares a new structure in C syntax.

Syntax typedef struct [] { ; ; [ ] ; } [,]

Arguments

This is an optional tag name of a C structure which is normally required by a C compiler. It can be omitted with the xHarbour compiler, because is ignored.

The structure members are declared following the opening curly brace. A member declaration begins with the data type of the structure member. All data types listed in the #include file Wintypes.ch are recognized as C data types for member declarations.

This is the symbolic name of a structure member. It must follow the same naming rule like a memory variable. That is, it must begin with an underscore or an alphabetic character, followed by an underscore or alphanumeric characters.

This is the symbolic name of the structure to declare.

This is only used by a C compiler and ignored by the xHarbour compiler.

Description The typedef struct statement declares a new C structure class and implements it. C structures are supported in xHarbour for complete integration of non-xHarbour DLLs into an xHarbour application. Functions contained in external DLLs often require data being provided in form of structures, which is a data type that does not exist in xHarbour. The Hash() data type of xHarbour is similar to a C structure, but not identical. Structures organize multiple data in a contiguous block of memory. Individual data is held in so called "structure members" which are comparable to instance variables of an xHarbour object. As a matter of fact, the typedef struct statement declares an xHarbour class that has the instance variables to . These instance variables hold the values of structure members. A new structure object is created by specifying with the (struct) statement. The typedef struct statement is intentionally modelled in C syntax to provide an xHarbour programmer with the easiest form of structure declaration: Copy & Paste. C structures are only required when an xHarbour application needs to call a function in an external DLL via DllCall(). This applies to API functions of the operating system or Third Party DLLs. If such function expects a structure as 180

Statement Reference

typedef struct

parameter, the structure declaration is provided in include files (*.H file) and can be copied into the PRG code of the xHarbour application.

Structure declaration via Copy & Paste When a C structure declaration is copied from a *.H file into a PRG file, it must be modified so that the xHarbour preprocessor is capable of translating the typedef struct declaration. At minimum, one semicolon (;) must be added after the opening curly brace ({). This makes sure that the preprocessor recognizes the structure declaration as one line of PRG code. After the semicolon is added, the PRG should be compiled to see if the preprocessor recognizes all declarations. Common C data types are listed in the #include file Wintypes.ch. Any C data type not listed in this file must be mapped to the basic C data types listed in CStruct.ch. If a is not translated by the preprocessor, it is assumed to be the name of a structure that must be declared. If it is not declared, a runtime error is generated.

C strings C data types like CHAR, TCHAR or WCHAR are declared in C syntax like an array in xHarbour. For example: typedef struct { ; CHAR name[64] : } TESTSTRUCT

The structure member name is declared to hold 64 bytes. The C language treats this as a "byte array", while xHarbour programmers would use the data type "Character string" to represent this structure member. To reflect both "points of view", xHarbour structures provide a special object maintaining byte arrays. They have a method :asString() which returns the contents of a C byte array as an xHarbour Character string.

Info See also: Category: Header: Source: LIB: DLL:

C Structure class, DllCall(), pragma pack(), (struct) C Structure support, xHarbour extensions cstruct.ch, winapi.ch, wintypes.ch rtl\cstruct.prg xhb.lib xhbdll.dll

Example // // // // //

The example demonstrates how an xHarbour structure object can be passed to a Windows Api function. Note that the TIME_ZONE_INFORMATION structure holds two SYSTEMTIME structures in its members. In addition, the StandardName and DaylightName members contain Byte arrays. #include "CStruct.ch" #include "wintypes.ch"

// required for "typedef struct" // includes Windows C data types

pragma pack(4)

// all Windows structures are // aligned at a 4 byte boundary // structures are declared via // copy&paste from Windows SDK

typedef struct _SYSTEMTIME { ; WORD wYear; // ^ this ";" must be added WORD wMonth;

Statement Reference

181

typedef struct WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME;

typedef struct _TIME_ZONE_INFORMATION { ; LONG Bias; // ^ this ";" must be added WCHAR StandardName[32]; // member contains a byte array SYSTEMTIME StandardDate; // member contains a structure LONG StandardBias; WCHAR DaylightName[32]; SYSTEMTIME DaylightDate; LONG DaylightBias; } TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION;

#define DC_CALL_STD

0x0020

// calling convention for DllCall()

PROCEDURE Main // creation of structure object LOCAL oTimeZone := (struct TIME_ZONE_INFORMATION) // pass structure object by reference (it is an OUT parameter) DllCall( "Kernel32.dll", DC_CALL_STD, ; "GetTimeZoneInformation", @oTimeZone ) ? "Date :" // display structure data ? "Year :", oTimeZone:standardDate:wYear ? "Month:", oTimeZone:standardDate:wMonth ? "Day :", oTimeZone:standardDate:wDay ? ? "Regular time:" ? "Hour :", oTimeZone:standardDate:wHour ? "Min. :", oTimeZone:standardDate:wMinute ? "Sec. :", oTimeZone:standardDate:wSecond ? ? "Daylight saving time:" ? "Hour :", oTimeZone:dayLightDate:wHour ? "Min. :", oTimeZone:dayLightDate:wMinute ? "Sec. :", oTimeZone:dayLightDate:wSecond ? ? "Time zone:" ? "Std. :", oTimeZone:standardName:asString() ? "Sav. ;", oTimeZone:daylightName:asString() RETURN

182

Statement Reference

WITH OBJECT

WITH OBJECT Identifies an object to receive multiple messages.

Syntax WITH OBJECT : [] [:] END

Arguments WITH OBJECT

is the symbolic name of a variable that holds a reference to an object. The object is to receive messages in the WITH OBJECT control structure. :

All expressions that begin with the send operator in the OBJECT WITH block are sent as messages to .

Description The WITH OBJECT control structure delimits a block of statements where the object variable receives multiple messages in abbreviated form. The name of the object variable can be omitted from a message sending expression, so that only the send operator (:) followed by the message to send must be typed. WITH OBJECT basically relieves a programmer from typing. The name of the object variable is typed only once at the beginning of the WITH OBJECT block, and all subsequent messages sent to the object start with the send operator, omitting the object's variable name.

Info See also: Category:

CLASS, METHOD (implementation), HB_QWith(), HB_SetWith() Control structures, Statements, xHarbour extensions

Example // The example builds a simple database browser using a TBrowse object. // The columns added to the object and the cursor navigation logic is // programmed using the WITH OBJECT control structure. #include "inkey.ch" PROCEDURE Main LOCAL oTBrowse, aFields, cField, nKey USE Customer aFields := Array( FCount() ) AEval( aFields, {|x,i| aFields[i] := FieldName(i) } ) oTBrowse := TBrowseDB()

Statement Reference

183

WITH OBJECT WITH OBJECT oTBrowse FOR EACH cField IN aFields :addColumn( TBColumnNew( cField, FieldBlock( cField ) ) ) NEXT END nKey := 0 DO WHILE nKey K_ESC WITH OBJECT oTBrowse DO WHILE .NOT. :stabilize() ENDDO nKey := Inkey(0) SWITCH nKey CASE K_UP :up() CASE K_DOWN :down() CASE K_LEFT :left() CASE K_RIGHT :right() CASE K_PGUP :pageUp() CASE K_PGDN :pageDown() CASE K_HOME :home() CASE K_END :end() END END ENDDO

; EXIT ; EXIT ; EXIT ; EXIT ; EXIT ; EXIT ; EXIT ; EXIT

CLOSE Customer RETURN

184

Statement Reference

Command Reference

Command Reference

185

? | ??

? | ?? Displays values of expressions to the console window.

Syntax ? [] ?? []

Arguments

is an optional, comma separated list of expressions whose values are output. When no expression is specified, the ? command outputs a new line while ?? outputs nothing.

Description The ? and ?? commands are text mode console commands that display the result of a comma separated list of expressions to the currently selected output device. This can be the screen, or console window or the printer. The functional equivalent of both commands are the QOut() and QQOut() functions. The difference between ? and ?? is that the ? command first outputs a carriage-return/line-feed pair so that the output of always begins at a new line, while ?? outputs the values of at the current cursor or printhead position. The ? or ?? command first locates the current cursor or printhead position and shifts it one to the right. Row() and Col() are updated with the new cursor position if SET PRINTER is OFF, otherwise they are updated with the new printhead position. Should the output of ? or ?? reach the right border of the screen (defined by MaxCol()), it will wrap to the next line. Should the output of ? or ?? reach the bottom border of the screen (defined by MaxRow()), the screen will scroll up one line. It is possible to output the expression(s) to the printer by using the SET PRINTER ON before using the ? or ?? command. It is also possible to output to a text file using the SET ALTERNATE TO command, followed by the SET ALTERNATE ON command. The SET CONSOLE OFF command will prevent display on the screen without interrupting the output to the printer or text file. When the expression(s) need formatting, use the Transform() function or any user-defined function. For padding, use any of the Pad() functions to center, left align or right align the expression(s).

Info See also: Category: Source: LIB: DLL:

@...SAY, PadC() | PadL() | PadR(), QOut() | QQOut(), SET ALTERNATE, SET CONSOLE, SET DEVICE, SET PRINTER, Transform() Console commands rtl\console.c xhb.lib xhbdll.dll

Example // This example displays a list of expressions: PROCEDURE Main LOCAL var1 := 1, var2 := Date(), var3 := .T.

186

Command Reference

? | ?? ? "This line will be displayed on the console." ? "This line will be displayed beneath the previous line." ?? "No carriage return / linefeed for this expression!" ? var1, var2, var3, "These were variables" RETURN

Command Reference

187

@...BOX

@...BOX Displays a box on the screen.

Syntax @ , , , BOX ; [COLOR ]

Arguments and

Numeric values indicating the screen coordinates for the upper left corner of the @...BOX output. and

Numeric values indicating the screen coordinates for the lower right corner of the @...BOX output.

The appearance of the box to display is as a character string holding up to nine characters. The first eight characters define the border of the box while the ninth character is used to fill the box. #define constants to be used for are available in the BOX.CH #include file.

Pre-defined box strings for @...BOX Constant

Description

B_SINGLE B_DOUBLE B_SINGLE_DOUBLE B_DOUBLE_SINGLE

Single-line box Double-line box Single-line top, double-line sides Double-line top, single-line sides



An optional SetColor() compliant color string can be specified to draw the box. It defaults to the standard color of SetColor().

Description The @...BOX command displays a box on the screen as specified with , using the standard color of SetColor() or , if specified. The first eight characters of the string define the border of the box in clockwise direction, beginning with the upper left corner. An optional nineth character fills the area inside the box. Alternatively, a single character can be passed which is used to draw the entire box border. When the box is completely drawn, the cursor is positioned at the coordinates +1 and +1, so that Row() and Col() can be used to start displaying text in the upper left corner of the box area.

188

Command Reference

@...BOX

Info See also: Category: Header: LIB: DLL:

@...CLEAR, @...SAY, @...TO, DispBox(), Scroll() Output commands box.ch xhb.lib xhbdll.dll

Example // The example demonstrates how characters are used to draw a box. // Alphabetic characters define instead of characters // holding graphic signs. #include "Box.ch" PROCEDURE Main CLS @ 10, 10, 20, 50 BOX "AbCdEfGhi" COLOR "W+/R" Inkey(0) @ 10, 10, 20, 50 BOX B_DOUBLE + Space(1) @ Row(), Col() SAY "Using #define constant" @ MaxRow()-1, 0 RETURN

Command Reference

189

@...CLEAR

@...CLEAR Clears the contents of the screen.

Syntax @ , [ CLEAR [TO , ] ]

Arguments @ ,

Numeric values indicating the screen coordinates for the upper left corner of the @...CLEAR command. If the CLEAR option is not used, only one row of the screen is cleared from the position , to the rightmost column. CLEAR

When this option is used, a rectangular area on the screen is cleared, beginning at and down to and . TO ,

Numeric values indicating the screen coordinates for the lower right corner of the @...CLEAR command. defaults to MaxRow() and defults to MaxCol(). Both parameters require the CLEAR option be used.

Description The @...CLEAR command is used to clear a rectangular area on the screen in text mode applications. This is accomplished by displaying white space characters in the specified region using the standard color value of SetColor(). After the screen is cleared, the cursor is positioned at the top, left corner of the cleared rectangle. The new cursor position is reflected by the Row() and Col() functions.

Info See also: Category: Source: LIB: DLL:

@...BOX, CLEAR SCREEN, DispBox(), Scroll(), SetColor(), SetPos() Output commands rtl\scroll.c, rtl\setpos.c xhb.lib xhbdll.dll

Example // The example demonstrates various possibilities of // erasing the screen and parts thereof. PROCEDURE Main SetColor( "W+/B" ) CLEAR SCREEN SetColor( "W+/R" ) @ 2, 0

190

// deletes the second row

Command Reference

@...CLEAR @ 20, 40 CLEAR

// erase area to bottom/right

@

// use all four coordinates

5, 30 CLEAR TO 15, 55

RETURN

Command Reference

191

@...GET

@...GET Creates a Get object (entry field) and displays it to the screen

Syntax @ , [SAY GET [WHEN [VALID [MESSAGE [SEND

; [PICTURE ] COLOR ] ; [PICTURE ] [COLOR ] ; ] ; | RANGE , ] ; ] ; ]

Arguments @ ,

The parameters are numeric values specifying the row and column coordinates for the screen output. The range for rows on the screen is 0 to MaxRow(), and for columns it is 0 to MaxCol(). The coordinate 0,0 is the upper left corner of the screen. SAY

This is a value of data type C, D, L or N which is displayed in front of the Get object. It is typically a character string indicating the name of the entry field. PICTURE

If specified, is a character string holding the PICTURE format to be used for displaying . COLOR

The parameter is an optional character string defining the color for the output of . It defaults to the current SetColor() setting. When is specified as a literal color string, it must be enclosed in quotes. GET

This is a memory of field variable holding the value to be edited by the user, PICTURE

If specified, is a character string holding the PICTURE format to be used for display and editing of . COLOR

The parameter is an optional character string defining the colors for the display and editing of . It defaults to the current SetColor() setting. The first color value is used for the display of , while the second defines the editing color. When is specified as a literal color string, it must be enclosed in quotes. WHEN

This is a logical expression or a code block returning a logical value. If specified, must result in .T. (true) to allow editing. If the expression yields .F. (false), the Get object is not editable but skipped. 192

Command Reference

@...GET VALID

This is a logical expression or a code block returning a logical value. If specified, must result in .T. (true) to end editing. When the result is .F. (false), the currently edited value of is invalid and the user cannot leave the Get object unless editing is cancelled. RANGE ,

When the value of is numeric or a Date, the minimum and maximum values allowed for can be specified with the RANGE clause. Note that RANGE and VALID are mutually exclusive. MESSAGE

This is an optional character string displayed in the message row when a Get object is active. The message row is defined with the MSG AT option of the READ command. SEND

This is an optional message to be sent to the Get object before it is displayed. Refer to the Get class for possible messages that can be sent to the Get object.

Description The @...GET command creates a new object of the Get class, adds it to the GetList array and displays it to the screen. The GetList array is a default PUBLIC varible that is reserved for being used by the Get system. It is recommended, however, to declare a new variable named GetList and initialize it with an empty array before the first @...GET command is issued. The value to be edited is held in the variable . If the SAY clause is used, is displayed at the screen position , , followed by the value of . The PICTURE clause optionally specifies a picture format string for the display of , while the COLOR defines the color. Refer to SetColor() and Transform() for color values and picture formatting of the SAY clause. If PICTURE is specified, it defines the picture formatting of for display and editing. See the table below for these picture formatting rules. If the WHEN clause is specified, it determines wether or not a Get object can receive input focus during the READ command. The expression must be a logical expression or a code block returning a logical value. If yields .T. (true) the corresponding Get object receives input during READ. When it is .F. (false) this Get object is skipped during READ. The VALID clause is similar to the WHEN clause, but it is evaluated during the READ command before the user advances to the next get object, i.e. before the current Get object looses input focus. If yields .T. (true), the next Get object receives input focus. Otherwise, the input focus remains with the current Get object and the user must change the edited value until results in .T. (true), or editing is cancelled. Instead of the VALID clause, the RANGE option can be used for numeric values and Dates. The minimum and maximum value valid for must then be specified with and . The PICTURE clause defines the formatting of for display and editing. It is a character string defining a picture function and/or template. A picture function begins with the @ character. If the picture string contains both, the picture function must appear first, followed by a blank space and the template characters.

Command Reference

193

@...GET

PICTURE functions for editing @A

Only alphabetic characters are allowed.

@B @C @D @E @K @R @S

Numbers are left justified. CR is displayed after positive numbers. Date values are displayed in the SET DATE format. Dates are displayed in British format, numbers in European format. Clears the Get when the first key pressed is alphanumeric. Inserts non-template characters for display. Limits the display to characters and allows horizontal scrolling when the edited value exceeds . DB is displayed after negative numbers. Displays zero values as blanks. Forces all letters to uppercase. Displays negative numbers in parentheses with leading spaces. Displays negative numbers in parentheses without leading spaces.

@X @Z @! @( @)

PICTURE templates for editing A

Only alphabetic characters are allowed.

N X L Y 9 # ! $

Only alphanumeric characters are allowed Any character is allowed. Only T or F is allowed For logical values. Only Y or N is allowed for logical values. Only digits, including signs, are allowed. Only digits, signs and blank spaces are allowed. Alphabetic characters are converted to uppercase. The dollar sign is displayed in place of leading spaces for numbers. Numbers are padded with the asterisk. Position of the decimal point. Position of the comma.

* . ,

Info See also: Category: Source: LIB: DLL:

@...SAY, @...CLEAR, Col(), Get(), GetNew(), GetReader(), READ, ReadModal(), Row() Get system, Input commands rtl\getsys.prg, rtl\tgetlist.prg xhb.lib xhbdll.dll

Example // The example displays two Get entry fields using // different picture formatting rules PROCEDURE Main() LOCAL GetList := {} LOCAL cVar := Space(50) LOCAL nId := 0 CLS @ 3,1 SAY "Name" GET cVar PICTURE "@!S 30" @ 4,1 SAY "Id " GET nId PICTURE "999.999" READ

194

Command Reference

@...GET ? "The name you entered is", cVar ? "The id you entered is" , nId RETURN

Command Reference

195

@...PROMPT

@...PROMPT Displays a menu item for a text mode menu.

Syntax @ , PROMPT ; [MESSAGE ]

Arguments @ ,

Numeric values indicating the screen coordinates for the display of . PROMPT

A character string holding the menu item of the text mode menu. MESSAGE

Optionally, a character string can be associated with which is displayed as a message when SET MESSAGE is set to a screen row larger than zero. Instead of a character string, a code block can be specified. In must return a character string.

Description The @...PROMPT command is used to define a single menu item of a simple text mode menu. A text mode menu is usually built by specifying the @...PROMPT command multiple times before the MENU TO command is issued to activate the menu. The screen cursor is located one column to the right of after @...PROMPT has displayed the menu item. Note: For an example of @...PROPMT usage see the MENU TO command.

Info See also: Category: Source: LIB: DLL:

196

AChoice(), MENU TO, SET MESSAGE, SET WRAP, SetColor() Input commands rtl\menuto.prg xhb.lib xhbdll.dll

Command Reference

@...SAY

@...SAY Displays data at a particular row and column position.

Syntax @ , SAY [PICTURE [COLOR

; ; ] ; ]

Arguments @ ,

The parameters are numeric values specifying the row and column coordinates for the output. The range for rows on the screen is 0 to MaxRow(), and for columns it is 0 to MaxCol(). The coordinate 0,0 is the upper left corner of the screen. When SET DEVICE TO PRINTER is active, the largest coordinate for both, row and column, is 32766. SAY

This is an expression whose value is output to the current device. PICTURE

The PICTURE clause defines a character string which specifies how to format the value of for output. See the explanation of formatting rules below. COLOR

The parameter is an optional character string defining the color for output. It defaults to the current SetColor() setting. When is specified as a literal color string, it must be enclosed in quotes.

Description @...SAY is a text-mode output command that outputs the value of an expression to the current device, which is either the screen or a printer. Only values of simple data types like Character, Date, Numeric and Logic are output. Complex values, like Array or Object cannot be used with @...SAY. The output device for @...SAY is selected with the SET DEVICE command. The SET CONSOLE setting has no effect. When the SCREEN is the output device, @...SAY outputs the value of at the specified row and column position and moves the screen cursor to the end of the displayed value. Row() and Col() reflect the new position of the cursor. With printed output, the printhead position is changed and PRow() and PCol() are updated accordingly. When the row coordinate for printed output is smaller than the current value of PRow(), an EJECT command is automatically sent to the printer. If the column coordinate including SET MARGIN is smaller than the current value of PCol(), a "new line" command is sent to the printer along with the number of spaces to position the printhead to the new column. To redirect the @...SAY output to a file, SET DEVICE TO PRINTER and SET PRINTER TO . The output color can be specified with a color string compliant with the SetColor() function. The default color used is the standard color, which is the first color value of a color string. Command Reference

197

@...SAY

Output can be formatted using the PICTURE clause. It specifies a character string that may consist of two parts: a picture function and a picture mask. A picture function begins with the @ sign, followed by one or more letters indicating a picture function to apply. A picture mask is a series of characters. When both, picture function and mask, are used in the picture string, they must be separated with a single space character and the picture function must be placed first in the picture string.

Picture function A picture function specifies formatting rules for the entire output string. It must begin with the @ sign followed by one or more letters listed in the table below:

Picture function characters Function

Formatting rule

B C D E L R X Z ( !

Displays numbers left-justified Displays CR after positive numbers Displays dates in SET DATE format Displays dates and numbers in British format Displays numbers with leading zeros instead of blank spaces Nontemplate characters are inserted Displays DB after negative numbers Displays zeros as blanks Encloses negative numbers in parentheses Converts alphabetic characters to uppercase

Picture mask The picture mask must be separated by a single space from the picture function. When no picture function is used, the picture string is identical with the picture mask. The mask defines formatting rules for individual characters in the output string. Characters from the following table can be used. The position of a character of a picture mask specifies formatting for the character of the output string at the same position. An exception is the @R function which causes non-mask characters being inserted into the output string.

Picture mask characters

198

Character

Formatting rule

A,N,X,9,# L Y ! $ * . ,

Displays digits for any data type Displays logicals as "T" or "F" Displays logicals as "Y" or "N" Converts alphabetic characters to uppercase Displays a dollar sign in place of a leading space in a number Displays an asterisk in place of a leading space in a number Specifies a decimal point position Specifies a comma position

Command Reference

@...SAY

Info See also: Category: Source: LIB: DLL:

? | ??, @...CLEAR, @...GET, Col(), GetNew(), PCol(), PRow(), QOut() | QQOut(), Row(), SetColor(), Transform() Output commands rtl\console.c xhb.lib xhbdll.dll

Example // The example demonstrates different formatting with @...SAY and // the PICTURE clause PROCEDURE Main LOCAL nGain LOCAL nLoss LOCAL cPhone LOCAL cName

:= := := :=

8596.58 -256.50 "5558978532" "Jon Doe"

@ 10, 1 SAY nGain PICTURE "@E 9,999.99" // result: 8.596,58 @ 11, 1 SAY nLoss PICTURE "@)" // Result: (256.50) @ 12, 1 SAY cPhone PICTURE "@R (999)999-9999" // Result: (555)897-8532 @ 13, 1 SAY cName PICTURE "@!" // Result: JOHN DOE RETURN

Command Reference

199

@...TO

@...TO Displays a single or double lined frame on the screen.

Syntax @ , TO , ; [COLOR ] [DOUBLE]

Arguments @ ,

Numeric values indicating the screen coordinates for the upper left corner of the frame to display. TO ,

Numeric values indicating the screen coordinates for the lower right corner of the frame to display.

An optional SetColor() compliant color string can be specified to draw the frame. It defaults to the standard color of SetColor(). DOUBLE

This option displays the frame with a double line. If omitted, a single line is used.

Description The @...TO command displays a frame on the screen using the standard color of SetColor() or , if specified. When the frame is completely drawn, the cursor is positioned at the coordinates +1 and +1, so that Row() and Col() can be used to start displaying text in the upper left corner of the frame area.

Info See also: Category: Source: LIB: DLL:

@...BOX, @...CLEAR, DispBox() Output commands rtl\box.c xhb.lib xhbdll.dll

Example // The example displays two frames using different colors and // borders. PROCEDURE Main CLS @ 10, 5 TO 20, 35 COLOR "W+/B" @ Row(), Col() SAY "Single" @ 10, 45 TO 20, 75 COLOR "N/BG" DOUBLE

200

Command Reference

@...TO @ Row(), Col() SAY "Double" RETURN

Command Reference

201

ACCEPT

ACCEPT Basic user input routine.

Syntax ACCEPT [] TO

Arguments

This is an optional expression of data type C, D, L or N. The value of is displayed before the user can input data.

This is a character string holding the name of the variable to assign the user input to. It must be of PRIVATE or PUBLIC scope. If does not exist, a PRIVATE variable is created.

Description The ACCEPT command exists for compatibility reasons only. It is a very basic text-mode command that accepts user input to be assigned as a character string to a single memory variable. During user input only the Return key is recognized as termination key. The Escape key does not terminate the ACCEPT command.

Info See also: Category: Source: LIB: DLL:

@...GET, @...SAY, Inkey(), INPUT, KEYBOARD Input commands rtl\accept.c xhb.lib xhbdll.dll

Example // The example shows a simple command line utility used to // count the lines in an ASCII file. Note the PARAMETERS // statement: it declares a parameter of PRIVATE scope for Main(). PROCEDURE Main PARAMETERS cFileName IF Empty( cFileName ) ACCEPT "Enter a file name: " TO cFileName ENDIF IF Empty( cFileName ) ? "User aborted" ELSEIF .NOT. File( cFileName ) ? "File not found:", cFileName ELSE ? "Line count:", LTrim( Str( FLineCount( cFileName ) ) ) ENDIF RETURN

202

Command Reference

APPEND BLANK

APPEND BLANK Creates a new record in the current work area.

Syntax APPEND BLANK

Description The APPEND BLANK command creates a new record for the database file open in the current work area and moves the record pointer to the new record. All fields of the record are filled with empty data of the corresponding field data types. That is: Character fields are filled with blank spaces, Date fields contain CtoD(""), logical fields contain .F. (false), Memo fields contain nothing and Numeric fields contain 0. Shared file access: When the database is opened in SHARED mode, the APPEND BLANK command attempts to lock the ghost record before appending a new record to the file (the ghost record is the one located at LastRec()+1). If this record lock fails, function NetErr() is set to .T. (true) and no record is appended. When the record lock succeeds, it remains active until a new APPEND BLANK command is issued or the lock is explicitely released with the UNLOCK command. A file lock obtained with the FLock() function is not released by the APPEND BLANK command. Note: APPEND BLANK works only in the current work area. Its functional equivalent is the DbAppend() function which can create a new record in other work areas when used in an aliased expression.

Info See also: Category: Source: LIB: DLL:

APPEND FROM, DbAppend(), FLock(), Neterr(), RLock(), USE Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The examples demonstrates a basic technique for creating a new record // in a shared database: PROCEDURE Main LOCAL cFirstName := Space(40) LOCAL cLastName := Space(50) USE Address ALIAS Addr SHARED NEW IF .NOT. NetErr() SET INDEX TO AddressA, AddressB ENDIF CLS @ 10,5 SAY "Enter first name:" GET cFirstName @ 11,5 SAY "Enter last name :" GET cLastName READ IF .NOT. Empty( cFirstName + cLastName ) APPEND BLANK IF NetErr() ? "Unable to create new record"

Command Reference

203

APPEND BLANK ELSE REPLACE addr->FirstName WITH cFirstName addr->LastName WITH cLastName ENDIF ENDIF

, ;

USE RETURN

204

Command Reference

APPEND FROM

APPEND FROM Imports records from a database file or an ASCII text file.

Syntax APPEND FROM ; [FIELDS ;] [ ; ] [WHILE ;] [FOR ;] [VIA ] [SDF | DELIMITED [WITH BLANK | TAB | PIPE | ] ]

Arguments FROM

This is the name of the source file as a literal character string or a character expression enclosed in parentheses. When the file name is specified without a file extension, .dbf is assumed as default extension, unless the SDF or DELIMITED option is specified. In this case, the default file extension is .txt. FIELDS

The names of the fields to import from the external file can be specified as a comma separated list of literal field names or character expressions enclosed in parentheses. When this option is omitted, all fields of the source file are imported.

This option defines the number of records to import. It defaults to ALL. The NEXT scope imports the first records, while the RECORD scope imports only one record having the record number . WHILE

This is a logical expression indicating to continue importing records while the condition is true. The APPEND FROM operation stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the source file. Those records where yields .T. (true) are imported. VIA

The VIA option specifies the replaceable database driver (RDD) to use for opening the source file. is a character expression. If it is written as a literal name, it must be enclosed in quotes. When no RDD is specified, the RDD active in the current work area is used to open the import file. If the VIA clause is used, the specified RDD must be linked to the application. Use the REQUEST command to force an RRD be linked. SDF

The SDF option specifies the source file as an ASCII file in System Data Format. See file format description below. Command Reference

205

APPEND FROM DELIMITED

The DELIMETED option specifies the source file as a delimited ASCII file where field values are separated with a comma and Character values are enclosed with a delimiting character. The default delimiter for Character values is a double quotation mark. DELIMITED WITH BLANK | TAB | PIPE

When the delimiter is specifiwed as BLANK, field values in the ASCII text file are separated by one space and character fields are not enclosed in delimiters. Alternatively, the delimiting character between field values can be specified as TAB (Chr(9)) or PIPE (Chr(124)). DELIMITED WITH

The WITH option specifies the delimiting character to enclose values of Character fields in. can be specified as a literal character or a character expression enclosed in parentheses. can also be specified as an array with two elements: { , }. If this option is used, the array must be enclosed in parentheses. It defines the delimiting characters for field values of type "C" and the delimiters between field values. Important: If the DELIMITED WITH option is used in the APPEND FROM command, it must be placed as the last option in the command.

Description APPEND FROM is a database command used to import data from a second file into the current work area. Imported records are added to the end of the table open in the current work area. When the external file is a database, only fields with matching names are imported. Fields with matching names must have the same data type, otherwise a runtime error occurs. The file in the current work area can be opened in SHARED mode. APPEND FROM automatically maintains required record locks while data is being imported. The import file is attempted to be opened in SHARED and READONLY mode. If opening the import file fails, APPEND FROM raises a runtime error. When the external file is an ASCII text file, all date values must be stored in the StoD() compliant format yyyymmdd. Other specifications for supported ASCII formats ar listed in the folowing tables:

SDF Text File File Element

Format

Character fields Date fields Logical fields Memo fields Numeric fields Field separator Record separator End of file marker

Padded with trailing blanks yyyymmdd T or F Ignored Padded with leading blanks or zeros None Carriage return/linefeed 0x1A or CHR(26)

DELIMITED Text File

206

File Element

Format

Character fields Date fields

May be delimited, with trailing blanks truncated yyyymmdd Command Reference

APPEND FROM Logical fields Memo fields Numeric fields Field separator Record separator End of file marker

T or F Ignored Leading zeros may be truncated Comma Carriage return/linefeed 0x1A or CHR(26)

DELIMITED WITH BLANK Text File File Element

Format

Character fields Date fields Logical fields Memo fields Numeric fields Field separator Record separator End of file marker

Not delimited, trailing blanks may be truncated yyyymmdd T or F Ignored Leading zeros may be truncated Single blank space Carriage return/linefeed 0x1A or CHR(26)

Field length: When the length of Character fields in the current work area is shorter than the length of a corresponding field in the import file, character data is truncated up to the length of the field in the current work area. Truncated data is lost. If the field is longer, remaining characters are filled with blank spaces. When the length of a numeric field in the current work area does not suffice to hold all digits of an imported numeric field, a runtime error is created. Deleted records: Records in an import database file that are marked for deletion are ignored when SET DELETED is set to ON. These records are not imported. With SET DELETED OFF, all records matching the import scope are imported and the deleted flag is set accordingly.

Info See also: Category: Source: LIB: DLL:

COPY TO, DbAppend(), UPDATE Database commands rdd\dbcmd.c, rtl\dbdelim.prg xhb.lib xhbdll.dll

Example // The example creates a subset of records from a database // within an intermediate file. PROCEDURE Main USE Address NEW COPY STRUCTURE TO Tmp USE Tmp

// create an intermediate file

APPEND FROM Address FOR "LONDON" $ Upper(CITY) Browse() USE ERASE Tmp.dbf RETURN

Command Reference

// delete intermediate file

207

AVERAGE

AVERAGE Calculates the average of numeric expressions in the current work area.

Syntax AVERAGE ; TO ; [] ; [WHILE ] ; [FOR ]

Arguments AVERAGE

This is a comma separated list of numeric expressions that are evaluated for the records of the current work area. TO

A comma separated list of variable names that are assigned the results of the calculation. The number of must match exactly the number of .

This option defines the number of records to process. It defaults to ALL. The NEXT scope processes the next records. WHILE

This is a logical expression indicating to continue calculation while the condition is true. The AVERAGE operation stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are included in the calculation.

Description The AVERAGE command is used to calculate average values for one or more numeric expressions. The expressions are evaluated in the current work area. The number of records to include in the calculation can be restricted using a FOR and/or WHILE condition or by explicitely defining a scope.

Info See also: Category: Source: LIB: DLL:

COUNT, DbEval(), SUM, TOTAL Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // This example calculates the average payments for the first half // of this year: PROCEDURE Main

208

Command Reference

AVERAGE LOCAL nAvg USE Sales NEW AVERAGE Payment TO nAvg FOR Month(SALEDATE) < 7 .AND. ; Year(SALEDATE) == Year(Date()) USE ? nAvg RETURN

Command Reference

209

CANCEL

CANCEL Terminates program execution unconditionally.

Syntax CANCEL

Description CANCEL is a compatibility command that is replaced by the QUIT command. Both perform the same action of terminating an xHarbour application.

Info See also: Category: Source:

QUIT Environment commands Library is rtl.lib

Example // Refer to the QUIT command

210

Command Reference

CLEAR ALL

CLEAR ALL Closes files in all work areas and releases all dynamic memory variables.

Syntax CLEAR ALL

Description The CLEAR ALL command closes all databases and associated files, like index and memo files, releases all dynamic memory variables (PRIVATE amd PUBLIC variables), closes alternate files, and finally selects work area 1 as current. As a result, all resources related to work areas and dynamic memory variables are released. Note: GLOBAL, LOCAL and STATIC memory variables cannot be released with CLEAR ALL. Also, files opened with FOpen() remain open.

Info See also: Category: LIB: DLL:

CLEAR MEMORY, CLOSE, RELEASE, RESTORE, SAVE, USE, SET ALTERNATE, SET PRINTER Memory commands xhb.lib xhbdll.dll

Command Reference

211

CLEAR MEMORY

CLEAR MEMORY Releases all dynamic memory variables.

Syntax CLEAR MEMORY

Description The CLEAR MEMORY command releases all dynamic memory variables (PRIVATE and PUBLIC variables). When the command is complete, neither symbolic names of PRIVATE and PUBLIC variables exist nor their values. This is different from the RELEASE command, which assigns the value NIL to dynamic variables currently visible. Note: GLOBAL, LOCAL and STATIC memory variables are not affected by CLEAR MEMORY.

Info See also: Category: Source: LIB: DLL:

212

CLEAR ALL, CLEAR GETS, RELEASE, RESTORE, SAVE Memory commands rtl\memvars.c xhb.lib xhbdll.dll

Command Reference

CLEAR SCREEN

CLEAR SCREEN Clears the screen in text mode.

Syntax CLEAR SCREEN or CLS

Description CLEAR SCREEN is used in text-mode applications to erase the entire screen display and move the cursor to position 0,0.

Info See also: Category: Source: LIB: DLL:

@...CLEAR, Scroll(), SetPos() Output commands rtl\scroll.c, rtl\setpos.c xhb.lib xhbdll.dll

Command Reference

213

CLEAR TYPEAHEAD

CLEAR TYPEAHEAD Empties the keyboard buffer.

Syntax CLEAR TYPEAHEAD

Description The CLEAR TYPEAHEAD command clears the keyboard buffer by removing all pending key strokes from the internal buffer. Key strokes are collected in this buffer, for example, when the user holds a key pressed and the application needs more time for processing key strokes than recording them. CLEAR TYPEAHEAD is particularly used before calling a function that supports a default key handling, such as Achoice() or DbEdit() or MemoEdit(). When CLEAR TYPEAHEAD is called before such functions, they begin in a defined state.

Info See also: Category: Source: LIB: DLL:

HB_KeyPut(), Inkey(), KEYBOARD, SET TYPEAHEAD Input commands rtl\inkey.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of clearing the keyboard // buffer PROCEDURE MAIN KEYBOARD "xHarbour" DO WHILE NextKey() 0 ? Chr( Inkey() ) ENDDO

// produce screen output // by polling the keyboard // buffer

KEYBOARD "xHarbour" CLEAR TYPEAHEAD DO WHILE NextKey() 0 ? Chr( Inkey() ) ENDDO

// No screen output

RETURN

214

Command Reference

CLOSE

CLOSE Closes one or more specified files.

Syntax CLOSE [ | ALL | ALTERNATE | DATABASES | FORMAT | INDEXES ]

Arguments

This is the alias name of the work area whose files should be closed. It can be specified as a literal alias name or a character expression enclosed in parentheses. ALL

This option closes all files in all work areas. Work areas become unused with all filters, indexes, relations and format definitions released. In addition, alternate files are closed. ALTERNATE

Only the currently open alternate file is closed. The option has the same effect as issuing the SET ALTERNATE TO command without a file name. DATABASES

All files associated with work areas are closed. This affects database, index and memo files. All work areas become unused with all filters, indexes and relations released. The current format definition stays intact. FORMAT

Only the currently defined format definition is released. The option has the same effect as issuing the SET FORMAT TO command without a format name. INDEXES

All index files open in the current work area are closed.

Description The CLOSE command accepts various options to specify one of more files to close. When it is invoked without an option, the files in the current work area are closed. This has the same effect as the USE command called with no file name.

Info See also: Category: Source: LIB: DLL:

DbCloseAll(), DbCloseArea(), QUIT, RETURN, SET ALTERNATE, SET INDEX, Set(), USE Database commands, Environment commands rdd\dbcmd.c, rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of the CLOSE command // together with different options

Command Reference

215

CLOSE PROCEDURE Main USE Address ALIAS Addr INDEX Addr1, Addr2 ? IndexOrd()

// result: 1

CLOSE INDEXES ? IndexOrd() ? Alias()

// result: 0 // result: ADDR

CLOSE Addr ? Alias()

// result: ""

RETURN

216

Command Reference

COMMIT

COMMIT Writes memory buffers of all used work areas to disk.

Syntax COMMIT

Description The COMMIT command flushes the memory buffers of all used work areas and writes them to disk. Data held in memory for database and index files are permanently written to the respective files. Changes to the data become visible to other processes in a network environment. It is recommended to call COMMIT before UNLOCK. To flush the memory buffers of a single work area, call function DbCommit().

Info See also: Category: Source: LIB: DLL:

DbCommit(), DbCommitAll(), GO, SKIP Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The examples demonstrates a basic technique for changing a record // in a shared database: PROCEDURE Main LOCAL cFirstName := Space(40) LOCAL cLastName := Space(50) USE Address ALIAS Addr SHARED NEW IF ! NetErr() SET INDEX TO AddressA, AddressB ENDIF CLS @ 10,5 SAY "Enter first name:" GET cFirstName @ 11,5 SAY "Enter last name :" GET cLastName READ IF .NOT. RLock() ? "Unable to lock record" ELSE REPLACE addr->FirstName WITH cFirstName addr->LastName WITH cLastName COMMIT UNLOCK ENDIF

, ;

USE RETURN

Command Reference

217

CONTINUE

CONTINUE Resumes a pending LOCATE command.

Syntax CONTINUE

Description The CONTINUE command resumes a database search initiated with the LOCATE command in the current work area. The search is continued with the FOR condition specified with the last LOCATE command. The scope restriction and WHILE condition of LOCATE is ignored. CONTINUE searches for the next record in the current work area that matches the FOR condition of the last LOCATE command issued for the current work area. If a match is found, the record pointer is positioned on this record and the Found() function returns .T. (true). When there is no match, the record pointer is positioned on the ghost record (Lastrec()+1), function Found() returns .F. (false) and function Eof() returns .T. (true). Each work area can have its own LOCATE condition. It remains active until a new LOCATE command is executed or the work area is closed.

Info See also: Category: Source: LIB: DLL:

DbSeek(), Eof(), Found(), LOCATE, SEEK Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example uses LOCATE and CONTINUE to list customers // living in the city of New York. PROCEDURE MAIN LOCAL cCity := "New York" FIELD FirstName, LastName USE Customer NEW LOCATE FOR Upper(FIELD->City) = Upper(cCity) DO WHILE Found() ? LastName, FirstName CONTINUE ENDDO CLOSE Customer RETURN

218

Command Reference

COPY FILE

COPY FILE Copies a file to a new file or to an output device.

Syntax COPY FILE TO |

Arguments

This is the name of the source file to copy. It must include path and file extension and can be specified as a literal file name or as a character expression enclosed in parentheses. TO

This is the name of the target file to create. It must include path and file extension and can be specified as a literal file name or as a character expression enclosed in parentheses. TO

This is the name of an output device, such as LPT1, for example. It can be specified as a literal device name or as a character expression enclosed in parentheses. When the device does not exist, a file with the name is created.

Description COPY FILE is a file command that copies a source file to a new file or output device. When does not include drive and directory information, the file is searched first in the current directory and then in the directory specified with SET DEFAULT. If is not found, a runtime error is generated. When exists, it is overwritten without warning.

Info See also: Category: Source: LIB: DLL:

COPY TO, ERASE, FErase(), File(), FRename(), RENAME, SET DEFAULT File commands rtl\copyfile.c xhb.lib xhbdll.dll

Example // This example demonstrates various possibilities of the COPY FILE // command PROCEDURE Main LOCAL cFile := "TEST.TXT" COPY FILE (cFile) TO Tmp.txt COPY FILE Tmp.txt TO LPT1 RETURN

Command Reference

219

COPY STRUCTURE

COPY STRUCTURE Copies the current database structure to a new database file.

Syntax COPY STRUCTURE [FIELDS ] ; TO

Arguments FIELDS

A comma separated list of literal field names, or character expressions enclosed in parentheses, specifies the database fields of the current work area to be included in the new database file. When no fields are specified, all fields are included. TO

This is the name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses.

Description COPY STRUCTURE is a database command used for creating an empty database file based on the field definitions of the current work area. All fields of the current work area are used for the new database unless a list of field names is provided. Should already exist, it will be overwritten without warning.

Info See also: Category: Source: LIB: DLL:

APPEND FROM, COPY STRUCTURE EXTENDED, CREATE, DbAppend(), DbCopyStruct(), DbCopyExtStruct(), DbCreate() Database commands rtl\dbstrux.prg xhb.lib xhbdll.dll

Example // The example demonstrates a technique for creating a subset of records // in a temporary database file. PROCEDURE Main USE Address NEW COPY STRUCTURE TO Temp USE Temp APPEND FROM Address FOR Trim(Upper(Address->City)) = "LONDON" < database operations with temporary file > CLOSE Temp ERASE Temp.dbf RETURN

220

Command Reference

COPY STRUCTURE EXTENDED

COPY STRUCTURE EXTENDED Copies field information to a new database file.

Syntax COPY STRUCTURE EXTENDED TO

Arguments TO

This is name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses.

Description The COPY STRUCTURE EXTENDED command copies field information of the current work area into a new database file. Field information is stored in the records of the new file and can be retrieved using the following pre-defined field names and database structure:

Fields in a structure extended file Position

Field name

Type

Length

Decimals

1 2 3 4

FIELD_NAME FIELD_TYPE FIELD_LEN FIELD_DEC

Character Character Numeric Numeric

10 1 3 4

0 0 0 0

A database of this structure is called "structure extended" since it stores structural information of a database in its records. The CREATE FROM database command can then be used to create a database file of this structure programmatically. Note: The length of a field of type Character is calculated as the sum of FIELD_LEN plus 256 * FIELD_DEC. The maximum length, however, is limited to 64k. Use a MEMO field to store longer Character strings.

Info See also: Category: Source: LIB: DLL:

COPY STRUCTURE, CREATE, CREATE FROM, DbCopyExtStruct(), DbCreate(), DbStruct(), FieldName(), Type() Database commands rtl\dbstrux.prg xhb.lib xhbdll.dll

Example // The examples demonstrates a technique for changing the structure of // an existing database file at runtime. PROCEDURE Main LOCAL cOldFile := "Address.dbf" LOCAL cBackup := StrTran( cOldFile, ".dbf", ".bak" )

Command Reference

221

COPY STRUCTURE EXTENDED USE (cOldFile) COPY STRUCTURE EXTENDED TO Tmp USE Tmp EXCLUSIVE APPEND BLANK REPLACE FIELD->FIELD_NAME REPLACE FIELD->FIELD_TYPE REPLACE FIELD->FIELD_LEN REPLACE FIELD->FIELD_DEC CLOSE Tmp

WITH WITH WITH WITH

"Newfield" "C" 20 0

RENAME (cOldFile) TO (cBackup) CREATE (cOldFile) FROM Tmp APPEND FROM (cBackup) CLOSE (cOldFile) ERASE Tmp.dbf RETURN

222

Command Reference

COPY TO

COPY TO Exports records from the current work area to a database or an ASCII text file.

Syntax COPY TO ; [FIELDS ;] [ ; ] [WHILE ;] [FOR ;] [VIA ] [SDF | DELIMITED [WITH BLANK | TAB | PIPE | ] ]

Arguments TO

This is the name of the target file as a literal character string or a character expression enclosed in parentheses. When the file name is specified without a file extension, .dbf is assumed as default extension, unless the SDF or DELIMITED option is specified. In this case, the default file extension is .txt. FIELDS

The names of the fields to export to the external file can be specified as a comma separated list of literal field names or character expressions enclosed in parentheses. When this option is omitted, all fields of the source file are exported.

This option defines the number of records to export. It defaults to ALL. The NEXT scope exports the next records, while the RECORD scope exports only one record having the record number . WHILE

This is a logical expression indicating to continue exporting records while the condition is true. The COPY TO operation stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are exported. VIA

The VIA option specifies the replaceable database driver (RDD) to use for opening the target file. is a character expression. If it is written as a literal name, it must be enclosed in quotes. When no RDD is specified, the RDD active in the current work area is used to open the external file. If the VIA clause is used, the specified RDD must be linked to the application. Use the REQUEST command to force an RRD be linked. SDF

The SDF option specifies the target file as an ASCII file in System Data Format. See file format description below. Command Reference

223

COPY TO DELIMITED

The DELIMETED option specifies the target file as a delimited ASCII file where field values are separated with a comma and Character values are enclosed with a delimiting character. The default delimiter for Character values is a double quotation mark. DELIMITED WITH BLANK | TAB | PIPE

When the delimiter is specified as BLANK, field values in the new created ASCII text file are separated by one space and character fields are not enclosed in delimiters. Alternatively, the delimiting character between field values can be specified as TAB (Chr(9)) or PIPE (Chr(124)). DELIMITED WITH

The WITH option specifies the delimiting character to enclose values of Character fields in. can be specified as a literal character or a character expression enclosed in parentheses. can also be specified as an array with two elements: { , }. If this option is used, the array must be enclosed in parentheses. It defines the delimiting characters for field values of type "C" and the delimiters between field values. Important: If the DELIMITED WITH option is used in the COPY TO command, it must be placed as the last option in the command.

Description COPY TO is a database command used to export data of the current work are into a second file. Exported records are added to the end of the target file. The target file receives data from all fields of the current work area, unless a list of fields is explicitely specified. The file in the current work area can be opened in SHARED mode. COPY TO creates the target file and opens it in EXCLUSIVE mode while data is being exported. When the target file is an ASCII text file, all date values are written as a string in the format yyyymmdd. Other specifications for supported ASCII formats ar listed in the folowing tables:

SDF Text File File Element

Format

Character fields Date fields Logical fields Memo fields Numeric fields Field separator Record separator End of file marker

Padded with trailing blanks yyyymmdd T or F Ignored Padded with leading blanks or zeros None Carriage return/linefeed 0x1A or CHR(26)

DELIMITED Text File

224

File Element

Format

Character fields Date fields Logical fields Memo fields Numeric fields Field separator

May be delimited, with trailing blanks truncated yyyymmdd T or F Ignored Leading zeros may be truncated Comma Command Reference

COPY TO Record separator End of file marker

Carriage return/linefeed 0x1A or CHR(26)

DELIMITED WITH BLANK Text File File Element

Format

Character fields Date fields Logical fields Memo fields Numeric fields Field separator Record separator End of file marker

Not delimited, trailing blanks may be truncated yyyymmdd T or F Ignored Leading zeros may be truncated Single blank space Carriage return/linefeed 0x1A or CHR(26)

Deleted records: Records that are marked for deletion in the current work area are ignored when SET DELETED is set to ON. These records are not exported. With SET DELETED OFF, all records matching the import scope are exported and the deleted flag is set accordingly in the target file.

Info See also: Category: Source: LIB: DLL:

APPEND FROM, COPY FILE, COPY STRUCTURE Database commands rdd\dbcmd.c, rtl\dbdelim.prg xhb.lib xhbdll.dll

Examples // The example creates a subset of records from a database // within an intermediate file. PROCEDURE Main USE Address NEW COPY TO Tmp FOR "LONDON" $ Upper(CITY) USE Tmp Browse() USE ERASE Tmp.dbf RETURN

// delete intermediate file

// The example creates different delimited ASCII files. PROCEDURE Main USE Address NEW // Creates a regular DELIMITED ASCII file COPY TO Test.txt DELIMITED // Uses Chr(9) as field delimiter COPY TO Test1.txt DELIMITED WITH TAB // Uses "|" as field delimiter

Command Reference

225

COPY TO COPY TO Test2.txt DELIMITED WITH PIPE // Encloses character values in single quotes and separates // fields with Chr(255) COPY TO Test3.txt DELIMITED WITH ( {"'", Chr(255) } ) USE RETURN

226

Command Reference

COUNT

COUNT Counts records in the current work area.

Syntax COUNT TO ; [] ; [WHILE ] ; [FOR ]

Arguments TO

The name of the variable that is assigned the result of the COUNT operation. When does not exist, it is created as a PRIVATE variable.

This option defines the number of records to process. It defaults to ALL. The NEXT scope processes the next records. WHILE

This is a logical expression indicating to continue counting while the condition is true. The COUNT operation stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are included in the count.

Description The COUNT command is used to count the number of records in the current work area based on the result of one or more logical expressions. The expressions are evaluated in the current work area. The number of records to include in the count can be restricted using a FOR and/or WHILE condition or by explicitely defining a scope.

Info See also: Category: Source: LIB: DLL:

AVERAGE, DbEval(), SUM, TOTAL, UPDATE Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example counts the number of sales that exceed a limit PROCEDURE Main LOCAL nSales := 0 USE Sales NEW COUNT TO nSales FOR FIELD->Amount * FIELD->Price > 500 USE

Command Reference

227

COUNT ? "Sales of more than 500:", nSales RETURN

228

Command Reference

CREATE

CREATE Creates and opens an empty structure extended database file.

Syntax CREATE

Arguments

This is the name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses.

Description The CREATE command creates a new database file and opens it exclusively in the current work area. The database has the following pre-defined field names and database structure:

Fields in a structure extended file Position

Field name

Type

Length

Decimals

1 2 3 4

FIELD_NAME FIELD_TYPE FIELD_LEN FIELD_DEC

Character Character Numeric Numeric

10 1 3 4

0 0 0 0

A database of this structure is called "structure extended" since it stores structural information of a databse in its records. The CREATE FROM database command can then be used to create a database file of this structure programmatically. Note: The length of a field of type Character is calculated as the sum of FIELD_LEN plus 256 * FIELD_DEC. The maximum length, however, is limited to 64k. Use a MEMO field to store longer Character strings.

Info See also: Category: Source: LIB: DLL:

COPY STRUCTURE EXTENDED, CREATE FROM, DbCopyStruct(), DbCopyExtStruct(), DbCreate(), DbStruct() Database commands rtl\dbstrux.prg xhb.lib xhbdll.dll

Example // The example demonstrates how to create a database file programmatically // using a structure extended file. PROCEDURE Main CREATE Temp APPEND BLANK

Command Reference

229

CREATE REPLACE FIELD_NAME FIELD_TYPE FIELD_LEN FIELD_DEC CLOSE Temp

WITH WITH WITH WITH

"Lastname" , ; "C" , ; 25 , ; 0

CREATE Address FROM Temp RETURN

230

Command Reference

CREATE FROM

CREATE FROM Creates a new database file from a structure extended file.

Syntax CREATE FROM [NEW] ; [ALIAS ] ; [VIA ]

Arguments CREATE

This is name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses. FROM

This is name of the structure extended database file that holds field information for the database to create. can be specified as a literal file name or as a character expression enclosed in parentheses. NEW

The newly created file is automatically opened in a new work area when the NEW option is specified. Omitting this option causes the file be opened in the current work area. ALIAS

Optionally, the alias name for the work area of can be specified. It defaults to the file name of . If specified, the alias name must begin with an underscore or an alphabetic character, followed by a series of underscores, digits or alphabetic characters, VIA

The VIA option specifies the replaceable database driver (RDD) to use for opening the new database file. is a character expression. If it is written as a literal name, it must be enclosed in quotes. If omitted, defaults to the return value of RddSetDefault().

Description The CREATE FROM command uses field information stored in the records of a structure extended file to create a new database file. A structure extended datbase file has the following pre-defined field names and structure:

Fields in a structure extended file Position

Field name

Type

Length

Decimals

1 2 3 4

FIELD_NAME FIELD_TYPE FIELD_LEN FIELD_DEC

Character Character Numeric Numeric

10 1 3 4

0 0 0 0

Command Reference

231

CREATE FROM

CREATE FROM reads field information from the structure extended file and creates from it a new database file. A structure extended file may have more fields than listed in the table, but only the listed ones are required. The new database file is automatically opened. Note: The length of a field of type Character is calculated as the sum of FIELD_LEN plus 256 * FIELD_DEC. The maximum length, however, is limited to 64k. Use a MEMO field to store longer Character strings.

Info See also: Category: Source: LIB: DLL:

COPY STRUCTURE, COPY STRUCTURE EXTENDED, CREATE, DbCopyStruct(), DbCreate(), DbStruct() Database commands rtl\dbstrux.prg xhb.lib xhbdll.dll

Example // please refer to the COPY STRUCTURE EXTENDED example for a usage // scenario of CREATE FROM.

232

Command Reference

DO

DO Executes a function or procedure.

Syntax DO [WITH ]

Arguments

This is the symbolic name of the function or procedure to execute. WITH

Optionally, a comma separated list of parameters to pass to the function or procedure can be specified following the WITH option.

Description The DO command exists for compatibility reasons. It executes the function or procedure having the symbolic name and passes the parameters specified as on to it. Note: it is recommended to use the execution operator instead of the DO command.

Info See also: Category: Source: LIB: DLL:

( ), FUNCTION, PROCEDURE Statements vm\do.c xhb.lib xhbdll.dll

Example // The example demonstrates two possibilities of calling // a subroutine. The first uses the DO command while the // second uses the () execution operator. PROCEDURE Main // Procedural syntax DO Test WITH "Hello", "World" // Functional syntax Test( "Hi", "There" ) RETURN

PROCEDURE Test( c1, c2 ) ? c1, c2 RETURN

Command Reference

233

DEFAULT TO

DEFAULT TO Assigns a default value to a NIL argument.

Syntax DEFAULT TO ; [, TO ]

Arguments

This is an expression whose value is assigned to when the variable contains NIL.

The symbolic names of the variable to assign a default value to.

Description The DEFAULT TO command assigns the value of to the variable when contains NIL. Multiple variables can be assigned default values by separating a list of TO options with commas. The command is used in functions and procedures that accept optional arguments. Optional arguments receive NIL as value and are assigned default values using DEFAULT TO.

Info See also: Category: LIB: DLL:

:=, PValue(), IF, STORE, Valtype() Memory commands xhb.lib xhbdll.dll

Example // The example shows a function that normalizes strings in // length and capitilization. FUNCTION Normalize( cStr, nPad ) DEFAULT cString TO "" , ; nPad TO Len(cStr) RETURN PadR( Upper( cStr[1] ) + Lower( SubStr( cStr, 2 ), nPad )

234

Command Reference

DELETE

DELETE Marks one or more records for deletion.

Syntax DELETE [] [WHILE ] [FOR ]

Arguments

This option defines the number of records to mark for deletion. It defaults to the current record. The NEXT scope deletes the next records, while the RECORD scope deletes only one record having the record number . The option ALL marks all records for deletion. WHILE

This is a logical expression indicating to continue marking records for deletion while the condition is true. The DELETE command stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are marked for deletion.

Description The DELETE command marks one or more records in the current work area for deletion. Records with the deletion flag set become unvisible when SET DELTED is set to ON. Whether or not the deleted flag is set for the current record can be tested with the Deleted() function. The flag marks a record only logically for deletion, it does not remove s record physically from a database file. The logical deletion flag can be removed with the RECALL command. When a database is open in SHARED mode, the current record must be locked with the RLock() function before DELETE may be called. Failure to do so generates a runtime error. If multiple records should be marked for deletion, the entire file must be locked using FLock(), or the file must be open in EXCLUSIVE mode. The PACK command removes all records with the deletion flag set physically from a database. The ZAP command removes all records at once, leaving an empty database file. Note: When the current record is marked for deletion and SET DELETED is ON, the record remains visible until the record pointer is moved.

Command Reference

235

DELETE

Info See also: Category: Source: LIB: DLL:

DbDelete(), DbEval(), DbRecall(), Deleted(), FLock(), PACK, RECALL, RLock(), SET DELETED, ZAP Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of SET DELETED with a record // marked for deletion PROCEDURE Main USE Customer EXCLUSIVE GO TOP ? Deleted() ? Recno() DELETE SET DELETED ON

// result; .F. // result: 1

GO TOP ? Deleted() ? Recno()

// result; .F. // result: 2

SET DELETED OFF GO TOP ? Deleted() ? Recno()

// result; .T. // result: 1

RECALL ? Deleted()

// result; .F.

CLOSE Customer RETURN

236

Command Reference

DELETE FILE

DELETE FILE Deletes a file from disk.

Syntax DELETE FILE ERASE

Arguments

This is name of the file to delete. It must include path and file extension and can be specified as a literal file name or as a character expression enclosed in parentheses. The path can be omitted from when the file resides in the current directory.

Description DELETE FILE, or its synonym ERASE, is a file command that deletes a file from disk. When does not include drive and directory information, the file is searched only in the current directory. Directories specified with SET DEFAULT or SET PATH are ignored by this command. The file must be closed before it can be deleted. When the file is not found or when it is in use, either a runtime error is generated, or a file error occurs that can be queried with function FError().

Info See also: Category: Source: LIB: DLL:

CLOSE, CurDir(), FErase(), FError(), File(), FRename(), RENAME, USE File commands rtl\philes.c xhb.lib xhbdll.dll

Example // The example deletes a group of index files in the current directory. #include "Directry.ch" PROCEDURE Main LOCAL aDir := Directory( "*.ntx" ) LOCAL i, imax := Len( aDir ) FOR i:=1 TO imax DELETE FILE ( aDir[i,F_NAME] ) NEXT RETURN

Command Reference

237

DELETE TAG

DELETE TAG Deletes a tag from an index.

Syntax DELETE TAG [IN ] [, [IN ] ]

Arguments

This is the symbolic name of the index to remove from an index file. It can be specified as a literal name or a character expression enclosed in parentheses.

is the name of the file containing the index to remove. If not specified, all index files open in the current work area are searched for the index with the name . The file name can be specified as a literal name or a character expression enclosed in parentheses. When the file extension is omitted, it is determined by the database driver that opened the file.

Description The DELETE TAG command deletes an index from an index file in the current work area. The index is identified by its tag name, which is equivalent to an alias name of a work area. If no index file is specified, all indexes in the current work area are searched for a matching tag name. When the tag name does not exist or the index file is not open, a runtime error is generated. If the index to delete is the controlling index, the records in the current work area are listed in physical order after index deletion. Note: The number of indexes that can be stored in an index file is determined by the replaceable database driver maintaining a work area. While DBFNTX and DBFNDX support only one index per file, the DBFCDX RDD supports many indexes in one index file.

Info See also: Category: Source: LIB: DLL:

INDEX, OrdDestroy(), SET ORDER, SET INDEX Database commands, Index commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates three indexes in one file using the DBFCDX driver. // The effect of deleting the controlling index is demonstrated. REQUEST DBFCDX PROCEDURE Main RddSetDefault( "DBFCDX" ) USE Customer INDEX ON Upper(FirstName) TAG FName TO Cust01 INDEX ON Upper(LastName) TAG LName TO Cust01

238

Command Reference

DELETE TAG INDEX ON Upper(City)

TAG City

TO Cust01

FOR n:=1 TO 3 ? OrdName(n), OrdKey(n) NEXT WAIT SET ORDER TO TAG City Browse() DELETE TAG City Browse() USE RETURN

Command Reference

239

EJECT

EJECT Ejects the current page from the printer.

Syntax EJECT

Description The EJECT command ejects the current page from the printer by sending a form feed control character (Chr(12)) to the printer. In addition, the functions for maintaining the current postion of the printhead are reset to zero (see PCol() and PRow()). If a printer row is addressed with @...SAY that is smaller than the current printhead row, EJECT is automatically executed. To suppress this automatic formfeed, use SetPrc() to reset the internal printer row and column counters.

Info See also:

DevPos(), IsPrinter(), PCol(), PRow(), SET CONSOLE, SET DEVICE, SET PRINTER, SetPrc() Console commands, Printer commands rtl\console.c xhb.lib xhbdll.dll

Category: Source: LIB: DLL:

Example // The exampledemonstrates a simple printing routine that lists // data from a customer database PROCEDURE Main LOCAL nLines := 50 LOCAL nPages := 1 USE Customer NEW SET PRINTER ON SET PRINTER TO LPT1 DO WHILE ! Eof() ? "Page: "+Str(nPages,8) ? "Date: "+DtoC(Date()) DO WHILE .NOT. Eof() .AND. PRow() CustNo ; FIELDS CustNo, FirstName, LastName, Inv->Total CLOSE DATABASE RETURN

Command Reference

251

KEYBOARD

KEYBOARD Writes a string or numeric key codes into the keyboard buffer.

Syntax KEYBOARD KEYBOARD KEYBOARD

Arguments

This is the character string that is written into the keyboard buffer.

Alternatively, a numeric key code can be specified. Normally, the #define constants listed in the Inkey.ch files are used for .

A mixture of character strings or numeric key codes can be specified as a one dimensional array.

Description The KEYBOARD command first clears the keyboard buffer and then fills it with the key codes specified as character strin, numeric values or within an array. Thus, all pending key strokes are discarded before new characters are written into the keyboard buffer. They remain in the buffer until being fetched from it during a wait state in which the keyboard buffer is polled for the next key stroke. Wait states are employed by functions and commands that wait for user input, such as Achoice(), READ or MemoEdit().

Info See also: Category: Header: Source: LIB: DLL:

Chr(), CLEAR TYPEAHEAD, HB_KeyPut(), Inkey(), LastKey(), NextKey(), SET KEY, SET TYPEAHEAD Input commands Inkey.ch rtl\inkey.c xhbdll.lib xhbdll.dll

Examples // The example writes a string into the keyboard buffer so that // Memoedit() begins editing this text in a new line. PROCEDURE MAIN LOCAL cString KEYBOARD "xHarbour:" + Chr(13) + Chr(10) cString := MemoEdit() CLS

252

Command Reference

KEYBOARD ? cString RETURN // The example does the same as the previous one but // passes an array to the KEYBOARD command. PROCEDURE MAIN LOCAL cString KEYBOARD { "xHarbour:", 13, 10 } cString := MemoEdit() CLS ? cString RETURN

Command Reference

253

LOCATE

LOCATE Scans the current work area for a record matching a condition.

Syntax LOCATE [] FOR ; [WHILE ] ;

Arguments

This option defines the number of records to scan. It defaults to ALL. The NEXT scope scans the next records, while REST scans records beginning from the current record to the end of file. The search begins with the first record unless a scope is defined. FOR

This is a logical expression which is evaluated in the current work area while records are scanned. The record scan stops when yields .T. (true). WHILE

This is a logical expression indicating to continue scanning records while the condition is true. The LOCATE operation stops as soon as yields .F. (false).

Description The LOCATE command sequentially scans the records in current work area and stops if a record matching the FOR condition is found. In this case, function Found() returns .T. (true). When no match is found, or when the WHILE condition yields .F. (false), or when the record pointer gets out of scope, Found() return .F. (false), and the scan stops. If a record matching the FOR condition is found, it becomes the current one. The search can then be continued using the CONTINUE command to find the next matching record. Hence, the FOR condition of the LOCATE command remains active for subsequent CONTINUE commands. Each work area may have its own LOCATE condition, which is persistent until a new LOCATE command is issued or the work area is closed. Note, however, that scope and WHILE condition are not available for a subsequent CONTINUE command. Both commands, LOCATE and CONTINUE, can be used very flexible for performing complex searches that do not rely on an indexed database. Since the records in the current database are scanned sequentially, a search with LOCATE/CONTINUE can be time consuming. A search on an indexed database with SEEK is much faster but has the drawback of a less flexible search condition.

Info See also: Category: Source: LIB: DLL:

CONTINUE, DbSeek(), Eof(), Found(), SEEK, SET FILTER, SET SCOPE Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example uses LOCATE and CONTINUE to list customers // living in the city of New York.

254

Command Reference

LOCATE PROCEDURE MAIN LOCAL cCity := "New York" FIELD FirstName, LastName USE Customer NEW LOCATE FOR Upper(FIELD->City) = Upper(cCity) DO WHILE Found() ? LastName, FirstName CONTINUE ENDDO CLOSE Customer RETURN

Command Reference

255

MENU TO

MENU TO Activates a text-mode menu defined with @...PROMPT commands.

Syntax MENU TO

Arguments

This is the name of a memory variable to receive the result of menu selection. If the variable does not exist, a PRIVATE variable of this name is created.

Description MENU TO is a compatibility command activating a text-mode menu whose menu items are defined with @...PROMPT commands. When the menu is activated, the user can navigate a light bar with the cursor keys, indicating the currently selected menu item. The light bar is displayed in the enhanced color value of SetColor() while other menu items are displayed in the standard color. A user selects a menu item by pressing the Return, PgUp or PgDn key. As a result, the MENU TO command terminates user input and assigns the ordinal position of the selected menu item as a numeric value to . Menu selection is also terminated when the Escape key is pressed. In this case, no menu item is selected and the value zero is assigned to .

Info See also: Category: Source: LIB: DLL:

@...PROMPT, AChoice(), SET MESSAGE, SET WRAP Input commands rtl\menuto.prg xhb.lib xhbdll.dll

Example // The example builds a simple text-mode menu for editing // a text file or browsing a database. PROCEDURE Main SET MESSAGE TO MaxRow() SET WRAP ON DO WHILE .T. CLS @ 3, 20 SAY

"Select an option

" COLOR "W+/R"

@ 5, 20 PROMPT "Database - Browse() " MESSAGE {|| MyMsg(1) } @ 7, 20 PROMPT "Text file - MemoEdit()" MESSAGE {|| MyMsg(2) } @ 9, 20 PROMPT "QUIT " MESSAGE {|| MyMsg(3) } MENU TO nPrompt SWITCH nPrompt CASE 1

256

Command Reference

MENU TO USE Customer Browse() USE EXIT CASE 2 MemoEdit( MemoRead( "TestMenu.prg" ) ) EXIT DEFAULT QUIT END ENDDO RETURN

FUNCTION MyMsg( n ) SWITCH n CASE 1 ; RETURN "Browses a database" ; EXIT CASE 2 ; RETURN "Displays a text file" ; EXIT CASE 3 ; RETURN "Ends program" ; EXIT END RETURN ""

Command Reference

257

PACK

PACK Removes records marked for deletion physically from a database file.

Syntax PACK

Description The PACK command removes all records marked for deletion physically from the database file open in the current work area. Disk space occupied by deleted records is recovered and all open indexes are REINDEXed. When the PACK command is complete, the record pointer is positioned on the first logical record. The database nust be open in EXCLUSIVE mode to run the PACK command. Otherwise, a runtime error is generated.

Info See also: Category: Source: LIB: DLL:

DELETE, Deleted(), RECALL, REINDEX, SET DELETED, USE, ZAP Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example removes inactive customers from a database: PROCEDURE Main USE Customer INDEX Cust01, Cust02 EXCLUSIVE ? LastRec() // result: 200 DELETE FOR Year(CONTCTDATE)-Year(Date()) > 5 PACK ? LastRec() CLOSE Customer RETURN

258

// result: 194

Command Reference

QUIT

QUIT Terminates program execution unconditionally.

Syntax QUIT

Description The QUIT command terminates program execution unconditionally. Before control goes back to the operating system, all files are closed and all EXIT PROCEDURES are executed, unless a runtime error occurs during program shutdown. In this case, the ErrorLevel() function is set to 1 which is the applications's return code to the operating system.

Info See also: Category: Source: LIB: DLL:

BEGIN SEQUENCE, Break(), ErrorLevel(), EXIT PROCEDURE, RETURN, TRY...CATCH Memory commands vm\initexit.c xhb.lib xhbdll.dll

Example // The example shows a typical usage of the QUIT command for a // command line utility that relies on a command line parameter // to work properly PROCEDURE Main( cFileName ) CLS IF Empty( cFileName ) .OR. ! File( cFileName ) ? "Usage myApp.exe " QUIT ENDIF RETURN

Command Reference

259

READ

READ Activates editing of @...GET entry fields in text mode.

Syntax READ [SAVE] ; [MENU ] ; [MSG AT , , ] ; [MSG COLOR ]

Arguments SAVE

If SAVE is specified, the GetList array holding the Get objects declared with @...GET remains intact when READ is terminated. By default, the GetList array is emptied when READ is complete. MENU

Optionally, a TopBarMenu() object can be specified. In this case, the menu can be activated during READ. MSG AT , ,

This option specifies three numeric values as screen coordinates for the region where the message of the active Get object is displayed. is the screen row, while and are the column boundaries for message display. A message is defined with the MESSAGE option of the @...GET command. MSG COLOR

The parameter is an optional character string defining the color for the message to display.

Description The READ command activates full screen editing of all Get objects previously declared with @...GET commands. A user can enter data in the displayed entry fields and navigate between them. Editing starts with the first entry field, unless the WHEN clause of @...GET indicates that editing is not allowed. In this case, the next entry field that is allowed to be edited is activated and receives input focus. When a user changes to the next entry field, a VALID condition, if present, is evaluated with the current value of the entry field. If this data validation fails, input focus remains with the current entry field, otherwise the next Get object, or entry field, receives input focus. The READ command recognizes different types of keyboard input for editing entry fields, navigating between them, and terminating data entry:

Keys for navigation

260

Key

Description

Left Ctrl+Left Right Ctrl+Right

Moves cursor one character to the left Moves cursor one word to the left Moves cursor one character to the right Moves cursor one word to the right Command Reference

READ Home End Comma | Period Up Down Ctrl+Home Return

Moves cursor to the first character Moves cursor to the last character Moves cursor to behind decimal point (only when numeric values are edited) Activates previous GET Activates next GET Activates the first GET Activates next GET

Keys for editing Key

Description

ASCII character Backspace Ctrl+Backspace Ctrl+T Ctrl+U Ctrl+Y Delete Insert

Changes the edit buffer (if PICTURE format permits) Deletes one character left of the cursor Deletes one word left of the cursor Deletes one word right of the cursor Undo changes Deletes all characters from cursor to the end Deletes one character at the cursor position Toggles insert mode

Keys for terminating READ Key

Description

Esc

Terminates READ and discards the currently edited value Terminates READ when the last GET has input focus and when ReadExit() is .T. (true) Terminates READ when the first GET has inout focus and when ReadExit() is .T. (true) Terminates READ when the last GET has input focus Terminates READ and assigns the currently edited value

Down Up Return Page Down, Page Up and Ctrl+W

Info See also: Category: Source: LIB: DLL:

@...GET, @...SAY, CLEAR GETS, Get(), LastKey(), ReadModal(), TopBarMenu() Get system, Input commands rtl\getsys.prg, rtl\tgetlist.prg xhb.lib xhbdll.dll

Command Reference

261

RECALL

RECALL Removes a deletion mark from one or more records.

Syntax RECALL [] ; [WHILE ] ; [FOR ]

Arguments

This option defines the number of records to unmark for deletion. It defaults to the current record. The NEXT scope removes the deletion mark from the next records, while the RECORD scope processes only one record having the record number . The option ALL marks all records for deletion. The default scope becomes ALL when a FOR condition is specified. WHILE

This is a logical expression indicating to continue unmarking records for deletion while the condition is true. The RECALL command stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are unmarked for deletion.

Description The RECALL command removes the deletion mark for one or more records in the current work area. A record is marked for deletion with the DELETE command. When a database is open in SHARED mode, the current record must be locked with the RLock() function before RECALL may be called. Failure to do so generates a runtime error. If multiple records should be unmarked for deletion, the entire file must be locked using FLock(), or the file must be open in EXCLUSIVE mode. Note: The RECALL command can remove a deletion flag only until PACK is executed.

Info See also: Category: Source: LIB: DLL:

DbEval(), DbRecall(), DELETE, Deleted(), FLock(), RLock(), PACK, SET DELETED, ZAP Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of a deletion mark. PROCEDURE Main USE Customer NEW EXCLUSIVE

262

Command Reference

RECALL DELETE RECORD 20 ? Deleted(), Recno()

// result: .T.

20

RECALL ? Deleted(), Recno()

// result: .F.

20

CLOSE Customer RETURN

Command Reference

263

REINDEX

REINDEX Rebuilds all open indexes in the current work area.

Syntax REINDEX [EVAL ] ; [EVERY ]

Arguments EVAL

This parameter is a code block that must return a logical value. The indexing operation continues as long as EVal() returns .T. (true). The operation is stopped when Eval() returns .F. (false). The code block is evaluated for each record unless the EVERY option is specified. It is recommened to use EVERY in conjunction with EVAL. EVERY

This option is a numeric value specifying the number of records after which the EVAL block is evaluated. This can improve the indexing operation especially for large databases. EVERY is ignored when no EVAL block is supplied.

Description The REINDEX command rebuilds all open indexes in the current work area. During the ope ration the FOR condition, UNIQUE flag and ASCENDING/DESCENDING status defined with the INDEX command are maintained. REINDEX requires a database be opened in EXCLUSIVE mode, otherwise a runtime error is generated. When the operation is complete, the first index becomes the controlling index and the record pointer is positioned on the first logical record. Important: REINDEX does not repair an index file header. If an index file gets corrupted, use the INDEX command to re-create index files from scratch.

Info See also: Category: Source: LIB: DLL:

INDEX, OrdCondSet(), OrdCreate(), OrdListRebuild(), PACK, SET INDEX, USE Database commands, Index commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // This example reindexes the indexes open in the current work area: PROCEDURE Main USE Customer INDEX Cust01, Cust02, Cust03 EXCLUSIVE REINDEX CLOSE Customer RETURN

264

Command Reference

RELEASE

RELEASE Deletes or resets dynamic memory variables.

Syntax RELEASE RELEASE ALL [LIKE | EXCEPT ]

Arguments

A comma separated list of symbolic names of PRIVATE and/or PUBLIC variables to release. ALL [LIKE|EXCEPT ]

Mask to define the variable names of visible dynamic memory variables to include or exclude from releasing. can be specified using the wildcard characters (*) and (?).

Description The RELEASE command is used in two different ways. Either by specifying the exact symbolic name(s) of one or more dynamic memory variable(s), or by using a variable name's skeleton together with wildcard characters. The asterisk (*) matches multiple characters while the question mark matches any character at the same position. As a general rule, the RELEASE command assigns NIL to the specified variables, it does not release their symbolic names immediately. This happens only when the releasing routine returns control to the calling routine. The option ALL releases all currently visible dynamic variables. When combined either with LIKE (include) or with EXCEPT (exclude), followed by a skeleton specifying a group of variable names using wild card characters, the intended group of variables is selectively released. GLOBAL, LOCAL and STATIC memory variables are not affected by CLEAR MEMORY.

Info See also: Category: Source: LIB: DLL:

CLEAR MEMORY, PRIVATE, PUBLIC, SAVE, RESTORE Memory commands vm\memvars.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of releasing PIVATE and // PUBLIC variables in a main and a sub-routine. PROCEDURE Main PRIVATE cPrivA := 11 , ; cPrivB := 22 PUBLIC

cPubA cPubB

? cPrivA

Command Reference

:= "Hello", ; := "World" // result: 11

265

RELEASE ? cPubA

// result: Hello

TestProc() ? cPrivA ? cPrivB

// result: NIL // result: 22

? cPubB ? cPubA

// result: World // runtime error

RETURN PROCEDURE TestProc() MEMVAR cPrivA, cPrivB PRIVATE cPrivA := 1000, ; cPrivB := 2000 ? cPrivA ? cPrivB

// result: 1000 // result: 2000

RELEASE cPrivB ? cPrivA ? cPrivB

// result: 1000 // result: NIL

RELEASE ALL ? cPrivA ? cPrivB

// result: NIL // result: NIL

? cPubA

// result: Hello

RELEASE cPubA ? Type("cPubA") RETURN

266

// result: U

Command Reference

RENAME

RENAME Changes the name of a file.

Syntax RENAME TO

Arguments

This is name of the file to rename. It must include path and file extension and can be specified as a literal file name or as a character expression enclosed in parentheses. The path can be omitted from when the file resides in the current directory. TO

This is the new file name including file extension. Drive and/or path are optional. can be specified either as a literal string or as a character expression enclosed in parentheses.

Description The RENAME command changes the name of a file. The file is searched in the current directory only, unless a full qualified file name including drive and path is specified. Directories specified with SET DEFAULT and SET PATH are ignored by RENAME. If is specified as a full qualified file name and its directory differs from the one of , the source file is moved to the new directory and stored under the new file name. When the new file either exists or is currently open, RENAME aborts the operation. Use the File() function to test for the existence of . A file must be closed before attempting to rename it. Important: Database files with memo fields have accompanying memo files. Memo files must be renamed along with their database files.

Info See also: Category: Source: LIB: DLL:

COPY FILE, CurDir(), ERASE, FErase(), FError(), File(), FRename() File commands rtl\philes.c xhb.lib xhbdll.dll

Example // The example shows a user defined function that renames a database file // along with its memo file. PROCEDURE Main ? File( "Customer.dbf" ) ? File( "Customer.fpt" )

// result: .T. // result: .T.

? File( "Cust2005.dbf" ) ? File( "Cust2005.fpt" )

// result: .F. // result: .F.

Command Reference

267

RENAME DbRename( "Customer.dbf", "Cust2005.dbf" ) ? File( "Customer.dbf" ) ? File( "Customer.fpt" )

// result: .F. // result: .F.

? File( "Cust2005.dbf" ) ? File( "Cust2005.fpt" )

// result: .T. // result: .T.

RETURN FUNCTION LOCAL LOCAL LOCAL LOCAL

DbRename( cOldFile, cNewFile ) cOldName := SubStr( cOldFile, 1, Rat( ".", cOldFile ) ) cNewName := SubStr( cNewFile, 1, Rat( ".", cNewFile ) ) cMemoExt, n aMemoExt := { "DBT", "FPT", "SMT" }

IF ! File( cOldFile ) .OR. File( cNewFile ) RETURN .F. ENDIF FOR n:=1 TO 3 IF File( cOldName + aMemoExt[n] ) cMemoExt := aMemoExt[n] EXIT ENDIF NEXT RENAME (cOldFile) TO (cNewFile) IF ! Empty(cMemoExt) .AND. File( cOldName+cMemoExt ) RENAME (cOldName+cMemoExt) TO (cNewName+cMemoExt) ENDIF RETURN .T.

268

Command Reference

REPLACE

REPLACE Assigns values to field variables.

Syntax REPLACE [, [NEXT [WHILE [FOR

WITH ; WITH ] ; |ALL] ; ] ; ]

Arguments

This is the symbolic name of the field variable to assign a new value to. The field variable is searched in the current work area unless prefixed with an alias name of another work area. WITH

The value of is assigned to . Note that must yield a value of the same data type as the field variable. Memo fields must be assigned values of data type Character. NEXT

This option defines the number of records to process for assignment operations. It defaults to the current record. The NEXT scope performs assignments to the fields of the next records. ALL

The option ALL processes all records. It becomes the default scope when a FOR condition is specified. WHILE

This is a logical expression indicating to continue processing records while the condition is true. The REPLACE command stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are processed.

Description The REPLACE command assigns values to one or more field variables. The field variables are identified with their symbolic field names and are searched in the current work area, unless being prefixed with the alias name of a different work area. The scope of the REPLACE command is the current record when no further condition of scope is specified. otherwise, all records matching scope and condition are processed. When a database is open in SHARED mode, the current record must be locked with the RLock() function before REPLACE may be called. Failure to do so generates a runtime error. If multiple records should be processed, the entire file must be locked using FLock(), or the file must be open in Command Reference

269

REPLACE

EXCLUSIVE mode. This applies to files open in all work areas praticipating in the assignment operation. Note: When field variables that are part of an index expression of open indexes are changed, the corresponding index is automatically updated, unless the index is created with the CUSTOM attribute. In the latter case a custom index must be updated manually. It is recommended to SET ORDER TO 0 before changing field variables that are part of index expressions. This makes sure that the relative record pointer position does not change automatically while indexes are updated.

Info See also: Category:

COMMIT, DbRlock(), FLock(), RLock() Database commands

Example // The example demonstrates how to assigne values to a database // open in SHARED mode. PROCEDURE Main LOCAL cFirstname, cLastname USE Customer INDEX CustA, CustB ALIAS Cust NEW SHARED cFirstname := Cust->Firstname cLastname := Cust->Lastname CLS @ 5,1 SAY "First name:" GET cFirstname @ 6,1 SAY "Last name :" GET cLastname READ IF .NOT. Empty( cFirstname + cLastname ) .AND. RLock() REPLACE Firstname WITH cFirstname, ; Lastname WITH cLastname COMMIT UNLOCK ENDIF CLOSE Cust RETURN

270

Command Reference

RESTORE

RESTORE Loads dynamic memory variables from disk into memory.

Syntax RESTORE FROM [ADDITIVE]

Arguments FROM

This is the name of the memory file to open. It can include path and file extension. When no path is given, the file is searched in the current directory. The default file extension is MEM. can be specified as a literal file name or as a character expression enclosed in parentheses. ADDITIVE

This option specifies that the dynamic variables should be loaded in addition to existing ones. If the option is omitted, all dynamic memory variables currently available are released first.

Description The RESTORE command loads dynamic memory variables previously stored with the SAVE command from a memory file. The default extension for memory files is MEM. Dynamic memory variables are PRIVATE and PUBLIC variables. Their symbolic names exist at runtime of an application. Thus, the symbolic names are re-created from a memory file with the RESTORE command. If dynamic variables of the same name are visible when the command is executed, they are overwritten with the values stored in the memory file. Variables that do not exist are created new as PRIVATE variables. When the ADDITIVE clause is not specified, all currently existing dynamic variables are released befor the memory file is loaded. GLOCBAL, LOCAL and STATIC variables are not affected by the RESTORE command.

Info See also: Category: Source: LIB: DLL:

GLOBAL, HB_DeSerialize(), LOCAL, PRIVATE, PUBLIC, RESTORE, STATIC Memory commands vm\memvars.c xhb.lib xhbdll.dll

Example // The example demonstrates saving and restoring of dynamic memory // variables. PROCEDURE Main PRIVATE cString1, cString2 PUBLIC dDate PUBLIC lLogic

Command Reference

:= Date() := .F.

271

RESTORE SAVE TO AllVars SAVE ALL LIKE c* TO StringVar SAVE ALL EXCEPT cString? TO SomeVars RELEASE ALL CLEAR MEMORY RESTORE FROM AllVars RESTORE FROM StringVar RESTORE FROM SomeVars RETURN

272

Command Reference

RUN

RUN Executes an operating system command.

Syntax RUN

Arguments

This is the command to be executed on the operating system level. It can be specified as literal or as character string in parentheses.

Description The RUN command opens a new command shell and executes the operating system commands specified with . RUN does not return until is completed by the operating system. When RUN is complete, the new command shell is closed.

Info See also: Category: Source: LIB: DLL:

( ), FUNCTION, PROCEDURE Statements vm\run.c xhb.lib xhbdll.dll

Example // The example executes the DIR command, directs its output into // a file and displays the result with Notepad.exe PROCEDURE Main LOCAL cCommand := "Notepad.exe files.lst" CLS ? "DIR command" RUN dir > files.lst ? "Executing Notepad.exe" RUN (cCommand) ? "Done" RETURN

Command Reference

273

SAVE

SAVE Saves dynamic memory variables to a memory file.

Syntax SAVE TO [ALL [LIKE | EXCEPT ]]

Arguments FROM

This is the name of the memory file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is MEM. can be specified as a literal file name or as a character expression enclosed in parentheses. ALL [LIKE|EXCEPT ]

Mask to define the variable names of visible dynamic memory variables to include or exclude from saving. can be specified using the wildcard characters (*) and (?).

Description The SAVE command writes dynamic memory variables currently visible to a memory file. The default extension for memory files is MEM. Only variables of data type Character, Date, Logic and Numeric can be written to a MEM file. Other data types are not supported. The vaiables can later be loaded into memory using the RESTORE commandDynamic memory variables are PRIVATE and PUBLIC variables. Their symbolic names exist at runtime of an application. Thus, the symbolic names are written into a memory file along with their values. The option ALL stores all currently visible dynamic variables. When combined either with LIKE (include) or with EXCEPT (exclude), followed by a skeleton specifying a group of variable names using wild card characters, the intended group of variables is selectively stored. GLOBAL, LOCAL and STATIC memory variables cannot be written to a memory file with the SAVE command.

Info See also: Category: Source: LIB: DLL:

GLOBAL, HB_Serialize(), LOCAL, PRIVATE, PUBLIC, RESTORE, STATIC Memory commands vm\memvars.c xhb.lib xhbdll.dll

Example // Refer to the RETSORE example

274

Command Reference

SEEK

SEEK Searches a value in an index.

Syntax SEEK [LAST] [SOFTSEEK]

Arguments

This is an arbitrary expression whose value is searched in the controlling index. The data type of the value must match with the data type of the index expression. LAST

This option determines the record to begin the search with if there are multiple records having the same index value. By default, the search starts with the first of multiple records. SOFTSEEK

This option controls the position of the record pointer when the searched value is not found. If omitted, the record pointer is positioned on the ghost record (Lastrec()+1). When SOFTSEEK is specified and the value is not found, the record pointer is positioned on the record with the next higher index value.

Description The SEEK command searches a value in the controlling index. When the value is found, the record pointer is positioned on this record and function Found() returns .T. (true). When the value is not found in the index, the record pointer is positioned on Lastrec()+1 (without SOFTSEEK) or on the record having the next higher index value (with SOFTSEEK). In either case, function Found() returns .F. (false). If SOFTSEEK is used and no higher index value is found, the record pointer is positioned on Lastrec()+1, and function Eof() returns .T. (true). The LAST option is useful if the searched value is found in multiple records. By default, the record pointer is positioned on the first of multiple records matching the search value. With the LAST option specified, the record pointer is positioned on the last of multiple records matching the search value. Note: When the index expression yields a value of data type Character, the search value can be a character string that contains one character up to the length of the index value. When the searched value is shorter than the index value, the search includes only Len() characters.

Info See also: Category: Source: LIB: DLL:

DbSeek(), Eof(), Found(), LOCATE, SET SCOPE, SET SOFTSEEK, Set() Database commands, Index commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates different search conditions and values based // on the names "Jane Doe" and "John Doe" PROCEDURE Main

Command Reference

275

SEEK USE Test INEX ON Upper(Lastname+FirstName) TO Test ? Len( FIELD->LASTNAME)

// result: 15

SEEK "A" ? Found(), Eof(),Trim(Lastname)

// result: .F., .T., ""

SEEK "A" SOFTSEEK ? Found(), Eof(),Trim(Lastname)

// result: .F., .F., "Doe"

SEEK "DOE" ? Found(), Eof(),Trim(Firstname) // result: .T., .F., "Jane" SEEK "DOE" LAST ? Found(), Eof(),Trim(Firstname) // result: .T., .F., "John" RETURN

276

Command Reference

SELECT

SELECT Changes the current work area.

Syntax SELECT |

Arguments

This is a numeric value between 0 and 65535. It specifies the number of the work area to become the current one. All database commands and unaliased functions are executed in the current work area. The value 0 has a special meaning: it selects the next unused work area disregarding its work area number.

This is the symbolic alias name of a used work area. The alias name is specified with the USE command. Note: both work area number or alias name can be specified as literal value or as expression enclosed in parentheses.

Description The SELECT command is used to select the current work area. A work area is a logical entity where database files are open along with their accompanying files, like memo or index files. The maximum number of work areas is restricted to 65535. Work areas can be selected using their numeric identifier. When a work area is occupied by an open database, it can be selected using the alias name specified with the USE command. The alias name is a powerful means for executing expressions in a work area that is not the current one. All that is required is to enclose an expression in parentheses and prefix it with the alias name and alias operator.

Info See also: Category: Source: LIB: DLL:

Alias(), DbSelectArea(), Select(), SET INDEX, USE, Used() Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates how different operatations can be coded // for multiple work areas. PROCEDURE Main SELECT 1 USE Customer ALIAS Cust ? Select() USE Invoice ALIAS Inv NEW ? Select()

Command Reference

// result: 1

// result: 2

277

SELECT USE Sales NEW ? Select()

// result: 3

SELECT Cust ? LastRec() ? Inv->(LastRec())

// result: 200 // result: 369

CLOSE ALL RETURN

278

Command Reference

SET ALTERNATE

SET ALTERNATE Records the console output in a text file.

Syntax SET ALTERNATE TO [ [ADDITIVE]] or SET ALTERNATE on | OFF | ( )

Arguments TO

This is the name of a standard ASCII text file that receives console output. The default extension for is .TXT. The file name can be specified as a string literal or a character expression enclosed in parentheses. When the file name is specified without drive letter and path, the file is created in the current directory. An existing file with the same name is overwritten without warning. ADDITIVE

The ADDITIVE option causes console output be appended to an existing file. Without this option, a new and empty file is created before output is written to the file. ON | OFF | ( )

This option toggles if output is written to a file. With ON or .T. (true). console output is written to the file. OFF or .F. (false) switch this mode off.

Description The SET ALTERNATE command writes console output to an ASCII text file with the default extension .TXT. The file is created as a new file unless the ADDITIVE option is used. Output to the file starts when SET ALTERNATE ON is executed and it ends with SET ALTERNATE OFF. The latter does not close the file but stops recording output. The file can be closed with CLOSE ALTERNATE, CLOSE ALL or SET ALTERNATE TO with no argument. Some commands which display output to the console view have a TO FILE clause. It has the same result as the SET ALTERNATE command. A full-screen command such as @...SAY can not be echoed to a file. Instead, use SET PRINTER TO with SET DEVICE TO PRINTER to enable this. Note: alternate files are not related to work areas. Therefore, only one file can be open with SET ALTERNATE at any time.

Command Reference

279

SET ALTERNATE

Info See also: Category: Source: LIB: DLL:

CLOSE, FCreate(), FOpen(), FWrite(), Set(), SET CONSOLE, SET PRINTER Console commands rtl\console.c xhb.lib xhbdll.dll

Example // This example creates an alternate file and writes the results // of the ? command to the file: PROCEDURE Main SET ALTERNATE TO MyFile SET ALTERNATE ON USE Employees NEW DO WHILE !EOF() ? Employees->Name SKIP ENDDO SET ALTERNATE OFF CLOSE ALTERNATE CLOSE Employees RETURN

280

Command Reference

SET AUTOPEN

SET AUTOPEN Toggles automatic opening of a structural index file.

Syntax SET AUTOPEN ON | off | ()

Arguments ON | off | ()

The option toggles if a structural index file is automatically opened with the USE command. With ON or .T. (true), an index file is automatically opened. OFF or .F. (false) switch this mode off.

Description Some replaceable database drivers support automatic opening of index files with the USE command when the index file has the same file name as the database file (without extension). An example is the DBFCDX driver. SET AUTOPEN toggles this behavior. When SET AUTOPEN is set to ON, which is the default, the USE command automatically opens an index file having the same name as the database file and the file extension returned from OrdBagExt(). Note: if an index file is automatically opened, a controlling index is not activated. The default index order is zero, i.e. records are accessible in physical order in the work area. To select a controlling index, call OrdSetFocus() or use SET AUTORDER for a default controlling index.

Info See also: Category: Source: LIB: DLL:

OrdListAdd(), OrdSetFocus(), Set(), SET AUTORDER, SET AUTOSHARE, USE Database commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of SET AUTOPEN with the // DBFCDX driver. REQUEST DBFCDX PROCEDURE Main RddSetDefault( "DBFCDX" ) SET AUTOPEN OFF USE Customer INDEX ON CustID TAG ID TO Customer INDEX ON Upper(LastName+FirstName) TAG Name TO Customer USE Customer ? OrdCount(), OrdKey()

// result: 0

""

SET AUTOPEN ON

Command Reference

281

SET AUTOPEN USE Customer ? OrdCount(), OrdKey()

// result: 2

""

SET AUTORDER TO 1 USE Customer ? OrdCount(), OrdKey() ? Ordkey( 2 )

// result: 2 CUSTID // result: Upper(LastName+FirstName)

USE RETURN

282

Command Reference

SET AUTORDER

SET AUTORDER Defines the default controlling index for automatically opened index files.

Syntax SET AUTORDER TO

Arguments

This is a numeric value specifying the ordinal position of the index to select as the controlling index when SET AUTOPEN is set to ON. The default is zero.

Description When SET AUTOPEN is set to ON and the RDD supports automatic opening of structural indexes, the SET AUTORDER command specifies the index to activate as the controlling index. The default value for is zero, i.e. no controlling index is activated when an index file is automatically opened with the USE command. In this case, records of the database are accessible in physical order in the work area. Note: refer to SET AUTOPEN for an example of automatic selection of the controlling index.

Info See also: Category: Source: LIB: DLL:

OrdSetFocus(), Set(), SET AUTOPEN, SET AUTOSHARE, USE Database commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Command Reference

283

SET AUTOSHARE

SET AUTOSHARE Defines network detection for shared file access.

Syntax SET AUTOSHARE TO []

Arguments

A numeric value 0, 1 or 2 can be specified for . The default is 0. If omitted, the network detection mode is switched off.

Description SET AUTOSHARE is a compatibility command useful for changing a multi -user application to a stand-alone application by changing one line of code in the start routine of a program. This requires changing only the value of :

Values for SHARE mode detection Value

Description

0 *) 1

Disables SHARE mode detection Opens database SHARED in a network, and EXCLUSIVE if no network is detected Always opens databases EXCLUSIVE

2 *) default

To take advantage of SET AUTOSHARE, an application must be programmed for multi-user access, respecting the rules for network programming. For example, record locks must be obtained with RLock() before changing field variables. This way, a multi-user application is created. To change this application to a single user version, SET AUTOSHARE TO 2 is coded in the start routine. A developer can SET AUTOMODE TO 1 on the development machine. In this case, performance advantages from EXCLUSIVE file access are avqilable during the development cycle, while SHARED file access is granted in a multi-user environment.

Info See also: Category: LIB: DLL:

284

Set(), SET AUTOPEN, SET AUTORDER, USE Database commands, SET commands, xHarbour extensions xhb.lib xhbdll.dll

Command Reference

SET BACKGROUND TASKS

SET BACKGROUND TASKS Enables or disables the activity of background tasks.

Syntax SET BACKGROUND TASKS on | OFF | ()

Arguments on | OFF | ()

The option toggles the activity of background tasks defined with function HB_BackGroundAdd(). With ON or .T. (true), background task processing is enabled. OFF or .F. (false), which is the default, disable the activity of background tasks.

Description SET BACKGROUND TASKS toggles the activity of background task processing. Backgound tasks are defined with function HB_BackGroundAdd() and run concurrently to regular program routines. Use function HB_IdleAdd() to process concurrent tasks during idle states only. To enable background task processing, SET BACKGROUND TASKS must be set to ON.

Info See also: Category: Source: LIB: DLL:

HB_BackGroundAdd(), Set(), SET BACKGROUNDTICK Background processing, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates how the time can be displayed // continuously while MemoEdit() is active. PROCEDURE Main LOCAL nTask HB_IdleAdd( {|| HB_BackGroundRun() } ) nTask := HB_BackGroundAdd( {|| ShowTime( MaxRow(), MaxCol()-7 ) }, 1000 ) SET BACKGROUND TASKS ON MemoEdit( MemoRead( "Test.prg" ), 1, 0, MaxRow()-2, MaxCol() ) HB_BackGroundDel( nTask ) RETURN

PROCEDURE ShowTime( nRow, nCol ) DispoutAt( nRow, nCol, Time() ) RETURN

Command Reference

285

SET BACKGROUNDTICK

SET BACKGROUNDTICK Defines the processing interval for background tasks.

Syntax SET BACKGROUNDTICK

Arguments

This is a numeric value specifying the number of instructions to be processed by the xHarbour virtual machine before a new cycle of background task processing is started. The default value is 1000.

Description SET BACKGROUNDTICK can be used to "fine tune" background task processing. The default value of 1000 is usually adequate for a good balance between regular and background task processing. Background tasks run concurrently with the main program. When is enlarged, the main program gets more CPU time since less time is required for background task checking. Reducing improves the response time for background tasks.

Info See also: Category: Source: LIB: DLL:

286

HB_BackGroundAdd(), Set(), SET BACKGROUND TASKS Background processing, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET BELL

SET BELL Toggles automatic sounding of the bell in the GET system.

Syntax SET BELL on | OFF | ()

Arguments on | OFF | ()

The option toggles the bell during user input in the GET system. The default setting is OFF.

Description SET BELL is a compatibility command that toggles the automatic sounding of the bell during user input with the GET system. When set to ON, the bell sounds if the last position in a GET entry field is reached, or when invalid data is entered.

Info See also: Category: Source: LIB: DLL:

@...GET, Chr(), SET CONFIRM, SET SCOREBOARD, Set(), Tone() Environment commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

287

SET CENTURY

SET CENTURY Sets the date format to include two or four digits.

Syntax SET CENTURY on | OFF | ( )

Arguments on | OFF | ( )

ON activates the display of century digits, and OFF deactivates them. Alternatively, a logical expression can be specified in parentheses. .T. (true) represents ON, while .F. (false) stands for OFF.

Description The SET CENTURY command enables or disables the display of century digits. By using the four digit notation for a year, dates of any century can be input. While SET CENTURY ON displays the four digit notation, SET CENTURY OFF will hide the century digits and will only display the year without century. The century information is not removed from date values. Only the display and input of date values is affected. Dates from 01/01/0100 to 12/31/2999 are supported.

Info See also: Category: Source: LIB: DLL:

CtoD(), Date(), DtoC(), DtoS(), SET DATE, SET EPOCH, Set(), StoD() SET commands rtl\set.c xhb.lib xhbdll.dll

Example // This example shows the result of the SET CENTURY command: PROCEDURE Main SET CENTURY OFF ? Date() SET CENTURY ON ? Date() RETURN

288

// Result: 12/06/05

// Result: 12/06/2005

Command Reference

SET COLOR

SET COLOR Defines default colors for text-mode applications.

Syntax SET COLO[U]R TO ; [ [ ] ; [,] ; [,] ; [,] ; [,] ; ] or: SET COLO[U]R TO ( )

Arguments TO [, ...]

A comma separated list of up to five color values can be specified that define the default colors for screen display in text-mode applications TO ( )

Alternatively, a color string enclosed in parentheses can be used to define the default colors.

Description SET COLOR is a compatibility command used to define screen colors in text-mode applications. The command is entirely superseeded by function SetColor(). Refer to this function for an explanation how color values are coded.

Info See also: Category: LIB: DLL:

@...GET, @...SAY, Set(), SetColor() Output commands, SET commands xhb.lib xhbdll.dll

Command Reference

289

SET CONFIRM

SET CONFIRM Determines how a GET entry field is exited.

Syntax SET CONFIRM on | OFF | ()

Arguments on | OFF | ()

The option determines if an exit key must be pressed to end editing in a GET entry field. With ON or .T. (true), the Return key must be pressed to leave a GET. OFF or .F. (false), which is the default, changes focus to the next GET once the user types past the last position in the edit buffer.

Description SET CONFIRM is a compatibility command for the GET system in text-mode applications. When SET CONFIRM is OFF, the cursor moves to the next GET if the user types past the last position in the edit buffer of the current GET. With SET CONFIRM ON, the user is required to type an exit key (E.g. the Return key) to advance the cursor to the next GET.

Info See also: Category: LIB: DLL:

290

@...GET, READ, ReadModal(), SET BELL, SET SCOREBOARD, Set() Input commands, SET commands xhb.lib xhbdll.dll

Command Reference

SET CONSOLE

SET CONSOLE Sets if console display is shown on the screen.

Syntax SET CONSOLE ON | off | ( )

Arguments ON | off | ( )

Alternatively to the options ON or OFF, a logical expression in parentheses can be specified. .T. (true) represents ON, while .F. (false) stands for OFF.

Description The SET CONSOLE command determines whether or not output from console commands is sent to the screen. The console commands display output on the screen without referencing row and/or column position of the cursor. Console commands can simultaneously send output to a printer and/or ASCII text file. Output can be directed to a printer by using the TO PRINTER clause, if it is supported by console commands, or the SET PRINTER ON command. Echoing the output to a file is achieved by the TO FILE clause or the SET ALTERNATE or SET PRINTER TO commands. When SET CONSOLE is OFF, no output is displayed on the screen. Output to a file or printer however, is not affected by this setting. Note: all commands that use explicit row and column positions for output are not affected by the SET CONSOLE setting. Their output is controlled with the SET DEVICE command which selects the output device.

Info See also: Category: Source: LIB: DLL:

Set(), SET ALTERNATE, SET DEVICE, SET PRINTER Console commands rtl\set.c xhb.lib xhbdll.dll

Example This example uses REPORT FORM to output records to the printer while no ouput is send to the screen: USE Employees NEW SET CONSOLE OFF REPORT FORM Name TO PRINTER SET CONSOLE ON

Command Reference

291

SET CURSOR

SET CURSOR Toggles the display of the screen cursor in text-mode applications

Syntax SET CURSOR on | OFF | ()

Arguments on | OFF | ()

The option determines if the screen cursor is visible or not. With ON or .T. (true), the cursur is visible. OFF or .F. (false), hides the screen cursor.

Description SET CURSOR is used to display or hide the screen cursor in text-mode applications. Normally, the screen cursor must only be visible when a user enters data. The command is superseeded by the SetCursor() function which cannot only show/hide the cursor, but also define the cursor's shape.

Info See also: Category: Source: LIB: DLL:

292

SET CONSOLE, Set(), SetCursor(), SetPos() Output commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET DATE

SET DATE Specifies the date format for input and display.

Syntax SET DATE FORMAT [TO] or SET DATE [TO] AMERICAN ansi British French German Italian Japan usa

| | | | | | |

Arguments TO

is a character expression specifying which type of date format will be used. The value of must be a string of up to 12 characters. If specified, determines the format (placement and number of digits) of the day, month and year. Position of day, month and year digits is defined by the number of occurrences of the letters d, m and y. Any other characters are displayed in the date values.

If FORMAT is omitted, one of the following keywords can be used to specify the desired date format.

Keywords for SET DATE Keyword

Date format

AMERICAN ANSI BRITISH FRENCH GERMAN ITALIAN JAPAN USA

mm/dd/yy yy.mm.dd dd/mm/yy dd/mm/yy dd.mm.yy dd-mm-yy yy/mm/dd mm-dd-yy

Description The SET DATE command specifies the format for the display and input of date values. It is a global setting valid for an entire xHarbour application.

Command Reference

293

SET DATE

Info See also: Category: Source: LIB: DLL:

CtoD(), Date(), DtoC(), DtoS(), Set(), SET CENTURY, SET EPOCH SET commands rtl\set.c xhb.lib xhbdll.dll

Example // In this example the FORMAT clause directly specifies the date format PROCEDURE Main ? Set( _SET_DATEFORMAT ) ? Date()

// result: mm/dd/yy // result: 12/21/05

SET DATE FORMAT TO "yy:mm:dd" ? Date() RETURN

294

// result: 05:12:21

Command Reference

SET DBFLOCKSCHEME

SET DBFLOCKSCHEME Selects the locking scheme for shared database access.

Syntax SET DBFLOCKSCHEME TO

Arguments TO

This is a numeric value defining the locking scheme for record locks in shared database access. Values listed in the following table or #define constants from the DBINFO.CH file can be used for

Constants for SET DBFLOCKSCHEME Constant

Value

Description

DB_DBFLOCK_DEFAULT DB_DBFLOCK_CLIP DB_DBFLOCK_CL53 DB_DBFLOCK_VFP DB_DBFLOCK_CL53EXT DB_DBFLOCK_XHB64

0 1 2 3 4 5

Default locking scheme Clipper 5.2 locking scheme Clipper 5.3 locking scheme Visual FoxPro locking scheme Emulated shared locking Locking scheme for files > 4GB

Description This setting defines the locking scheme used for record locks with shared database access. The default locking scheme is DBFLOCK_DEFAULT. The locking scheme used as the default depends on the RDD used for opening a database. When the DBFCDX RDD is used, the default locking scheme is DBFLOCK_VFP. For DBF, DBFFPT, DBFDBT and DBFNTX the DBFLOCK_CLIP locking scheme is used as the default. Note: In the NTX header file, there is a flag which informs that DBFLOCK_CL53 should be used. The DBFLOCKSCHEME command needs to be set before opening a database file. Different locking schemes can be set for each work area, but one file should never be accessed with different locking schemes at the same time. Always use UNLOCK to release all locks before changing the locking scheme for a database file. Setting the locking scheme to 1 will lock the database files like CA-Clipper 5.2 does. To use CAClipper 5.3's locking scheme, set DBFLOCKSCHEME to 2. This will emulate shared locks using exclusive locks. Visual FoxPro's locking scheme is selected with DBFLOCKSCHEME set to 3. When using locking scheme 4, a shared locking will be emulated. This scheme is very useful with systems that do not support shared locks. Although there are no problems with xHarbour, be cautious when using this scheme with a Clipper application in a network environment. Note that the file size is up to 4GB which makes this locking scheme the finest for use with a FAT32 file system. It can also be used for DBFNTX and DBFCDX. When using files larger than 4GB, use scheme 5. This locking scheme requires large file support by the operating system. Note that it does not reduce the size of the file. This scheme was tested successfully on aLinux systems. Command Reference

295

SET DBFLOCKSCHEME

Note: The DBFLOCK_CL53 locking scheme uses the same locking scheme as the locking scheme that COMIX for CA-Clipper uses. On POSIX (Linux and other *nixes) platforms SHARED locks are used when possible in all locking schemes. So it's not necessary to set DBFLOCK_CL53 which cannot work when 32bit file IO is used (maximum lock offset has 31bit). In DOS/Windows the DBFLOCK_CL53 will be probably the most efficient for multi-user applications. The locking scheme selected for an open database file can be checked with function DbInfo(DBI_LOCKSCHEME).

Info See also: Category: Header: Source: LIB: DLL:

Set(), DbInfo(), DbRLock(), RddSetDefault(), RLock() Database commands, SET commands, xHarbour extensions DbInfo.ch rdd\dbcmd.c, rtl\set.c xhb.lib xhbdll.dll

Example #include "DbInfo.ch" REQUEST DBFCDX PROCEDURE Main() LOCAL aStruct := { { "FIELD1", "C", 30, 0 }, ; { "FIELD2", "N", 10, 2 } } RddSetDefault( "DBFCDX" ) SET DBFLOCKSCHEME TO DB_DBFLOCK_CL53 DbCreate( "test", aStruct, "DBFCDX") USE Test SHARED APPEND BLANK IF ! NetErr() FIELD1->"This is a test" FIELD2->100 ? "Append operation completed" COMMIT ELSE ? "Append operation failed" ENDIF RETURN

296

Command Reference

SET DECIMALS

SET DECIMALS Defines the number of decimal places for displaying numeric values on the screen.

Syntax SET DECIMALS TO []

Arguments

This is a numeric value specifying the number of decimal places for screen output of numbers. The default value is 2. If is omitted, the number of decimal places is set to zero.

Description SET DECIMALS defines the number of decimal places for the display of numbers in text-mode applications. Note that the command affects only the display and not the accuracy of calculations with numeric values. If a number has more decimal places than , the number is rounded for display. Note: to activate a fixed number of decimal places for screen display, SET FIXED must be set to ON.

Info See also: Category: Source: LIB: DLL:

@...GET, @...SAY, SET FIXED, Set(), Str(), Transform() Output commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

297

SET DEFAULT

SET DEFAULT Sets the default drive and directory.

Syntax SET DEFAULT TO []

Arguments TO

The parameter specifies the default drive and directory for an xHarbour application to create and/or open files. Directories are separated by backslashes and the drive letter is separated with a colon. can be specified as a literal path or as a character expression enclosed in parentheses. If is omitted, the current drive and directory of the operating system is used as default directory

Description The SET DEFAULT command specifies the drive and directory where the application creates and saves files. The initial value of is the directory from where the xHarbour application is started. Use the SET PATH command to add additional directories to be searched for files. Note: The SET DEFAULT command does not change the default directory of the operating system.

Info See also: Category: Source: LIB: DLL:

CurDir(), DefPath(), File(), Set(), SET PATH SET commands rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of changing the default // drectory of an xHabour application. PROCEDURE Main SET PATH TO ? File( "Customer.dbf" )

// Result: .F.

SET DEFAULT TO C:\xhb\data ? File( "Customer.dbf" )

// Result: .T.

SET DEFAULT TO C: SET DEFAULT TO .. SET DEFAULT TO \

// define default drive // Change to parent directory // Change to root directory

RETURN

298

Command Reference

SET DELETED

SET DELETED Specifies visibility of records marked for deletion.

Syntax SET DELETED on | OFF | ( )

Arguments on | OFF | ( )

This option toggles whether records marked for deletion are visible or not. The default is OFF or .F. (false), i.e. all records are visible. To change the setting use ON or .T. (true) as parameter. The parameter can also be specified as a logical expression enclosed in parentheses.

Description The SET DELETED setting controls the visibility of records marked for deletion. A deletion mark is set with the DELETE command and can be removed with RECALL. SET DELETED is a global setting valid for all work areas. To suppress visibility of deleted records in a single work area, SET DELETED to OFF and use a filter expression like SET FILTER TO Deleted(). Visibility of deleted records is suppressed while navigating the record pointer with SKIP, GO TOP or GO BOTTOM. During such relative navigation, all records carrying the deleted flag are ignored. Absolute navigation with GOTO , however, allows for positioning the record pointer to a deleted record even when SET DELETED is ON. Note: The SET DELETED setting has no effect on index creation with INDEX or REINDEX.

Info See also: Category: Source: LIB: DLL:

DbDelete(), DbRecall(), DELETE, Deleted(), RECALL, Set(), SET FILTER Database commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Example // This example illustrates the effect of SET DELETED PROCEDURE Main USE Customer EXCLUSIVE DELETE NEXT 3 GOTO 1 SET DELETED ON SKIP 3

// deletes record 1-3 // go to record #1

GO TOP ? Recno(), Deleted()

// // // // // // // //

GOTO 1 ? Recno(), Deleted()

// absolute navigation // result: 1 .T.

? Recno(), Deleted() RECALL ALL

Command Reference

Ignore deleted records skip 3 records (first three are ignored) result: 6 .F. has no effect since DELETED is ON first logical record result: 4 .F.

299

SET DELETED SET DELETED OFF RECALL ALL

// removes all deletion flags

GO TOP ? Recno(), Deleted()

// first logical record // result: 1 .F.

CLOSE Customer RETURN

300

Command Reference

SET DELIMITERS

SET DELIMITERS Defines delimiting characters for GET entry fields and their visibility.

Syntax SET DELIMITERS on | OFF | () or SET DELIMITERS TO [ | DEFAULT]

Arguments on | OFF | ()

The option determines if GET entry fields are displayed within delimiting characters or not. With ON or .T. (true), the delimiters are displayed. OFF or .F. (false), hide the delimiters. TO

A two character string can be specified for . The first character is used as left delimiter and the second character defines the right delimiter for GET entry fields. The DEFAULT option resets the delimiting characters to their default value which is two colons (::).

Description SET DELIMITERS defines delimiting characters diplayed to the left and right of GET entry fields. The command exists forcompatibility reasons and is only used in text-mode applications.

Info See also: Category: Source: LIB: DLL:

@...GET, SET INTENSITY, Set() Output commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

301

SET DESCENDING

SET DESCENDING Changes the descending flag of the controlling index at runtime.

Syntax SET DESCENDING on | OFF | ()

Arguments on | OFF | ()

This option toggles the descending flag of the controlling order in the current work area. The initial value of this setting is identical with the vlaue of the descending flag upon index creation. The value ON or .T. (true) enables the descending order, the value OFF or .F. (false) disables it. Note that when specifiying as a logical expression, it must be enclosed in parentheses.

Description The SET DESCENDING command is an equivalent to function OrdDescend(). It allows to change, or reverse, the ascending/descending order for navigating the record pointer of an indexed database. Note that SET DESCENDING is only effective during runtime of an application. It does not change the DESCENDING flag in the file header of an index file. This flag can only be set with the INDEX command upon index creation.

Info See also: Category: Source: LIB: DLL:

INDEX, OrdCondSet(), OrdDescend() Index commands, SET commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of SET DESCENDING at runtime PROCEDURE Main USE Customer // create an ascending index INDEX ON Upper(LastName) TO Cust01 GO TOP ? Recno(), Lastname

// go to first logical record // result: 28 Abbey

SET DESCENDING ON

// change to descending order

GO TOP ? Recno(), Lastname

// go to first logical record // result: 131 Zwillick

CLOSE Customer RETURN

302

Command Reference

SET DEVICE

SET DEVICE Selects the ouput device for @...SAY commands.

Syntax SET DEVICE TO SCREEN | printer

Arguments TO SCREEN

This outputs all @...SAY commands to the screen. The output is not influenced by the SET PRINTER and SET CONSOLE settings. TO PRINTER

Outputs all @...SAY commands to the device set with SET PRINTER TO. Possible devices are local printer, network printer or a file.

Description The SET DEVICE command sends the output of @...SAY commands either to the screen, or a printer. When SET DEVICE TO PRINTER is used, no output is displayed on the screen. The @...SAY command respects the settings set by SET MARGIN. When the output is send to the printer, an automated EJECT is performed when the current printhead row position is less than the last print row position. When such an EJECT is executed, PCol() and PRow() values are set to zero. To The SetPRC() function can then be used to initialize PCol() and PRow() with new values. To direct the output of @...SAY to a file, use SET PRINTER TO and SET DEVICE TO PRINTER.

Info See also: Category: Source: LIB: DLL:

@...SAY, EJECT, PCol(), PRow(), Set(), SET PRINTER, SetPrc() Output commands rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates how to direct the output of @...SAYs // to the printer and to a file: PROCEDURE Main SET DEVICE TO PRINTER @ 2,10 SAY "Hello there" EJECT SET PRINTER TO MyOutputFile.txt SET DEVICE TO PRINTER @ 10, 10 SAY "Current file is MyOutputFile.txt" SET PRINTER TO

Command Reference

303

SET DEVICE SET DEVICE TO SCREEN RETURN

304

Command Reference

SET DIRCASE

SET DIRCASE Specifies how directories are accessed on disk.

Syntax SET DIRCASE LOWER | mixed | upper |

Arguments LOWER | mixed | upper |

The case for directory access can be specified using a keyword or a numeric value for .

Case sensitivity for directory access Keyword



Description

MIXED *) LOWER UPPER *) default

0 1 2

Mixed case is allowed Directories are converted to lower case Directories are converted to upper case

Description SET DIRCASE defines how character strings programmed in xHarbour are converted before they are passed to the operating system for directory access. The command is only relevant when the operating system treats directory names differently by case. Windows is not case sensitive.

Info See also: Category: Source: LIB: DLL:

Directory(), Set(), SET DIRSEPARATOR, SET FILECASE Environment commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Command Reference

305

SET DIRSEPARATOR

SET DIRSEPARATOR Specifies the default separator for directories.

Syntax SET DIRSEPARATOR

Arguments

A single character can be specified that is used a separator for directories. The default is a backslash.

Description SET DIRSEPARATOR defines the separating character for directories when they are accessed by the operating system. The default separator is "\". Some operating systems use the forwar slash "/" as separator.

Info See also: Category: Source: LIB: DLL:

306

Set(), SET DIRCASE, SET FILECASE Environment commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET EOL

SET EOL Defines the end-of-line character(s) for ASCII text files.

Syntax SET EOL

Arguments

A character string holding the end-of-line character(s) for ASCII text files. The default is Chr(13)+Chr(10).

Description SET EOL is an environment command defining the new-line delimiter(s) for files in ASCII format. This applies to regular text files as well as files in DELIMITED or SDF format. The end-of-line character is operating system dependent. Windows uses Chr(13)+Chr(10) as end-of-line characters. Note: the operating system dependent end-of-line characters can also be queried with function HB_OsNewLine().

Info See also: Category: LIB: DLL:

Chr(), HB_OsNewLine(), Set() Environment commands, SET commands, xHarbour extensions xhb.lib xhbdll.dll

Command Reference

307

SET EPOCH

SET EPOCH Determines the interpretation of date values without century digits.

Syntax SET EPOCH TO

Arguments TO

This is a numeric value specifying the reference year to which all character strings representing a date without century are compared.

Description The SET EPOCH command determines the interpretation of date strings that do not carry century digits. Conversion functions such as CtoD() use the value of as reference for a century. When decade and year of the string value to convert are larger than or equal to the last two digits of , the value is assumed to fall into the same century like . When the value is smaller, it is assumed to fall into the next century. By default, SET EPOCH is 1900 so dates without century digits will fall into the twentieth century. xHarbour supports dates from 01/01/0100 to 12/31/2999.

Info See also: Category: Source: LIB: DLL:

CtoD(), Date(), DtoC(), DtoS(), Set(), SET CENTURY, SET DATE SET commands rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect or a reference year set with // SET EPOCH: PROCEDURE Main SET DATE FORMAT TO "mm/dd/yyyy" ? CtoD("05/27/1903") // Result: 05/27/1903 ? CtoD("05/27/55") // Result: 05/27/1955 SET EPOCH TO 1950 ? CtoD("05/27/1910") ? CtoD("05/27/69") ? CtoD("05/27/06") RETURN

308

// Result: 05/27/1910 // Result: 05/27/1969 // Result: 05/27/2006

Command Reference

SET ERRORLOG

SET ERRORLOG Defines the default error log file.

Syntax SET ERRORLOG TO [ADDITIVE]

Arguments

This is the name of the file that stores information about runtime errors. The default file is named "Error.log" ADDITIVE

If this option is specified, new error information is appended to the log file. Otherwise, is overwritten when a new error occurs.

Description The SET ERRORLOG command is used in customized error handling routines where error information about runtime errors is written to a user-defined file. By default, runtime error information is stored in the Error.log file. Note: xHarbour's default error handling routine is programmed in the file ERRORSYS.PRG.

Info See also: Category: Source: LIB: DLL:

BEGIN SEQUENCE, Error(), ErrorBlock(), Set(), SET ERRORLOOP, TRY...CATCH Environment commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates how a particular type of errors can be logged // in a separate file. The file receives information about file open errors. PROCEDURE Main ? OpenDatabases() RETURN FUNCTION LOCAL LOCAL LOCAL

OpenDatabases() aErrLog := Set( _SET_ERRORLOG ) oError lSuccess := .T.

SET ERRORLOG TO DbOpenError.log ADDITIVE USE Customer SET INDEX TO Cust01, Cust02 SET ERRORLOG TO ( aErrLog[1] ) RETURN lSuccess

Command Reference

309

SET ERRORLOOP

SET ERRORLOOP Defines the maximum recursion depth for error handling.

Syntax SET ERRORLOOP TO

Arguments

A numeric value specifying the maximum number of recursive calls within the xharbour error handling routine. The default value is 8.

Description The SET ERRORLOOP command restricts recursive calls within the xHarbour error handling routine to a number of calls. This is required when a runtime error occurs in an error handling routine. In this case, an endless recursion is suppressed by terminating the application when the error handling routine has not resolved a runtime error after invocations. Note: xHarbour's default error handling routine is programmed in the file ERRORSYS.PRG.

Info See also: Category: LIB: DLL:

310

Set() Environment commands, SET commands, xHarbour extensions xhb.lib xhbdll.dll

Command Reference

SET ESCAPE

SET ESCAPE Sets the ESC key as a READ exit key.

Syntax SET ESCAPE ON | off | ( )

Arguments ON | off | ( )

This option toggles whether or not the ESC key is an exit key for the READ command. The default is ON or .T. (true), i.e. ESC terminates READ. To change the setting use OFF or .F. (false) as parameter. The parameter can also be specified as a logical expression enclosed in parentheses.

Description The SET ESCAPE command enables or disables the ESC key as exit key for the READ command. When enabled, the ESC key voids all changes made in the buffer of the current GET object and ends the user input. With SET ESCAPE OFF, the ESC key is ignored during the READ command. Note that SET KEY allows for associating a procedure with a key. This may override the SET ESCAPE setting.

Info See also: Category: Header: Source: LIB: DLL:

READ, ReadExit(), Set(), SET KEY, SetCancel(), SetKey() SET commands set.ch rtl\set.c xhb.lib xhbdll.dll

Command Reference

311

SET EVENTMASK

SET EVENTMASK Sets which events should be returned by the Inkey() function.

Syntax SET EVENTMASK TO

Arguments TO

is a numeric value specifying the type of events to return by the Inkey() function. The argument can be a combination , or sum, of #define constants taken from the file Inkey.ch. It can also be specified as a numeric expression enclodes in parentheses.

Constants for Constant

Value

Events returned by Inkey()

INKEY_MOVE INKEY_LDOWN INKEY_LUP INKEY_RDOWN INKEY_RUP INKEY_MMIDDLE INKEY_MWHEEL INKEY_KEYBOARD INKEY_ALL

1 2 4 8 16 32 64 128 255

Mouse pointer moved Left mouse button pressed Left mouse button released Right mouse button pressed Right mouse button released Middle mouse button pressed Mouse wheel turned Key pressed All events are returned

The default value for is INKEY_KEYBOARD, i.e. the Inkey() function returns only keyboard events and ignores the mouse.

Description The SET EVENTMASK command determines which type of events should be returned by the Inkey() function. By default, only keyboard events are returned by Inkey(). This is a compatibility setting and should be changed to INKEY_ALL at program start. The reaction to events coming from the mouse can then be programmed in a DO CASE or SWITCH structure.

Info See also: Category: Header: Source: LIB: DLL:

HB_KeyPut(), Inkey(), Lastkey(), Nextkey(), MCol(), MRow(), SET KEY, Set() Input commands, SET commands Inkey.ch rtl\set.c xhb.lib xhbdll.dll

Example // The example changes the event mask for Inkey() to ALL events // and displays the mouse cursor position. #include "Inkey.ch" PROCEDURE Main

312

Command Reference

SET EVENTMASK LOCAL nEvent SET EVENTMASK TO INKEY_ALL DO WHILE Lastkey() K_ESC ? nEvent := Inkey(0) IF nEvent > 999 // display current mouse cursor position ?? MRow(), MCol() ENDIF ENDDO RETURN

Command Reference

313

SET EXACT

SET EXACT Determines the mode for character string comparison.

Syntax SET EXACT on | OFF | ( )

Arguments on | OFF | ( )

This option toggles if an exact comparison is performed with character strings. or not. The default is OFF or .F. (false), i.e. characters are compared up the length of the shorter string. To change the setting use ON or .T. (true) as parameter. The parameter can also be specified as a logical expression enclosed in parentheses.

Description The SET EXACT command determines the mode for character string comparison with the comparison operators (=, >, , = "L" GO TOP

318

Command Reference

SET FILTER ? Recno(), Lastname

// result: 182 MacDonald

CLOSE Customer RETURN

Command Reference

319

SET FIXED

SET FIXED Toggles fixed formatting for displaying numbers in text-mode.

Syntax SET FIXED on | OFF | ()

Arguments ON | off | ()

The option toggles if numeric values are displayed with a fixed number of decimal places, or not. The default is OFF, or .F. (false). When set to ON or .T. (true), numbers are displayed with SET DECIMALS number of decimal places.

Description SET FIXED is used in text-mode applications for displaying numeric values with a fixed number of decimal places. The number of decimals defaults to 2 and can be changed with SET DECIMALS. If a number has more decimal places, the number is rounded for display, not truncated. Note that SET FIXED affects only the display and not the accuracy of calculations with numeric values.

Info See also: Category: Source: LIB: DLL:

320

Exp(), Log(), Round(), SET DECIMALS, Set(), Sqrt(), Val() Environment commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET FUNCTION

SET FUNCTION Associates a character string with a function key.

Syntax SET FUNCTION TO

Arguments

This is the numeric code for the function key to associate with. See table below. TO

A character string to write into the keyboard buffer when the function key is pressed.

Description SET FUNCTION is a compatibility command that associates a character string with a particular function key (F1..F10/F12). The function keys are numbered from 1 to 40 according to the following table:

Numeric codes for function keys Number

Actual key

1 - 10 11 - 20 21 - 30 31 - 40

F1 - F10 Shift+F1 - Shift+F10 Ctrl+F1 - Ctrl+F10 Alt+F1 - Alt+F10

When a function key, or key combination, is associated with , this string is written into the keyboard buffer via SET KEY.

Info See also: Category: Source: LIB: DLL:

KEYBOARD, SET KEY, SetKey() Input commands, SET commands rtl\setfunc.prg xhb.lib xhbdll.dll

Example // The example demonstrates how the string associated with a function // key can be read from the keyboard buffer. #include "Inkey.ch" PROCEDURE Main LOCAL cStr LOCAL nKey, bBlock SET FUNCTION 2 TO "Edit" DO WHILE Lastkey() K_ESC

Command Reference

321

SET FUNCTION nKey := Inkey(0) IF ( bBlock := SetKey( nKey ) ) NIL Eval( bBlock ) ? DO WHILE Nextkey() 0 // displays: Edit ?? Chr( Inkey() ) // when F1 is pressed. ENDDO ENDIF ENDDO RETURN

322

Command Reference

SET INDEX

SET INDEX Opens one or more index files in the current work area.

Syntax SET INDEX TO [] [ADDITIVE]

Arguments TO

The names of the index files to open in the current work area can be specified as a comma separated list of literal file names or character expressions enclosed in parentheses. When this option is omitted, all index files open in the current work area are closed. ADDITIVE

This option is only useful when is specified. In this case, the files are opened in addition to already open files. If ADDITIVE is omitted, all open index files are closed prior to opening new ones.

Description The SET INDEX command opens index files in the current work area. The first index file specified becomes the controlling index. If the file contains multiple indexes, the first index in the multiple index file becomes the controlling index. All open indexes are closed when SET INDEX is issued, unless the ADDITIVE option is used. After the indexes are opened, the record pointer is positioned on the first logical record of the controlling index, unless the ADDITIVE option is used. ADDITIVE neither changes the controlling index nor the record pointer. The command SET ORDER can later be used to change the controlling index.

Info See also: Category: Source: LIB: DLL:

CLOSE, DbClearIndex(), DbSetIndex(), INDEX, OrdListAdd(), REINDEX, SET ORDER, USE Database commands, Index commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates three index files holding one index each. PROCEDURE Main USE Customer INDEX ON Upper(FirstName) INDEX ON Upper(LastName+Firstname) INDEX ON Upper(City) ? IndexOrd(), IndexKey()

TAG FName TO Cust01 TAG LName TO Cust02 TAG City TO Cust03

// result: 1 Upper(City)

SET INDEX TO Cust01, Cust02

Command Reference

323

SET INDEX ? IndexOrd(), IndexKey()

// result: 1 Upper(FirstName)

SET ORDER TO TAG LName ? IndexOrd(), IndexKey()

// result: 2 Upper(LastName+FirstName)

SET INDEX TO Cust03 ADDITIVE ? IndexOrd(), IndexKey() // result: 2 Upper(LastName+FirstName) SET ORDER TO 3 ? IndexOrd(), IndexKey()

// result: 3 Upper(City)

CLOSE Customer RETURN

324

Command Reference

SET INTENSITY

SET INTENSITY Toggles usage of enhanced colors for GET and PROMPT

Syntax SET INTENSITY ON | off | ()

Arguments ON | off | ()

The option toggles whether or not the commands GET and PROMPT use the enhanced color for displaying the current entry fieldor menu item. The default is ON, or .T. (true). When set to OFF or .F. (false), GET and PROMPT use only the standard color for display.

Description SET INTENSITY is a compatibility command for text-mode applications. It determines if @...GET and @...PROMPT use only the standard color for display or highlight the current entry field or menu item with the enhanced color. Refer to function SetColor() for standard and enhanced color.

Info See also: Category: Source: LIB: DLL:

@...GET, @...PROMPT, @...SAY, Set(), SetColor() Output commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

325

SET KEY

SET KEY Associates a key with a procedure.

Syntax SET KEY TO []

Arguments

is the numeric Inkey() value of the key to associate with a procedure. Refer to the file INKEY.CH for numeric key codes. TO

The name of the procedure to execute must be specified as a literal name or as a macro expression. When the parameter is omitted, the procedure association is removed from the key.

Description The SET KEY command associates a key with a procedure. The procedure is executed automatically when the key is pressed during a wait state. A wait state is employed by functions and commands that wait for user input, except for the Inkey() function. This includes the AChoice(), DBEdit(), MemoEdit() functions, and the ACCEPT, INPUT, READ and WAIT commands. The associated procedure receives as parameters the return values of ProcName(), ProcLine() and ReadVar(). Notes: SET KEY is a compatibility command superseded by the SetKey() function. The F1 key is automatically associated with a procedure named HELP at program start. If such a procedure is linked, it is executed when F1 is pressed during a wait state.

Info See also: Category: Header: Source: LIB: DLL:

Inkey(), KEYBOARD, LastKey(), PROCEDURE, ProcLine(), SetKey() SET commands Inkey.ch rtl\setkey.c xhb.lib xhbdll.dll

Example // Refer to the SetKey() function for an example.

326

Command Reference

SET MARGIN

SET MARGIN Defines the left margin for text-mode print output.

Syntax SET MARGIN TO []

Arguments

This is a numeric value defining the number of blank spaces the print head should be advanced on the left side of a page before print output starts. Omitting the parameter sets the left margin to zero.

Description SET MARGIN is a compatibility command for printing in text-mode. A left margin is produced by advancing the print head by blank spaces. After this, data sent to the printer is output in the current print row. Note that PCol() reflects the number of blank spaces "printed" as left margin.

Info See also: Category: Source: LIB: DLL:

@...SAY, PCol(), PRow(), SET DEVICE, SET PRINTER, Set(), SetPrc() Output commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

327

SET MEMOBLOCK

SET MEMOBLOCK Defines the default block size for memo files.

Syntax SET MEMOBLOCK TO

Arguments TO

is a numeric value defining the new memo block size.

Description The SET MEMOBLOCK command defines the memo block size for RDDs that support variable block sizes for memo fields. The block size is the minimum amount of space allocated in memo files when storing character strings in memo fields. When large strings are stored in memo fields, they occupy the number of Int( Len(cString)/ ) plus one blocks in the memo file. The initial memo block size depends on the replaceable database driver used to open a database in a work area. The following table lists the default sizes for memo blocks of RDDs shipped with xHarbour:

Default memo block sizes Memo type

Block size

Changeable

DBT FPT SMT

512 64 64

No Yes Yes

When the memo block size is changed for an RDD, this setting is valid for database files that are created new. It is not possible to change the memo block size for existing databases.

Info See also: Category: Header: Source: LIB: DLL:

DbInfo(), RddSetDefault(), Set() Database commands, SET commands Set.ch rtl\set.c xhb.lib xhbdll.dll

Example // The example deonstrates changing the memo block size for a newly // created database #include "dbInfo.ch" REQUEST Dbfcdx PROCEDURE Main LOCAL aStruct RddSetDefault( "DBFCDX" )

328

Command Reference

SET MEMOBLOCK USE Customer SHARED ALIAS Cust VIA "DBFCDX" aStruct := DbStruct() ? DbInfo( DBI_MEMOEXT ) ? DbInfo( DBI_MEMOBLOCKSIZE )

// result: .fpt // result: 64

SELECT 0 SET MEMOBLOCK TO 128 DbCreate( "Test.dbf", aStruct, "DBFCDX" ) USE TEST ? DbInfo( DBI_MEMOEXT ) ? DbInfo( DBI_MEMOBLOCKSIZE )

// result: .fpt // result: 128

CLOSE ALL RETURN

Command Reference

329

SET MESSAGE

SET MESSAGE Defines the screen row for @...PROMPT messages.

Syntax SET MESSAGE TO [ [CENTER | CENTRE]]

Arguments

This is anumeric value specifying the row coordinate on the screen where @...PROMPT messages are displayed. If is set to zero, the display of messages is suppressed. CENTER

When this option is used, messages are displayed centered on the screen. Otherwise, they are displayed left justified in the specified screen row.

Description SET MESSAGE determines where and if messages are displayed for text-mode menus defined with the MESSAGE option of the @...PROMPT command. Text mode menus are activated with the MENU TO command.

Info See also: Category: LIB: DLL:

330

@...GET, @...PROMPT, MENU TO, SET WRAP, Set() Output commands, SET commands xhb.lib xhbdll.dll

Command Reference

SET OPTIMIZE

SET OPTIMIZE Toggles filter optimization with indexed databases.

Syntax SET OPTIMIZE ON | off | ()

Arguments ON | off | ()

This option toggles the filter optimization for database navigation in the current work area. The initial value of this setting is defined by the RDD used to open database ans index files. The value ON or .T. (true) enables the optimization, the value OFF or .F. (false) disables it. Note that when specifiying as a logical expression, it must be enclosed in parentheses.

Description The SET OPTIMIZE command determines whether or not to optimize filters in the current work area. Optimization is based on index expressions of indexes open in the current work area. When a filter condition matches with an index expression, the RDD, such as DBFCDX, compares values stored in the index rather than the database. This leads to an enhanced performance since less disk I/O is required during database navigation.

Info See also: Category: Source: LIB: DLL:

Set(), SET FILTER, SET INDEX Database commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

331

SET ORDER

SET ORDER Selects the controlling index.

Syntax SET ORDER TO SET ORDER TO TAG [IN Name, Employees->Phone SKIP ENDDO EJECT SET PRINTER OFF CLOSE RETURN

336

Command Reference

SET RELATION

SET RELATION Synchronizes the record pointers in one or more work areas.

Syntax SET RELATION TO [| INTO ] ; [, [TO] | INTO ] [ADDITIVE]

Arguments TO

This is the expression used to relate the current work area with a secondary one. The current work area becomes the parent of the secondary, which is also referred to as child work area. The effect of such a relation is that the record pointer in the child work area is synchronized with the parent work area. The database in the child work area must have a controlling index whose index expression matches . The record pointer in the child work area is synchronized using a SEEK operation. The value of is passed to SEEK. When no argument is passed, all active relations in the current work area are cleared. TO

This is a numeric expression. The record pointer in the child work area is synchronized either with a GOTO operation or with a SEEK operation. GOTO is used when there is no controlling index in the child work area. SEEK is used when the controllng index in the child work area is of numeric data type. INTO

The parameter specifies the alias name of the child work area. It can be specified as a literal alias name, or a character expression enclosed in parentheses. ADDITIVE

This option is only meaningful when relations are already defined in the current work area. In this case, all relations remain active, and new ones are defined. If ADDITIVE is omitted, all existing relations are cleared prior to defining new ones.

Description The SET RELATION command relates a parent work area with one or more child work areas. This causes the record pointer in a child work area to be synchronized with the record pointer in the parent work area. Synchronization of the record pointer in a child work area is accomplished either relative via an index, or absolute via a record number. Relative synchronization This requires a controlling index in the child work area. Each time the record pointer moves in the parent work area, the value of is SEEKed in the child work area. As a consequence, the data type of must match the data type of the controlling index in the child work area. Absolute synchronization Command Reference

337

SET RELATION

When the child work area has no controlling index, or when the type of the index expression is not numeric and the relation expression is numeric, the child work area is synchronized via GOTO . Notes The record pointer in the child work area is positioned on Lastrec()+1 when there is no match with the relation expression. It is illegal to relate a parent work area directly or indirectly with itself. The SET RELATION command does not support SOFTSEEK. It always acts as if SOFTSEEK is set to OFF. When relating two work areas based on matching record numbers, use the Recno() function for the SET RELATION TO expression. Make sure that the child work area has no controlling index.

Info See also: Category: Source: LIB: DLL:

DbClearRelation(), DbRelation(), DbRSelect(), DbSetRelation(), Found(), RecNo(), SET INDEX, SET ORDER, SET SOFTSEEK Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example lists data from a customer and an invoice database PROCEDURE Main USE Customer ALIAS Cust USE Invoice ALIA Inv NEW INDEX ON CustNo TO Invoice01 SELECT Cust SET RELATION TO CustNo INTO Inv // Invoice data changes whith each SKIP in Customer database DO WHILE .NOT. Eof() ? Cust->LastName, Cust->FirstName, Inv->Total SKIP ENDDO CLOSE ALL RETURN

338

Command Reference

SET SCOPE

SET SCOPE Changes the top and/or bottom scope for navigating in the controlling index.

Syntax SET SCOPE TO [ [, ]]

Arguments TO

This is an expression whose value is used to define the top scope, or top boundary, for indexed database navigation. Its data type must match with the data type of the index expression of the controlling index. Alternatively, can be a code block that must return a value of the correct data type. If is omitted and is defined, it is used for both, the top and bottom scope. SET SCOPE TO with no argument clears a defined scope. ,

This is the same like , except that the bottom scope, or bottom boundary is defined.

Description The SET SCOPE command defines or clears the top and bottom scope for indexed database navigation. The top and bottom scope values define the range of values valid for navigating the record pointer within the controlling index. When a scope is set, the GO TOP command is equivalent to SEEK , while GO BOTTOM is the same as SEEK LAST. Attempting to move the record pointer before does not change the record pointer but causes function BoF() to return .T. (true). When the record pointer is moved beyond , it is advanced to the ghost record (Lastrec()+1) and function EoF() returns .T. (true).

Info See also: Category: Header: Source: LIB: DLL:

BoF(), EoF(), Found(), GO, OrdKey(), OrdScope(), SET INDEX, SET ORDER, SKIP Database commands, Index commands Ord.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates indexed database navigation // restricted by scopes. #include "Ord.ch" PROCEDURE Main

Command Reference

339

SET SCOPE USE Customer INDEX ON Upper(LastName) TO Cust01 GO TOP ? Recno(), Bof(), Eof(), Lastname // result:

25 .F. .F. Abbey

GO BOTTOM ? Recno(), Bof(), Eof(), Lastname // result:

127 .F. .F. Zwillick

SET SCOPE TO "E", "G" GO TOP ? Recno(), Bof(), Eof(), Lastname // result:

558 .F. .F. Earley

SKIP -1 ? Recno(), Bof(), Eof(), Lastname // result:

558 .T. .F. Earley

GO BOTTOM ? Recno(), Bof(), Eof(), Lastname // result: 1660 .F. .F. Gwinnell SKIP ? Recno(), Bof(), Eof(), Lastname // result: 1996 .F. .T. RETURN

340

Command Reference

SET SCOPEBOTTOM

SET SCOPEBOTTOM Changes the bottom scope for navigating in the controlling index.

Syntax SET SCOPEBOTTOM TO []

Arguments TO

This is an expression whose value is used to define the bottom scope, or bottom boundary, for indexed database navigation. Its data type must match with the data type of the index expression of the controlling index. Alternatively, can be a code block that must return a value of the correct data type. Omitting the argument clears the bottom scope.

Description The SET SCOPEBOTTOM command defines or clears the bottom scope for indexed database navigation. Refer to SET SCOPE for more explanations.

Info See also: Category: Header: Source: LIB: DLL:

OrdScope(), SET SCOPE Database commands, Index commands Ord.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Command Reference

341

SET SCOPETOP

SET SCOPETOP Changes the top scope for navigating in the controlling index.

Syntax SET SCOPETOP TO []

Arguments TO

This is an expression whose value is used to define the top scope, or top boundary, for indexed database navigation. Its data type must match with the data type of the index expression of the controlling index. Alternatively, can be a code block that must return a value of the correct data type. Omitting the argument clears the top scope.

Description The SET SCOPETOP command defines or clears the top scope for indexed database navigation. Refer to SET SCOPE for more explanations.

Info See also: Category: Header: Source: LIB: DLL:

342

OrdScope(), SET SCOPE Database commands, Index commands Ord.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Command Reference

SET SCOREBOARD

SET SCOREBOARD Toggles the display of messages from READ and MemoEdit().

Syntax SET SCOREBOARD ON | off | ()

Arguments ON | off | ()

The option toggles whether or not messages generated by READ or MemoEdit() are displayed on the screen. The default is ON, or .T. (true). When set to OFF or .F. (false), READ and MemoEdit() messages are suppressed.

Description SET SCOREBOARD is a compatibility command that influences the display of messages generated by MemoEdit() or READ. Such messages inform the user about the Insert/Overstrike mode during editing, or if invalid data is input. The messages are displayed in the top screen row, if activated.

Info See also: Category: LIB: DLL:

@...GET, MemoEdit(), READ, Set() Output commands, SET commands xhb.lib xhbdll.dll

Command Reference

343

SET SOFTSEEK

SET SOFTSEEK Enables or disables relative seeking.

Syntax SET SOFTSEEK on | OFF | ( )

Arguments on | OFF | ( )

This option toggles whether the SEEK command employs relative seeking or not. The default is OFF or .F. (false), i.e. SEEK searches for an exact match. To change the setting use ON or .T. (true) as parameter. The parameter can also be specified as a logical expression enclosed in parentheses.

Description The SET SOFTSEEK command changes the global setting for searching relatively with the SEEK command. The default setting is OFF. This setting is valid for all work areas. It can be overridden for individual work areas by calling the DbSeek() function in place of the SEEK command. When SOFTSEEK is set to OFF, the SEEK command searches for an exact match with the searched value. If the value is not found, the record pointer is placed on the ghost record (Lastrec()+1) and function EoF() returns .T. (true). When SOFTSEEK is set to ON and the searched value is not found, the record pointer is positioned on the record with the next higher index value. As a result, Eof() yields .F. (false), unless there is no higher index value. Irrespective of the SOFTSEEK setting, function Found() returns .F. (false) when the searched value is not found. Note: The SOFTSEEK setting is ignored for automatic SEEK operations that are performed due to SET RELATION in a child work area.

Info See also: Category: Source: LIB: DLL:

DbSeek(), Eof(), Found(), SEEK, SET INDEX, SET ORDER, SET RELATION Index commands, SET commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of SOFTSEEK using a database // that contains "Jane" and "John" as names, but not "Jim" PROCEDURE Main USE Test INEX ON Name TO Test SET SOFTSEEK OFF SEEK "Jane" ? Found(), Eof(), Name

344

// result: .T., .F., "Jane"

Command Reference

SET SOFTSEEK SEEK "Jim" ? Found(), Eof(), Name

// result: .F., .T., ""

SET SOFTSEEK ON SEEK "Jim" ? Found(), Eof(), Name

// result: .F., .F., "John"

SEEK "John" ? Found(), Eof(), Name

// result: .T., .F., "John"

CLOSE Test RETURN

Command Reference

345

SET STRICTREAD

SET STRICTREAD Toggles read optimization for database access.

Syntax SET STRICTREAD on | OFF | ( )

Arguments on | OFF | ( )

The option toggles whether or not internal memory buffers are used for loading field variables into memory variables. The default is OFF, or .F. (false). When set to ON or .T. (true), performance optimization is suppressed.

Description SET STRICTREAD is part of xHarbour's optimization for database access. This is accomplished by means of internal memory buffers used to hold the contents of field variables. If field variables must be accessed that are held in a buffer already, no file access is required when SET STRICTREAD is set to OFF. This is the default and optimizes field access. When SET STRICTREAD is set to ON, the contents of field variables are always read from disk.

Info See also: Category: Source: LIB: DLL:

346

Set(), SET OPTIMIZE Database commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET TRACE

SET TRACE Toggles output of function TraceLog().

Syntax SET TRACE ON | off | ()

Arguments ON | off | ()

The option toggles whether or not output of function TraceLog() is directed into the trace log file. The default is ON, or .T. (true). When set to OFF or .F. (false), function TraceLog() produces no output.

Description The SET TRACE command is part of xHarbour's tracing system which allows for logging function, method or procedure calls in an arbitrary way. The default file receiving entries from the TraceLog() function is named Trace.log. It can be changed with Set(_SET_TRACEFILE).

Info See also: Category: Source: LIB: DLL:

Set(), TraceLog() Environment commands, SET commands, xHarbour extensions rtl\set.c xhb.lib xhbdll.dll

Example // The example produces a trace.log file with an log entry // for PROCEDURE Test() PROCEDURE Main SET TRACE OFF TraceLog() ? "Hello World" SET TRACE ON Test( "Hi there" ) RETURN

PROCEDURE Test( cMsg ) Tracelog( cMsg ) ? cMsg RETURN

Command Reference

347

SET TYPEAHEAD

SET TYPEAHEAD Dimensions the size of the keyboard buffer.

Syntax SET TYPEAHEAD TO

Arguments TO

This is a numeric value specifiying the maximum number of key strokes that can accumulate in the internal keyboard buffer. The value must lie within the range of 0 and 4096.

Description The SET TYPEAHEAD command sets the number of keystrokes that the internal keyboard buffer can hold. This command does not affect the amount of key strokes that can be added to the keyboard buffer programmatically using the KEYBOARD command. Before the new buffer size is set, the buffer is cleared first. When is set to zero, keyboard polling is suspended. Explicit requests for keyboard input by using the NextKey() function, for example, enables the buffer temporarily.

Info See also: Category: Source: LIB: DLL:

348

CLEAR TYPEAHEAD, Inkey(), KEYBOARD, SetCancel(), Set() SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET UNIQUE

SET UNIQUE Includes or excludes non-unique keys to/from an index.

Syntax SET UNIQUE on | OFF | ( )

Arguments on | OFF | ( )

This option toggles whether records resulting in duplicate index entries are included in an index or not. The default is OFF or .F. (false), i.e. all records are included in an index. To change the setting use ON or .T. (true) as parameter. The parameter can also be specified as a logical expression enclosed in parentheses.

Description The SET UNIQUE command determines how many records of a database, that result in the very same index value, are included in an index. With SET UNIQUE OFF, all records are included. When the setting is ON, a record is only included in an index when the index value of the record does not exist in the index. That is, an index value exists only once in an index. SET UNIQE is a global setting valid for all work areas. It can be overridden for individual work areas with the UNIQUE option of the INDEX command. Note: It is important to understand that the SET UNIQUE setting affects indexes, not databases. It is possible to add, for example, the name "Miller" ten times to an address database. When the database is indexed on "LASTNAME" and SET UNIQUE is ON, only the first record containing "Miller" is added to the index. If this index is later selected as the controlling index, the remaining nine "Miller" records are not visible.

Info See also: Category: Source: LIB: DLL:

DbCreateIndex(), INDEX, OrdCreate(), PACK, REINDEX, SEEK, Set() Index commands, SET commands rdd\dbcmd.c, rtl\set.c xhb.lib xhbdll.dll

Command Reference

349

SET VIDEOMODE

SET VIDEOMODE Changes the current video mode of the application.

Syntax SET VIDEOMODE TO

Arguments TO

is a numeric value representing a certain video mode.

Description The SET VIDEOMODE command changes the current display to text mode and different graphic modes. Two modes are supported for which the #define constant LLG_VIDEO_TEXT and LLG_VIDEO_VGA_640_480_16 are used. Note: When changing from LLG_VIDEO_TEXT to LLG_VIDEO_VGA_640_480_16, all displayed text lines are converted to the equivalent graphic display. This conversion is not applied when switching back.

Info See also: Category: Header: Source: LIB: DLL:

350

Set() Output commands, SET commands Set.ch rtl\set.c xhb.lib xhbdll.dll

Command Reference

SET WRAP

SET WRAP Toggles wrapping of the highligh bar in text-mode menus.

Syntax SET WRAP on | OFF | ( )

Arguments on | OFF | ( )

The option toggles whether or not the highlight bar of a MENU TO menu wraps when the user reaches the first or last menu item. The default is OFF, or .F. (false), i.e. wrapping of the highlight bar is disabled.

Description SET WRAP is a compatibility command defining the behavior of text-mode menus activated with MENU TO. When SET WRAP is set to ON, the highlight bar wraps to the last menu item if the user reaches the first menu item, and vice versa.

Info See also: Category: Source: LIB: DLL:

@...PROMPT, MENU TO, SET MESSAGE, Set() Output commands, SET commands rtl\set.c xhb.lib xhbdll.dll

Command Reference

351

SKIP

SKIP Moves the record pointer to a new position.

Syntax SKIP [] [ALIAS | ]

Arguments

This is a numeric expression specifying the number of records to move the record pointer from its current position. Positive values for move the record pointer downwards and negative values move it upwards. When no argument is passed, defaults to 1. ALIAS |

The ALIAS option specifies the work area in which to move the record pointer. It can be specified as a symbolic alias name or as the numeric work area number.

Description The SKIP command moves the record pointer of a work area to a new position. The new position is specified as a "distance" from the current record pointer, i.e. in number of records. A negative "distance" moves the record pointer towards the begin-of-file while positive value for moves it towards the end-of-file. A SKIP command issued with no value for advances the record pointer to the next record towards the end. SKIP performs a logical navigation of the record pointer. That is, it navigates database records according to the controlling index, active filters and scopes (see INDEX, SET FILTER and SET SCOPE). A physical navigation is performed when no index and filter is active. In this case, SKIP navigates the record pointer in the order how records are stored in a database. The command allows for navigating the record pointer of work areas other than the current work area by using the ALIAS option. The record pointer cannot be moved outside physical or logical boundaries. Both are reached with GO TOP or GO BOTTOM. When SKIP moves the record pointer using a negative distance and reaches the TOP, the record pointer remains on TOP and function BoF() returns .T. (true). When SKIP moves the record pointer using a positive value for that goes beyond BOTTOM, the record pointer is positioned on the ghost record (Lastrec()+1) and function EoF() returns .T. (true). Networking: Use SKIP 0 to make changes to a record visible to other work stations while a record is locked.

352

Command Reference

SKIP

Info See also: Category: Source: LIB: DLL:

Bof(), COMMIT, DbSkip(), Eof(), GO, LOCATE, RecNo(), SEEK Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The the example demonstrates the effect of SKIP PROCEDURE Main USE Customer ? LastRec() ? RecNo()

// result: 1995 // result: 1

SKIP 200 ? RecNo()

// result: 201

SKIP -500 ? RecNo() ? Bof()

// result: 1 // result: .T.

GO BOTTOM SKIP 10 ? RecNo() ? Eof()

// result: 1996 // result: .T.

CLOSE Customer RETURN

Command Reference

353

SORT

SORT Creates a new, physically sorted database.

Syntax SORT TO ; ON [/[A | D][C]] ; [, [/[A | D][C]]] ; [] ; [WHILE ] ; [FOR ]

Arguments TO

This is the name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses. ON

The field names to use from the current work area for the sort operation must be specified as literal names, or as character expressions enclosed in parentheses. /A | /D

These flags define the sorting order for a field. /D means Descending. /A stands for Ascaneding and is the default. /C

This flag is only meaningful for fields of data type Character. If the flag is used, sorting of character values is case-insensitive.

This option defines the number of records to sort. It defaults to ALL. The NEXT scope sorts the next records, while the REST scope sorts records beginning with the current record down to the end of file. WHILE

This is a logical expression indicating to continue sorting while the condition is true. The SORT command stops processing as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are added to the target database.

Description The SORT command creates a new database file and adds to it records from the current work area in sorted order. Fields of data type Character are sorted according to their ASCII values, unless the /C flag is used. In this case, the sorting of character values is case-insensitive. Numeric fields are sorted by 354

Command Reference

SORT

value, Date fields in chronological order and Logical fields with .T. (true) being the high value. Memo fields cannot be sorted. The default sorting order is ascending (/A flag). It can be changed to descending using the /D flag. The SORT command requires a file lock in the current work area (see function FLock()). Alternatively, the database must be used in EXCLUSIVE mode. Records marked for deletion are not included in the target database when SET DELETED is set to ON.

Info See also: Category: Source: LIB: DLL:

ASort(), FLock(), INDEX, OrdCreate(), USE Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates a physically sorted database. PROCEDURE Main USE Customer SORT TO Cust01 ON Lastname, Firstname USE Cust01 Browse() CLOSE Cust01 RETURN

Command Reference

355

STORE

STORE Assigns a value to one ore more variables.

Syntax STORE TO or := [ := ...]

Arguments

The value of is assigned to the variables specified with . TO

The symbolic names of variables to assign a value to is specified as a comma separated list. Variables that do not exist are created as PRIVATE variables.

Description The STORE command exists for compatibility reasons. It is superseded by the inline-assignment operator (:=).

Info See also: Category: LIB: DLL:

356

:=, GLOBAL, FIELD, LOCAL, STATIC, MEMVAR Memory commands xhb.lib xhbdll.dll

Command Reference

SUM

SUM Calculates the sum of numeric expressions in the current work area.

Syntax SUM ; TO ; [] ; [WHILE ] ; [FOR ]

Arguments

This is a comma separated list of numeric expressions that are evaluated for the records of the current work area. TO

A comma separated list of variable names that are assigned the results of the calculation. The number of must match exactly the number of .

This option defines the number of records to sum. It defaults to ALL. The NEXT sums the next records, while the REST scope sums records beginning with the current record down to the end of file. WHILE

This is a logical expression indicating to continue calculation while the condition is true. The SUM operation stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are included in the calculation.

Description The SUM command is used to calculate sum values for one or more numeric expressions. The expressions are evaluated in the current work area. The number of records to include in the calculation can be restricted using a FOR and/or WHILE condition or by explicitly defining a scope. Records marked for deletion are not included in the calculation when SET DELETED is set to ON.

Command Reference

357

SUM

Info See also: Category: Source: LIB: DLL:

AVERAGE, DbEval(), TOTAL Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example adds daily sales for the month of December. PROCEDURE Main LOCAL nSales := 0 USE Invoice SUM FIELD->Total TO nSales FOR ; Month(PayDate) == 12 .AND. Year(PayDate)=Year(Date()) ? "December sales:", nSales CLOSE Invoice RETURN

358

Command Reference

TEXT

TEXT Displays a block of literal text.

Syntax TEXT [TO PRINTER] [TO FILE ] ENDTEXT

Arguments TO PRINTER

The text is additionally output to the printer. TO FILE

The text is additionally output to the file . It can be specified as a literal file name or as a character expression enclosed in parentheses. The default extension is TXT.

This is a literal text block enclosed in TEXT and ENDTEXT. The text is output to the screen and displayed exactly as written in the PRG source code file.

Description The TEXT...ENDTEXT command outputs a block of literal text to the console. Output can be directed additionally to a printer or a file. When SET CONSOLE is set to OFF, the screen output is suppressed. The command exists for compatibility reasons.

Info See also: Category: Source: LIB: DLL:

? | ??, @...SAY, MLCount(), MemoLine(), SET ALTERNATE, SET CONSOLE, SET DEVICE, SET PRINTER Console commands rtl\text.prg xhb.lib xhbdll.dll

Command Reference

359

TOTAL

TOTAL Creates a new database summarizing numeric fields by an expression.

Syntax TOTAL ON ; [FIELDS ] ; TO ; [] ; [WHILE ] ; [FOR ]

Arguments ON

This is an expression whose value identifies groups of records to summarize. Each time the value of changes, a new record is added to the target database and a new calculation begins. Records in the current work area should be indexed or sorted by . FIELDS

The names of the numeric fields to summarize can be specified as a comma separated list of literal field names or character expressions enclosed in parentheses. When this option is omitted, no calculation is performed. Instead, only the records that match first are added to the target database. TO

This is name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses.

This option defines the number of records to process. It defaults to ALL. The NEXT processes the next records, while the REST scope totals records beginning with the current record down to the end of file. WHILE

This is a logical expression indicating to continue calculation while the condition is true. The TOTAL operation stops as soon as yields .F. (false). FOR

This is a logical expression which is evaluated for all records in the current work area. Those records where yields .T. (true) are included in the calculation.

Description The TOTAL command is used to calculate numeric totals for groups of records. A record group is identified by the value of . Each time this value changes, a new record is added to the target database and the values of numeric fields listed in are summarized until changes again. As a consequence, the records in the current work area must be indexed or sorted by for a correct calculation. 360

Command Reference

TOTAL

The target database has the same structure as the source database. This requires the field length of numeric fields be large enough to hold total values. If the result is too large, a runtime error is generated. Records marked for deletion are not included in the calculation when SET DELETED is set to ON.

Info See also: Category: Source: LIB: DLL:

AVERAGE, INDEX, SORT, SUM Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example calculates total sales from an invoice database // by part number PROCEDURE Main USE Invoice INDEX ON PartNo TO Temp TOTAL ON PartNo TO TotalSales USE TotalSales Browse() CLOSE ALL RETURN

Command Reference

361

UNLOCK

UNLOCK Releases file and/or record locks in the current or all work areas

Syntax UNLOCK [ALL]

Arguments ALL

This option causes all locks be released in all work areas. Without this option, only the locks in the current work area are released.

Description The UNLOCK command releases file and record locks in the current or all work areas previously set with RLock() or FLock(). Locking is required when a database is open in SHARED mode and changed data must to be written to a database file.

Info See also: Category: Source: LIB: DLL:

362

DbRUnlock(), DbUnlock(), DbUnlockAll(), FLock(), RLock(), SET RELATION, USE Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Command Reference

UPDATE

UPDATE Updates records in the current work area from a second work area.

Syntax UPDATE FROM ON ; [RANDOM] ; REPLACE WITH ; [, WITH ]

Arguments FROM

This is the alias name of the second work area used update the current work area. It can be specified as a literal alias name or a character expression enclosed in parentheses. ON

This is an expression whose value is searched in the second work area to find the records for updating the current work area. RANDOM

The option allows records in the FROM work area to be in any order. If this option is specified, the current work area must be indexed on . REPLACE

This is the symbolic name of a field variable in the current work area to assign a new value to. WITH

The result of of is assigned to . Note that must yield a value of the same data type as the field valriable. Memo fields must be assigned values of data type Character.

Description The UPDATE command replaces fields in the current work area with values from a second work area based on . An update occurs when provides the same value in both work areas. This requires the current work area be indexed on and that no multiple key values exist in this index. When there are multiple records with the same key value, only the first record with this key value is updated. The FROM work area, however, can have duplicate key values. If RANDOM is not specified both work areas must be indexed on . If RANDOM is specified, only the current work area needs to be indexed on . In a multi-user application in network operation, the file in the current work area must be exclusively open or a file lock with FLock() must be applied. Records marked for deletion are not processed in either work area when SET DELETED is set to ON.

Command Reference

363

UPDATE

Info See also: Category: Source: LIB: DLL:

364

AVERAGE, DbEval(), INDEX, OrdCreate(), REPLACE, SORT, SUM, TOTAL Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Command Reference

USE

USE Opens a database and its associated files in a work area.

Syntax USE [ ; [INDEX ] ; [ALIAS ] ; [EXCLUSIVE | SHARED] ; [NEW] ; [READONLY] ; [VIA ]]

Arguments

This is name of the database file to open. It can include path and file extension. The default file extension is DBF. can be specified as a literal file name or as a character expression enclosed in parentheses. If no argument is specified, all files open in the current work area are closed. INDEX

The names of the index files to open along with the database can be specified as a comma separated list of literal file names or character expressions enclosed in parentheses. When this option is omitted, the datbase is opened without indexes. ALIAS

This is the symbolic alias name of the work area. It can be specified as a literal alias name or a character expression enclosed in parentheses. It defaults to the file name of without extension. EXCLUSIVE

This option opens the database file for exclusive access. All other users in a network environment cannot access the database until the file is closed. SHARED

This option opens the database file for shared use in a network environment. NEW

NEW selects the next free work area and then opens the database. Without the option, all files open in the current work area are closed before is opened in the current work area. READONLY

This option is required if the file is marked as read-only in the file system. VIA

The option specifies the replaceable database driver (RDD) to use for maintaining the database and its associated files. It defaults to RddSetDefault() and must be a character expression.

Command Reference

365

USE

Description The USE command opens a database file along with its associated memo files in the current work area. Optionally, index files belonging to the database can be opened as well. Only one database can be open at any time in one work area. The maximum number of work areas is 65535. USE operates in the current work area, which can be selected using the SELECT command. As an alternative, the NEW option of USE selects the next free work area as current and then opens the file. When the database is open, its record pointer is positioned on the first logical record, if indexes are opened, or on record number 1. Index files can be opened along with the database using the INDEX option. It is, however, recommended to open first the database file alone, check the success of file opening with NetErr() and then open associated index files in a separate operation using SET INDEX. File access to the database in a multi-user environment is controlled with the options SHARED and EXCLUSIVE. Shared file access requires record locking for updating records during database operations. This is accomplished with function RLock().

Info See also: Category: Source: LIB: DLL:

CLOSE, DbSetIndex(), DbUseArea(), NetErr(), OrdListAdd(), RddSetDefault(), SELECT, SET DEFAULT, SET INDEX, SET PATH, Used() Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the recommended procedure of opening a databse // and its indexes in a multi-user environment: PROCEDURE Main USE Customer SHARED NEW IF .NOT. NetErr() SET INDEX TO Cust01, Cust02, Cust03 ELSE ? "Unable to open database" BREAK ENDIF CLOSE ALL RETURN

366

Command Reference

WAIT

WAIT Suspend program execution until a key is pressed.

Syntax WAIT [] [TO ]

Arguments

An expression returning a message to display while the program waits for user input can be specified. If omitted, the user is prompted with the default message: "Press any key to continue..." TO

Optionally, the name of a variable to receive the pressed key as a character value can be specified. When does not exist or is not visible, it is created as a private variable.

Description WAIT is a simple console input command that employs a wait state until the user presses a key. The command displays a message on the screen in a new line. The message can be suppressed by passing a null string ("") for . The key pressed by the user can be assigned as character value to a variable for further processing. Note: WAIT is a compatibility command that should be replaced with function Inkey().

Info See also: Category: Source: LIB: DLL:

@...GET, ACCEPT, Inkey(), INPUT, MENU TO Input commands rtl\wait.prg xhb.lib xhbdll.dll

Example // The example shows how to query for a single key stroke. PROCEDURE Main ? "Program started..." ? WAIT "Press Q to QUIT, any other key to continue" TO cKey IF cKey $ "qQ" ? "Program aborted" QUIT ENDIF ? "Normal program termination". RETURN

Command Reference

367

ZAP

ZAP Delete all records from the current database file

Syntax ZAP

Description The ZAP command deletes all records from a database, leaving an empty database file consisting of the file header only. All associated files like memo file or open index files are emptied as well. The file operations performed by ZAP require a database file be open in EXCLUSIVE mode. The operation is irreversible, i.e. all data stored in a ZAPped file is lost. It is impossible to RECALL data when the ZAP command is complete. Use DELETE to mark a record for deletion without losing stored data. Records marked for deletion can be recalled.

Info See also: Category: Source: LIB: DLL:

DELETE, PACK, RECALL, USE Database commands rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows how to prepare for a ZAP operation in a network PROCEDURE Main USE Customer EXCLUSIVE IF .NOT. NetErr() SET INDEX TO Cust01, Cust02, Cust03 ZAP ELSE ? "ZAP failed" ENDIF CLOSE Customer RETURN

368

Command Reference

Function Reference

Function Reference

369

AAdd()

AAdd() Adds one element to the end of an array.

Syntax AAdd( , ) --> xValue

Arguments

A variable holding an array to add an element to.

An arbitrary value to add to .

Return The function returns the value added to the array.

Description The AAdd() function increases the length of the array by one element and assigns the value to the new element. It is the last element of . AAdd() dynamically grows an array one element at a time. This is convenient when less than 100 elements should be added to . To collect more elements in a loop, for example, it is recommended to dimension the array adequately or to grow multiple elements at a time using the ASize() function. When is of data type Array, a multi-dimensional array is created.

Info See also: Category: Source: LIB: DLL:

ADel(), AEval(), AFill(), AIns(), ASize() Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // This example adds 10 numbers to an array and displays a message // after adding each element. PROCEDURE MAIN() LOCAL n, aArray := {} ? Len( aArray )

// result: 0

FOR n := 1 to 10 AAdd( aArray, n ) ? "Added value", n, "to the array." NEXT ? Len( aArray ) RETURN NIL

370

// result: 10

Function Reference

Abs()

Abs() Returns the absolute value of a numeric expression.

Syntax Abs( ) --> nPositive

Arguments

A numeric expression whose absolute value is calculated.

Return The function returns the absolute value of the passed argument. The result is always greater than or equal to zero.

Description The function removes the minus sign from negative numeric values and leaves non-negative values unchanged. This allows for determining the magnitude of numbers regardless of their sign.

Info See also: Category: Source: LIB: DLL:

Exp(), Int(), Log(), Max(), Min() Numeric functions rtl\abs.c xhb.lib xhbdll.dll

Example // The example demonstrates results from Abs() PROCEDURE Main() LOCAL nVal1 := 200 LOCAL nVal2 := 900 ? nVal1 - nVal2

// result: -700

? Abs( nVal1 - nVal2 ) ? Abs( nVal2 - nVal1 )

// result: // result:

? Abs( 0 ) ? Abs( -700 ) RETURN NIL

Function Reference

700 700

// result: 0 // result: 700

371

AChoice()

AChoice() Displays a list of items to select one from.

Syntax AChoice( [] , [] , [] , [] , , [], [] , [] , []

; ; ; ; ; ; ; ; ) --> nSelectedItem

Arguments and



Numeric values indicating the screen coordinates for the upper left corner of the AChoice() window. The default value for both parameters is zero.

Numeric value indicating the bottom row screen coordinate. It defaults to MaxRow().

Numeric value indicating the right column screen coordinate. It defaults to MaxCol().

A one dimensional array containing characters strings must be passed for . It represents a list of items to choose one from. The character strings are displayed in the AChoice() window. Note: No element in may contain a null-string (""). A null-string is treated as Endof-list marker.

This parameter is optional. Either a logical value or an array containing logical values or character strings can be specified. It defaults to .T. (true) which means that all items in can be selected. If .F. (false) is specified for , the Ahoice() window is displayed but the function returns immediately, allowing no selection. When an array is passed, it must have at least the same number of elements as and is treated as parallel array indicating individual elements that can be selected. If an element of contains .T. (true), the corresponding item in is selectable, otherwise it is displayed but not selectable. As an alternative, elements in may contain character strings. They are treated as macro-expressions and are evaluated with the macro-operator. The result of the macroexpression must be a logical value.

372

Function Reference

AChoice()

This is an optional character string holding the symbolic name of a user-defined function. The user function is called each time a key is pressed while AChoice() is active. The return value of the user function influences the AChoice() behavior. Note that the user function must be specified without parentheses, only the symbolic name may be passed.

Optionally, the first item to start the selection with can be specified as a numeric value. It indicates the ordinal position of the element in and defaults to 1, the first element.

specifies the offset from the first window row to position the hilight bar in at initial display. It defaults to zero, i.e. the highlight bar is displayed in the row when AChoice() begins.

Return AChoice() returns a numeric value. It indicates the position of the selcted item in . When the user makes no selection, the return value is zero.

Description AChoice() is a console window function that presents to the user a list of items to select one from. The function maintains a window region and displays in it the items specified as the array containing character strings. The colors for display are taken from the current SetColor() string. That is, normal items are displayed in Standard color, the highlight in Enhanced color and unselectable items with the Unselected color The user can navigate through the list using cursor keys. AChoice() automatically scrolls the list within the defined window region if the user attempts to navigate the highlight bar outside the window. The user selects an item by pressing the Return key or by double clicking an item, and aborts selection with the Esc key. Direct navigation to an item as accomplished by pressing letter keys. In this case, AChoice() moves the highlight to the next item whose first letter matches the pressed key.

Navigation without user function AChoice() recognizes in its default navigation mode the keys listed in following table. The default mode is present when no user function is specified.

AChoice() default navigation Key

Navigation

Up arrow Down arrow Home End Ctrl+Home Ctrl+End PgUp PgDn Ctrl+PgUp Ctrl+PgDn Return Esc

Go to previous item Go to next item Go to first item in menu Go to last item in menu Go to first item in window Go to last item in window Go to previous page Go to next page Go to the first item in menu Go to last item in menu Select current item Abort selection

Function Reference

373

AChoice() Left arrow Right arrow

Abort selection Abort selection

First letter

Go to next item beginning with first letter

Left click *) Go to clicked item Left double click *) Select clicked item *) Mouse keys must be activated with SET EVENTMASK

Navigation with user function AChoice() processes some very basic navigation keys automatically when a user function is specified. This nvigation occurs before the user function is called. All keys not listed in the following table are passed on to the user function which may instruct AChoice() to take appropriate action.

AChoice() restricted navigation Key

Navigation

Down arrow Ctrl+Home Ctrl+End PgUp PgDn Ctrl+PgUp Ctrl+PgDn

Go to next item Go to first item in window Go to last item in window Go to previous page Go to next page Go to the first item in menu Go to last item in menu

Left click *) Go to clicked item *) Mouse keys must be activated with SET EVENTMASK

After default action is taken, AChoice() invokes the user function, passing three parameters for further processing: 1)

The current AChoice() mode (see table below).

2)

The current element in the array of items.

3)

The relative row position of the highlight bar within the window region.

AChoice() modes passed to the user function indicate the internal state. They are encoded as numeric values for which #define constants exist in the ACHOICE.CH file.

AChoice() modes Constant

Mode

Description

AC_IDLE AC_HITTOP AC_HITBOTTOM AC_EXCEPT AC_NOITEM

0 1 2 3 4

Idle Attempt to move cursor past top of list Attempt to move cursor past bottom of list Unknown key pressed No selectable items

The user function can process the passed parameters. It then instructs AChoice() how to proceed by returning one of the following numeric values. All user-function return values are also available as #define constants.

374

Function Reference

AChoice()

User-function return values for AChoice() Constant

Value

Action

AC_ABORT AC_SELECT AC_CONT AC_GOTO

0 1 2 3

Abort selection Make selection Continue AChoice() Go to the next item whose first character matches the key pressed

Info See also: Category: Header: Source: LIB: DLL:

@...PROMPT, DbEdit(), MENU TO, TBrowseNew() Array functions, UI functions achoice.ch rtl/achoice.prg xhb.lib xhbdll.dll

Example // // // //

The example uses AChoice() to display names of files in the current directory. Only files with the TXT or PRG extension can be selected. A selected file is displayed using MemoEdit(). Note how the return value of the user function triggers the AChoice() action. #include "Achoice.ch" #include "Inkey.ch" MEMVAR

aFiles

PROCEDURE Main LOCAL nSelect LOCAL aItems := Directory() LOCAL i, imax := Len( aItems ) LOCAL aSelect := Array( imax ) LOCAL cScreen SetColor( "W/N" ) CLS SetColor( "N/BG,W+/B,,,W/BG" ) PRIVATE aFiles := AClone( aItems ) FOR i:=1 TO imax aItems[i] := Upper( aItems[i,1] ) aSelect[i] := ( ".TXT" $ aItems[i] .OR. ; ".PRG" $ aItems[i] ) NEXT DO WHILE LastKey() K_ESC nSelect := Achoice( 2, 2, MaxRow()-5, 30, ; aItems, aSelect, "USERFUNC" ) IF nSelect 0 // Display selected file SAVE SCREEN TO cScreen MemoEdit( MemoRead( aItems[nSelect] ) ) RESTORE SCREEN FROM cScreen KEYBOARD Chr(255) // sets Lastkey() to 255 Inkey()

Function Reference

375

AChoice() ENDIF ENDDO RETURN

FUNCTION LOCAL LOCAL LOCAL

UserFunc( nMode, nElement, nRow ) nKey := LastKey() nRet := AC_CONT cMsg

DO CASE CASE nMode == AC_IDLE // do some idle processing cMsg := " File: " + aFiles[nElement,1] + ; " Size: " + Str( aFiles[nElement,2] ) + ; " Date: " + DtoC( aFiles[nElement,3] ) + ; " Time: " + aFiles[nElement,4] DispOutAt( MaxRow(), 0, Padr(cMsg, MaxCol()+1), "W+/R" ) CASE nMode == AC_EXCEPT // key handling for unknown keys IF nKey == K_ESC nRet := AC_ABORT ELSEIF nKey == K_RETURN .OR. nKey == K_LDBLCLK nRet := AC_SELECT ELSEIF nKey > 31 .AND. nKey < 255 nRet := AC_GOTO ENDIF ENDCASE RETURN nRet

376

Function Reference

AClone()

AClone() Creates a deep copy of an array.

Syntax AClone( ) --> aClone

Arguments

A variable holding the array to duplicate.

Return The function returns a reference to the created array.

Description AClone() is an array function that duplicates an array. Unlike ACopy(), which operates only on onedimensional arrays, AClone() performs a deep copy and iterates through all dimenstions of an array. If an array element contains an array, this sub-array is duplicated as well. As a result, all array references contained in one array are duplicated, resulting in a deep copy of the source array. Note Array elements holding values of complex data types other than type Array are not duplicated. That is, Hashes, Code blocks and Objects are not duplicated. AClone() transfers only their reference to the result array. Source and result array then contain the exact same value of the complex data type.

Info See also: Category: Source: LIB: DLL:

ACopy(), ADel(), AIns(), ASize() Array functions vm/arrayshb.c xhb.lib xhbdll.dll

Example // This example demonstrates the difference between ACopy() and AClone() // -> aTgt1 is a shallow copy of the source array // -> aTgt2 is a deep copy of the source array PROCEDURE Main LOCAL aSrc := { 1, { "A", "B" } } LOCAL aTgt1 := ACopy( aSrc, Array(2) ) LOCAL aTgt2 := AClone( aSrc ) // check first element of sub-array ? aTgt1[2,1] // result: A ? aTgt2[2,1] // result: A // change first element of sub-array in source array aSrc[2,1] := "no clone" // re-check first element of sub-array ? aTgt1[2,1] // result: no clone

Function Reference

377

AClone() ? aTgt2[2,1] RETURN

378

// result: A

Function Reference

ACopy()

ACopy() Copy elements from a source array into a target array.

Syntax ACopy( , , [], [] , []

; ; ; ; ) --> aTarget

Arguments

The source array whose elements are copied.

The target array recieving copied values.

This is a numeric expression indicating the first element in the source array to begin copying with. It defaults to 1, the first element of .

A numeric expression specifying the number of elements to copy from to . It defaults to the maximum possible number that can be copied. This number depends on the size of source and target array, and the start elements of both arrays.

A numeric expression indicating the first element in the target array that receives copied values. It defaults to 1.

Return The function returns a reference to the array.

Description ACopy() is an array function that iterates over the elements of a source array and copies values stored in these elements to a target array. Copying begins with the element of the source array. The value of this element is copied to the element of the target array. The function then proceeds to the next element in both arrays. The copy process is complete when either elements are copied, or the last element in one of both arrays is reached. If the source array contains more elements than the target array, copying stops when the last element of the target array is reached, and vice versa. The number of elements in both arrays is not changed by ACopy(). The function operates in the first dimension of an array. Only values of the simple data types Character, Date, Logic, Numeric and NIL are actually copied. Values of the complex data types Array, Code block, Hash and Object are represented by references to their values. Hence, ACopy() copies the references to complex values from source to target array. As a result both arrays contain references to the same complex values. This is especially important when copying multi-dimensional array with ACopy() since both arrays contain references to the same sub-arrays when copying is complete. Function Reference

379

ACopy()

Note: use function AClone() to obtain a true "deep copy" of multi-dimensional arrays.

Info See also: Category: Source: LIB: DLL:

AClone(), ADel(), AEval(), AFill(), AIns(), ASort() Array functions vm/arrayshb.c xhb.lib xhbdll.dll

Example // This example copies the values from one array to another and // displays the results on the screen. PROCEDURE Main() LOCAL aSource := {"xHarbour", "dot", "com"} LOCAL aTarget := {"xHarbour", "dot", "net"} ACopy( aSource, aTarget, 3, 1, 3) ? aSource[1], aSource[2], aSource[3] ? aTarget[1], aTarget[2], aTarget[3] AAdd( aSource, "is") AAdd( aSource, "great") ACopy(aSource, aTarget, , , 2) ? aSource[1], aSource[2], aSource[3], aSource[4], aSource[5] ? aTarget[1], aTarget[2], aTarget[3] ? Len( aTarget ) RETURN

380

Function Reference

ADel()

ADel() Deletes an element from an array.

Syntax ADel( , , [] ) --> aArray

Arguments

A variable holding the array to delete an element from.

This is a numeric expression indicating the ordinal position of the array element to delete. It must be in the range between 1 and Len().

Optionally, a logical value can be specified. If .T. (true) is passed, the length of the array is reduced by one element. The default value is .F. (false) leaving the number of elements in unchanged.

Return The return value is a reference to .

Description The array function ADel() deletes the element at position from the array . All subsequent elements are shifted up by one position so that the last element contains the value NIL when the function returns. This default behaviour leaves the number of elements in the array unchanged. If the third parameter is specified as .T. (true), the last element is removed from the array and the number of elements is reduced by 1.

Info See also: Category: Source: LIB: DLL:

AAdd(), ACopy(), AFill(), AIns(), ASize() Array functions vm/arrayshb.c xhb.lib xhbdll.dll

Example // This example demonstrates two results of deleting an // array element PROCEDURE Main() LOCAL aArray := { "A", "B", "C" } ADel( aArray, 2 ) ? Len( aArray )

Function Reference

// result: 3

381

ADel() ? aArray[1], aArray[2], aArray[3]

// result: A C NIL

ADel( aArray, 2, .T. ) ? Len( aArray ) ? aArray[1], aArray[2]

// result: 2 // result: A NIL

RETURN

382

Function Reference

ADir()

ADir() Fills pre-allocated arrays with file and/or directory information.

Syntax ADir( [], [] , [] , [] , [] , []

; ; ; ; ; ) --> nDirEnries

Arguments

is a character string specifying the directory and file mask used to search for files. The file mask may contain wild card characters, like "*" or "?". If no path is givven, ADir() searches in the SET DEFAULT directory.

A pre-allocated array to fill with the file names of the found files. Each element contains a character string holding a file name without path information, as reported by the operating system.

A pre-allocated array to fill with numeric values indicating the file size.

A pre-allocated array to fill with the "last change" date values.

A pre-allocated array to fill with the "last change" Time values. The values are of data type Character and contain the time formatted as "hh:mm:ss".

A pre-allocated array to fill with file attributes. Recognized attributes are Normal, Hidden, System and Directory. The are combined in one character string. If is omitted, ADir() includes only normal files in the search result.

Return The function returns a numeric value indicating the number of files meeting the search condidtion defined with .

Description ADir() searches a directory for files meeting a search pattern , and optionally fills arrays with various file information. The number of files meeting the search condition is usually determined in an initial call to ADir(). The return value of the initial call is then used to pre-allocate onedimensional arrays that are filled with the desired informationin a second call to ADir().

Function Reference

383

ADir()

To include files with Hidden, Directory, or System attributes, the according attribute must be specified for the search. Note: ADir() is a compatibility function. It is superseded by the Directory() function which returns all file information in a multi-dimensional array.

Info See also: Category: Source: LIB: DLL:

AChoice(), AEval(), AScan(), ASort(), Directory(), Len() Array functions, File functions rtl\adir.prg xhb.lib xhbdll.dll

Example // // // //

This example demonstrates the two-step approach for obtaining file information about .LOG files. The initial call determines the number of files found. This result is used to pre-allocate arrays to fill in a second call to ADir(). PROCEDURE MAIN() LOCAL aName, aSize, aDate, aTime, aAttr LOCAL nLen, i nLen := ADir( "*.log" ) IF nLen > 0 aName := aSize := aDate := aTime := aAttr :=

Array( Array( Array( Array( Array(

nLen nLen nLen nLen nLen

) ) ) ) )

ADir( "*.log", aName, aSize, aDate, aTime, aAttr ) FOR i := 1 TO nLen ? aName[i], aSize[i], aDate[i], aTime[i], aAttr[i] NEXT ELSE ? "This directory does not contain .log files." ENDIF RETURN

384

Function Reference

AEval()

AEval() Evaluates a code block for each array element.

Syntax AEval( , , [], [] ) --> aArray

Arguments

This is the array to iterate.

The code block evaluated for the elements of . It receives two parameters: the value of the current array element and its numeric position in the array.

This is a numeric expression indicating the first element in the array to begin with. It defaults to 1, the first element of .

A numeric expression specifying the number of elements to pass to the code block. It defaults to 1+Len()-.

Return The function returns a reference to .

Description The array function AEval() traverses an array beginning with the element and passes the values of individual array elements to the code block . The code block is evaluated and AEval() proceeds to the next array element until either elements are processed or the end of the array is reached. The return value of the code block is ignored. With each iteration, the code block receives as parameters the value stored in the current array element and a numeric value indicating the ordinal position of the current array element. Note that AEval() is appropriate for iterating an array once. Operations that require a more sophisticated iteration or that alter array elements are programmed in FOR...NEXT or FOR EACH loops.

Info See also: Category: Source: LIB: DLL:

DbEval(), Eval(), FOR, FOR EACH, HEval(), QOut() | QQOut() Array functions, Code block functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The first part of the example displays the contents of an array while the // second part first increases the value of the elements and then displays it

Function Reference

385

AEval() // on the screen. PROCEDURE Main() LOCAL aArray := {"A", "B", "C", "D", "E", "F" } ? "Simple iteration: " AEval( aArray, {|x| QQOut(x) } )

// result: ABCDEF

? "Fill array with consecutive numbers: " AEval( aArray, {|x,n| aArray[n] := n } ) // Note: LOCAL variable is visible within code block // since aArray and code block are created in the // same procedure. AEval( aArray, {|x| QQOut(LTrim(Str(x))) } ) // result: 123456 RETURN

386

Function Reference

AFields()

AFields() Fills pre-allocated arrays with structure information of the current work area.

Syntax AFields( [], [], [] , []

; ; ; ) --> nCount

Arguments

A pre-allocated array to fill with the field names of the work area. Each element contains a character string.

A pre-allocated array to fill with the field types of the work area. Each element contains a single character.

A pre-allocated array to fill with the field lengths of the work area. Each element contains a numeric value.

A pre-allocated array to fill with the decimal places of the fields of the work area. Each element contains a numeric value.

Return The function returns a numeric value indicating the number of array elements filled. If no parameter is passed or if the work area is not used, the return value is zero.

Description AField() is used to obtain structural information about a database open in a work area. The function operates in the current work area unless it is prefixed with the alias operator. One or more arrays must be pre-allocated to receive the desired information. Use function FCount() to dimension the arrays large enough to hold all avialable information. Note that AFields exists for compatibility reasons. It is superseded by the DbSTruct() function, which retrieves all structural information in a multi-dimensional array.

Function Reference

387

AFields()

Info See also: Category: Source: LIB: DLL:

AChoice(), AEval(), AScan(), DbCreate(), DbStruct() Array functions, Field functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example fills an array with field names and displays the // names and field contents within AEval(). PROCEDURE Main LOCAL aNames USE Customer aNames := Array( FCount() ) AFields( aNames ) AEval( aNames, {|cName| QOut(cName, &cName) } ) CLOSE ALL RETURN

388

Function Reference

AFill()

AFill() Fills an array with a constant value.

Syntax AFill( , , [], [] ) --> aArray

Arguments

This is the variable holding the array to fill with a value.

An expression yielding a value of arbitrary data type. The expression is evaluated once and the resulting value is assigned to each element of .

This is a numeric expression indicating the first element in the array to fill. It defaults to 1.

A numeric expression specifying the number of elements to fill. It defaults to 1+Len()-.

Return The function returns a reference to .

Description The array function AFill() traverses the passed array and assigns the value of to the specified number of elements, beginning at position . The array is only traversed in its first dimension. Milti-dimensional arrays cannot be filled using AFill(). Note: is evaluated only once, i.e. all elements are assigned the same value. If the value is of complex data type that is a referenceto to a value (e.g. Array or Object), all elements contain the same reference to the same value.

Info See also: Category: Source: LIB: DLL:

AAdd(), AEval(), AIns(), DbStruct(), Directory() Array functions vm/arrayshb.c xhb.lib xhbdll.dll

Example // The example creates an array filled with "0" and demonstrates the // effect of using a complex data type (Array) to fill an array with. PROCEDURE Main() LOCAL aArray[3] // using a simple data type

Function Reference

389

AFill() AFill( aArray, "A" ) ? aArray[1], aArray[2], aArray[3]

// result: A A A

// using a complex data type AFill( aArray, { "A", "B" } ) ? aArray[1,1], aArray[1,2] ? aArray[2,1], aArray[2,2] ? aArray[3,1], aArray[3,2]

// result: A B // result: A B // result: A B

// changing one element aArray[3,2] := "DON'T" ? aArray[1,1], aArray[1,2] ? aArray[2,1], aArray[2,2] ? aArray[3,1], aArray[3,2]

// result: A DON'T // result: A DON'T // result: A DON'T

// One assignment changes all elements // since aArray contains three times // the same array reference. RETURN

390

Function Reference

AIns()

AIns() Inserts an element into an array.

Syntax AIns( , , [], [] ) --> aArray

Arguments

A variable holding the array to insert an element into.

This is a numeric expression indicating the ordinal position where to insert the new array element. It must be in the range between 1 and Len().

A value of arbitrary data type to assign to the new array element. It defaults to NIL.

Optionally, a logical value can be specified. If .T. (true) is passed, the length of the array is enlarged by one element. The default value is .F. (false) leaving the number of elements in unchanged.

Return The function returns a reference to .

Description The array function AIns() inserts a new element at position into the array . All subsequent elements are shifted down by one position so that the last element is lost when the function returns. This default behaviour leaves the number of elements in the array unchanged. The new array element is initialized with NIL, but can be assigned a value when parameter is not NIL. If the fourth parameter is specified as .T. (true), the function first adds a new element and then shifts all elements down, beginning at the specified position. This way, the last element is preserved and the number of elements is enlarged by one.

Info See also: Category: Source: LIB: DLL:

AAdd(), ACopy(), ADel(), AEval(), AFill(), ASize() Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // This example demonstrates two results of inserting an // array element

Function Reference

391

AIns() PROCEDURE Main() LOCAL aArray := { "A", "B", "C" } AIns( aArray, 2 ) ? Len( aArray ) // result: 3 ? aArray[1], aArray[2], aArray[3] // result: A NIL B AIns( aArray, 2, "C", .T. ) ? Len( aArray ) // result: 4 ? aArray[1], aArray[2], aArray[3], aArray[4] // result: A C NIL B RETURN

392

Function Reference

ALenAlloc()

ALenAlloc() Determines for how much array elements memory is pre-allocated.

Syntax ALenAlloc( ) --> nElements

Arguments

This is the array to query pre-allocated memory for.

Return The function returns a numeric value specifying the number of elements memory is pre-allocated for.

Description The function is used to determine for how much array elements memory is pre-allocated. This is accomplished with function ASizeAlloc() which is available for memory optimization of dynamically growing arrays.

Info See also: Category: Source: LIB: DLL:

Function Reference

AAdd(), Array(), ASizeAlloc() Array functions, xHarbour extensions vm\arrayshb.c xhb.lib xhbdll.dll

393

Alert()

Alert() Displays a text-mode dialog box with a message.

Syntax Alert( , [], [], [] ) --> nChoice

Arguments

This is the message to display in the dialog box. It can be of any data type but is usually a character string or an array filled with strings. If is a character string, the semicolon is treated as a new line character. When it is an array, each element is displayed in a new line of the dialog box.

is an array filled with character strings. Each element is displayed as prompt for the user to make a selection. If no parameter is passed, defaults to { "Ok" }.

This is a color string holding two color values. The Normal color is used to display the dialog box along with . The options to select from are displayed in the Enhanced color. The default is "W+/R,W+/B".

Optionally, a numeric value can be specified, indicating the number of seconds to wait for a key press before the dialog box closes automatically. It defaults to zero, which means that the dialog box does not close automatically.

Return The function returns a numeric value indicating the ordinal position within of the prompt selected by the user. When the ESC key is pressed, the user aborted the selection and the return value is 0. If is specified and this number of seconds has elapsed without a key press, the return value is 1.

Description Alert() displays a simple text-mode dialog box and lets the user select an option. The user can move a highlight bar using arrow keys or the TAB key. To select an option, the user can press ENTER, SPACE or the first letter of an option.

394

Function Reference

Alert()

Info See also: Category: Source: LIB: DLL:

@...PROMPT, AChoice(), DispBox(), DispOut(), MENU TO UI functions rtl\alert.prg xhb.lib xhbdll.dll

Example // The example displays a message to terminate or resume the program. // After 5 seconds without user response, the program quits automatically. PROCEDURE Main() LOCAL cMessage, aOptions, nChoice cMessage := "Quit program?;(auto-quit in 5 seconds)" aOptions := { "Yes", "No" } nChoice := Alert( cMessage, aOptions, , 5) DO CASE CASE nChoice == 0 ? "Program not interrupted ..." CASE nChoice == 1 QUIT CASE nChoice == 2 ? "Program resumed ..." ENDCASE RETURN

Function Reference

395

Alias()

Alias() Returns the alias name of a work area.

Syntax Alias( [] ) --> cAlias

Arguments

is the numeric ordinal position of a work area. Work areas are numbered from 1 to 65535.

Return The function returns the alias name of the work area specified with . If no parameter is passed, the alias name of the current work area is returned. When no database is open in the work area, the return value is a null string ("").

Description The alias name of a work area exists while a database is open in it. Alias names are used to address work areas via a symbolic name and are specified with the USE command or the DbUseArea() function. Alias names are always created in upper case letters.

Info See also: Category: Source: LIB: DLL:

DbInfo(), DbUseArea(), OrdName(), OrdNumber(), SELECT, Select(), USE Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates usage of functions Alias() and Select(), // both ofwhich are used to address work areas. PROCEDURE Main USE Customer NEW ALIAS Cust USE Invoice NEW ALIAS Inv ? Alias() ? Select()

// result: INV // result: 2

? Alias(1) ? Select( "CUST" )

// result: CUST // result: 1

CLOSE ALL RETURN

396

Function Reference

AllTrim()

AllTrim() Removes leading and trailing blank spaces from a string.

Syntax AllTrim( ) --> cTrimmed

Arguments

is any character string.

Return The function returns the passed string without leading and trailing blank spaces.

Description This function removes leading and trailing spaces from a string. Use function LTrim() or RTrim() to remove spaces on the left or right end of .

Info See also: Category: Source: LIB: DLL:

LTrim(), PadC() | PadL() | PadR(), RTrim() Character functions rtl\trim.c xhb.lib xhbdll.dll

Example // This example removes all leading and trailing spaces from strings. PROCEDURE Main() ? ""

// result:

? ""

// result:

? ""

RETURN NIL

Function Reference

397

AltD()

AltD() Activates and/or invokes the "classic" debugger.

Syntax AltD( [] ) --> NIL

Arguments

If no parameter is passed, the debugger is invoked, when it is activated. Passing numeric 1 activates the debugger and numeric zero deactivates it.

Return The return value is always NIL.

Description Function AltD() toggles the activity of the "classic" debugger which runs in text mode only. To activate the debugger, AltD(1) must be called in a program. A subsequent call to AltD() with no parameter invokes the debugger and displays the PRG source code file with the current line being executed. A programmer can then inspect variables or execute a program step by step. Calling AltD(0) disables the debugger. When the debugger is activated, the key combination Alt+D invokes the debugger as well. This way, a program can run until a certain situation is reached that must be debugged.

Info See also: Category: Source: LIB: DLL:

Set() Debug functions debug\dbgaltd.prg xhb.lib xhbdll.dll

Example // // // // //

The example demonstrates how to invoke the "classic" debugger. To run the example, create the executable with "classic" debug information or call xbuild on the command line: --> xbuild -B -CLASSIC test.prg PROCEDURE Main LOCAL dDate := Date() LOCAL nKey AltD(1) AltD()

// activates debugger // invokes debugger unconditionally

? "Today is:", dDate IF Day( dDate ) == 1 AltD() ENDIF

398

// invokes debugger conditionally

Function Reference

AltD() nKey := Inkey(0)

// debugger is invoked by pressing Alt+D

? "Last key:", nKey RETURN

Function Reference

399

AmPm()

AmPm() Converts a time string into am/pm format.

Syntax AmPm( ) --> cFormattedTime

Arguments

is a character string returned by the Time() function.

Return The return value is the formatted time string.

Description AmPm() is a utility function that converts the 24h time string returned by the Time() function to a 12h am/pm time string.

Info See also: Category: Source: LIB: DLL:

Time(), Transform() Conversion functions rtl\ampm.c xhb.lib xhbdll.dll

Example // The example demonstrates formatting of Time() string PROCEDURE Main LOCAL cMidnight LOCAL cMorning LOCAL cNoon LOCAL cEvening ? AmPm( ? AmPm( ? AmPm( ? AmPm( RETURN

400

:= := := :=

cMidNight cMorning cNoon cEvening

"00:00:00" "07:30:45" "12:00:00" "19:30:45"

) ) ) )

// // // //

result: 12:00:00 am result: 07:30:45 am result: 12:00:00 pm result: 7:30:45 pm

Function Reference

Array()

Array() Creates an uninitialized array of specified length.

Syntax Array( [, ] ) --> aArray

Arguments

A comma separated list of numeric values can be passed. Each value indicates the number of elements to create for each dimension of the array. Passing a single numeric value creates a onedimensional array.

Return The function returns an array dimensioned according to the passed parameters. All elements of the array contain the value NIL.

Description Array variables are usually initialized within a variable declaration. The Array() function allows for creating arrays programmatically outside a variable declaration. Array() can be part of an expression or can be called from within a code block. The return value of Array() is a reference to an array of the specified dimensions. The number of elements in the array is limited by memory resources of the operating system.

Info See also: Category: Source: LIB: DLL:

AAdd(), AClone(), ACopy(), ADel(), AEval(), AFill(), AIns(), Hash() Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example demonstrates different approaches of creating // uninitialized arrays. PROCEDURE Main() LOCAL xValue LOCAL aArray[2,3]

// declaration

xValue := Array( 3, 5 )

// programmatically

? Len( aArray ), Len( aArray[1] )

// result: 2 3

? Len( xValue ), Len( xValue[1] ) RETURN NIL

// result: 3 5

Function Reference

401

Asc()

Asc() Returns the ASCII code for characters.

Syntax ASC( ) --> nAsciiCode

Arguments

is any character expression.

Return The functions returns the numeric ASCII code for .

Description This function returns the ASCII value of the leftmost character of any character expression. Note: passing a null string ("") yields 0. It is the same result as passing Chr(0). A null string, however, is different from Chr(0).

Info See also: Category: Source: LIB: DLL:

Chr(), Inkey(), Str(), Val() Conversion functions rtl\chrasc.c xhb.lib xhbdll.dll

Example // The example displays the ASCII values of several characters and // character strings PROCEDURE Main() ? ? ? ? ?

Asc( Asc( Asc( Asc( Asc(

" " ) "A" ) "a" ) "xHarbour" ) "XHARBOUR" )

// // // // //

result: 32 result: 65 result: 97 result: 120 result: 88

RETURN

402

Function Reference

AScan()

AScan() Searches a value in an array beginning with the first element.

Syntax Ascan( , , [], [], [], []

; ; ; ; ; ) --> nElement

Arguments

This is the array to iterate.

is either the value to search in or a code block containing the search condition. The code block receives a single parameter which is the value stored in the current array element. The code block must return a logical value. When the return value is .T. (true), the function stops searching and returns the position of the corresponding array element.

This is a numeric expression indicating the first element in the array to begin the search with. It defaults to 1, the first element of .

A numeric expression specifying the number of elements to search. It defaults to 1+Len()-.

This parameter influences the comparison for searching character strings in . If .T. (true) is passed, an exact string comparison is performed. When omitted or if .F. (false) is passed, string comparison follows the SET EXACT rules.

This parameter is only relevant for arrays that contain single characters in their elements. A single character is treated like a numeric ASCII value when is .T. (true). The default is.F. (false).

Return AScan() returns the numeric ordinal position of the array element that contains the searched value. When no match is found, the return value is 0.

Description The array function AScan() traverses the array for the value specified with . If is not a code block, AScan() compares the values of each array element for being equal with the searched value. If this comparison yields .T. (true), the function stops searching and returns the numeric position of the array element containing the searched value. Function Reference

403

AScan()

If a code block is passed for , it is evaluated and receives as parameter the value of the current array element. The code block must contain a comparison rule that yields a logical value. AScan() considers the value as being found when the codeblock returns .T. (true). Otherwise the function proceeds with the next array element. Note: use function RAscan() to search an array beginning with the last element.

Info See also: Category: Source: LIB: DLL:

AEval(), Asc(), ASort(), ATail(), Eval(), IN, RAscan(), SET EXACT Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example demonstrates simple and complex searching in arrays. PROCEDURE Main() LOCAL aArray := { "A", 1, Date(), NIL, .F. } // one dimensional array ? AScan( aArray, 1 ) ? AScan( aArray, .F. )

// result: 2 // result: 5

? AScan( aArray, {|x| Valtype(x)=="D" } ) // result: 3 // two dimensional array aArray := Directory( "*.prg" ) ? AScan( aArray, {|a| Upper(a[1]) == "TEST.PRG" } ) // result: 28 RETURN

404

Function Reference

ASize()

ASize() Changes the number of elements in an array.

Syntax ASize( , ) --> aArray

Arguments

This is the array whose size is changed.

A numeric expression specifying the number of elements the result array should have.

Return The function returns the reference to .

Description The array function ASize() is used to dynamically increase or decrease the size of to elements. When the array is enlarged, new elements are added to the end of and are initialized with NIL. When the number of elements is decreased, they are removed from the end of . The values in the removed elements are lost. The size of arrays is limited by the memory resources of the operating system.

Info See also: Category: Source: LIB: DLL:

AAdd(), ADel(), AFill(), AIns(), ASizeAlloc() Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // This example demonstrates the use of the ASize function. // It increases and decreases the size of an array. PROCEDURE Main() LOCAL aArray := { 45 } ? Len( aArray )

// result: 1

ASize( aArray, 3 ) ? Len( aArray ) ? aArray[1], aArray[2], aArray[3]

// result: 3 // result: 45 NIL NIL

ASize( aArray, 1 ) ? Len( aArray ) ? aArray[1]

// result: 1 // result: 45

RETURN

Function Reference

405

ASizeAlloc()

ASizeAlloc() Pre-allocates memory for an array.

Syntax ASizeAlloc( ,

) --> aArray

Arguments

This is the array to pre-allocate memory for.

A numeric value specifying the number of elements to reserve memory for.

Return The function returns the array .

Description Function ASizeAlloc() pre-allocates memory for number of elements of an array. This improves dynamically growing arrays when elements are added to the array using AAdd(). Note: the function does not change the number of elements of , it reserves only memory for them, thus optimizing memory usage with dynamic arrays.

Info See also: Category: Source: LIB: DLL:

AAdd(), Array(), ALenAlloc(), ASize() Array functions, xHarbour extensions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example creates an empty array and pre-allocates // memory for 1000 elements. Note that the examples ends // with a runtime error, since element 100 does not exist. PROCEDURE Main LOCAL aArray := {} ASizeAlloc( aArray, 1000 ) ? ALenAlloc( aArray )

// result: 1000

AAdd( aArray, 10 ) ? Len( aArray ) ? aArray[100] RETURN

406

// result: 1 // runtime error

Function Reference

ASort()

ASort() Sorts an array.

Syntax ASort( , [], [], [] ) --> aArray

Arguments

The array to be sorted.

This is a numeric expression indicating the first element in the array to begin sorting with. It defaults to 1, the first element of .

A numeric expression specifying the number of elements to sort. It defaults to 1+Len()-.

Optionally, a code block defining a sorting rule can be passed. If this parameter is omitted, all values stored in are sorted in ascending order. When a code block is specified, it must be declared with two parameters and must return a logical value. The code block receives the values of two adjacent array elements. When the code block returns .T. (true), the first code block parameter is considered smaller than the second. If .F. (false) is returned, the first code block parameter is larger.

Return The function returns a reference to .

Description ASort() sorts an array entirely or partially by the values stored in its elements. If the code block is omitted, the function expects to be a one dimensional array containing simple data types. The values are sorted in ascending order. Character strings are sorted by their ASCII values, dates are sorted chronologically, Logical .F. (false) is smaller than .T. (true), and Numerics are sorted by their value. If is specified, it is used to define the comparison rule for "smaller". The code block must have two parameters which receive the values of two array elements. The first code block parameter is considered smaller, when the code block returns .T. (true), otherwise it is considered larger than the second code block parameter. The definition of an appropriate comparison rule allows for sorting an array in descending order, and/or to sort multi-dimensional arrays.

Function Reference

407

ASort()

Info See also: Category: Source: LIB: DLL:

AEval(), AScan(), Eval(), SORT Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example demonstrates the sorting of one- and two-dimensional // arrays in ascending and descending order. PROCEDURE Main() LOCAL i, aNum LOCAL aNames

:= { 3, 1, 4, 42 } := { { "gilbert", 1 }, ; { "eats" , 2 }, ; { "grape" , 3 } }

// one-dimensional array ? "Ascending: " ASort( aNum ) FOR i := 1 TO Len( aNum ) ?? aNum[i] NEXT

// result: 1 3 4 42

? "Descending: " ASort( aNum ,,, {|x,y| x > y } ) FOR i := 1 TO Len( aNum ) // result: 42 4 3 1 ?? aNum[i] NEXT // two-dimensional array sorted by second column ? "Descending: " ASort( aNames ,,, {|x,y| x[2] > y[2] } ) FOR i := 1 TO Len( aNames ) ? aNames[i,1] NEXT // result: // grape // eats // gilbert RETURN

408

Function Reference

At()

At() Locates the position of a substring within a character string.

Syntax At( , , [], [] ) --> nPos

Arguments

is the substring to search for.

is the searched character string.

A numeric expression indication the position of the first character in to begin the search with. It defaults to 1.

A numeric expression indicating the position of the last character in to include in the search. It defaults to Len(). If is a negative value, the position for the last character is counted from the end of .

Return The function returns a numeric value which is the position in where is found. The return value is zero when is not found.

Description This function At() searches the string from left to right for the character string . The search begins at position and is case-sensitive. If does not contain , the function returns 0. Note: use function RAt() to search from right to left.

Info See also: Category: Source: LIB: DLL:

$, HB_ATokens(), HB_RegEx(), IN, Left(), RAt(), Right(), StrTran(), SubStr() Character functions rtl\at.c xhb.lib xhbdll.dll

Example // The example demonstrates various results of At(). PROCEDURE Main() LOCAL cString := "xHarbour" ? At( "Ha", cString )

Function Reference

// result: 2

409

At()

410

? At( "ARB" , cString )

// result: 0

? At( "ARB" , Upper(cString) )

// result: 3

? At( "r" , cString )

// result: 4

? At( "r" , cString, 5 )

// result: 8

? At( "r" , cString, 5, 7 ) RETURN

// result: 0

Function Reference

ATail()

ATail() Returns the last element of an array.

Syntax ATail( ) --> xValue

Arguments

is the array to retrieve the last element from.

Return The function returns the value stored in the last element of .

Description The function ATail() retrieves the value of the last element in the array named . This function does not alter the size of the array.

Info See also: Category: Source: LIB: DLL:

[ ] (array), AEval(), AScan(), ASort(), Len() Array functions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example shows thee ways of obtaining the last element // of an array PROCEDURE Main() LOCAL aArray := { "A", "B", "C" } // functional ? ATail( aArray ) // positive subscript ? aArray[ Len(aArray) ] // negative subscript ? aArray[-1] RETURN

Function Reference

411

Bin2I()

Bin2I() Converts a signed short binary integer (2 bytes) into a numeric value.

Syntax Bin2I( ) --> nNumber

Arguments

This is a character string whose first two bytes are converted to a 16 bit signed integer value of numeric data type.

Return The function returns a numeric value in the range of -(2^15) to +(2^15) - 1.

Description Bin2I() is a binary conversion function that converts a two byte binary number (Valtype()=="C") to a numeric value (Valtype()=="N"). The parameter is usually the return value of function I2Bin(). The range for the numeric return value is determined by a signed short integer.

Info See also: Category: Source: LIB: DLL:

Bin2L(), Bin2U(), Bin2W(), FRead(), I2Bin(), L2Bin(), U2Bin(), W2Bin(), Word() Binary functions, Conversion functions rtl\binnum.c xhb.lib xhbdll.dll

Example // The example demonstrates encoding of binary signed 16 bit integer // numbers and their conversion to numeric values. PROCEDURE Main ? Bin2I( Chr(0)

+

Chr(0) )

// result:

0

? Bin2I( Chr(1) + Chr(0) ) ? Bin2I( Chr(255) + Chr(255) )

// result: // result:

1 -1

? Bin2I( Chr(0) ? Bin2I( Chr(0)

// result: // result:

256 -256

+ Chr(1) ) + Chr(255) )

? Bin2I( Chr(255) + Chr(127) ) ? Bin2I( Chr(0) + Chr(128) ) RETURN

412

// result: 32767 // result: -32768

Function Reference

Bin2L()

Bin2L() Converts a signed long binary integer (4 bytes) into a numeric value.

Syntax Bin2L( ) --> nNumber

Arguments

This is a character string whose first four bytes are converted to a 32 bit signed integer value of numeric data type.

Return The function returns a numeric value in the range of -(2^31) to +(2^31) - 1.

Description Bin2L() is a binary conversion function that converts a four byte binary number (Valtype()=="C") to a numeric value (Valtype()=="N"). The parameter is usually the return value of function L2Bin(). The range for the numeric return value is determined by a signed long integer.

Info See also: Category: Source: LIB: DLL:

Bin2I(), Bin2U(), Bin2W(), FRead(), I2Bin(), L2Bin(), U2Bin(), W2Bin(), Word() Binary functions, Conversion functions rtl\binnum.c xhb.lib xhbdll.dll

Example // The example demonstrates encoding of binary signed 32 bit integer // numbers and their conversion to numeric values. PROCEDURE Main ? Bin2L( Chr(0) +

Chr(0) +

Chr(0) +

Chr(0) )

// result:

0

? Bin2L( Chr(1) + Chr(0) + Chr(0) + Chr(0) ) ? Bin2L( Chr(255) + Chr(255) + Chr(255) + Chr(255) )

// result: // result:

1 -1

? Bin2L( ? Bin2L(

// result: // result:

256 -256

Chr(0) + Chr(1) + Chr(0) + Chr(0) ) Chr(0) + Chr(255) + Chr(255) + Chr(255) )

? Bin2L( Chr(255) + Chr(255) + Chr(255) + Chr(127) ) ? Bin2L( Chr(0) + Chr(0) + Chr(0) + Chr(128) ) RETURN

Function Reference

// result: 2147483647 // result: -2147483648

413

Bin2U()

Bin2U() Converts an unsigned long binary integer (4 bytes) into a numeric value.

Syntax Bin2U( ) --> nNumber

Arguments

This is a character string whose first four bytes are converted to a 32 bit unsigned integer value of numeric data type.

Return The function returns a numeric value in the range of 0 to (2^32) - 1.

Description Bin2U() is a binary conversion function that converts a four byte binary number (Valtype()=="C") to a numeric value (Valtype()=="N"). The parameter is usually the return value of function U2Bin(). The range for the numeric return value is determined by an unsigned long intege r.

Info See also: Category: Source: LIB: DLL:

Bin2I(), Bin2L(), Bin2W(), FRead(), I2Bin(), L2Bin(), U2Bin(), W2Bin(), Word() Binary functions, Conversion functions rtl\binnum.c xhb.lib xhbdll.dll

Example // The example reads the number of records from the file header // of a DBF file and displays the converted numeric value. PROCEDURE Main() LOCAL nHandle LOCAL cInteger := Space( 4 ) LOCAL cFile := "Customer.dbf" nHandle := FOpen( cFile

)

IF nHandle > 0 FSeek( nHandle, 4 ) FRead( nHandle, @cInteger, 4 ) ? "Number of records in file:", Bin2U( cInteger ) FClose( nHandle ) ELSE ? "Cannot open file:", cFile ENDIF RETURN

414

Function Reference

Bin2W()

Bin2W() Converts an unsigned short binary integer (2 bytes) into a numeric value.

Syntax Bin2W( ) --> nNumber

Arguments

This is a character string whose first two bytes are converted to a 16 bit unsigned integer value of numeric data type.

Return The function returns a numeric value in the range of 0 to +(2^16) - 1.

Description Bin2W() is a binary conversion function that converts a two byte binary number (Valtype()=="C") to a numeric value (Valtype()=="N"). The parameter is usually the return value of function W2Bin(). The range for the numeric return value is determined by an unsigned short integer.

Info See also: Category: Source: LIB: DLL:

Bin2I(), Bin2L(), Bin2U(), FRead(), I2Bin(), L2Bin(), U2Bin(), W2Bin(), Word() Binary functions, Conversion functions rtl\binnum.c xhb.lib xhbdll.dll

Example // The example reads the header size from the file header // of a DBF file and displays the converted numeric value. PROCEDURE Main() LOCAL nHandle LOCAL cInteger := Space( 2 ) LOCAL cFile := "Customer.dbf" nHandle := FOpen( cFile

)

IF nHandle > 0 FSeek( nHandle, 8 ) FRead( nHandle, @cInteger, 2 ) ? "Size of file header:", Bin2W( cInteger ) FClose( nHandle ) ELSE ? "Cannot open file:", cFile ENDIF RETURN

Function Reference

415

BlobDirectExport()

BlobDirectExport() Exports the contents of a binary large object (BLOB) to a file.

Syntax BlobDirectExport( , , [] ) --> lSuccess

Arguments

is the numeric identifier of the binary large object to export. The ID can be obtained using functions BlobDirectPut() or DbFieldInfo( DBS_BLOB_POINTER, ). An array of blob IDs can also be obtained using BlobRootGet() when the blob IDs are previously written to the root area of a blob file.

This is a character string containing the name of the file to receive the exported data. It must be specified with a file extension. If contains no drive and/or directory information, the current directory is used. SET DEFAULT and SET PATH settings are ignored.

A numeric value specifying how to write data to the target file. #define constants must be used for this parameter.

Constants for BlobDirectExport() Constant

Description

BLOB_EXPORT_APPEND BLOB_EXPORT_OVERWRITE *) *) default value

Appends to the target file Overwrites the target file

Return The return value is .T. (true) if data is successfully exported, otherwise .F. (false) is returned.

Description BlobDirectExport() copies the contents of a single binary large object (BLOB) to an external file. The object is identified by its numeric ID. A BLOB is stored either in a memo field (DBFCDX RDD) or in a stand alone DBV file which is not associated with a database file (DBFBLOB RDD). BlobDirectExport() is usually required for the latter case. If BLOBs are stored in a database with an associated memo file, function BlobExport() is more comfortable to use, since it accepts a numeric field position of a memo field, rather than a numeric BLOB identifier. The numeric BLOB ID is obtained using DbFieldInfo() or must be taken from the array returned by BlobRootGet(). If the target file does not exist, it is created. If it exists, it is either overwritten or data is appended to the file, depending on . When the file operation fails, BlobDirectExport() returns .F. (false) and function NetErr() is set to .T. (true). This can happen when the target file is currently locked by another process in concurrent file access.

416

Function Reference

BlobDirectExport()

Notes: BLOBs are stored in memo files having the .FPT or .DBV extension. They are maintained by the RDDs DBFCDX or DBFBLOB. DBFNTX, in contrast, does not support BLOBs. The file Blob.ch must be #included for BlobDirectExport() to work.

Info See also: Category: Header: Source: LIB: DLL:

BlobDirectGet(), BlobDirectImport(), BlobDirectPut(), BlobExport(), BlobRootGet(), DbFieldInfo() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // // // //

The example demonstrates two possibilities of exporting BLOB data. The first example uses the DBFCDX RDD while the second uses the DBFBLOB RDD which does not maintain a database file, but only the BLOB file. #include "Blob.ch" REQUEST DBFBLOB REQUEST DBFCDX PROCEDURE Main LOCAL nBlobID, nFieldPos LOCAL aBlobID // DBF and FPT file exist USE PhotoArchive ALIAS Photos VIA "DBFCDX" LOCATE FOR FIELD->PhotoName = "Sunset in Malibu" IF Found() nFieldPos := FieldPos( "JPEG" ) nBlobID := DbFieldInfo( DBS_BLOB_POINTER, nFieldPos ) IF BlobDirectExport( nBlobID, "Sunset.jpg" ) ? "File successfully eported" ELSE ? "Unable to export BLOB data" ENDIF ENDIF // Only DBV file exists USE BlobStorage ALIAS Blob VIA "DBFBLOB" aBlobID := BlobRootGet() IF Valtype( aBlobID ) == "A" // Export second BLOB to file IF BlobDirectExport( aBlobID[2], "Picture02.jpg" ) ? "File successfully eported" ELSE ? "Unable to export BLOB data" ENDIF ELSE ? "Error: Blob root is not created" ENDIF

Function Reference

417

BlobDirectExport() USE RETURN

418

Function Reference

BlobDirectGet()

BlobDirectGet() Loads data of a binary large object (BLOB) into memory.

Syntax BlobDirectGet( , [], [] ) --> xBlobData

Arguments

is the numeric identifier of the binary large object (BLOB) to load into memory. The ID can be obtained using functions BlobDirectPut() or DbFieldInfo( DBS_BLOB_POINTER, ). An array of blob IDs can also be obtained using BlobRootGet(), when the blob IDs are previously written to the root area of a blob file.

This is a numeric value specifying the first byte of the BLOB to include in the returned string. If is a positive number, data is loaded from the beginning, or the left side, of the BLOB. If is a negative number, the data is loaded from the end, or the right side, of the BLOB. Note: Both parameters, and , are ignored if the BLOB does not contain a character string.

This is a numeric value specifying the number of bytes to load, beginning at position . If omitted, all bytes from to the end of the BLOB are loaded.

Return The function returns the BLOB data loaded into memory. The data type of a BLOB depends on the stored BLOB. It can be determined using function Valtype().

Description BlobDirectGet() loads the contents of a single binary large object (BLOB) into memory. The object is identified by its numeric ID. A BLOB is stored either in a memo field (DBFCDX RDD) or in a stand alone DBV file which is not associated with a database file (DBFBLOB RDD). BlobDirectGet() is usually required for the latter case. If BLOBs are stored in a database with an associated memo file, function BlobGet() is more comfortable to use, since it accepts a numeric field position of a memo field, rather than a numeric BLOB identifier. The numeric BLOB ID is obtained using DbFieldInfo() or must be taken from the array returned by BlobRootGet(). Notes: BLOBs are stored in memo files having the .FPT or .DBV extension. They are maintained by the RDDs DBFCDX or DBFBLOB. DBFNTX, in contrast, does not support BLOBs. The file Blob.ch must be #included for BlobDirectGet() to work.

Function Reference

419

BlobDirectGet()

Info See also:

BlobDirectExport(), BlobDirectImport(), BlobDirectPut(), BlobExport(), BlobRootGet(), DbFieldInfo() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Category: Header: Source: LIB: DLL:

Example // // // //

The example demonstrates two possibilities of loading BLOB data. The first example uses the DBFCDX RDD while the second uses the DBFBLOB RDD which does not maintain a database file, but only the BLOB file. #include "Blob.ch" REQUEST DBFBLOB REQUEST DBFCDX PROCEDURE Main LOCAL nBlobID, nFieldPos LOCAL aBlobID LOCAL cImage // DBF and FPT file exist USE PhotoArchive ALIAS Photos VIA "DBFCDX" LOCATE FOR FIELD->PhotoName = "Sunset in Malibu" IF Found() // Get numeric field position nFieldPos := FieldPos( "JPEG" ) // Get numeric BLOB ID nBlobID := DbFieldInfo( DBS_BLOB_POINTER, nFieldPos ) // Load BLOB cImage := BlobDirectGet( nBlobID ) // < ... process BLOB data ... > ENDIF // Only DBV file exists USE BlobStorage ALIAS Blob VIA "DBFBLOB" aBlobID := BlobRootGet() IF Valtype( aBlobID ) == "A" // Load second BLOB cImage := BlobDirectGet( nBlobID[2] ) // < ... process BLOB data ... > ELSE ? "Error: Blob root is not created" ENDIF USE RETURN

420

Function Reference

BlobDirectImport()

BlobDirectImport() Imports a file into a binary large object (BLOB).

Syntax BlobDirectImport( , ) --> nNewBlobID

Arguments

is the numeric identifier of the binary large object to receive the file contents of . The ID can be obtained using functions BlobDirectPut() or DbFieldInfo( DBS_BLOB_POINTER, ). An array of blob IDs can also be obtained using BlobRootGet() when the blob IDs are previously written to the root area of a blob file. All data of is discarded, and the BLOB receives a new ID which is returned by the function. If zero is passed, a new BLOB is added to the BLOB file.

This is a character string containing the name of the file to import BLOB data from. It must be specified with a file extension. If contains no drive and/or directory information, the current directory is used. SET DEFAULT and SET PATH settings are ignored. If does not exist, a runtime error is raised. If the file cannot be opened due to another process having exclusive access to the file, function NetErr() is set to .T. (true).

Return The function returns a numeric value which is the BLOB identifier of the new BLOB. The return value is zero, when the operation fails.

Description BlobDirectImport() copies the contents of an external file into a single binary large object (BLOB). The object is identified by its numeric ID. A BLOB is stored either in a memo field (DBFCDX RDD) or in a stand alone DBV file which is not associated with a database file (DBFBLOB RDD). BlobDirectImport() is usually required for the latter case. If BLOBs are stored in a database with an associated memo file, function FieldPut() is more comfortable to use, since it accepts a numeric field position of a memo field, rather than a numeric Blob identifier. The numeric Blob ID is obtained using DbFieldInfo() or must be taken from the array returned by BlobRootGet(). When data is imported into an existing BLOB, the BLOB is entirely discarded and a new BLOB is created. As a consequence, the existing BLOB ID becomes invalid, and BlobDirectImport() returns a new BLOB ID. The imported data can only be accessed via the new BLOB ID. Notes: BLOBs are stored in memo files having the .FPT or .DBV extension. They are maintained by the RDDs DBFCDX or DBFBLOB. DBFNTX, in contrast, does not support BLOBs. The file Blob.ch must be #included for BlobDirectImport() to work.

Function Reference

421

BlobDirectImport()

Info See also: Category: Header: Source: LIB: DLL:

BlobDirectGet(), BlobDirectExport(), BlobExport(), BlobGet(), BlobImport(), BlobRootGet(), DbFieldInfo() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // The example demonstrates how to import JPG files into a DBV file. #include "Blob.ch" REQUEST DBFBLOB PROCEDURE Main LOCAL aFile LOCAL aFiles := Directory( "*.jpg" ) LOCAL aBlobID := {} DbCreate( "ImageArchive", {}, "DBFBLOB" ) USE ImageArchive NEW VIA "DBFBLOB" FOR EACH aFile IN aFiles AAdd( aBlobID, BlobDirectImport( 0, aFile[1] ) ) NEXT IF BlobRootLock() .AND. BlobRootPut( aBlobID ) BlobRootUnlock() ELSE Alert( "Unable to lock BLOB root;try again later" ) ENDIF USE RETURN

422

Function Reference

BlobDirectPut()

BlobDirectPut() Assigns data to a binary large object (BLOB).

Syntax BlobDirectPut( , ) --> nNewblobID

Arguments

is the numeric identifier of the binary large object to assign to. The ID can be obtained using functions BlobDirectPut() or DbFieldInfo( DBS_BLOB_POINTER, ). An array of blob IDs can also be obtained using BlobRootGet() when the blob IDs are previously written to the root area of a blob file. All data of is discarded, and the BLOB receives a new ID which is returned by the function. If zero is passed, a new BLOB is added to the BLOB file.

This is the value to assign to the BLOB. The supported data type of can vary between RDDs maintaining BLOB files.

Return The function returns a numeric value which is the BLOB identifier of the new BLOB. The return value is zero, when the operation fails.

Description BlobDirectPut() assigns the value of to a single binary large object (BLOB). The object is identified by its numeric ID. A BLOB is stored either in a memo field (DBFCDX RDD) or in a stand alone DBV file which is not associated with a database file (DBFBLOB RDD). BlobDirectPut() is usually required for the latter case. If BLOBs are stored in a database with an associated memo file, function FieldPut() is more comfortable to use, since it accepts a numeric field position of a memo field, rather than a numeric Blob identifier. The numeric Blob ID is obtained using DbFieldInfo() or must be taken from the array returned by BlobRootGet(). When data is assigned to an existing BLOB, the BLOB is entirely discarded and a new BLOB is created. As a consequence, the existing BLOB ID becomes invalid, and BlobDirectPut() returns a new BLOB ID. The imported data can only be accessed via the new BLOB ID. Notes: BLOBs are stored in memo files having the .FPT or .DBV extension. They are maintained by the RDDs DBFCDX or DBFBLOB. DBFNTX, in contrast, does not support BLOBs. The file Blob.ch must be #included for BlobDirectPut() to work.

Function Reference

423

BlobDirectPut()

Info See also: Category: Header: Source: LIB: DLL:

BlobDirectExport(), BlobDirectGet(), BlobDirectImport(), BlobExport(), BlobRootGet(), DbFieldInfo() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // The example demonstrates how to collect contents of files // in a single DBV file. #include "Blob.ch" REQUEST DBFBLOB PROCEDURE Main LOCAL aFile, cText LOCAL aFiles := Directory( "*.prg" ) LOCAL aBlobID := {} DbCreate( "Repository", {}, "DBFBLOB" ) USE Repository NEW VIA "DBFBLOB" FOR EACH aFile IN aFiles cText := MemoRead( aFile[1] ) AAdd( aBlobID, BlobDirectPut( 0, cText ) ) NEXT IF BlobRootLock() .AND. BlobRootPut( aBlobID ) BlobRootUnlock() ELSE Alert( "Unable to lock BLOB root;try again later" ) ENDIF USE RETURN

424

Function Reference

BlobExport()

BlobExport() Exports the contents of a memo field holding a binary large object (BLOB) to a file.

Syntax BlobExport( , , [] ) --> lSuccess

Arguments

This is a numeric value specifying the ordinal position of the memo field holding the BLOB to be exported.

This is a character string containing the name of the file to receive the exported data. It must be specified with a file extension. If contains no drive and/or directory information, the current directory is used. SET DEFAULT and SET PATH settings are ignored.

A numeric value specifying how to write data to the target file. #define constants must be used for this parameter.

Constants for BlobExport() Constant

Description

BLOB_EXPORT_APPEND BLOB_EXPORT_OVERWRITE *) *) default value

Appends to the target file Overwrites the target file

Return The return value is .T. (true) if data is successfully exported, otherwise .F. (false) is returned.

Description BlobExport() copies the contents of a single binary large object (BLOB) to an external file. The object is identified by the ordinal position of the memo field holding the BLOB data. This position can be obtained using function FieldPos(). If the target file does not exist, it is created. If it exists, it is either overwritten or data is appended to the file, depending on . When the file operation fails, BlobExport() returns .F. (false) and function NetErr() is set to .T. (true). This can happen when the target file is currently locked by another process in concurrent file access. Note: the file Blob.ch must be #included for BlobExport() to work.

Function Reference

425

BlobExport()

Info See also: Category: Header: Source: LIB: DLL:

BlobDirectGet(), BlobDirectExport(), BlobDirectImport(), BlobDirectPut(), BlobRootGet(), DbFieldInfo() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // The example demonstrates how to export BLOB data to an external file. #include "Blob.ch" REQUEST DBFCDX PROCEDURE Main LOCAL nFieldPos USE PhotoArchive ALIAS Photos VIA "DBFCDX" LOCATE FOR FIELD->PhotoName = "Sunset in Malibu" IF Found() nFieldPos := FieldPos( "JPEG" ) IF BlobExport( nFieldPos, "Sunset.jpg" ) ? "File successfully eported" ELSE ? "Unable to export BLOB data" ENDIF ENDIF USE RETURN

426

Function Reference

BlobGet()

BlobGet() Reads the contents of a memo field holding a binary large object (BLOB).

Syntax BlobGet( , [], [] ) --> xBlobData

Arguments

This is a numeric value specifying the ordinal position of the memo field holding the BLOB to read.

This is a numeric value specifying the first byte of the BLOB to include in the returned string. If is a positive number, data is loaded from the beginning, or the left side, of the BLOB. If is a negative number, the data is loaded from the end, or the right side, of the BLOB. Note: Both parameters, and , are ignored if the BLOB does not contain a character string.

This is a numeric value specifying the number of bytes to load, beginning at position . If omitted, all bytes from to the end of the BLOB are loaded.

Return The function returns the BLOB data loaded into memory. The data type of a BLOB depends on the stored BLOB. It can be determined using function Valtype(). If the indicated field at position is not amemo field, the return value is NIL.

Description BlobGet() exists for compatibility reasons. It does the same as function FieldGet() but is restricted to memo fields. Note: the file Blob.ch must be #included for BlobGet() to work.

Info See also: Category: Header: Source: LIB: DLL:

Function Reference

BlobDirectGet(), FieldGet() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

427

BlobImport()

BlobImport() Imports a file into a memo field.

Syntax BlobImport( , ) --> lSuccess

Arguments

This is a numeric value specifying the ordinal position of the memo field to receive the contents of the file .

This is a character string containing the name of the file to import BLOB data from. It must be specified with a file extension. If contains no drive and/or directory information, the current directory is used. SET DEFAULT and SET PATH settings are ignored. If does not exist, a runtime error is raised. If the file cannot be opened due to another process having exclusive access to the file, function NetErr() is set to .T. (true).

Return The return value is .T. (true) if data is successfully imported, otherwise .F. (false) is returned.

Description BlobImport() copies the contents of an external file into a memo field holding binary large objects (BLOB). The memo field is identified by its ordinal position, which can be obtained using function FieldPos(). Note: the file Blob.ch must be #included for BlobImport() to work.

Info See also: Category: Header: Source: LIB: DLL:

BlobDirectGet(), BlobDirectExport(), BlobExport(), BlobGet(), BlobRootGet(), FieldPos() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // In this example, an image file is moved into an image // archive database #include "Blob.ch" REQUEST DBFCDX PROCEDURE Main LOCAL nFieldPos LOCAL cFileName := "Sunset.jpg"

428

Function Reference

BlobImport() USE PhotoArchive ALIAS Photos VIA "DBFCDX" APPEND BLANK IF .NOT. NetErr() nFieldPos := FieldPos( "JPEG" ) REPLACE Photos->PhotoName WITH "Sunset in Malibu" REPLACE Photos->FileName WITH cFileName IF BlobImport( nFieldPos, cFileName ) FErase( cFileName ) ENDIF ENDIF USE RETURN

Function Reference

429

BlobRootDelete()

BlobRootDelete() Deleted the root area of a BLOB file.

Syntax BlobRootDelete() --> lSuccess

Return The return value is .T. (true) if the root area is successfully deleted, otherwise .F. (false) is returned.

Description BlobRootDelete() removes the data stored in the root area of a BLOB file. This data is written by BlobRootPut(). Note: the file Blob.ch must be #included for BlobRootDelete() to work.

Info See also: Category: Header: Source: LIB: DLL:

BlobRootGet(), BlobRootPut(), BlobRootLock() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // The example demonstrates the coding pattern that must be used to // remove the root area of a BLOB file. #include "Blob.ch" REQUEST DBFCDX PROCEDURE Main USE PhotoArchive ALIAS Photos VIA "DBFCDX" IF BlobRootLock() BlobRootDelete() BlobRootUnlock() ELSE Alert( "Unable to lock the root area" ) ENDIF USE RETURN

430

Function Reference

BlobRootGet()

BlobRootGet() Retrieves data from the root area of a BLOB file.

Syntax BlobRootGet() --> xBlobData

Return The function returns the data stored in the root area of a BLOB file. The data type of this data can be determined using Valtype().

Description BlobRootGet() is used to read the data stored in the root area of a BLOB file. This data must be previously written with BlobRootPut(). When the BLOB file is open in SHARED mode, function BlobRootLock() must be called to avoid conflicts in concurrent file access. This is the only function that places a lock on the root area of a BLOB file. Note: the file Blob.ch must be #included for BlobRootGet() to work.

Info See also: Category: Header: Source: LIB: DLL:

Function Reference

BlobRootDelete(), BlobRootLock(), BlobRootPut() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

431

BlobRootLock()

BlobRootLock() Places a lock on the root area of a BLOB file.

Syntax BlobRootLock() --> lSuccess

Return The return value is .T. (true) if the root area is successfully locked, otherwise .F. (false) is returned.

Description BlobRootLock() is the only function that can place a lock on the root area of a BLOB file. A lock is required to avoid concurrency conflicts when a BLOB file is open in SHARED mode. It must be released later with BlobRootUnlock(). Note: the file Blob.ch must be #included for BlobRootLock() to work.

Info See also: Category: Header: Source: LIB: DLL:

BlobRootGet(), BlobRootPut(), BlobRootUnlock() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // The example demonstrates the coding pattern that must be used to // read the root area of a shared BLOB file. #include "Blob.ch" REQUEST DBFCDX PROCEDURE Main LOCAL xBlobRoot USE PhotoArchive ALIAS Photos VIA "DBFCDX" SHARED IF BlobRootLock() xBlobRoot := BlobRootGet() BlobRootUnlock() ? Valtype( xBlobRoot ) ELSE Alert( "Unable to lock the root area" ) ENDIF USE RETURN

432

Function Reference

BlobRootPut()

BlobRootPut() Stores data in the root area of a BLOB file.

Syntax BlobRootPut( ) --> lSuccess

Arguments

This is the value to assign to the BLOB. The supported data type of can vary between RDDs maintaining BLOB files.

Return The return value is .T. (true) if the data is successfully written to the root area of a BLOB file, otherwise .F. (false) is returned.

Description BlobRootPut() is used to store data in the root area of a BLOB file. The root area is a unique storage place within a BLOB file that is only accessible with the functions BlobRootGet() and BlobRootPut(). When the BLOB file is open in SHARED mode, function BlobRootLock() must be called to avoid conflicts in concurrent file access. This is the only function that places a lock on the root area of a BLOB file. Note: the file Blob.ch must be #included for BlobRootPut() to work.

Info See also: Category: Header: Source: LIB: DLL:

BlobRootDelete(), BlobRootGet(), BlobRootLock() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

Example // This example creates a stand alone DBV file and stores the BLOB IDs // in the root area of the BLOB file. #include "Blob.ch" REQUEST DBFBLOB PROCEDURE Main LOCAL aFile LOCAL aFiles := Directory( "*.jpg" ) LOCAL aBlobID := {} DbCreate( "ImageArchive", {}, "DBFBLOB" ) USE ImageArchive NEW VIA "DBFBLOB"

Function Reference

433

BlobRootPut() FOR EACH aFile IN aFiles AAdd( aBlobID, BlobDirectImport( 0, aFile[1] ) ) NEXT IF BlobRootLock() .AND. BlobRootPut( aBlobID ) BlobRootUnlock() ELSE Alert( "Unable to lock BLOB root;try again later" ) ENDIF USE RETURN

434

Function Reference

BlobRootUnlock()

BlobRootUnlock() Releases the lock on the root area of a BLOB file.

Syntax BlobRootUnlock() --> NIL

Return The return value is always NIL.

Description BlobRootUnlock() releases the a lock previously set with function BlobRootLock(). A lock is required when a BLOB file is open in SHARED mode and the root area of a BLOB file is accessed. Note: the file Blob.ch must be #included for BlobRootUnlock() to work.

Info See also: Category: Header: Source: LIB: DLL:

Function Reference

BlobRootGet(), BlobRootLock(), BlobRootPut() Blob functions, Database functions blob.ch rdd\dbcmd.c, rdd\dbffpt\dbffpt1.c xhb.lib xhbdll.dll

435

BoF()

BoF() Determines if the record pointer reached the begin-of-file boundary.

Syntax BoF() --> lBeginOfFile

Return The function returns .T. (true) when an attempt is made to move the record pointer in a work area backwards beyond the first logical record, or when the database in a work area has no records. In all other situations, Bof() returns .F. (false).

Description The database function Bof() is required t o determine if the record pointer has reached the begin-of-file during a backwards oriented database navigation. This can only be achieved with passing a negative value to SKIP or DbSkip(). Once the begin-of-file is reached, the record pointer remains at the first logical record and Bof() returns .T. (true). Bof() continues to return .T. (true) until the record pointer is moved forwards again. BoF() operates on logical records unless no index is open in the work area and no filter or scope is set. With no filter, index or scope, Bof() returns .T. (true) when attempting to move the record pointer to a record number < 1. The function operates in the current work area. To query the begin-of-file in a different work area, use an aliased expression.

Info See also: Category: Source: LIB: DLL:

DbGoto(), DbSkip(), Eof(), GO, INDEX, SET DELETED, SET FILTER, SET SCOPE, SKIP Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example illustrates the Bof() state of a work area during // physical and logical record pointer movement. #include "Ord.ch" PROCEDURE Main LOCAL nCount := 0 USE Customer INDEX ON Upper(LastName+FirstName) TO Cust01 ? BoF(), LastName

// result: .F. Alberts

// physical movement of record pointer GOTO 10 ? BoF(), nCount, Recno() // result: .F.

0

10

// logical movement of record pointer

436

Function Reference

BoF() DO WHILE .NOT. BoF() SKIP -1 nCount ++ ENDDO // Note: from record #10 we skipped 5 records back // to hit begin-of-file, and ended up at record #20 // That's because the database is indexed. ? BoF(), nCount, Recno() // result: .T. 5 ? BoF(), LastName SKIP 0 ? BoF(), LastName

20

// result: .T. Alberts // result: .T. Alberts

SKIP 1 ? BoF(), LastName

// result: .F. Becker

SET SCOPETOP TO "G"

// restrict logical navigation

GO TOP ? BoF(), LastName

// result: .F. Grastner

SKIP -1 ? BoF(), LastName

// BoF reached due to scope // result: .T. Grastner

CLOSE Customer RETURN

Function Reference

437

Break()

Break() Exits from a BEGIN SEQUENCE block.

Syntax Break( ) --> NIL

Arguments

This is an arbitrary expression whose value is passed to the RECOVER USING statement of the last BEGIN SEQUENCE .. ENDSEQUENCE block. Use the value NIL for to pass no expression value.

Return The return value is always NIL.

Description The Break() function branches program flow to the RECOVER statement of the last BEGIN SEQUENCE block and passes the value of to the variable defined with the USING option, if defined. If BEGIN SEQUENCE is used with no RECOVER statement, program flow continues with the next executable statement following ENDSEQUENCE. Break() is mainly used in conjunction with error handling, when a user defined code block replaces the standard ErrorBlock().

Info See also: Category: Source: LIB: DLL:

BEGIN SEQUENCE, ErrorBlock(), ErrorNew(), Throw(), TRY...CATCH Error functions vm\break.c xhb.lib xhbdll.dll

Example // // // // // //

The example shows a typical usage scenario for the Break() function. It is called from within a user defined error code block. The error code block receives an error object created by the xHarbour runtime system. The error object is passed to Break() and ends up in the RECOVER USING variable. The error condition can then be inspected. PROCEDURE Main OpenDatabase() ? "Files are open" ? "Program can start" RETURN

PROCEDURE OpenDatabase LOCAL oError LOCAL bError := ErrorBlock( {|e| Break(e) } )

438

Function Reference

Break() BEGIN SEQUENCE USE Customer NEW SHARED USE Invoice NEW SHARED ErrorBlock( bError ) RECOVER USING oError ErrorBlock( bError ) ? "Unrecoverable error:" ? oError:description ? oError:operation ? oError:subsystem QUIT ENDSEQUENCE RETURN

Function Reference

439

Browse()

Browse() Browse a database file

Syntax Browse( [] , [] , [], []

; ; ; ) --> lOk

Arguments and

Numeric values indicating the screen coordinates for the upper left corner of the Browse() window. The default value for is 1 and for is zero.

Numeric value indicating the bottom row screen coordinate. It defaults to MaxRow().

Numeric value indicating the right column screen coordinate. It defaults to MaxCol().

Return The return value is .F. (false) if there is no database open in the work area, otherwise .T. (true) is returned.

Description The Browse() function displays a simple database browser in a console window. Data is taken from the database open in the current work area, unless Browse() is used in an aliased expression. The function provides for basic database navigation and editing using the following keys:

Table navigation with Browse()

440

Key

Description

Up Down PgUp PgDn Left Right Home End

Move up one row (previous record) Move down one row (next record) Move to the previous screen Move to the next screen Move one column to the left (previous field) Move one column to the right (next field) Move to the leftmost visible column Move to the rightmost visible column

Ctrl+Home Ctrl+End Ctrl+Left Ctrl+Right Ctrl+PgUp Ctrl+PgDn

Move to the leftmost column Move to the rightmost column Pan one column to the left Pan one column to the right Move to the top of the file Move to the end of the file Function Reference

Browse() Enter Del Esc

Edit current cell Toggles the deleted flag of current record. Terminate Browse()

A status line is displayed on top of the Browse() window presenting the user the following information:

Browse() status information Display

Description

Record ###/###

Current record number / Total number of records. There are no records, the database is empty. A new record is about to be added. Current record is deleted. Top-of-file is reached.

A new record is automatically added when the user browses past the end of the database and edits a field on the new record.

Info See also: Category: Source: LIB: DLL:

DbEdit(), TBrowse(), TBrowseDB() Database functions, UI functions rtl\browse.prg xhb.lib xhbdll.dll

Example // The example shows how to browse an indexed database. PROCEDURE Main USE Customer INDEX ON Upper(Lastname+Firstname) TO Cust01 Browse() CLOSE Customer RETURN

Function Reference

441

CDoW()

CDoW() Returns the name of a week day from a date.

Syntax CDoW( ) --> cDayName

Arguments

This is an expression returning a value of data type Date.

Return The function returns a character string holding the weekday name of . When is an empty date, the function returns a null string ("").

Description The CDoW() function converts a date value into the name of the corresponding week day. Use CMonth() to obtain the month name as character value. Both functions are used to format date values in a textual way. Note: xHarbour's national language support allows for returning the name of a weekday in various languages. Refer to HB_LangSelect() for selecting a language module.

Info See also: Category: Source: LIB: DLL:

CMonth(), CtoD(), Date(), Day(), DoW(), HB_LangSelect(), Month(), Year() Conversion functions, Date and time rtl\datec.c xhb.lib xhbdll.dll

Example // The example demonstrates the conversion of a date value into text. PROCEDURE Main LOCAL dDate := Date() LOCAL cText := "Today is " cText cText cText cText

+= += += +=

CDoW( dDate ) + ", " LTrim( Str( Day( dDate ) ) ) + ". " CMonth( dDate ) + " " LTrim( Str( Year( dDate ) ) )

? cText // result: Today is Tuesday, 24. January 2006 RETURN

442

Function Reference

Chr()

Chr() Converts a numeric ASCII code to a character.

Syntax Chr( )

--> cCharacter

Arguments

This is an expression yielding a numeric value in the range of 0 to 255.

Return The function returns a single character that has the numeric ASCII code .

Description The function converts a numeric value to a character of the corresponding ASCII code. ASCII codes are integer values in the range of 0 to 255. When a value outside this range is passed, it is corrected according to the following rules: 1)

If the value is larger than 255, the ASCII code is calculated as modulus 256.

2)

If is negative, the ASCII code is calculated as 256 + modulus 256.

The Chr() function is used to compose character strings consisting of non-printable characters. Such strings can contain control characters for a device, like printer or keyboard, for example.

Info See also: Category: Source: LIB: DLL:

Asc(), Inkey(), KEYBOARD Numeric functions, Conversion functions rtl\chrasc.c xhb.lib xhbdll.dll

Example // The example converts various numeric values to characters // and creates a text string including non-printable characters PROCEDURE Main LOCAL cText ? Chr(65) ? Chr(322)

// result: A // result: B

? Asc( Chr(322) ) ? 322 % 256

// result: 66 // result: 66

n := -142 ? Chr( n )

// result: r

? Asc( Chr(n) ) ? 256+n % 256

// result: 114 // result: 114

Function Reference

443

Chr() cText := "This is a" cText += Chr(13) + Chr(10) cText += "two line text" ? cText RETURN

444

Function Reference

CMonth()

CMonth() Returns the name of a month from a date.

Syntax CMonth( )

--> cMonthName

Arguments

This is an expression returning a value of data type Date.

Return The function returns a character string holding the month name of . When is an empty date, the function returns a null string ("").

Description The CMonth() function converts a date value into the name of the corresponding month. Use CDoW() to obtain the weekday name as character value. Both functions are used to format date values in a textual way. Note: xHarbour's national language support allows for returning the name of a month in various languages. Refer to HB_LangSelect() for selecting a language module.

Info See also: Category: Source: LIB: DLL:

CDoW(), Date(), Day(), DoW(), DtoC(), HB_LangSelect(), Month(), StoD(), Year() Conversion functions, Date and time rtl\datec.c xhb.lib xhbdll.dll

Example // The example uses a user defined function to fill an array // with all month names abbreviated to the first three letters. PROCEDURE Main LOCAL aMonths := MonthNames(3) // display all month names AEval( aMonths, {|c| QOut(c) } ) RETURN FUNCTION MonthNames( nLen ) LOCAL aArray[12] LOCAL i, cDate, cMonth FOR i:=1 TO 12 cDate := "2000" + PadL( i, 2, "0" ) + "01" cMonth:= CMonth( StoD( cDate ) ) IF Valtype( nLen ) == "N" aArray[i] := Left( cMonth, nLen )

Function Reference

445

CMonth() ELSE aArray[i] := cMonth ENDIF NEXT RETURN aArray

446

Function Reference

Col()

Col() Returns the current column position of the screen cursor

Syntax Col() --> nColPos

Return The function returns a numeric value indicating the current column position of the screen cursor. The leftmost column has position 0 and the rightmost position is identified by MaxCol().

Description The function returns the current cursor column position within a console window (text-mode). The cursor position changes with screen output using console output commands and functions. Use function SetPos() to position the screen cursor at a defined row and column coordinate.

Info See also: Category: Source: LIB: DLL:

@...CLEAR, @...GET, @...SAY, CLEAR SCREEN, MaxCol(), MaxRow(), PCol(), PRow(), Row(), SetMode(), SetPos() Screen functions rtl\setpos.c xhb.lib xhbdll.dll

Example // The examples displays and changes the screen cursor position. PROCEDURE Main ? Col()

// result: 0

? "xHarbour" ? Col() RETURN

Function Reference

// result: 8

447

ColorSelect()

ColorSelect() Selects a color from the current SetColor() string.

Syntax ColorSelect( ) --> NIL

Arguments

A numeric value identifying the ordinal position of a color value in the SetColor() string. is zero based, i.e. the first color value has the ordinal position 0.

Return The return value is always NIL.

Description The function ColorSelect() selects a color value from the current SetColor() string for standard console output. ColorSelect() does not change the SetColor() string. Constants from the COLOR.CH file can be used to address a specific color value:

#defined constants for ColorSelect() Constant

Value

Description

CLR_STANDARD CLR_ENHANCED CLR_BORDER CLR_BACKGROUND CLR_UNSELECTED

0 1 2 3 4

All screen output commands and functions GETs and selection highlights Screen border (not supported on EGA and VGA monitors) Not supported Unselected GETs

If the SetColor() string contains more than five color values, other colors can be selected by passing a value > 4 to the function.

Info See also: Category: Header: Source: LIB: DLL:

SET COLOR, SetBlink(), SetColor() Screen functions color.ch rtl\setcolor.c xhb.lib xhbdll.dll

Example // The example demonstrates changing of colors for the ? command. #include "Color.ch" PROCEDURE Main LOCAL cColor := SetColor( "N/W,W+/N,W+/W,W+/B,GR+/B" ) ? "SetColor():", SetColor()

448

Function Reference

ColorSelect() ? ? "ColorSelect( CLR_STANDARD )" ColorSelect( CLR_ENHANCED ) ? "ColorSelect( CLR_ENHANCED )" ColorSelect( CLR_BORDER ) ? "ColorSelect( CLR_BORDER )" ColorSelect( 3 ) ? "ColorSelect( CLR_BACKGROUND )" ColorSelect( 4 ) ? "ColorSelect( CLR_UNSELECTED )" ColorSelect( 0 ) ? "Back to standard color" RETURN

Function Reference

449

ConvToAnsiCP()

ConvToAnsiCP() Converts an OEM string to the ANSI character set.

Syntax ConvToAnsiCP( ) --> cANSI_String

Arguments

This is a character string encoded with the OEM character set.

Return The function returns converted to the ANSI character set.

Description The function ConvToAnsiCP() is a synonym for HB_OemToAnsi(). Refer to function HB_OemToAnsi() .

Info See also: Category: Source: LIB: DLL:

450

HB_OemToAnsi() Conversion functions rtl\oemansi.c xhb.lib xhbdll.dll

Function Reference

ConvToOemCP()

ConvToOemCP() Converts an ANSI string to the OEM character set.

Syntax ConvToOemCP( ) --> cOEM_String

Arguments

This is a character string encoded with the ANSI character set.

Return The function returns converted to the OEM character set.

Description The function ConvToOemCP() is a synonym for HB_AnsiToOem(). Refer to function HB_AnsiToOem().

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_AnsiToOem() Conversion functions rtl\oemansi.c xhb.lib xhbdll.dll

451

CStr()

CStr() Converts a value to a character string.

Syntax CStr( ) --> cString

Arguments

This is a value of any data type.

Return The function returns a character string holding the converted value.

Description Function CStr() accepts a value of any data type and returns a character string holding in formation about the value. This character string can be output to the screen or printer, and is of informational use only when is a complex data type (Array, Code block, Hash or Object).

Info See also: Category: Source: LIB: DLL:

DtoS(), Str(), Transform(), Valtype(), ValToPrg(), ValToPrgExp() Conversion functions, Debug functions, xHarbour extensions rtl\cstr.prg xhb.lib xhbdll.dll

Example // The example demonstrates return values of function CStr() // for all data types available in xHarbour. PROCEDURE Main LOCAL aArray LOCAL bBlock LOCAL cString LOCAL dDate LOCAL hHash LOCAL lLogic LOCAL nNumber LOCAL obj LOCAL pPointer LOCAL undef ? ? ? ? ? ? ? ? ?

452

CStr( CStr( CStr( CStr( CStr( CStr( CStr( CStr( CStr(

:= := := := := := := := := :=

aArray bBlock cString dDate hHash lLogic nNumber obj pPointer

{ 1, 2, 3 } {|| Time() } "xHarbour" Date() { "A" => 1, "B" => 2 } .T. 1.2345 Get():new() ( @Main() ) NIL

) ) ) ) ) ) ) ) )

// // // // // // // // //

result: result: result: result: result: result: result: result: result:

{ Array of 3 Items } {|| Block } xHarbour 20061006 { Hash of 2 Items } .T. 1.2345 { GET Object } 4CB000

Function Reference

CStr() ? CStr( undef RETURN

Function Reference

)

// result: NIL

453

CtoD()

CtoD() Converts a character string into a Date value

Syntax CtoD( ) --> dDate

Arguments

This is a character string formatted as a date. Digits for day, month and year plus the separator sign must comply with the current SET DATE format. If the year is not given as a four digit number, the rules for SET EPOCH apply for the date conversion.

Return The function returns the converted Date value. If is not a valid date string, an empty date is returned.

Description The conversion function CtoD() is used to create date values from string literals formatted as a Date. Formatting of the string literal must comply with the current SET DATE format. That is, digits for day, month and year in are interpreted according to the sequence of the letters dd, mm and yy in the SET DATE format string. The conversion rules of SET EPOCH apply for the year when it is not specified with four digits. Use function StoD() to convert a string to a date value independently of SET DATE.

Info See also: Category: Source: LIB: DLL:

Date(), DtoC(), DtoS(), SET CENTURY, SET DATE, SET EPOCH, StoD() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example outlines the importance of the SET DATE format // for the conversion of string literals to Date values. PROCEDURE Main SET DATE ITALIAN

// select Italian date format

? CMonth( CtoD( "05-01-06" ) )

// result: January

SET DATE AMERICAN

// select US date format

? CMonth( CtoD( "05/01/06" ) )

// result: May

RETURN

454

Function Reference

CurDir()

CurDir() Returns the current directory of a drive

Syntax CurDir( [] ) --> cDirPath

Arguments

A single character, optionally followed by a colon, specifies the disk drive to query. If omitted, the current drive is queried.

Return The function returns the current directory of the specified disk drive as a character string without leading and trailing directory separator.

Description The function is used to determine the current directory of a disk drive. If the drive does not exist or the root directory is current, CurDir() returns a null string (""). Note that CurDir() reports the current directory of the operating system for a specified drive. It does not report directories set with SET DEFAULT or SET PATH. Use function DirChange() to change the current directory.

Info See also: Category: Source: LIB: DLL:

CurDrive(), DirChange(), Directory(), DirRemove(), File(), Getenv(), MakeDir() Directory functions, File functions rtl\philes.c xhb.lib xhbdll.dll

Example // The example lists the current directories for drive C: to I: PROCEDURE Main LOCAL nDrive := Asc( "C" ) LOCAL i FOR i:=1 TO 7 ? Chr(nDrive) + ":\"+ CurDir( Chr(nDrive) ) nDrive ++ NEXT RETURN

Function Reference

455

CurDrive()

CurDrive() Determines or changes the current disk drive

Syntax CurDrive( [] ) --> cOldDrive

Arguments

A single character, optionally followed by a colon, specifies the disk drive to select as current. If omitted, the disk drive is not changed.

Return The function returns the a single letter specifying the disk drive that is current before the function is called (the previous disk drive).

Description CurDrive() queries the current disk drive and optionally changes to a new one. The new disk drive to change to is specified with . Use function IsDisk() to check for the existence of a disk drive.

Info See also: Category: Source: LIB: DLL:

CurDir(), DiskChange(), DiskName(), DiskSpace(), Getenv(), IsDisk(), SET DEFAULT, SET PATH File functions rtl\philesx.c xhb.lib xhbdll.dll

Example // The example queries and changes the current disk drive // and displays the current directory for each drive. PROCEDURE Main ? CurDrive( "C:" ) ? CurDrive()

// result: D // result: C

? CurDir() ? CurDrive( "D" )

// result: temp // result: C

? CurDir() ? CurDrive()

// result: xhb\source\samples // result: D

? CurDir()

// result: xhb\source\samples

RETURN

456

Function Reference

Date()

Date() Returns the current date from the operating system.

Syntax Date() --> dDate

Return The function returns the operating system's date setting.

Description The Date() function retrieves the current system date as reported by the system clock. The returned value is of Valtype() == "D". The display of Date values depends on the SET DATE format.

Info See also: Category: Source: LIB: DLL:

CtoD(), DtoC(), DtoS(), SET CENTURY, SET DATE, SET EPOCH, StoD(), Time() Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example extracts various information from the current date PROCEDURE Main ? CDoW( ?? ",", ?? ".", ?? "" ,

Date() ) LTrim( Str( Day( Date() ) ) ) CMonth( Date() ) LTrim( Str( Year( Date() ) ) )

// result: Wednesday, 25. January 2006 ? Date() + 7 RETURN

Function Reference

// result: 02/01/06

457

Day()

Day() Extracts the numeric day number from a Date value.

Syntax Day( ) --> nDay

Arguments

This is an expression returning a value of data type Date.

Return The function returns the numeric day number of . When is an empty date, the function returns zero.

Description This function is used to extract the numeric day of a month from a Date value.

Info See also: Category: Source: LIB: DLL:

CDow(), CMonth(), CtoD(), Date(), Days(), DoW(), DtoC(), DtoS(), Month(), Str(), Year() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example shows results of the function Day() PROCEDURE Main ? Date() ? Day( Date()) ? Day( Date() + 7 )

// result: 01/25/06 // result: 25 // result: 1

RETURN

458

Function Reference

Days()

Days() Calculates the number of days from elapsed seconds.

Syntax Days( ) --> nDays

Arguments

A numeric value indicating the number of seconds to convert to days.

Return The function returns the converted value as an integer number of days.

Description This function converts a number of seconds to their equivalent number of days as integer value. One day has 86400 seconds.

Info See also: Category: Source: LIB: DLL:

Date(), ElapTime(), Seconds(), Secs(), Time() Date and time rtl\samples.c xhb.lib xhbdll.dll

Example // The example shows the conversion of seconds representing time spans // of Minute, Hour, Day and Year into equivalent number of days. PROCEDURE Main ? ? ? ?

Days( Days( Days( Days(

60 ) 3600 ) 86400 ) 31536000 )

// // // //

result: result: result: result:

0 0 1 365

RETURN

Function Reference

459

DbAppend()

DbAppend() Appends a new record to a database open in a work area.

Syntax DbAppend( [] ) --> NIL

Arguments

This parameter defaults to .T. (true). It causes all pending record locks set with RLock() or DbRLock() be released before a new record is appended to the database. Pass .F. (false) to keep all record locks intact.

Return The return value is always NIL.

Description The DbAppend() function adds a new record to the end of the database i n the current work area. Use an aliased expression to append a record in a different work area. All fields of the new record are filled with empty data of their respective data types. That is, Character fields are filled with blank spaces, Date fields contain empty dates, logical fields contain .F. (false) and numeric fields zero. Memo fields contain a null string (""). The DbAppend() function is guaranteed to add a new record when the database file is open for EXCLUSIVE access by the application. This, however, is rarely the case. In a multi-user environment, databases are usually open for SHARED access. As a result, DbAppend() tries to lock the new record so that no other user can change it during the operation. If this lock fails, there is no new record available for the application. Instead, the function NetErr() is set to .T. (true) indicating a failure of locking the new record. A failure of this kind can happen, for example, when another application has obtained a file lock prior to DbAppend(). Such an error condition is gracefully handled if NetErr() is checked after DbAppend(). If DbAppend() has successfully locked the new record, all other records locks set in the database are released by default. To keep pending record locks in place, the value .F. (false) must be passed to DbAppend().

Info See also: Category: Source: LIB: DLL:

APPEND BLANK, DbRLock(), DbUnlock(), DbUnlockAll(), RLock() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows a typical coding pattern for appending a new // record to a database open in SHARED mode PROCEDURE Main USE Customer SHARED ALIAS Cust SET INDEX TO Cust01, Cust02

460

Function Reference

DbAppend() Cust->( DbAppend() ) IF NetErr() ? "Unabled to append new record" ELSE ? "Fill data to new record" REPLACE Cust->Firstame WITH "Paul" REPLACE Cust->Lastname WITH "Newman" DbCommit() DbUnlock() ENDIF WAIT Browse() CLOSE Customer RETURN

Function Reference

461

DbClearFilter()

DbClearFilter() Clears the current filter condition in a work area.

Syntax DbClearFilter() --> NIL

Return The return value is always NIL.

Description The function clears an active filter condition in the current work area. As a result, all records previously filtered become visible again in database navigation. Use an aliased expression to clear a filter in a different work area.

Info See also: Category: Source: LIB: DLL:

DbFilter(), DbSetFilter(), SET DELETED, SET FILTER, SET SCOPE Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates visibility of filtered records PROCEDURE Main USE Customer ALIAS Cust SHARED INDEX ON Upper(Lastname+Firstname) TO Cust01 GO TOP ? Cust->Lastname

// result: Alberts

SET FILTER TO Cust->Lastname > "E" GO TOP ? Cust->Lastname

// result: Feldman

Cust->(DbClearFilter()) GO TOP ? Cust->Lastname

// result: Alberts

CLOSE Cust RETURN

462

Function Reference

DbClearIndex()

DbClearIndex() Closes all indexes open in the current work area.

Syntax DbClearIndex() --> NIL

Return The return value is always NIL.

Description The function DbClearIndex() closes all indexes open in the current work area. When the operation is complete, all pending index updates are written to disk and the records become accessible in physical order again. Use an aliased expression to close indexes in a different work area. Note: This function is superseded by the OrdListClear() function.

Info See also: Category: Source: LIB: DLL:

DbCreateIndex(), DbReindex(), DbSetIndex(), DbSetOrder(), OrdListClear(), SET INDEX Database functions, Index functions rdd\rddord.prg xhb.lib xhbdll.dll

Example // refer to the example for OrdListClear()

Function Reference

463

DbClearRelation()

DbClearRelation() Clears all active relations in a work area.

Syntax DbClearRelation() --> NIL

Return The return value is always NIL.

Description DbClearRelation() clears all active relations in the current work area. Database navigation is then no longer synchronized with child work areas. The function has the same effect as specifying SET RELATION TO with no further argument. Refer to the SET RELATION command for more information. Use an aliased expression to clear relations in a different work area.

Info See also: Category: Source: LIB: DLL:

464

DbRelation(), DbSetRelation(), OrdSetRelation(), SET RELATION Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

DbCloseAll()

DbCloseAll() Close all open files in all work areas.

Syntax DbCloseAll() --> NIL

Return The return value is always NIL.

Description The function closes all open databases and all associated files like index or memo files. In addition, all format files are closed and work area #1 is selected as the current work area.

Info See also: Category: Source: LIB: DLL:

CLOSE, DbCloseArea(), DbUseArea(), SELECT, Select(), USE, Used() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates closing of all databases with one // function call. PROCEDURE Main() USE Test NEW ? Select()

// result: 1

USE Test1 NEW ? Select()

// result: 2

? (1)->(Used()) ? (2)->(Used())

// result: .T. // result: .T.

DbCloseAll() ? Select() ? (1)->(Used()) ? (2)->(Used()) RETURN

Function Reference

// result: 1 // result: .F. // result: .F.

465

DbCloseArea()

DbCloseArea() Closes a database file in a work area.

Syntax DbCloseArea() --> NIL

Return The return value is always NIL.

Description The DbCloseArea() function closes the database open in the current work area and all associated files, like index or memo files. Use an aliased expression to close a database in a different work area. Closing a database causes all pending file buffers being flushed to disk before files are closed. Also, all file and record locks are released when files are closed.

Info See also: Category: Source: LIB: DLL:

CLOSE, DbCloseAll(), DbCommit(), DbUseArea(), USE Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example PROCEDURE Main() USE Customer ALIAS Cust ? (1)->(Used())

// result: .T.

DbEdit() Cust->(DbCloseArea()) ? (1)->(Used()) RETURN

466

// result: .F.

Function Reference

DbCommit()

DbCommit() Writes database and index buffers to disk.

Syntax DbCommit() --> NIL

Return The return value is always NIL.

Description The DbCommit() function writes all database and index buffers held in memory to disk. The function operates in the current work area, unless it is used in an aliased expression. Memory buffers serve as cache for field variables and index values so that assignments to field variables become immediately visible to an application without any file I/O. When a database is open in SHARED mode, however, such changes are not visible to other applications in a multi-user environment until the changes are commited to disk.

Info See also: Category: Source: LIB: DLL:

CLOSE, COMMIT, DbCloseAll(), DbCommitAll(), DbRUnlock(), DbUnlock(), RLock() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows a typical coding pattern for updating records // in a multi-user environment. PROCEDURE Main() LOCAL cLastName, cFirstName USE Customer ALIAS Cust SHARED NEW SET INDEX TO Cust01, Cust02 cFirstname := Cust->Firstname cLastname := Cust->Lastname @ 10, 10 SAY "First name" GET cFirstname @ 11, 10 SAY " Last name" GET cLastname READ IF Updated() .AND. RLock() // obtain record lock REPLACE Cust->Firstname WITH cFirstname REPLACE Cust->Lastname WITH cLastname DbCommit() // flush memory buffers DbUnlock() // release record lock ENDIF CLOSE Cust RETURN NIL

Function Reference

467

DbCommitAll()

DbCommitAll() Writes database and index buffers of all used work areas to disk.

Syntax DbCommitAll() --> NIL

Return The return value is always NIL.

Description The DbCommitAll() function writes buffers of all work areas to disk. It performs the same operations as DbCommit(), except that all work areas with open databases are iterated in one function call.

Info See also: Category: Source: LIB: DLL:

CLOSE, COMMIT, DbCloseAll(), DbCommit(), DbRUnlock(), DbUnlock(), RLock() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // refer to function DbCommit()

468

Function Reference

DbCopyExtStruct()

DbCopyExtStruct() Creates a structure extended database file.

Syntax DbCopyExtStruct( ) --> lSuccess

Arguments TO

This is name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory. The default file extension is DBF.

Return The function returns .T. (true) when the structure extended file is sucessfully created, or .F. (false) when no database is open in a work area.

Description Function DbCopyExtStruct() creates a new structure extended database file. It is the functional equivalent of command COPY STRUCTURE EXTENDED. Refer to this command for more information on structure extended database files.

Info See also: Category: Source: LIB: DLL:

COPY STRUCTURE, COPY STRUCTURE EXTENDED, CREATE, CREATE FROM, DbCopyStruct(), DbCreate(), DbStruct() Database functions, xHarbour extensions rdd\dbstrux.prg xhb.lib xhbdll.dll

Example // The example creates a structure extended database file // and displays its contents. PROCEDURE Main USE Customer DbCopyExtStruct( "Test.dbf" ) USE Test Browse() USE RETURN

Function Reference

469

DbCopyStruct()

DbCopyStruct() Creates a new database based on the current database structure.

Syntax DbCopyStruct( , [] ) --> NIL

Arguments

This is a character expression holding the name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory.

Optionally, a one dimensional array can be specified which contains the field names of the current work area to include in the new database. If is omitted, all fields are included.

Return The return value is always NIL.

Description Function DbCopyStruct() create a new, empty database file with a structure that is based on the database currently open in a work area. If is empty, the new file has the same structure as the open database. Otherwise, the new file contains only the fields listed in . DbCopyStruct() can be used to create a subset of the currently open database, based on a given field list.

Info See also: Category: Source: LIB: DLL:

COPY STRUCTURE, COPY STRUCTURE EXTENDED, DbCopyExtStruct(), DbCreate(), DbStruct() Database functions, xHarbour extensions rdd\dbstrux.prg xhb.lib xhbdll.dll

Example // The example creates a new database holding only two fields of // the Customer database. PROCEDURE Main USE Customer DbCopyStruct( "Test.dbf", { "Firstname", "Lastname" } ) USE Test APPEND FROM Customer Browse()

470

Function Reference

DbCopyStruct() USE RETURN

Function Reference

471

DbCreate()

DbCreate() Creates an empty database from a structure definition array.

Syntax DbCreate( , , [] , [] , []

; ; ; ; ) --> NIL

Arguments

This is a character expression holding the name of the database file to create. It can include path and file extension. When no path is given, the file is created in the current directory.

A variable holding the reference of a two-dimensional array that has at least four columns. The first column must contain character strings holding the field names, the second column specifies the field type using single letters of C, D, L, N, M, the third column holds numeric values with the length of the fields, and the fourth column is only relevant for numeric fields. It specifies the number of decimal places that can be stored in a numeric field. The following #define constants exist in file DBSTRUCT.CH to address each column of .

#define constants for the structure definition array Constant

Value

Meaning

DBS_NAME DBS_TYPE DBS_LEN DBS_DEC

1 2 3 4

Field name Field type Field length Field decimals

Note: only the first four columns of are used. If the array has more columns, they are ignored.

The replaceable database driver to use for creating the new database file can be specified as a character string. It defaults to the return value of RddSetDefault().

This optional parameter instructs the RDD if and how to open the database after creation. Three values are possible:

Open modes for new database files

472

Value

Description

NIL (*) .F.

the database is not opened. the database is opened in the current work area. Function Reference

DbCreate() .T. (*) default

the database is opened in a new, unused work area.



A character expression specifying the symbolic alias name to assign to the work area where is opened can be optionally passed. If not given, is build from the file name of without extension.

Return The return value is always NIL.

Description This function creates the database file specified as from the two-dimensional array . If no file extension is included with the .DBF extension is assumed. The array specified with must contan at least four columns as outlined above. The DbCreate( ) function does not use the decimal field to calculate the length of a character field that can store than 256 characters. Values of up to the maximum length of a character field, which is 65,519 bytes, can be assigned directly to the DBS_LEN column of . The parameter specifies the name of the Replaceable Database Driver to use for database creation. If not specified, the return value of RddSetDefault() is used. The parameter specifies if the already created database is to be opened, and where. If NIL, the file is not opened. If .T. (true), it is opened in a new work area, and if .F. (false) it is opened in the current work area, closing any file already occupying that area. The parameter specifies the alias name for the newly opened database.

Info See also: Category: Header: Source: LIB: DLL:

AFields(), COPY STRUCTURE EXTENDED, CREATE, CREATE FROM, DbStruct() Database functions Dbstruct.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows how to create a new database from a // structure definition array using the DBFCDX driver. REQUEST DBFCDX PROCEDURE Main() LOCAL aStruct := { ; { "CHARACTER", { "NUMERIC" , { "DOUBLE" , { "DATE" , { "LOGICAL" , { "MEMO1" , { "MEMO2" , }

"C", "N", "N", "D", "L", "M", "M",

25, 8, 8, 8, 1, 10, 10,

0 0 2 0 0 0 0

}, }, }, }, }, }, }

; ; ; ; ; ; ;

DbCreate( "testdbf", aStruct, "DBFCDX", .T., "MYALIAS" )

Function Reference

473

DbCreate() Browse() RETURN

474

Function Reference

DbCreateIndex()

DbCreateIndex() Creates a new index and/or index file.

Syntax DbCreateIndex( , , [], [] , []

; ; ; ; ) --> NIL

Arguments

is a character string with the name of the file that stores the new index. When the file extension is omitted, it is determined by the database driver that creates the file.

This is a character expression which describes the index expression in textual form. The expression is evaluated for the records in the current work area. The return value of determines the logical order of records when the index is the controlling index. The data type of the index may be Character, Date, Numeric or Logical. The maximum length of an index expression and its value is determined by the replaceable database driver used to create the index.

It is the same like but is specified as a code block that can be evaluated. If omitted, the code block is created from .

If the optional parameter is set to .T. (true), it suppresses inclusion of records that yield duplicate index values. When an index value exists already in an index, a second record resulting in the same index value is not added to the index. When is omitted, the current SET UNIQUE setting is used as default.

This is a character string holding the symbolic name of the index to create in an index file. It is analogous to the alias name of a work area. Support for depends on the RDD used to create the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

Return The return value is always NIL.

Description The index function DbCreateIndex() creates an index for the database open in the current work area. Use an aliased expression to create an index in a different work area. If the work area has indexes open, they are closed prior to creating the new index. During index creation, the code block is evaluated for each record of the work area and its return Function Reference

475

DbCreateIndex()

value is added to the index. When index creation is complete, the new index becomes the controlling index. As a result, records are viewed in logical index order and no longer in physical order.

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), DbReindex(), DbSetIndex(), DbSetOrder(), INDEX, OrdCreate(), OrdListAdd(), OrdSetFocus() Database functions, Index functions rdd\rddord.prg xhb.lib xhbdll.dll

Example // The example creates an index file Emp01 on the expression // Upper(Lastname+Firstname). Note the two notations for the index // expression. PROCEDURE Main USE Employees NEW EXCLUSIVE DbCreateIndex( "Emp01", ; "Upper(Lastname+Firstname)", ; {|| Upper(Lastname+Firstname) } ; ) ? IndexKey()

// result: Upper(Lastname+Firstname)

Browse() RETURN

476

Function Reference

DbDelete()

DbDelete() Marks records for deletion.

Syntax DbDelete() --> NIL

Return The return value is always NIL.

Description This function marks a record for deletion in the current or aliased work area. If SET DELETED is ON, the record will continue to be visible until the record pointer in the work area is moved. Note that DbDelete() sets a flag on the current record which marks it only as deleted. Call PACK to physically remove records marked as deleted from the database. Once set, the Deleted flag can be removed again using the DbRecall() function. In a networking situation, this function requires the current record be locked prior to calling the DbDelete() function.

Info See also: Category: Source: LIB: DLL:

DbRecall(), DELETE, Deleted(), PACK, RECALL Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows a typical coding pattern used for setting the // deletion flag in a networking situation. PROCEDURE Main LOCAL cCustID := "10" USE Customer ALIAS Cust INDEX CustId NEW IF Cust->(DbSeek( cCustId )) IF Cust->(RLock()) Cust->(DbDelete()) Cust->(DbUnLock()) ENDIF ENDIF USE RETURN

Function Reference

477

DbEdit()

DbEdit() Browse records in a table.

Syntax DbEdit( [] , [] , [] , [] , [] , [] , [] , [] , [ , [ , [ , [ , [ , [

; ; ; ; ; ; ; ; ; ; ; ; ; ) --> NIL

Arguments and

Numeric values indicating the screen coordinates for the upper left corner of the DbEdit() window. Both default to zero.

Numeric value indicating the bottom row screen coordinate. It defaults to MaxRow().

Numeric value indicating the right column screen coordinate. It defaults to MaxCol().

An array whose elements define the data displayed in each browser column. Data definition is very flexible and can be accomplished using different data types stored in each element of .

Data definition for DbEdit() Data type

Description

Character Code block Array

A macro expression whose return value is displayed. A code block whose return value is displayed. A two element array. The first element contains a character string or a code block as decribed above, the second element is a code block compliant with TBColumn():colorBlock.

If is not specified, the browser displays all fields of the current work area in its columns.

A character string holding the symbolic name of a user function, or a code block which calls a user function. The user function is called with three parameters: the current DbEdit() mode 478

Function Reference

DbEdit()

(numeric), the current column position (numeric) and the Tbrowse() object which represents the browser. The DbEdit() behavior depends on the presence or absence of a user function. See the discussion below.

This parameter can be specified as a character string defining a picture formatting string for the entire browser, or an array of Len() elements that hold picture strings for each individual browser column. Refer to @...SAY or Transform() for a description of picture formatting strings. If is not specified, proper data formatting is automatically applied.

This parameter defines the headers displayed for each column. If it is not specified, headers are derived from the contents of . A single character string is used as header for each column, while an array of Len() elements containing character strings defines individual headers for each column. Note that when a semi-colon (;) is contained in a heading string, it is interpreted as line break character, so that column headings consisting of multiple lines can be defined.

is a parallel array of character expressions whose character values are used to draw horizontal lines separating column headings from the data display area. Specifying as a single character expression defines the same heading separator for all columns. By default. a single-line separator is displayed.

This parameter has the same meaning and data types as except that it defines the vertical separating lines between columns. It defaults to a single separating line.

The parameter is used like for the display of a horizontal line separating the footing area of columns from the data area of the browser. If not specified, no footing separator is displayed.

The parameter is used like for the display of column footings. If omitted, no column footings are displayed.

An optional array of Len() elements containing logical values or code blocks can be specified. A code block must return a logical value. is used for prevalidating data entry in the current browser cell. It is compliant with TBColumn:preBlock.

The parameter is used in the same way as , but is used for post-validation and complies with TBColumn:postBlock.

Return DbEdit() returns .T. (true) if data can be displayed, otherwise .F. (false) is returned.

Function Reference

479

DbEdit()

Description The DbEdit() function displays a database browser in a console window navigating the record pointer in the current work area, unless it is called in an aliased expression. Data from a work area is displayed in the browser columns, and can be defined very flexible using the array. If no columns are explicitely defined, the browser displays all fields from the work area. The width of each column is determined at initial display by the number of characters required for displaying headers (), data area () and footings (). When called without a user fundtion, DbEdit() handles the following keys for navigating the browse cursor in the display:

Table navigation with DbEdit() Key

Description

Up Down PgUp PgDn Left Right Home End

Move up one row (previous record) Move down one row (next record) Move to the previous screen Move to the next screen Move one column to the left (previous field) Move one column to the right (next field) Move to the leftmost visible column Move to the rightmost visible column

Ctrl+Home Ctrl+End Ctrl+Left Ctrl+Right Ctrl+PgUp Ctrl+PgDn

Move to the leftmost column Move to the rightmost column Pan one column to the left Pan one column to the right Move to the top of the file Move to the end of the file

Ctrl+Up Ctrl+Down

Move current column to the left Move current column to the right

Enter Esc

Terminate DbEdit() Terminate DbEdit()

Left click *) Go to clicked row and column *) Mouse keys must be activated with SET EVENTMASK

DbEdit() user function If a user function is specified, all keys but Enter and Esc are automatically handled by DbEdit(). After each key stroke, the user function is called with three parameters : 1)

The current DbEdit() mode (see table below).

2)

A numeric value indicating the current column position of the browse cursor.

3)

The TBrowse() object representing the browser.

DbEdit() modes passed to the user function indicate the internal state. They are encoded as numeric values for which #define constants exist in the DBEDIT.CH file.

480

Function Reference

DbEdit()

DbEdit() modes Constant

Mode

Description

DE_INIT DE_IDLE

-1 0

DE_HITTOP DE_HITBOTTOM DE_EMPTY DE_EXCEPT

1 2 3 4

Initial browse display Idle, any cursor movement keystrokes are handled and no keystrokes are pending Attempt to move the record pointer past top of file Attempt to move the record pointer past bottom of file Work area has no records Key exception

The return value of the user function instructs DbEdit() how to proceed with browsing. The following #define constants from DBEDIT.CH can be used as return values:

User-function return values for DbEdit() Constant

Value

Description

DE_ABORT DE_CONT DE_REFRESH

0 1 2

Abort DbEdit(). Continue DbEdit() as is. Force reread/redisplay of all data rows.

Info See also: Category: Header: Source: LIB: DLL:

AChoice(), Browse(), MemoEdit(), TBrowse(), TBrowseDB(), TBColumn(), USE UI functions, Database functions dbedit.ch rtl\dbedit.prg xhb.lib xhbdll.dll

Example // // // //

The example calls DbEdit() with a user function and initializes the TBrowse object inits initial display with custom colors. A color block is defined so that the rows in the browser are displayed with alernating colors. #include "Inkey.ch" #include "Dbedit.ch" #ifndef DE_INIT #define DE_INIT #endif

-1

PROCEDURE Main LOCAL bColor := {|x| IIf( Recno() % 2 == 0, {1,2}, {3,4} ) } Local aCols := { ; { "LASTNAME" , bColor }, ; { "FIRSTNAME", bColor }, ; { "CITY" , bColor }, ; { "ZIP" , bColor } ; } USE Customer NEW DbEdit(,,,, aCols, "UserFunc", ,{ "Lastname","Firstname", "City", "Zip"} )

Function Reference

481

DbEdit() CLOSE ALL RETURN FUNCTION UserFunc( nMode, nCol, oTBrowse ) LOCAL GetList := {} LOCAL nReturn := DE_CONT DO CASE CASE nMode == DE_INIT oTBrowse:colorSpec := "n/bg,w+/r,w+/bg,w+/r,w+/gr" CASE nMode == DE_HITTOP Tone(1000) CASE nMode == DE_HITBOTTOM Tone(500) CASE LastKey() == K_ESC nReturn := DE_ABORT CASE LastKey() == K_ENTER SetCursor(1) @ Row(), Col() Get &(oTBrowse:getColumn(nCol):heading) READ SetCursor(0) CLEAR TYPEAHEAD ENDCASE RETURN nReturn

482

Function Reference

DbEval()

DbEval() Evaluates a code block in a work area.

Syntax DbEval( , [] , [], [] , [] , []

; ; ; ; ; ) --> NIL

Arguments

The parameter is a code block which is executed for every record matching with the conditions specified with the following parameters. If no other parameters are passed, is evaluated for all records.

This is an optional code block which must return a logical value. is evaluated for all records where yields .T. (true). is not executed for records where yields .F. (false). This is equivalent to the FOR condition of database commands.

This is an optional code block which must return a logical value. is evaluated while yields .T. (true). DbEval() returns immediately as soon as yields .F. (false). This is equivalent to the WHILE condition of database commands.

An optional numeric parameter restricting the number of records to process to , beginning with the current record. It is equivalent to the NEXT clause of database commands.

Only a single record is processed when the record number is specified. It is equivalent to the RECORD clause of database commands.

An optional logical value that defaults to .F. (false). In this case, is evaluated for all records. Specifying .T. (true) causes DbEval() to start processing with the current record and continue until the end of file is reached. is equivalent to the ALL (.F.) and REST (.T.) clauses of database commands.

Return The return value is always NIL.

Function Reference

483

DbEval()

Description The DbEval() function iterates the records in a work area and evaluates a code block for all records matching the scope and/or condition defined with parameters #2 to #5. By default, DbEval() navigates the record pointer in the current work area. Use an aliased expression to process records in a different work area.

Info See also: Category: Source: LIB: DLL:

AEval(), Eval(), HEval() Database functions, Code block functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example uses DbEval() to determine the number of deleted records // in a database to calculate the space that could be freed with PACK. PROCEDURE Main LOCAL nCount := 0 USE Customer NEW DbEval( {|| nCount++ }, ; {|| Deleted() } ) ? "File size could be reduced by", 100*nCount/Lastrec(),"percent" CLOSE Customer RETURN

484

Function Reference

Dbf()

Dbf() Retrieves the alias name of the current work area.

Syntax Dbf() -->

Return The function returns the alias name of the current work area as a character string.

Description The Dbf() function exists for compatibility reasons only. It is superseded by the Alias() function.

Info See also: Category: Source: LIB: DLL:

Function Reference

Alias(), Used() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

485

DbFieldInfo()

DbFieldInfo() Retrieves information about a database field

Syntax DbFieldInfo( , ) --> xFieldInfo

Arguments

The parameter is a numeric value specifying the type of information to query about a database field. #define constants listed in the table below must be used for .

A numeric value specifying the ordinal position of the field to query. Valid values are in the range from 1 to FCount().

Return DbFieldInfo() returns the queried information as supplied by the replaceable database driver (RDD).

Description DbFieldInfo() allows for querying detailed field information from the replaceable database driver (RDD). Depending on database and RDD used, different information may be available. The type of information to retrieve is specified with #define constants available in the DBINFO.CH and DBSTRUCT.CH header files.

Constants for DbFieldInfo() Constant

Return value

DBSTRUCT.CH DBS_DEC DBS_LEN DBS_NAME DBS_TYPE

Number of decimal places for the field. Numeric length of the field. Character string holding the name of the field. Character identifying the data type of the field.

DBINFO.CH DBS_BLOB_LEN DBS_BLOB_OFFSET DBS_BLOB_POINTER DBS_BLOB_TYPE

Number of bytes stored in a memo field (BLOB). Numeric file offset into memo file of the data in a memo field. Numeric value for usage with e.g. BlobDirectGet(), BlobDirectImport(). Character indicating the data type of a memo field (BLOB).

By default, DbFieldInfo() operates in the current work area. Use an aliased expression to query field information in different work areas.

486

Function Reference

DbFieldInfo()

Info See also: Category: Header: Source: LIB: DLL:

BlobDirectGet(), BlobDirectImport(), DbInfo(), DbOrderInfo(), DbRecordInfo(), DbStruct(), FieldDec(), FieldLen(), FieldName(), FieldType() Database functions, Field functions Dbinfo.ch, Dbstruct.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example retrieves structural information for a // single database with a user defined function. #include "Dbstruct.ch" PROCEDURE Main USE Customer AEval( FieldStruct( 1 ), {|x| QOut( x ) } ) USE RETURN FUNCTION FieldStruct( nFieldPos ) LOCAL aFStruct[4] aFStruct[DBS_NAME] aFStruct[DBS_TYPE] aFStruct[DBS_LEN ] aFStruct[DBS_DEC ]

:= := := :=

DbFieldInfo( DbFieldInfo( DbFieldInfo( DbFieldInfo(

DBS_NAME, DBS_TYPE, DBS_LEN , DBS_DEC ,

nFieldPos nFieldPos nFieldPos nFieldPos

) ) ) )

RETURN aFStruct

Function Reference

487

DbFileGet()

DbFileGet() Copies data from a field into an external file.

Syntax DbFileGet( , , ) --> lSuccess

Arguments

A numeric value specifying the ordinal position of the field to copy. Valid values are in the range from 1 to FCount().

Character string holding the name of the external file to copy a field's data to. The file name may include drive and directory and must include an extension. The file is created if it does not exist. Otherwise, the function attempts to open the file exclusively. When this fails, NetErr() is set to .T. (true).

The parameter triggers if a new file is created or data is appended to a file. The following constants from DBINFO.CH must be used:

Constants for the append mode Constant

Value

Description

FILEGET_APPEND FILEGET_OVERWRITE

1 0

Appends data to the file. Overwrites file with data.

Return The return value is .T. (true) when the operation is successful, otherwise .F. (false) is returned.

Description The DbFileGet() and DbFilePut() functions are mainly used to transfer data between memo fields holding large amounts of data (BLOB) and external files. Data written to an external file is then programmatically processed.

Info See also: Category: Header: Source: LIB: DLL:

488

BlobDirectExport(), BlobExport(), DbFilePut() Database functions, Field functions Dbinfo.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

DbFilePut()

DbFilePut() Copies the contents of an external file into a field.

Syntax DbFilePut( , [,] ) --> lSuccess

Arguments

A numeric value specifying the ordinal position of the field to copy to. Valid values are in the range from 1 to FCount().

A character string holding the name of the external file to copy into the field. The file name may include drive and directory and must include an extension. If the file does not exist, a runtime error is raised. The function attempts to open the file in shared mode. When this fails, NetErr() is set to .T. (true).

The parameter triggers how the contents of the file is stored in the field. The following constants from DBINFO.CH can be used:

Constants for the import mode Constant

Value

Description

FILEPUT_COMPRESS FILEPUT_ENCRYPT

1 2

Data is compressed Data is encrypted

Return The return value is .T. (true) when the operation is successful, otherwise .F. (false) is returned.

Description The DbFilePut() and DbFileGet() functions are mainly used to transfer data bewteen memo fields holding large amounts of data (BLOB) and external files. Data imported from an external file is then programmatically processed.

Info See also: Category: Header: Source: LIB: DLL:

Function Reference

BlobDirectImport(), BlobImport(), DbFileGet() Database functions, Field functions Dbinfo.ch rdd\dbcmd.c xhb.lib xhbdll.dll

489

DbFilter()

DbFilter() Returns the filter expression of a work area-

Syntax DbFilter() --> cFilter

Return The function returns a character string containing the filter expression of a work area, or a null string ("") when no filter is set.

Description The DbFilter() function can be used to query the filter condition set in a work area as a character string. This allows for temporarily disabling a filter and restore it later using the macro operator (&). Note, however, that this works only if a filter condition does not refer to lexical variables (GLOBAL, LOCAL, STATIC). By default, DbFilter() operates in the current work area. Use an aliased expression to query filter expressions of different work areas.

Info See also: Category: Source: LIB: DLL:

DbClearFilter(), DbRelation(), DbRSelect(), DbSetFilter(), SET FILTER Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example outlines a programming technique for saving // and restoring a filter condition in a work area PROCEDURE Main LOCAL cFilter USE Customer ALIAS CUst SHARED INDEX ON Upper(Lastname+Firstname) TO Cust01 SET FILTER TO Cust->Lastname = "S" GO TOP ? Cust->Lastname // result: Shiller ? cFilter := DbFilter()

// result: Cust->Lastname = "S"

DbClearFilter() GO TOP ? Cust->Lastname

// result: Alberts

SET FILTER TO &cFilter GO TOP ? Cust->Lastname

490

// result: Shiller

Function Reference

DbFilter() CLOSE Cust RETURN

Function Reference

491

DbGoBottom()

DbGoBottom() Moves the record pointer to last record.

Syntax DbGoBottom() --> NIL

Return The return value is always NIL.

Description The function moves the record pointer in the current or aliased work area to the last logical record. If no index or filter is set, this is the last physical record. Otherwise, it is the last record in logical order.

Info See also: Category: Source: LIB: DLL:

Bof(), DbGoto(), DbGoTop(), DbSeek(), DbSkip(), Eof(), GO, INDEX, SET FILTER, SKIP Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of DbGobottom() PROCEDURE Main USE Customer ? Recno(), LastRec()

// result:

1

225

? Recno(), LastRec()

// result: 225

225

? Eof() SKIP ? Eof()

// result: .F.

DbGobottom()

// result: .T.

USE RETURN

492

Function Reference

DbGoto()

DbGoto() Positions the record pointer on a particular record.

Syntax DbGoto( ) --> NIL

Arguments

The parameter identifies a single record in a database. For DBF files, this is the numeric record number, as returned by Recno() for a particular record.

Return The return value is always NIL.

Description The DbGoto() function moves the record pointer to the record identified with . This position is independent of any index or filter currently active in the work area, i.e. does not change with the logical order of records but identifies records physically. Issuing a DbGoto( Recno() ) call in a network enviroment will refresh the database and index buffers. This is the same as a DbSkip(0) call. The parameter may be something other than a record number, depending on the RDD used. In some data formats, for example, the value of is a unique primary key, while in other formats, could be an array offset if the data set was an array. If the record does not exist in the work area, the record pointer is positioned on the "ghost record" (Lastrec()+1), and both, BoF() and Eof(), are set to .T. (true).

Info See also: Category: Source: LIB: DLL:

Bof(), DbGoBottom(), DbGoTop(), DbSeek(), DbSkip(), Eof(), GO, OrdKeyGoTo() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example physically moves the record pointer and outlines // some important state variables of a work area. PROCEDURE Main USE Customer ? Recno(), LastRec()

// result:

1

225

DbGoto(10) ? Recno(), LastRec()

// result:

10

225

DbGoto(1000) ? Recno(), Bof(), Eof()

// result: 226

Function Reference

.T. .T.

493

DbGoto() DbGoto(-1) ? Recno(), Bof(), Eof()

// result: 226

.T. .T.

USE RETURN

494

Function Reference

DbGoTop()

DbGoTop() Moves the record pointer to first record.

Syntax DbGoTop() --> NIL

Return The return value is always NIL.

Description The function moves the record pointer in the current or aliased work area to the first logical record. If no index or filter is set, this is the first physical record. Otherwise, it is the first record in logical order.

Info See also: Category: Source: LIB: DLL:

Bof(), DbGoBottom(), DbGoto(), DbSeek(), DbSkip(), Eof(), GO, INDEX, SET FILTER, SKIP Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of DbGoTop() PROCEDURE Main USE Customer DbGobottom() ? Recno(), LastRec()

// result: 225

225

DbGoTop() ? Recno(), LastRec()

// result:

225

? Bof() SKIP -1 ? Bof()

1

// result: .F. // result: .T.

USE RETURN

Function Reference

495

DbInfo()

DbInfo() Queries and/or changes information about a database file open in a work area.

Syntax DbInfo( , [] ) --> xCurrentSetting

Arguments

This is a numeric parameter for which #define constants exist in the file DbInfo.ch. They identify the numerous settings that can be queried or changed in a work area and begin with the prefix DBI_ (see below).

is an optional argument specifying a new value for the work area setting identified by . The data type for depends on the work area setting to change (see below). If the work area setting is READONLY, the parameter is ignored.

Return The function returns the value of the specified work area setting which is set before the function is called.

Description DbInfo() is a universal function managing numerous work area settings available in xHarbour. Many of these settings can be changed via commands or functions, which is the recommended way. If a work area is not used, DbInfo() generates a runtime error. Also, if an RDD does not support a setting, it may create a runtime error or simply ignore the function call upon its own discretion. In the latter case, the return value of DbInfo() is NIL. The constants that can be used for are listed below: DBI_ALIAS

--> cAliasName (READONLY) See also: function Alias(). The return value is a character string holding the symbolic alias name of the work area.

DBI_BLOB_DIRECT_EXPORT { , , [] } --> lSuccess See also: function BlobDirectExport(). DbInfo() expects as second parameter an array with three elements. They are identical with the arguments of function BlobDirectExport(). The return value is of logical data type and indicates a successful operation. DBI_BLOB_DIRECT_GET

{ , [], [] } --> xBlobData See also: function BlobDirectGet(). DbInfo() expects as second parameter an array with three elements. They are identical with the arguments of function BlobDirectGet(). The return value is the data of the retrieved binary large object (BLOB).

DBI_BLOB_DIRECT_IMPORT { , } --> nNewBlobID 496

Function Reference

DbInfo()

See also: function BlobDirectImport(). DbInfo() expects as second parameter an array with two elements. They are identical with the arguments of function BlobDirectImport(). The return value is the numeric BLOB identifier of the new BLOB. DBI_BLOB_DIRECT_LEN

--> nBytes The second parameter must be the numeric identifier of a binary large object (BLOB) which can be queried using DbFieldInfo( DBS_BLOB_POINTER, ). The return value is the number of bytes occupied by the BLOB in the BLOB file.

DBI_BLOB_DIRECT_PUT

{ , } --> nNewBlobID See also: function BlobDirectPut(). DbInfo() expects as second parameter an array with two elements. They are identical with the arguments of function BlobDirectPut(). The return value is the numeric BLOB identifier of the new BLOB.

DBI_BLOB_DIRECT_TYPE

--> cDataType The second parameter must be the numeric identifier of a binary large object (BLOB) which can be queried using DbFieldInfo( DBS_BLOB_POINTER, ). The return value is a single letter indicating the data type stored in the BLOB. This letter has the same meaning as the return value of function Valtype().

DBI_BLOB_INTEGRITY

--> lSuccess This setting causes DbInfo() to test the integrity of internal tables referring to the data stored in a BLOB file. If the test fails, the return value is .F. (false) and the internal tables can be rebuild using Dbinfo( DBI_BLOB_RECOVER ).

DBI_BLOB_OFFSET

--> nFileOffset The second parameter must be the numeric identifier of a binary large object (BLOB) returned from function BlobDirectPut(). It can also be queried using DbFieldInfo( DBS_BLOB_POINTER, ). The return value is the numeric file offset where the BLOB is stored in the BLOB file.

DBI_BLOB_RECOVER

--> lSuccess Rebuilds the internal tables referring to the data stored in a BLOB file. This should only be called when DbInfo(DBI_BLOB_INTEGRITY) returns .F. (false). DbInfo() can only recover the internal tables referring to the data, it cannot recover the data when a BLOB file becomes corrupted.

DBI_BLOB_ROOT_GET

--> xBlobData See also: function BlobRootGet(). The return value is the data stored in the root area of a BLOB file.

DBI_BLOB_ROOT_LOCK

--> lSuccess See also: function BlobRootLock(). The return value is .T. (true) when a write lock is obtained for the root area of a BLOB file in concurrent file access. The root area must be locked before

Function Reference

497

DbInfo()

DbInfo(DBI_BLOB_ROOT_PUT) is executed. The lock is later released using DbInfo(DBI_BLOB_ROOT_UNLOCK). DBI_BLOB_ROOT_PUT

--> lSuccess See also: function BlobRootPut(). DbInfo() expects as second parameter the data to be stored in the root area of a BLOB file. The return value is .T. (true) when data is successfully written.

DBI_BLOB_ROOT_UNLOCK

--> NIL See also: function BlobRootUnlock(). Releases a lock placed on the root area of a BLOB file with DbInfo(BLOB_ROOT_LOCK). The return value is NIL.

DBI_BOF

--> lIsBeginOfFile (READONLY) See also: function Bof(). The return value is the logical begin-offile status of a work area.

DBI_CANPUTREC

--> lCanWriteData See also: function RddList(). The return value is .T. (true) when the RDD maintaining the file open in a work area supports writing data to the file. This is the case for all RDDs listed by RddList(RDT_FULL).

DBI_CHILDCOUNT

--> nChildCount See also: command SET RELATION. The return value is numeric, indicating the number of child work areas related to the current work area.

DBI_DBFILTER

--> cFilter See also: function DbFilter(). Returns the filter expression of the work area as a character string.

DBI_DB_VERSION

[] --> cRddVersionInfo Returns version information of the RDD maintaining files in a work area. When 1 is passed for the optional second parameter, the returned character string contains extended version information.

DBI_EOF

--> lIsEndOfFile (READONLY) See also: function Eof(). The return value is the logical end-of-file status of a work area.

DBI_FCOUNT

--> nFieldCount (READONLY) See also: function FCount(). The return value is the numeric field count in a work area.

DBI_FILEHANDLE

--> nFileHandle (READONLY) See also: function FOpen(). The return value is the numeric lowlevel file handle of the database file open in a work area.

DBI_FOUND 498

--> lIsFound (READONLY) Function Reference

DbInfo()

See also: function Found(). The return value is the logical found status of the last search operation in a work area. DBI_FULLPATH

--> cFullFileName The return value is a character string holding the fully qualified file name of the database open in a work area if the file resides in the directory specified with SET DEFAULT. When the file is located in another directory, a character string holding the file name without directory information is returned.

DBI_GETHEADERSIZE

--> nBytes (READONLY) See also: function Header(). The return value is the number of bytes occupied by the file header of the database open in a work area.

DBI_GETLOCKARRAY

--> aLockedRecords (READONLY) See also: function DbRLockList(). The return value is an array holding the record numbers of currently locked records.

DBI_GETRECSIZE

--> nRecordSize (READONLY) See also: function RecSize(). The return value is the number of bytes required to store a single record in the database open in a work area.

DBI_ISDBF

--> lIsDbf (READONLY) See also: function RddList(). The return value is .T. (true) when the the file open in a work area is a full functional database. This is the case for all RDDs listed by RddList(RDT_FULL).

DBI_ISFLOCK

--> lIsFileLock (READONLY) See also: function FLock(). The return value is .T. (true) when a file lock is placed on a database open in SHARED mode in the current work area.

DBI_ISREADONLY

--> lIsReadOnly (READONLY) See also: command USE. The return value is .T. (true) when a database file is open in READONLY mode in the current work area.

DBI_LASTUPDATE

--> dLastUpdate (READONLY) See also: function LUpdate(). The return value is the date of the last update of the database open in the current work area.

DBI_LOCKCOUNT

--> nLockedRecords (READONLY) See also: function DbRlockList(). The return value is the number of currently locked records.

DBI_LOCKOFFSET

--> nLockOffset (READONLY) See also: command SET DBFLOCKSCHEME. The return value is a numeric value indicating the virtual lock offset used to place write

Function Reference

499

DbInfo()

locks on records in concurrent database access. The virtual lock offset must be identical for all applications accessing the same database files. The lock offset can be changed using DbInfo(DBI_LOCKSCHEME). DBI_LOCKSCHEME

[] --> nOldLockScheme See also: command SET DBFLOCKSCHEME. The second parameter is optional and can be a numeric value between 0 and 5. It selects the locking scheme to use for aquiring write locks on records in concurrent file access. #define constants are available in DbInfo.ch for . They begin with the prefix DBFLOCK_.

DBI_MEMOBLOCKSIZE

[] --> nOldBlockSize See also: command SET MEMOBLOCK. The second parameter is optional and defines the block size for memo fields used by the RDD that opens database files in a work area. The return value is the current memo block size as a numeric value. Note that changing the memo block size is not supported by all RDDs.

DBI_MEMOEXT

[] --> See also: command SET MFILEEXT. The second parameter is optional and file extension for memo files used by the RDD that opens database files in a work area. The return value is the current memo file extension as a character string.

DBI_MEMOHANDLE

--> (READONLY) See also: function FOpen(). The return value is the numeric lowlevel file handle of the memo file open in a work area.

DBI_MEMOTYPE

--> nMemoType (READONLY) See also: function RddInfo(). The return value is numeric and indicates the type of a memo file associated with a database open in a work area. #define constants are available in DbInfo.ch that identify a memo file type. They begin with the prefix DB_MEMO_.

DBI_MEMOVERSION

--> nMemoVersion (READONLY) See also: function RddInfo(). The return value is numeric and indicates the version of a memo file associated with a database open in a work area. #define constants are available in DbInfo.ch that identify a memo file version. They begin with the prefix DB_MEMOVER_.

DBI_PASSWORD

[] --> NIL This setting defines a password of up to eight characters in length which is used for data encryption in the database file. Note that only data in a DBF file is encrypted. Data stored in index and/or memo files are not encrypted with the password.

DBI_RDD_VERSION

500

[] --> cVersion

Function Reference

DbInfo()

Returns version information of the RDD maintaining files in a work area. When 1 is passed for the optional second parameter, the returned character string contains extended version information. DBI_ROLLBACK

--> NIL See also: command REPLACE. Voids the last changes applied to a record with REPLACE or FieldPut(), which is like an Undo operation. Changes are discarded and the original values are assigned back to a record. This is possible until DbCommit() is executed, a write lock is released using DbUnlock(), or the record pointer is moved.

DBI_SCOPEDRELATION

--> lIsScoped (READONLY) See also: function DbSetRelation(). DbInfo() expects as second parameter a numeric value indicating the ordinal position in the list of relations to query the SCOPED attribute for. Relations are numbered in the sequence they are defined, beginning with 1. The return value is .T. (true) when the relation to the child work area is scoped, when the .T. was passed for the fourth parameter of DbSetRelation().

DBI_SHARED

--> lIsShared (READONLY) See also: command USE. The return value is .T. (true) when a database is open in SHARED mode with the USE command.

DBI_TABLEEXT

--> cFileExtension (READONLY) See also: function DbTableExt(). The return value is the file extension of the database file open in a work area as a character string.

DBI_TABLETYPE

--> nTableType (READONLY) See also: function RddInfo(). The return value is numeric, indicating the type of the database file open in a work area. #define constants are avaialble in DbInfo.ch to identify the database type. They begin with the prefix DB_DBF_.

DBI_VALIDBUFFER

--> lBufferIsValid (READONLY) The return value is .T. (true) when the internal memory buffer holding data of a record on disk is valid. A valid buffer is unchanged, i.e. it contains the same data as stored in the database file.

Function Reference

501

DbInfo()

Info See also: Category: Header: Source: LIB: DLL:

Alias(), DbFieldInfo(), DbOrderInfo(), DbRecordInfo(), DbUseArea(), RddInfo(), Select() Database functions, Info functions Dbinfo.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates some DbInfo() settings and how // to undo changes applied to a record. #include "DbInfo.ch" PROCEDURE Main USE Customer ALIAS Cust SHARED ? DbInfo( DBI_SHARED ) ? DbInfo( DBI_ISREADONLY )

// result: .T. // result: .F.

? FIELD->LastName ? DbInfo( DBI_VALIDBUFFER )

// result: Miller // result: .T.

RLock() ? ValToPrg( DbInfo(DBI_GETLOCKARRAY) )

// result: { 1 }

REPLACE FIELD->LastName WITH "JONES" ? FIELD->LastName ? DbInfo( DBI_ROLLBACK ) ? FIELD->LastName

// result: JONES // result: NIL // result: Miller

DbUnlock() USE RETURN

502

Function Reference

DbOrderInfo()

DbOrderInfo() Queries and/or changes information about indexes open in a work area.

Syntax DbOrderInfo( , [] , [|], []

; ; ; ) --> xCurrentSetting

Arguments

This is a numeric parameter for which #define constants exist in the file DbInfo.ch. They identify the numerous settings that can be queried or changed for indexes and begin with the prefix DBOI_ (see below).

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

A numeric value specifying the ordinal position of the index open in a work area to query information for. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the index to query can be passed. It is the string passed to the TAG option of the INDEX command and analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is an optional argument specifying a new value for the index setting identified by . The data type for depends on the index setting to change (see below). If the index setting is READONLY, the parameter is ignored.

Return The function returns the value of the specified index setting which is set before the function is called.

Description DbOrderInfo() is a universal function managing numerous index settings available in xHarbour. Note, however, that not all settings are supported by all RDDs. If a setting is not supported by an RDD, a call to DbOrderInfo() may be ignored or may rise a runtime error. When DbOrderInfo() is called in an unused work area, a runtime error is raised. The constants that can be used for are listed below: Function Reference

503

DbOrderInfo()

DBOI_BAGCOUNT

--> nOpenIndexFiles (READONLY) See also: command SET INDEX. This setting is supported by the DBFNTX RDD and returns the number of NTX index files open in a work area. Note that if an NTX index file is created with multiple TAG names, it may contain multiple indexes.

DBOI_BAGEXT

--> cFileExtension (READONLY) See also: function OrdBagExt(). The return value is the index file extension used by the RDD that opened a database in a work area as a character string.

DBOI_BAGNAME

--> cIndexFilename (READONLY) See also: function OrdBagName(). The return value is the name of the index file that contains the specified index as a character string.

DBOI_BAGNUMBER

--> nIndexFilePosition (READONLY) See also: command SET INDEX. This setting is supported by the DBFNTX RDD and returns the ordinal position of a single NTX index file in the list of open index files. Index files are numbered in the sequence they are opened beginning with one. DBOI_BAGNUMBER may yield a different result from DBOI_NUMBER when an NTX index file is created with multiple TAG names. In this case, the number of open NTX files may be different from the number of indexes available in a work area.

DBOI_BAGORDER

--> nFirstIndex (READONLY) The return value is the ordinal position of the firs index within a multi-key index file.

DBOI_CONDITION

--> cForCondition (READONLY) See also: function OrdFor(). The return value is a character string holding the FOR condition of the specified index. If the index is created without FOR condition, an empty string ("") is returned.

DBOI_CUSTOM

[] --> lIsCustomIndex See also: command INDEX. This setting is equivalent with the CUSTOM option of the INDEX command. When it is set to .T. (true) before an index is created, a custom index will be created with function OrdCreate(). If DBOI_CUSTOM is queried for an existing index file, its custom flag is returned as a logical value. This flag cannot be changed after index creation so that is ignored for existing indexes.

DBOI_EVALSTEP

--> nEvalStep (READONLY) See also: command INDEX. The return value is numeric and represents the value for the EVERY option when an index is created. The setting is supported by the DBFNTX and DBFCDX RDDs.

DBOI_EXPRESSION 504

--> cIndexKey (READONLY) Function Reference

DbOrderInfo()

See also: function OrdKey(). The return value is the key expression of the specified index as a character string. DBOI_FILEHANDLE

--> nFileHandle (READONLY) See also: function FOpen(). The return value is the numeric lowlevel file handle of the index file open in a work area.

DBOI_FINDREC

--> lFound See also: function OrdFindRec(). This setting is equivalent with function call OrdFindRec( nRecno, .F. ).

DBOI_FINDRECCONT

--> lFound See also: function OrdFindRec(). This setting is equivalent with function call OrdFindRec( nRecno, .T. ).

DBOI_FULLPATH

--> cFullFileName (READONLY) The return value is a character string holding the name of an index file, including file extension, that contains the specified index.

DBOI_INDEXEXT

--> cIndexFileExtension (READONLY) DBOI_INDEXEXT is a synonym for DBOI_ORDBAGEXT and returns the file extension for an index file.

DBOI_INDEXNAME

--> cIndexFileName (READONLY) DBOI_INDEXNAME is a synonym for DBOI_ORDBAGNAME and returns the file name for an index file.

DBOI_ISCOND

--> lIsForCondition (READONLY) See also: command INDEX. The return value is .T. (true) when the specified index is created with a FOR condition. Otherwise .F. (false) is returned.

DBOI_ISDESC

[] --> lOldDescending See also: command INDEX. The return value is .T. (true) when the specified index is created with the DESCENDING option. If an RDD supports to change ascending and descending indexes dynamically "on the fly", this setting works exactly the same as function OrdDescend().

DBOI_ISMULTITAG

--> lIsMultiTag (READONLY) This setting is supported by the DBFNTX RDD. The return value is .T. (true) when an NTX file can contain multiple indexes, otherwise .F. (false) is returned. Multiple indexes can be created when indexes with different TAG names are created for the same index file.

DBOI_ISREADONLY

--> lIsReadOnly (READONLY) See also: command USE. This setting is supported by the DBFNTX RDD. The return value is .T. (true) when the database file, that is associated with the index, is open in READONLY mode

Function Reference

505

DbOrderInfo()

in the current work area. The READONLY status is valid for both, datbase ans index files. DBOI_ISREINDEX

--> lIsReindexing (READONLY) See also: function OrdListRebuild(). The return value is .T. (true) while reindexing is in progress, otherwise .F. (false) is returned.

DBOI_KEYADD

[] --> lKeyIsAdded See also: function OrdKeyAdd(). This setting can only be used with custom built indexes, i.e. when an index is created with the CUSTOM option of the INDEX command. If the index is not a custom index, a runtime error is raised. The return value is .T. (true), when the new key value is successfully added to a custom index. Otherwise, .F. (false) is returned. If is omitted, it is created from the index key for the current record.

DBOI_KEYCOUNT

--> nKeyCount (READONLY) See also: function OrdKeyCount(). This setting returns the number of index keys included in the specified index as a numeric value.

DBOI_KEYDEC

--> nDecimals (READONLY) This setting can only be queried for DBFNTX. It returns the number of decimal places in a numeric index.

DBOI_KEYDELETE

[] --> lKeyIsDeleted See also: function OrdKeyDel(). This setting can only be used with custom built indexes, i.e. when an index is created with the CUSTOM option of the INDEX command. If the index is not a custom index, a runtime error is raised. The return value is .T. (true), when the specified key value is successfully removed from a custom index. Otherwise, .F. (false) is returned. If is omitted, the index key of the current record is removed from the index.

DBOI_KEYGOTO

--> lSuccess See also: function OrdKeyGoTo(). This setting moves the record pointer to the logical record position specified with . The return value is .T. (true) when the record pointer is successfully positioned, otherwise .F. (false). Note that if a filter condition is active in a work area, all records matching the filter are excluded.

DBOI_KEYGOTORAW

--> lSuccess See also: function OrdKeyGoto(). This setting differs from DBOI_KEYGOTO only by ignoring any filter condition that may be set in a work area. DBOI_KEYGOTORAW includes records that match a filter condition.

DBOI_KEYNO

--> nOrdKeyNo (READONLY) See also: function OrdKeyNo(). This setting returns a numeric value representing the logical record number of the current record.

506

Function Reference

DbOrderInfo()

If a filter is active in the work area, all records matching the filter condition are excluded. DBOI_KEYNORAW

--> nOrdKeyNo (READONLY) See also: function OrdKeyNo(). This setting differs from DBOI_KEYNO only by ignoring any filter condition that may be set in a work area. DBOI_KEYNORAW includes records that match a filter condition.

DBOI_KEYSINCLUDED

--> nAddedKeys (READONLY) See also: command INDEX. This setting is only relevant during index creation. It returns the number of index keys already added to an index. The setting is used to display indexing progress by calling a user defined routine via the EVAL option of the index command.

DBOI_KEYSIZE

--> nKeySize (READONLY) See also: function OrdKey(). This setting returns the number of bytes an index value of a single record occupies in the index file.

DBOI_KEYTYPE

--> cKeyType (READONLY) See also: function OrdKey(). This setting returns a single letter representing the data type of an index expression. The returned letter is equivalent with the return value of Valtype().

DBOI_KEYVAL

--> xIndexVal (READONLY) See also: function OrdKeyVal(). The setting returns the index value of the current record.

DBOI_LOCKOFFSET

--> nLockOffset (READONLY) See also: command SET DBFLOCKSCHEME. This setting returns the locking offset used by the selected locking scheme as a numeric value.

DBOI_NAME

--> cIndexName (READONLY) See also: function OrdName(). This setting returns the symbolic name of an index as a character string. The name is specified with the TAG option of the INDEX command when the index is created.

DBOI_NUMBER

--> nOrder (READONLY) See also: function OrdNumber(). This setting returns the ordinal position of an index in the list of open indexes based on its symbolic name. The name is specified with the TAG option of the INDEX command when the index is created.

DBOI_ORDERCOUNT

--> nIndexCount (READONLY) See also: function OrdCount(). This setting returns the number of indexes open in a work area as a numeric value.

DBOI_POSITION

Function Reference

[] --> nIndexKeyNo

507

DbOrderInfo()

See also: function OrdKeyGoto() and OrdKeyNo(). This setting queries and/or changes the logical position of the record pointer. If is specified, it must be a numeric value in the range between 1 and OrdKeyCount(). DBOI_RELKEYPOS

[] --> nRelativePos See also: function OrdKeyRelPos(). This setting queries and/or changes the relative position of the record pointer. If is specified, it must be a numeric value in the range between 0 and 1.

DBOI_SCOPEBOTTOM

[] --> xBottomScope See also: function OrdScope(). This setting queries and/or changes the bottom scope value for navigating the record pointer. If is specified, it must be of the same data type as the value of the index expression.

DBOI_SCOPEBOTTOMCLEAR --> xBottomScope See also: function OrdScope(). This setting releases the bottom scope value for navigating the record pointer. The return value is the previously set bottom scope value. DBOI_SCOPECLEAR

--> NIL See also: command SET SCOPE. This setting releases both, the top and bottom scope value for navigating the record pointer. It is equivalent with SET SCOPE TO and no arguments apecified. The return value is always NIL.

DBOI_SCOPESET

[] --> NIL See also: function OrdScope(). This setting allows for defining the same value for both, the top and bottom scope, with one function call. If is specified, its data type must be the same as the value of the index expression. The return value is always NIL.

DBOI_SCOPETOP

[] --> xTopScope See also: function OrdScope(). This setting queries and/or changes the top scope value for navigating the record pointer. If is specified, it must be of the same data type as the value of the index expression.

DBOI_SCOPETOPCLEAR

--> xTopScope See also: function OrdScope(). This setting releases the top scope value for navigating the record pointer. The return value is the previously set top scope value.

DBOI_SKIPUNIQUE

[] --> lSuccess This setting is equivalent with function OrdSkipUnique().

DBOI_SKIPWILD

508

--> lFound

Function Reference

DbOrderInfo()

See also: function OrdWildSeek(). This setting is equivalent with function call OrdWildSeek( cWildCardString, .F., .F. ). DBOI_SKIPWILDBACK

--> lFound See also: function OrdWildSeek(). This setting is equivalent with function call OrdWildSeek( cWildCardString, .F., .T. ).

DBOI_UNIQUE

--> lIsUnique (READONLY) See also: function OrdIsUnique(). The return value is .T. (true) when the specified index is created with the UNIQUE option of the INDEX command, otherwise .F. (false) is returned.

Info See also: Category: Header: Source: LIB: DLL:

Function Reference

DbInfo(), DbRecordInfo(), OrdBagExt(), OrdKey(), OrdName(), RddInfo() Database functions, Info functions Dbinfo.ch rdd\dbcmd.c xhb.lib xhbdll.dll

509

DbRecall()

DbRecall() Recalls a record previousy marked for deletion.

Syntax DbRecall() --> NIL

Return The return value is always NIL.

Description The DbDelete() function removes the deletion flag from a record marked as deleted. The deletion flag is set with function DbDelete(). Not that if SET DELETED is set to ON, functions and commands for relative database navigation ignore all records having the deleted flag set. This way, they become unvisible. In a networking situation, this function requires the current record be locked prior to calling the DbRecall() function.

Info See also: Category: Source: LIB: DLL:

DbDelete(), DELETE, Deleted(), RECALL Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates how to set and detect the deletion flag PROCEDURE Main USE Customer EXCLUSIVE DbGoto(10) DbDelete() ? Deleted()

// result: .T.

DbRecall() ? Deleted()

// result: .F.

USE RETURN

510

Function Reference

DbRecordInfo()

DbRecordInfo() Queries and/or changes information about a record of an open database file.

Syntax DbRecordInfo( , [], [] ) --> xOldSetting

Arguments

This is a numeric parameter for which #define constants exist in the file DbInfo.ch. They identify the individual data that can be queried for a single record.

The parameter identifies the record in a database to query data for. It defaults to the return value of Recno(), the current record.

This parameter is reserved for RDDs that allow the record information to be changed.

Return DbRecordInfo() returns the queried record information as supplied by the replaceable database driver (RDD).

Description DbRecordInfo() queries detailed record information from the replaceable database driver (RDD). Depending on database and RDD used, different information may be available. The type of information to retrieve is specified with #define constants available in the DBINFO.CH header file.

Constants for DbRecordInfo() Constant

Return value

DBRI_DELETED DBRI_ENCRYPTED DBRI_LOCKED DBRI_RAWDATA DBRI_RAWMEMOS DBRI_RAWRECORD DBRI_RECNO DBRI_RECSIZE DBRI_UPDATED

The Deleted() flag of a record as a logical value The encrypted flag of a record as a logical value The write lock status of a record as a logical value The raw data of a record as a character string The raw memo field data of a record as a character string The raw data of a record except memo fields as a character string The numeric relative record position, see OrdKeyNo() The numeric size of a record, see RecSize() The updated flag of a record as a logical value

By default, DbRecordInfo() operates in the current work area. Use an aliased expression to query field information in different work areas.

Function Reference

511

DbRecordInfo()

Info See also: Category: Header: Source: LIB: DLL:

512

Alias(), DbInfo(), DbFieldInfo(), DbOrderInfo(), DbUseArea(), Deleted(), OrdKeyNo(), RecSize(), RLock(), Select() Database functions, Info functions Dbinfo.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

DbReindex()

DbReindex() Rebuilds indexes open in a work area.

Syntax DbReindex() --> NIL

Return The return value is always NIL.

Description The function DbReindex() exists for compatibility reasons. Is is superseded by function OrdListRebuild(). DbReindex() rebuilds all open indexes in the current work area. Use an aliased expression to rebuild indexes in other work areas.

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), DbCreateIndex(), DbSetIndex(), DbSetOrder(), INDEX, OrdCreate(), OrdListRebuild(), REINDEX Database functions, Index functions rdd\rddord.prg xhb.lib xhbdll.dll

Example // refer to the example of OrdListRebuild()

Function Reference

513

DbRelation()

DbRelation() Returns the linking expression of a specified relation.

Syntax DbRelation( ) --> cLinkExpression

Arguments

The parameter is a numeric value indicating the ordinal position in the list of relations to retrieve the relation expression from. Relations are numbered in the sequence they are defined, beginning with 1.

Return The function returns a character string containing the relation expression specified with , or a null string ("") when no relation exists for .

Description The DbRelation() function can be used to query the relation expression for a given relation. In conjunction with DbRSelect(), all data required to save and restore relation data using the macro operator (&) can be obtained. Note, however, that this works only if a relation does not refer to lexical variables (GLOBAL, LOCAL, STATIC). DbRelation() retrieves the expression of the TO clause of the SET RELATION command, while DbRSelect() retrieves the data of the INTO clause. Refer to the SET RELATION command for more information on relations. By default, DbRelation() operates in the current work area. Use an aliased expression to query relation expressions of different work areas.

Info See also: Category: Source: LIB: DLL:

DbFilter(), DbRSelect(), DbSetRelation(), OrdSetRelation(), SET RELATION Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example opens three databases and defines two relations. // The result of various DbRelation() calls is shown. PROCEDURE Main USE Customer ALIAS Cust NEW EXCLUSIVE INDEX ON CustNo TO CustNo USE Parts ALIAS Part NEW EXCLUSIVE INDEX ON PartNo TO PartNo USE Order ALIAS Ord NEW SET RELATION TO CustNo INTO Cust, ;

514

Function Reference

DbRelation() TO PartNo INTO Part ? Alias() ? DbRelation(1) ? DbRelation(2)

// result: ORD // result: CustNo // result: PartNo

SELECT Part ? Alias() ? DbRelation(1)

// result: PART // result: null string ("")

? Ord->( DbRelation(1) ) ? Ord->( DbRelation(2) )

// result: CustNo // result: PartNo

CLOSE ALL RETURN

Function Reference

515

DbRLock()

DbRLock() Locks a record for write access.

Syntax DbRLock( [] ) --> lSuccess

Arguments

The parameter identifies a single record in a database. For DBF files, this is the numeric record number, as returned by Recno() for a particular record. It defaults to the current record.

Return The return value is .T. (true) when the record is successfully locked, otherwise .F. (false) is returned.

Description The DbRLock() function attempts to lock the record identified by in the current work area, and return .T. (true) if the record is locked. If is not specified, all active record locks are removed and the current record is locked. When a particular record is specified with , the function places a lock on this record and adds it to the list of active record locks. This list can be retrieved with function DbRLockList(). Use DbRUnLock() to release locks from individual records.

Info See also: Category: Source: LIB: DLL:

DbRLockList(), DbRUnlock(), DbUnlock(), DbUnlockAll(), FLock(), RLock(), UNLOCK Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example attempts to lock multiple records belonging to a // transaction and unlocks all if a single lock is not successful PROCEDURE Main LOCAL cTransActID := "01234" LOCAL nCount := 0 USE Accounts INDEX Transact SEEK (cTransActID) DO WHILE FIELD->TRANSACTID == cTransActID IF DbRLock( Recno() ) nCount ++ // successful lock SKIP // proceed to next record ELSE

516

Function Reference

DbRLock() nCount := -1 DbRUnlock() ENDIF ENDDO

// lock failed on this record // release all previous locks

IF nCount > 0 ENDIF RETURN

Function Reference

517

DbRLockList()

DbRLockList() Returns a list of locked records.

Syntax DbRLockList() --> aLockedRecords

Return The function returns a one-dimensional array holding the record identifiers of locked records, or an empty array if no record is locked.

Description The function is used to determine which and how many records are currently locked for shared access. It operates in the current work area unless used in an aliased expression.

Info See also: Category: Source: LIB: DLL:

DbRLock(), DbRUnlock(), DbUnlock(), DbUnlockAll(), FLock(), RLock(), UNLOCK Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // Theexample deonstrates the return value of DbRLockList() PROCEDURE Main() LOCAL aList, n USE Customer NEW ? LastRec()

// result: 225

DbGoto(10) ? DbRLock( Recno() )

// result: .T.

DbGoto( 180 ) ? DbRLock( Recno() )

// result: .T.

aList := DbRLockList() ? Len(aList)

// result: 2

FOR n:=1 TO Len( aList ) ?? aList[n] NEXT

// result: 10

180

USE RETURN

518

Function Reference

DbRSelect()

DbRSelect() Returns the child work area number of a relation.

Syntax DbRSelect( ) --> nWorkArea

Arguments

The parameter is a numeric value indicating the ordinal position in the list of relations to retrieve the child work area number. Relations are numbered in the sequence they are defined, beginning with 1.

Return The function returns as a numeric value the work area number of the relation specified with . The return value is zero if no relation is defined.

Description The function DbRSelect() determines the work area number of a child work area, the current work area is related to. It determines it from the ordinal position of a relation which is numbered according to the sequence a relation is defined with the SET RELATION command. DbRSelect() is used in conjunction with DbRelation() which retrieves the relation expression of a relation. Pass the return value of DbRSelect() to Alias() to find out the alias name of the child work area.

Info See also: Category: Source: LIB: DLL:

DbFilter(), DbRelation(), DbSetRelation(), OrdSetRelation(), SET RELATION Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example opens three databases and defines two relations. // The result of various DbRSelect() calls is shown. PROCEDURE Main USE Order ALIAS Ord NEW USE Parts ALIAS Part NEW EXCLUSIVE INDEX ON PartNo TO PartNo USE Customer ALIAS Cust NEW EXCLUSIVE INDEX ON CustNo TO CustNo SELECT Ord SET RELATION TO CustNo INTO Cust, ; TO PartNo INTO Part ? Alias()

Function Reference

// result: ORD

519

DbRSelect() ? ? ? ?

DbRSelect(1) DbRSelect(2) Alias(DbRSelect(1)) Alias(DbRSelect(2))

SELECT Part ? Alias() ? DbRSelect(1)

// // // //

result: result: result: result:

3 2 CUST PART

// result: PART // result: 0

CLOSE ALL RETURN

520

Function Reference

DbRUnlock()

DbRUnlock() Unlocks a record based on its indentifier.

Syntax DbRUnlock( [] ) --> NIL

Arguments

The parameter identifies a single record in a database. For DBF files, this is the numeric record number, as returned by Recno() for a particular record. If not specified, all active record locks are released.

Return The return value is always NIL.

Description The DbRUnlock() function releases a record lock for an individual record specified with . If no record identifier is passed to the function, DbRUnlock() bahaves like DbUnlock() since all active record locks are released. Locking and unlocking one or more records for shared write access is the task of DbRlock() and DbRUnlock(), while RLock() works with the current record and DbUnlock() releases all locks.

Info See also: Category: Source: LIB: DLL:

DbRLock(), DbRLockList(), DbUnlock(), RLock(), UNLOCK Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // // // //

The example shows a user defined function that accepts as parameter an array of record identifiers. These records are unlocked, unless the parameter is no array. In this case, all record locks are released. FUNCTION UnlockMultiple( aRecords ) IF Valtype( aRecords ) == "A" // release individual locka AEval( aRecords, {|nRecno| DbRUnlock( nRecno ) } ) ELSE DbRUnlock() // release all locka ENDIF RETURN DbRLockList()

Function Reference

// return remaining locks

521

DbSeek()

DbSeek() Searches a value in the controlling index.

Syntax DbSeek( , [], [] ) --> lFound

Arguments

The value to search for. Its data type must match the data type of the index expression of the controlling index.

This optional value defaults to .F. (false) causing the DbSeek() function to position the record pointer at Eof() if is not found in the index. When .T. (true) is passed for and is not found in the index, the record pointer is positioned on the record with the next higher index value.

is only relevant when the database contains multiple records having identical index values. It defaults to .F. (false) causing the DbSeek() function to position the record pointer on the first record found. .T. (true) instructs DbSeek() to position the record pointer on the last of multiple records having the same index value.

Return DbSeek() returns .T. (true) if is found, otherwise .F. (false).

Description The DbSeek() function is used to perform fast searches in databases. To accomplish this, the database must be indexed, since DbSeek() searches the value in the controlling index, rather than in the database. It operates in the current work area, unless it is used in an aliased expression. When DbSeek() finds in the controlling index, it returns .T. (true) and positions the record pointer to the corresponding record. The parameter optionally specifies which record to find if there are multiple records having the same index value. By default, the first record is found. If is .T. (true), DbSeek() positions the record pointer on the last of the records having identical index values. After a successful search, the function Found() returns .T. (true) until the record pointer is moved again. In addition, both functions, BoF() and EoF() return .F. (false). If the searched value is not found, DbSeek() positions the record pointer on the "ghost record" (Lastrec()+1) by default, and the function Found() returns .F. (false), while Eof() returns .T. (true). This behavior, however, depends on the SET SOFTSEEK setting, or the parameter , respectively. If SOFTSEEK is set to ON, or is .T. (true), the record pointer is moved to the record yielding the next higher index value. If such a record exists, both functions, Found() and Eof() return .F. (false). If no record with a higher index value than exists, the record pointer ends up at the "ghost record" (see above).

522

Function Reference

DbSeek()

Info See also: Category: Source: LIB: DLL:

BoF(), DbGoBottom(), DbGoTop(), DbSkip(), Eof(), Found(), LOCATE, OrdFindRec(), OrdKeyGoto(), OrdWildSeek(), SEEK Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example outlines various possibilities of searching a value // with DbSeek() and the resulting states of Found() and Eof(). PROCEDURE Main USE Customer NEW INDEX ON Upper(Lastname+Firstname) TO Cust01 // standard search ? DbSeek( "GRAY" ) ? Found(), Eof() ? Lastname, Firstname

// result: .T. // result: .T. .F. // result: Gray

Eileen

// find last matching record ? DbSeek( "GRAY", .F., .T. ) ? Found(), Eof() ? Lastname, Firstname

// result: .T. // result: .T. .F. // result: Gray

Robert

// no matching record ? DbSeek( "Gray" ) ? Found(), Eof() ? Lastname, Firstname

// result: .F. // result: .F. .T. // result: (empty string)

// no matching record, with softseek ? DbSeek( "GREGOR", .T. ) // result: .F. ? Found(), Eof() // result: .F. .F. ? Lastname, Firstname // result: Hellstrom

Eric

USE RETURN

Function Reference

523

DbSelectArea()

DbSelectArea() Selects the current work area.

Syntax DbSelectArea( | ) --> NIL

Arguments

A character string holding the alias name of the work area to select as current.

The numeric ordinal position of the work area to select. Work areas are numbered from 1 to 65535. The value 0 has a special meaning: it selects the next unused work area, irrespective of its ordinal number.

Return The return value is always NIL.

Description DbSelectArea() selects the current work area. The scope of all database commands and all unaliased database functions is the current work area. A work area can be thought of as the place where databases and accompanying files are open and become accessible. One work area can hold one open database. To operate with multiple open databases at a time requires an application to switch between work areas using DbSelectArea(). An alternative is given by aliased expressions that are prefixed with the alias name or work area number of the work area to select temporarily before executing a database function. Note that aliased expressions are only possible with database functions. Database commands operate always in the current work area.

Info See also: Category: Source: LIB: DLL:

DbUseArea(), SELECT, Select(), USE, Used() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example opens two databases in two different work areas // and outlines aliased expressions. PROCEDURE Main USE Customer ALIAS Cust DbSelectArea(10) USE Invoice ALIAS Inv ? Select() ? Cust->( Select() )

524

// result: 10 // result: 1

Function Reference

DbSelectArea() DbSelectArea(0) ? Select() ? (10)->( Alias() ) CLOSE ALL RETURN

Function Reference

// result:

2

// result: INV

525

DbSetDriver()

DbSetDriver() Retrieves and/or selects the default replaceable database driver.

Syntax DbSetDriver( [] ) --> cPreviousRDD

Arguments

This optional parameter is a character string holding the name of the RDD to select as current.

Return DbSetDriver() returns a character string with the name of driver that is active before the function is called.

Description The function exists for compatibility reasons and is replaced by function RddSetDefault().

Info See also: Category: Source: LIB: DLL:

RddSetDefault() Database functions, Database drivers rdd\dbcmd.c xhb.lib xhbdll.dll

Example // see function RddSetDefault() for an example

526

Function Reference

DbSetFilter()

DbSetFilter() Defines a filter condition for a work area.

Syntax DbSetFilter( , [] ) --> NIL

Arguments

A code block containing the filter expression. The expression must yield a logical value.

The filter expression in form of a character string.

Return The return value is always NIL.

Description The DbFilter() function defines a filter condition for the current work area in form of the code block . All records in the work area where the filter condition yields .F. (false) are ignored during database navigation. As a result, these records become invisible and are filtered. Although the second parameter is optional, it is recommended to specify the filter condition a second time as a character string. Otherwise, the DbFilter() function cannot obtain the filter condition and returns a null string (""), despite of a filter condition being active. It is recommended to move the record pointer once after calling DbSetFilter() to ensure that the current record is not visible when it does not match the filter condition. This is usually done with DbGoTop(). Optimization: filtering records can be a time consuming task since the filter condition is evaluated for each record during database navigation. This can be optimized when the filter condition matches the index expression of an open index and SET OPTIMIZE ist set to ON.

Info See also: Category: Source: LIB: DLL:

DbClearFilter(), DbFilter(), SET DELETED, SET FILTER, SET OPTIMIZE Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the effect of a filter condition PROCEDURE Main USE Customer INDEX ON Upper(LastName) TO Cust01 GO TOP ? Recno(), Lastname

Function Reference

// result: 28 Abbey

527

DbSetFilter() DbSetFilter( {|| Upper(LastName) > "L" }, ; 'Upper(LastName) > "L"' ) GO TOP ? Recno(), Lastname

// result: 182 MacDonald

? DbFilter()

// result: Upper(LastName) > "L"

CLOSE Customer RETURN

528

Function Reference

DbSetIndex()

DbSetIndex() Opens an index file.

Syntax DbSetIndex( ) --> NIL

Arguments

is a character string with the name of the file containing the index(es) to add to the list of open indexes in a work area. The file name can be specified including path information and extension. When the file extension is omitted, it is determined by the database driver that opened the database file in the work area.

Return The return value is always NIL.

Description DbSetIndex() exists for compatibility reasons. It is superseded by OrdListAdd(). Note that DBSetIndex() opens an index file only, it does not change the controlling index, unless it is the first index to open.

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), DbCreateIndex(), DbSetOrder(), OrdListAdd(), SET INDEX Database functions, Index functions rdd\rddord.prg xhb.lib xhbdll.dll

Example // refer to the OrdListAdd() function for an example

Function Reference

529

DbSetOrder()

DbSetOrder() Selects the controlling index.

Syntax DbSetOrder( ) --> NIL

Arguments

This is the numeric ordinal position of the index to activate as the controlling index. Indexes are numbered in the sequence they are opened with OrdListAdd(), beginning with 1. The value 0 has a special meaning: it de-activates the controlling index while leaving it open. Records are navigated in physical order when is set to 0.

Return The return value is always NIL.

Description DbSetOrder() exists for compatibility reasons. It is superseded by OrdSetFocus().

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), DbCreateIndex(), DbSetIndex(), OrdSetFocus(), SET ORDER Database functions, Index functions rdd\rddord.prg xhb.lib xhbdll.dll

Example // refer to the OrdSetFocus() function for an example

530

Function Reference

DbSetRelation()

DbSetRelation() Relates a child work area with a parent work area.

Syntax DbSetRelation( | , , , []

; ; ; ) --> NIL

Arguments

The numeric ordinal position of the child work area to relate to the current work area.

Optionally, the child work area can be specified as a character string holding the symbolic alias name of the child work area.

A code block containing the relation expression.

The relation expression in form of a character string.

The default value for is .F. (false), showing no effect on the relation. If .T. (true) is passed, database navigation in the child work area is restricted (scoped) to the records that relate to the current record in the parent work area.

Return The return value is always NIL.

Description The DbSetRelation() function relates a parent work area with the child work area specified as or . This causes the record pointer in a child work area to be synchronized with the record pointer in the parent work area, based on the expression . All existing relations remain active. Synchronization of the record pointer in a child work area is accomplished either relative via an index, or absolute via a record number. Relative synchronization This requires a controlling index in the child work area. Each time the record pointer moves in the parent work area, the return value of is SEEKed in the child work area. As a consequence, the data type of must match the data type of the controlling index in the child work area. Absolute synchronization Function Reference

531

DbSetRelation()

When the child work area has no controlling index, or when the type of the index expression is not numeric and the relation expression is numeric, the child work area is synchronized via GOTO with the record number of the parent work area. Scoped relation If .T. (true) is passed for and the child work area is selected as current work area, record pointer navigation in the child work area is restricted to the records where yields the same values in both, parent and child work area. As a result, the child work area presents a subset of records that match with the current record in the parent work area. Notes The record pointer in the child work area is positioned on Lastrec()+1 when there is no match with the relation expression. It is illegal to relate a parent work area directly or indirectly with itself. DbSetRelation() does not support SOFTSEEK. It always acts as if SOFTSEEK is set to OFF.

Info See also:

Bof(), DbClearRelation(), DbGoto(), DbRelation(), DbRSelect(), DbSeek(), Eof(), Found(), OrdSetRelation(), SET RELATION Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Category: Source: LIB: DLL:

Example // // // //

The example takes advantage of a scoped relation between an Invoice database and an Invoice Items database. The items belonging to an invoice are printed in a DO WHILE .NOT. Eof() loop, since the relation is scoped in the child work area. PROCEDURE Main USE Invoice ALIAS Inv NEW USE InvItems ALIAS Items NEW INDEX ON InvoiceNo + ItemID TO InvItemsA SELECT Inv DBSetRelation( "Items", {|| InvoiceNo }, "InvoiceNo", .T. ) FOR i:=1 TO 10 ? Inv->InvoiceNo, Inv->Date SELECT Items DO WHILE .NOT. Eof() ? Space(6), Items->Item_ID, Items->Descript, Items->Price SKIP ENDDO SELECT Inv SKIP NEXT RETURN

532

Function Reference

DbSkip()

DbSkip() Moves the record pointer in a work area.

Syntax DbSkip( [] ) --> NIL

Arguments

Numbers of records to move the record pointer. Positive values for move the record pointer forwards (towards the end of file), negative values move it backwards. The default value is 1, i.e. calling DbSkip() with no parameter advances the record pointer to the next record.

Return The return value is always NIL.

Description This function moves the record pointer by the number of records in the current work area, unless prefixed with an alias. Record pointer movement is relative to the current record and follows the logical order active in a work area. That is, indexes, filters and scopes define the order in which records are navigated. The record pointer cannot be moved beyond the begin or end of file. An attempt to do so causes either Bof() or Eof() be set to .T. (true), and the record pointer remains unchanged. Note: DbSkip(0) flushes and refreshes the internal database buffers. All changes made to the record become visible without moving the record pointer in either direction.

Info See also: Category: Source: LIB: DLL:

Bof(), DbGoBottom(), DbGoto(), DbGoTop(), DbSeek(), Eof(), GO, OrdSkipRaw(), SKIP Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // // // //

The example shows a typical coding pattern for scanning a database in a DO WHILE loop based on a condition. DbSkip() is always called at the end of the loop, when the condition must be tested for the next record. PROCEDURE Main() USE Customer ALIAS Cust NEW DO WHILE .NOT. EoF() ? Cust->Firstname,Cust->Lastname DbSkip() ENDDO

Function Reference

533

DbSkip() USE RETURN

534

Function Reference

DbSkipper()

DbSkipper() Helper function for browse objects to skip a database

Syntax DbSkipper( ) --> nSkipResult

Arguments

A numeric value indicating the number of records to skip the record pointer.

Return The return value is the number of records that are actually skipped.

Description DbSkipper() is a helper function used in the :skipBlock code block of the TBrowse object. It provides for standard skip behaviour when browsing data in a work area.

Info See also: Category: Source: LIB: DLL:

DbSkip(), SKIP, TBrowse() Object functions, Database functions, xHarbour extensions rtl\browdbx.prg xhb.lib xhbdll.dll

Example // The example builds a simple TBrowse object using standard // navigation code blocks. #include "inkey.ch" PROCEDURE Main LOCAL oTBrowse, aFields, cField, nKey USE Customer aFields := Array( FCount() ) AEval( aFields, {|x,i| aFields[i] := FieldName(i) } ) oTBrowse oTBrowse:skipBlock oTBrowse:goTopBlock oTBrowse:goBottomBlock

:= := := :=

TBrowseNew() {|n| DbSkipper(n) } {|| DbGoTop() } {|| DbGoBottom() }

WITH OBJECT oTBrowse FOR EACH cField IN aFields :addColumn( TBColumnNew( cField, FieldBlock( cField ) ) ) NEXT END nKey := 0 DO WHILE nKey K_ESC

Function Reference

535

DbSkipper() WITH OBJECT oTBrowse DO WHILE .NOT. :stabilize() ENDDO IF oTBrowse:hitTop Tone(1000) ELSEIF oTBrowse:hitBottom Tone(500) ENDIF nKey := Inkey(0) SWITCH nKey CASE K_UP :up() ; EXIT CASE K_DOWN :down() ; EXIT CASE K_LEFT :left() ; EXIT CASE K_RIGHT :right() ; EXIT CASE K_PGUP :pageUp() ; EXIT CASE K_PGDN :pageDown() ; EXIT CASE K_CTRL_PGUP :goTop() ; EXIT CASE K_CTRL_PGDN :goBottom() ; EXIT CASE K_HOME :home() ; EXIT CASE K_END :end() ; EXIT END END ENDDO CLOSE Customer RETURN

536

Function Reference

DbStruct()

DbStruct() Loads structural information of a database into an array.

Syntax DbStruct() --> aStructure

Return DbStruct() returns a two-dimensional array of four columns, filled with structural information of a database.

Description The DbStruct() function returns a two-dimensional array with FCount() elements. Each element, again, contains a sub-array with four elements holding information about each field of the database open in the current work area. The elements in the sub-arrays can be accessed using #define constants found in the DBSTRUCT.CH file.

Constants for the DbStruct() array Constant

Value

Meaning

DBS_NAME DBS_TYPE DBS_LEN DBS_DEC

1 2 3 4

Field name Field type Field length Field decimals

Info See also: Category: Header: Source: LIB: DLL:

AFields(), COPY STRUCTURE EXTENDED, CREATE FROM, DbCopyStruct(), DbCopyExtStruct(), DbCreate() Database functions DbStruct.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example is the code for a useful command line utility // that lists the database structure in a shell window. #include "DbStruct.ch" PROCEDURE Main( cDbfFile ) LOCAL aStruct IF Empty( cDbfFile ) .OR. .NOT. File( cDbfFile ) CLS ? "Usage: dbstruct.exe " QUIT ENDIF USE (cDbfFile) aStruct := DbStruct()

Function Reference

537

DbStruct() AEval( aStruct, {|a| QOut( PadR( a[DBS_NAME], 10 ), ; a[DBS_TYPE] , ; Str( a[DBS_LEN ], 3 ), ; Str( a[DBS_DEC ], 3 ) ; ) } ) USE RETURN

538

Function Reference

DbTableExt()

DbTableExt() Retrieves the default database file extension of the current RDD.

Syntax DbTableExt() --> cFileExtension

Return The function returns the default extension for database files used by the current RDD as a character string.

Description DbTableExt() returns the extension for database files used by the RDD that opens a database in the current work area. Different RDDs may maintain different default file extensions. They are used when a database file is created or opened and the file name is specified without extension. Note: DbTableExt() does not return the file extension of an open database.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbInfo(), DbOrderInfo(), OrdBagExt(), RddInfo() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

539

DbUnlock()

DbUnlock() Releases file and all record locks in a work area.

Syntax DbUnlock() --> NIL

Return The return value is always NIL.

Description This function releases all locks, i.e. file and record locks, in the current work area. Use an aliased expression to release locks in a different work area. File locks are set with FLock() and are required when multiple records are changed during a single database operation, while record locks are set with RLock() or DbRLock().

Info See also: Category: Source: LIB: DLL:

540

DbRLock(), DbRLockList(), DbUnlockAll(), FLock(), RLock(), UNLOCK Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

DbUnlockAll()

DbUnlockAll() Unlocks all records and releases all file locks in all work areas.

Syntax DbUnlockAll() --> NIL

Return The return value is always NIL.

Description The function iterates over all open work areas and releases file and record locks in each work area. It does the same as function DbUnlock() so that all work areas are processed within one function call.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbRLock(), DbRLockList(), DbUnlock(), FLock(), RLock(), UNLOCK Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

541

DbUseArea()

DbUseArea() Opens a database file in a work area.

Syntax DbUseArea( [] , [] , , [] , [] , [] , [] , []

; ; ; ; ; ; ; ) --> NIL

Arguments

If .T. (true) is passed for , the function selects the next unused work area before the database is opened. The default value is .F. (false), which opens the database in the current work area. If the current work area is used, all files are closed before the new database is opened.

is an optional character string with the name of the RDD to use for opening the database file. It defaults to the return value of RddSetDefault().

This is a character string holding the name of the database file to open. It can include path and file extension. The default file extension is DBF.

This is the symbolic alias name of the work area as a character string. It defaults to the file name of without extension.

Specifying .T. (true) for opens the database in SHARED mode. The default value depends on the SET EXCLUSIVE setting. If set to ON, defaults to .F. (false).

Specifying .T. (true) for opens the database in READONLY mode. The default value is .F. (false) which opens the file for read and write access.

This is a character string specifying the code page to use for character strings stored in the database. It defaults to the return value of HB_SetCodePage().

This parameter is reserved for a numeric server connection handle. This handle can be passed when a database file is opened on a server and the client station has established a connection to the server. 542

Function Reference

DbUseArea()

Return The return value is always NIL.

Description DbUseArea() opens an existing database file named in the current work area, or in the next unused work area when is set to .T. (true). The file is searched in the following directories: first in the current directory, then in the SET DEFAULT directory and finally in all directories specified with SET PATH. If the file cannot be found, a runtime error is raised. When a database is to be accessed in a network, it should be opened in SHARED mode, since EXCLUSIVE usage of a database file prevents other work stations from accessing the file. Shared database access requires to lock a database before changes can be written to a file. Refer to RLock() and FLock() for information about record and file locks in shared database access.

Info See also: Category: Source: LIB: DLL:

CLOSE, DbCloseArea(), RddSetDefault(), Select(), SET DEFAULT, SET PATH, Set(), USE Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example opens a database file using command // and function syntax. REQUEST DBFCDX PROCEDURE Main USE Customer ALIAS Cust NEW ? Alias()

// result: CUST

DbUseArea( .T., "DBFCDX" , "Orders", "Ord" ) ? Alias() // result: ORD CLOSE ALL RETURN

Function Reference

543

DefPath()

DefPath() Returns the SET DEFAULT directory.

Syntax DefPath() --> cDefaultPath

Return The function returns the SET DEFAULT directory as a character string.

Description Function DefPath() queries the SET DEFAULT directory. If SET DEFAULT is not set, a null string ("") is returned

Info See also: Category: Source: LIB: DLL:

544

CurDir(), CurDrive(), SET DEFAULT Directory functions, File functions, xHarbour extensions rtl\defpath.c xhb.lib xhbdll.dll

Function Reference

Deleted()

Deleted() Queries the Deleted flag of the current record

Syntax Deleted() --> lIsDeleted

Return The function returns .T. (true) if the current record is marked for deletion, otherwise .F. (false) is returned.

Description The Deleted() function queries the Deleted flag of the current record. By default, it operates in the current work area. Use an aliased expression to retrieve the flag from a different work area. The Deleted flag is set with function DbDelete() and can be removed with DbRecall(). Whether or not a record carries this flag is the task of the Deleted() function. Note that records marked for deletion are not visible during database navigation when SET DELETED is set to ON.

Info See also: Category: Source: LIB: DLL:

DbRecall(), DbRecordInfo(), DELETE, PACK, RECALL, SET DELETED Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // // // // //

This example uses Deleted() as part of an index expression so that all records carrying the deleted flag appear at the end of a database. This allows for an elegant technique of record recycling when new data must be stored. If a record is Deleted() its data is overwritten, otherwise a new record is appended. PROCEDURE Main USE Customer NEW INDEX ON IIf(Deleted(), Chr(255)+LastName, LastName+Chr(32) ) ; TO Cust01 GO BOTTOM IF Deleted() nRecno := Recno() DbRecall() ELSE APPEND BLANK nRecno := Recno() ENDIF GOTO nRecno

Function Reference

545

Deleted() USE RETURN

546

Function Reference

Descend()

Descend() Converts a value for a descending index.

Syntax Descend( ) --> xDescend

Arguments

An expression whose value must be of data type Character, Date, Logic or Numeric.

Return The function returns the converted value suitable for creating a descending index. The data type is the same as for , except for Date values. The converted value for Dates is of numeric data type.

Description Descend() is a utility function that can be used for the creation of a descending index. The argument passed to Descend() is converted so that the resulting value is sorted logically like the initial value in descending order. Any portion of an index expression can include the Descend() function. This allows for sorting partial index expressions in descending order. Any subsequent SEEK operations must convert the searched value using Descend(). If the entire index should be created in descending order, it is recommended to use the DESCENDING option of the INDEX command. This is advantageous since searched values do not need to be converted with Descend().

Info See also: Category: Source: LIB: DLL:

CtoD(), DbSeek(), DtoC(), DtoS(), INDEX, OrdCondSet(), OrdCreate(), OrdDescend(), SEEK, Str(), Val() Conversion functions rtl\descend.c xhb.lib xhbdll.dll

Example // The example creates a descending index using the Descend() // function and outlines how to search in such an index with SEEK. PROCEDURE Main ? Descend( 789 )

// result: -789

USE Customer NEW INDEX ON Descend(Upper(Lastname)) TO Temp GO TOP ? FIELD->Lastname

// result: Waters

GO BOTTOM ? FIELD->Lastname

// result: Alberts

Function Reference

547

Descend() SEEK Descend( "KELLER" ) ? FIELD->Lastname

// result: Keller

USE RETURN

548

Function Reference

DevOut()

DevOut() Outputs a value to the current device.

Syntax DevOut( , [], [, ] ) --> NIL

Arguments

Any expression whose value should be output to the current output device selected with the SET DEVICE command.

This is an optional SetColor() compliant color string that defines the output color. If omitted, the standard color of the currently selected color string is used. and

Two optional numeric values can be passed that specify the row and column coordinates for output. They default to Row() and Col() for the screen, and PRow() and PCol() for the printer output device.

Return The return value is always NIL.

Description DevOut() is a console function that outputs the value of an expression to the screen or the printer.

Info See also: Category: Source: LIB: DLL:

@...SAY, Col(), DevOutPict(), DevPos(), QOut() | QQOut(), Row(), SET DEVICE, SetPos() Output functions rtl\console.c xhb.lib xhbdll.dll

Example // The example shows the output of a value with // DevOut() and with the command @...SAY: PROCEDURE Main DevOut( "xHarbour compiler", "W+/R", MaxRow(), 2

)

@ MaxRow(), 2 SAY "xHarbour compiler" COLOR "W+/R" RETURN

Function Reference

549

DevOutPict()

DevOutPict() Outputs a PICTURE formatted value to the current device.

Syntax DevOutPict( , [,] ) --> NIL

Arguments

Any expression whose value should be output to the current output device selected with the SET DEVICE command.

A character string holding a PICTURE format which specifies how to format the value of for output. Refer to Transform() for picture formats.

This is an optional SetColor() compliant color string that defines the output color. If omitted, the standard color of the currently selected color string is used.

Return The return value is always NIL.

Description DevOutPict() is a console function that outputs the value of any expression using a picture transformation rule instead of using the default transformation for the type of .

Info See also: Category: Source: LIB: DLL:

@...SAY, Col(), DevOut(), DevPos(), QOut() | QQOut(), Row(), SET DEVICE, SetPos(), Transform() Output functions rtl\devoutp.prg xhb.lib xhbdll.dll

Example // Output a negative dollar amount using debit notation. PROCEDURE Main DevOutPict( -12.45, "@X $ 99,999.99" )

// result: $

12.45 DB

RETURN

550

Function Reference

DevPos()

DevPos() Moves the cursor or printhead to a row and column coordinate

Syntax DevPos( , ) --> NIL

Arguments @ ,

The parameters are numeric values specifying the row and column coordinates for output. The range for rows on the screen is 0 to MaxRow(), and for columns it is 0 to MaxCol(). The coordinate 0,0 is the upper left corner of the screen. When SET DEVICE TO PRINTER is active, the largest coordinate for both, row and column, is 32766.

Return The return value is always NIL.

Description The DevPos() function accepts numeric row and column coordinates and positions the screen cursor or printhead accordingly. Coordinates begin at point 0, 0 which is the upper left corner of the screen, or paper. When SET DEVICE is set to SCREEN, DevPos() moves the screen cursor to the specified coordinates and updates Row() and Col(). If the current device is the PRINTER, DevPos() moves the printhead to the new row and column coordinate, taking any SET MARGIN setting into account. In addition, the current printhead position as reported by PRow() and PCol() is considered. That is, if id smaller than PRow(), a formfeed (Chr(12)) is sent to the printer causing the printhead be positioned on a new page. If is smaller than PCol(), the printhead is positioned on a new line. Notes: use SetPrc() to adjust the internal counters of PRow() and PCol() if required. When printer output is redirected to a file, DevPos() output is recorded in that file.

Info See also: Category: Source: LIB: DLL:

Function Reference

@...SAY, Col(), DevOut(), PCol(), PRow(), QOut() | QQOut(), ROW(), SET DEVICE, SetPos(), SetPrc() Output functions rtl\console.c xhb.lib xhbdll.dll

551

DirChange()

DirChange() Changes the current directory.

Syntax DirChange( ) --> nOSError

Arguments

A character expression specifying the directory to select as the current directory. The directory may include a drive letter followed by a colon.

Return The function returns a numeric value representing the operating system error code (DOS error). A value of 0 indicates a successful operation.

Description The function attempts to change the current directory to the one specified with . If this operation fails, the function returns the OS error code indicating the reason for failure. See the FError() function for a description of OS errors.

Info See also: Category: Source: LIB: DLL:

DirRemove(), DiskChange(), DiskName(), FError(), IsDisk(), MakeDir() Directory functions, File functions rtl\dirdrive.c xhb.lib xhbdll.dll

Example // The example changes to existing and non-existing directories. PROCEDURE Main LOCAL cCurDir := CurDrive() + ":\" + CurDir() ? DirChange( "c:\temp" )

// result: 0

? DirChange( ".\data" )

// result: 2

? DirChange( cCurDir )

// result: 0

RETURN

552

Function Reference

Directory()

Directory() Loads file and directory information into a two-dimensional array.

Syntax Directory( , [] ) --> aDirectory

Arguments

This is a character string holding the drive, directory and/or file specification to retrieve information for. It defaults to the string "*.*" which retrieves all avalable information from the operating system.

Optionally, a character string holding file attributes can be specified. Information about files carrying these attributes is retrieved. One or more characters of the table below can be included in .

Attributes for Directory() Attribute

Meaning

D H S V

Include directories Include hidden files Include system files Search for the DOS volume label and exclude all other files

Return The function returns a two-dimensional array holding information about files that match . If no matching file is found, or if an error occurs, the return value is an empty array.

Description The Directory() function is used to collect file and/or directory information in a two dimensional array of five columns. Each column can be accessed using #define constants from the DIRECTRY.CH file.

Constants for the Directory() array Constant

Position

Description

Data type

F_NAME F_SIZE F_DATE F_TIME F_ATTR

1 2 3 4 5

File name File size in bytes Creation date Creation time File attributes

Character Numeric Date Character Character

Note that can include wild card characters to specify a group of files.

Function Reference

553

Directory()

Info See also: Category: Header: Source: LIB: DLL:

ADir(), AEval(), CurDir(), DirChange(), DirectoryRecurse(), DirRemove(), File(), FileStats(), IsDirectory(), MakeDir() Directory functions, File functions Directry.ch rtl\direct.c xhb.lib xhbdll.dll

Example // The example first retrieves information about a group of files and // then the volume information of the C: drive #include "Directry.ch" PROCEDURE Main LOCAL aDir aDir := Directory( "*.prg" ) AEval( aDir, {|a| QOut( a[F_NAME] ) } ) aDir := Directory( "C:", "V" ) AEval( aDir[1], {|x| QOut( x ) } ) RETURN

554

Function Reference

DirectoryRecurse()

DirectoryRecurse() Loads file information recursively into a two-dimensional array.

Syntax DirectoryRecurse( , [] ) --> aDirectory

Arguments

This is a character string holding the drive, directory and/or file specification to retrieve information for. It defaults to the string "*.*" which retrieves all avalable information from the operating system.

Optionally, a character string holding file attributes can be specified. Information about files carrying these attributes is retrieved. One or more characters of the table below can be included in .

Attributes for Directory() Attribute

Meaning

D H S V

Include directories Include hidden files Include system files Search for the DOS volume label and exclude all other files

Return The function returns a two-dimensional array holding information about files that match in the current directory and its sub-directories. If no matching file is found, or if an error occurs, the return value is an empty array.

Description The DirectoryRecurse() function is used in the same way as the Directory(). The only difference is that DirectoryRecurse() scans all sub-directories in addition to the directory specified with . The result is a two dimensional array of five columns. Each column can be accessed using #define constants from the DIRECTRY.CH file.

Constants for the Directory() array Constant

Position

Description

Data type

F_NAME F_SIZE F_DATE F_TIME F_ATTR

1 2 3 4 5

File name File size in bytes Creation date Creation time File attributes

Character Numeric Date Character Character

Note that can include wild card characters to specify a group of files.

Function Reference

555

DirectoryRecurse()

Info See also: Category: Header: Source: LIB: DLL:

ADir(), AEval(), CurDir(), DirChange(), Directory(), DirRemove(), File(), FileStats(), IsDirectory(), MakeDir() Directory functions, File functions, xHarbour extensions Directry.ch rtl\direct.c xhb.lib xhbdll.dll

Example // The example collects file in formation about PRG files in the // current directory and its sub-directories, and writes the result // to a file. PROCEDURE Main LOCAL aFiles SET ALTERNATE TO PrgFiles.txt SET ALTERNATE ON aFiles := DirectoryRecurse( "*.prg" ) AEval( aFiles, {|a| QOut( ValToPrg( A ) ) } ) SET ALTERNATE OFF SET ALTERNATE TO RETURN

556

Function Reference

DirRemove()

DirRemove() Removes a directory.

Syntax DirRemove( ) --> nOSError

Arguments

A character expression specifying the directory to remove. The directory may include a drive letter followed by a colon.

Return The function returns a numeric value representing the operating system error code (DOS error). A value of 0 indicates a successful operation.

Description The function attempts to remove the directory specified with . If this operation fails, the function returns the OS error code indicating the reason for failure. See the FError() function for a description of OS errors.

Info See also: Category: Source: LIB: DLL:

CurDir(), DirChange(), Directory(), IsDisk(), DiskChange(), DiskName(), MakeDir(), FError() Directory functions, File functions rtl\dirdrive.c xhb.lib xhbdll.dll

Example // The example creates and deletes directories and outlines possible // error conditions. PROCEDURE Main ? CurDrive()+":\"+CurDir()

// result: C:\xhb\tests

? MakeDir( "C:\Temp\Data" )

// result: 0

? DirRemove( "Data" )

// result: 2

? DirRemove( "C:\Temp\data" ) // result: 0 ? DirRemove( "C:\temp" ) RETURN

Function Reference

// result: 145

557

DiskChange()

DiskChange() Changes the current disk drive.

Syntax DiskChange( ) --> lSuccess

Arguments

This is a single character (A-Z) specifying the disk drive to select as current drive.

Return The funtion returns .T. (true) if the drive is selected as current drive, otherwise .F. (false) is returned.

Description The function attempts to change the current disk drive and returns .T. (true) when the operation is successful. Note: DiskChange() uses operating system functionalities. If a disk drive exists but has no disk inserted, the operating system prompts the user for inserting a disk. To suppress this behavior, call SetErrorMode() and pass 1 to it.

Info See also: Category: Source: LIB: DLL:

CurDrive(), CurDir(), DirChange(), DiskSpace(), IsDisk(), SetErrorMode() Directory functions, File functions, xHarbour extensions rtl\dirdrive.c xhb.lib xhbdll.dll

Example // The example demonstrates basic usage of DiskChange() and // includes a user defined function that queries disk drives. PROCEDURE Main LOCAL aDisk, cDisk ? CurDrive() ? CurDir()

// result: C // result: xhb\tests

? DiskChange( "D" )

// result: .T.

? CurDrive() ? CurDir()

// result: D // result: apps\data

? DiskChange( "K")

// result: .F.

? CurDrive() ? CurDir()

// result: D // result: apps\data

aDisk := GetDrives()

558

Function Reference

DiskChange() FOR EACH cDisk IN aDisk ? cDisk END RETURN FUNCTION LOCAL LOCAL LOCAL

GetDrives() cDrive := CurDrive() aDrives := {} nDrive := 1

FOR nDrive := 1 TO 26 IF DiskChange( Chr( 64 + nDrive ) ) AAdd( aDrives, Chr( 64 + nDrive ) ) ENDIF NEXT DiskChange( cDrive ) RETURN aDrives

Function Reference

559

DiskName()

DiskName() Returns the current disk drive.

Syntax DiskName() --> cDrive

Return The return value is a single character specifying the current disk drive.

Description The function is used to retrieve the drive letter of the current disk drive.

Info See also: Category: Source: LIB: DLL:

CurDrive(), CurDir(), DiskChange(), DiskSpace(), IsDisk() Directory functions, File functions rtl\dirdrive.c xhb.lib xhbdll.dll

Example // The example queries and changes the current disk drive PROCEDURE Main ? DiskName() ? DiskChange( "D" ) ? DiskName() RETURN

560

// result: C // result: .T. // result: D

Function Reference

DiskSpace()

DiskSpace() Returns the free storage space for a disk drive.

Syntax DiskSpace( [], [] ) --> nBytes

Arguments

The drive to query for free disk space is specified as a numeric value in the range of 1 (drive A:) to 26 (drive Z:). Omitting or passing 0 returns the disk space avalable on the current drive.

Optionally, the type of storage space on a drive to query can be specified using #define constants from the FILEIO.CH file. Valid constants are listed below:

Storage space types for DiskSpace() Constant

Value

Description

HB_DISK_AVAIL *) HB_DISK_FREE HB_DISK_USED HB_DISK_TOTAL *) default

0 1 2 3

Free disk space avialable to the application Total free disk space Used disk space Total disk space

Return The function returns a numeric value indicating the storage space of a disk drive. If no parameters are passed, DiskSpace() returns the free disk space on the current drive that is available to the application.

Description DiskSpace() determines free and used bytes on a disk drive. Some operating systems distinguish between total free bytes on disk and free bytes that are avalaible to the current user, or application. If the current operating system makes no such distinction, HB_DISK_AVAIL and HB_DISK_FREE yield the same results. Note: if information is requested on a disk that is not available, a runtime error 2018 is generated.

Function Reference

561

DiskSpace()

Info See also: Category: Header: Source: LIB: DLL:

Directory(), DiskName(), File(), FOpen(), FSeek(), IsDisk(), LastRec(), LUpdate(), RecCount(), RecSize() Directory functions, File functions fileio.ch rtl\diskspac.c xhb.lib xhbdll.dll

Example // The example lists two disk storage types for all drives taking // advantage of the runtime error created for unaccessible drives. #include "Fileio.ch" PROCEDURE Main LOCAL i, bError := ErrorBlock( {|e| Break(e) } ) FOR i:=1 TO 26 BEGIN SEQUENCE ? "Drive",Chr(64+i)+":", DiskSpace( i, HB_DISK_FREE ), ; DiskSpace( i, HB_DISK_TOTAL) RECOVER ?"Drive",Chr(64+i)+":", "not ready or not existent" END SEQUENCE NEXT ErrorBlock( bError ) RETURN

562

Function Reference

DispBegin()

DispBegin() Initiates buffering of console window output.

Syntax DispBegin() --> NIL

Return The return value is always NIL.

Description The DispBegin() function is used to buffer a series of commands and/or functions that produce output on the the screen (console window). The display becomes visible when DispEnd() is called. DispBegin() starts collecting screen output in an internal buffer so that complex output can be produced in a series of function calls. The result of individual function is not displayed, only the entire screen buffer is made visible when DispEnd() is called. Buffered screen output can result in a considerable performance increase. Note that DispBegin() calls can be nested, i.e. DispBegin() can be called repeatedly without calling DispEnd(). To make the buffered display visible, however, DispEnd() must be called as many times as DispBegin() is called. Buffered screen output becomes only visible after a matching number of DispEnd() calls. The number of pending DispEnd() calls can be obtained from function DispCount().

Info See also: Category: Source: LIB: DLL:

DispCount(), DispEnd(), DispOut() Screen functions rtl\gt.c xhb.lib xhbdll.dll

Example // The example uses buffered screen output to give the impression of // a box moving behind another box that stays in front. #include "Box.ch" PROCEDURE Main LOCAL cFront, nT:= 0, nL:= 0, nB:= 3, nR:= 30 CLS // display initial box in front DispBox( 8, 12, 18, 52, B_SINGLE+" ", "W+/B" ) DispOut( "I am in front" ) DO WHILE nT < 22 // buffered screen output displays second box // behind box in front. DispBegin()

Function Reference

563

DispBegin() cFront := SaveScreen(8,12,18,52) DispBox( nT, nL, nB, nR, B_DOUBLE+" ", "N/W*") DispOut( "I am moving behind a box" ) RestScreen( 8, 12, 18, 52, cFront ) DispEnd() Inkey(0.1) // buffered screen output erases moving box DispBegin() Scroll( nT, nL, nB, nR ) RestScreen( 8, 12, 18, 52, cFront ) DispEnd() // new coordinates for moving box nT++ ; nL++ ; nB++ ; nR++ ENDDO RETURN

564

Function Reference

DispBox()

DispBox() Displays a box on the screen.

Syntax DispBox( , , , , ; [] , [] ) --> NIL

Arguments and

Numeric values indicating the screen coordinates for the upper left corner of the DispBox() output. and

Numeric values indicating the screen coordinates for the lower right corner of the DispBox() output.

The appearance of the box to display can either be specified as numeric 1 (single line box), numeric 2 (double line box), or as a character string holding up to nine characters. The first eight characters define the border of the box while the ninth character is used to fill the box. #define constants to be used for are available in the BOX.CH #include file.

Pre-defined box strings for DispBox() Constant

Description

B_SINGLE B_DOUBLE B_SINGLE_DOUBLE B_DOUBLE_SINGLE

Single-line box Double-line box Single-line top, double-line sides Double-line top, single-line sides

If no is specified, a single-line box is drawn.

An optional SetColor() compliant color string can be specified to draw the box. It defaults to the standard color of SetColor().

Return The return value is always NIL.

Description The function DispBox() displays a box on the screen as specified with , using the standard color of SetColor() or , if specified. If a character string is used for , the first eight characters define the border of the box in clockwise direction, beginning with the upper left corner. An optional ninth character fills the area inside the box. Alternatively, a single character can be passed which is used to draw the entire box border. Function Reference

565

DispBox()

When the box is completely drawn, the cursor is positioned at the coordinates +1 and +1, so that a subsequent DispOut() call starts displaying in the upper left corner of the box area.

Info See also: Category: Header: Source: LIB: DLL:

@...BOX, @...CLEAR, @...TO, Scroll(), SetColor() Screen functions box.ch rtl\box.c xhb.lib xhbdll.dll

Example // The example demonstrates how characters are used to draw a box. // Alphabetic characters define instead of characters // holding graphic signs. #include "Box.ch" PROCEDURE Main CLS DispBox( 10,10,20,50, "AbCdEfGhi", "W+/R" ) Inkey(0) DispBox( 10,10,20,50, B_DOUBLE + Space(1) ) DispOut( "Using #define constant" ) @ MaxRow(),0 RETURN

566

Function Reference

DispCount()

DispCount() Retrieves the number of pending DispEnd() calls.

Syntax DispCount() --> nDispCount

Return The function returns a numeric value indicating how often DispEnd() must be called to make buffered screen output visible.

Description DispCount() is used to determine the number of DispEnd() calls required with nested DispBegin() calls. Buffered screen output becomes only visible, when the number of DispEnd() calls matches exactly with the number of DispBegin() calls.

Info See also: Category: Source: LIB: DLL:

DispBegin(), DispEnd(), DispOut() Screen functions rtl\gt.c xhb.lib xhbdll.dll

Example // The example uses a typical coding pattern for DispCount() that // forces buffered screen output to become visible. DO WHILE DispCount() > 0 DispEnd() ENDDO

Function Reference

567

DispEnd()

DispEnd() Displays buffered screen output.

Syntax DispEnd() --> NIL

Return The return value is always NIL.

Description DispEnd() terminates buffered screen output initiated with a call to DispBegin() and makes the buffered output visible. DispEnd() must be called as many times as DispBegin(). This is important for nested DispBegin() calls.

Info See also: Category: Source: LIB: DLL:

DispBegin(), DispCount(), DispOut() Screen functions rtl\gt.c xhb.lib xhbdll.dll

Example // see the example for DispBegin()

568

Function Reference

DispOut()

DispOut() Displays a value on the screen

Syntax DispOut( , [] ) --> NIL

Arguments

Any expression whose value should be output to the screen.

An optional SetColor() compliant color string can be specified for display. It defaults to the standard color of SetColor().

Return The return value is always NIL.

Description The DispOut() function displays the value of at the current cursor position on the screen, using the color , if specified. DispOut() ignores the SET DEVICE setting and sends output always to the screen.

Info See also: Category: Source: LIB: DLL:

Col(), DevOut(), DispBegin(), DispCount(), DispEnd(), DispOutAt(), OutStd(), QOut() | QQOut(), Row(), SetPos() Output functions, Screen functions rtl\console.c xhb.lib xhbdll.dll

Example // The example changes the current cursor position and displays // two strings using different colors. PROCEDURE Main CLS SetPos( 10, 20 ) DispOut( "xHarbour", "W+/R" ) DispOut( "compiler", "W+/G" ) RETURN

Function Reference

569

DispOutAt()

DispOutAt() Displays a value on the screen at a certain position.

Syntax DispOutAt( , , , [] , []

; ; ; ; ) --> NIL

Arguments

This is a numeric value specifying the row on the screen where the value of is displayed.

This is a numeric value specifying the column on the screen where the value of is displayed.

Any expression whose value should be output to the screen.

An optional SetColor() compliant color string can be specified for display. It defaults to the standard color of SetColor().

An optional logical value specifies whether or not to update the screen cursor position after display. .T. (true) updates the cursor position and .F. (false) leaves the cursor position unchanged. The default is the return value of function DispOutAtSetPos().

Return The return value is always NIL.

Description The DispOutAt() function displays the value of at the specified cursor position on the screen, using the color . The position of the screen cursor after display depends on parameter .

570

Function Reference

DispOutAt()

Info See also: Category: Source: LIB: DLL:

Col(), DispBegin(), DispCount(), DispEnd(), DispOut(), DispOutAtSetPos(), Row(), SetPos() Output functions, Screen functions, xHarbour extensions rtl\console.c xhb.lib xhbdll.dll

Example // The example uses background processing for displaying the time // continuously without changing the cursor position while Browse() // is active. PROCEDURE Main LOCAL nIdle, bTask, nTask SET BACKGROUND TASKS ON bTask := {|| DispoutAt( 0, MaxCol()-7, Time(), "W+/B", .F. ) } nTask := HB_BackGroundAdd( bTask, 1000 ) nIdle := HB_IdleAdd( {|| HB_BackGroundRun() } ) USE Customer Browse() USE HB_BackGroundDel( nTask ) HB_IdleDel( nIdle ) RETURN

Function Reference

571

DispOutAtSetPos()

DispOutAtSetPos() Toggles update of the screen cursor with DispOutAt().

Syntax DispOutAtSetPos( [] ) --> lOldSetting

Arguments

This is a logical value which can change the current setting.

Return The function returns the old setting.

Description DispOutAtSetPos() defines the default value for the fifth parameter of function DispoutAt().

Info See also: Category: Source: LIB: DLL:

572

DispOutAt(), SetPos() Output functions, Screen functions, xHarbour extensions rtl\console.c xhb.lib xhbdll.dll

Function Reference

DllCall()

DllCall() Executes a function located in a dynamically loaded external library.

Syntax DllCall( |, [] , | , []

; ; ; ) --> nResult

Arguments

A character string holding the name of the DLL file where the function is located. This is an external DLL, not created by xHarbour. If a character string is passed for , it must contain complete path information, unless the file is located in the current directory, or in the list of directories held in the SET PATH environment variable of the operating system.

Alternatively, the first parameter can be a numeric DLL handle as returned by function LoadLibrary().

The calling convention to use for the DLL function can optionally be specified. Constants are available for this parameter.

Calling conventions Constant

Value

Description

DC_CALL_CDECL DC_CALL_STD *) *) default

0x0010 0x0020

C calling convention (__cdecl) Standard convention for WinAPI (__stdcall)



This is a character string holding the symbolic name of the function to call. Unlike regular xHarbour functions, this function name is case sensitive.

Instead of the symbolic function name, the numeric ordinal position of the function inside the DLL file can be passed. This is, however, not recommended, since ordinal positions of functions may change between DLL versions.

The values of all following parameters specified in a comma separated list are passed on to the DLL function.

Return The function returns the result of the called DLL function as a numeric value.

Function Reference

573

DllCall()

Description Function DllCall() can be used to execute functions located in DLL files which are not created by the xHarbour compiler and linker. This allows for executing functions residing in system DLLs of the operating system or Third Party producers, for example. The DLL that contains a function is either specified by its numeric DLL handle, or by its symbolic file name. In the latter case, DllCall() loads the library, executes the function and frees the library when the function has returned. When a numeric DLL handle is specified, the DLL is already loaded by LoadLibrary(), and it remains loaded when the DLL function is complete. The DLL must then be released explicitely with FreeLibrary(). When more than three parameters are specified, all are passed on to the DLL function. However, since xHarbour has its own data types and more of them are available than in the C language, only values of a restricted number of data types can be passed. The values are converted to corresponding C data types.

Data type conversion PRG level

C level

Character C structure Date Logical NIL Numeric - Integer - Decimal number Pointer

*char *void DWORD DWORD ( DWORD ) NULL DWORD double *void

If other xHarbour data types are passed to DllCall(), a runtime error is generated. Note: many Windows API functions are available as a Unicode and an Ansi version. If this is the case, DllCall() uses the Ansi version of the WinAPI function.

Info See also: Category: Source: LIB: DLL:

DllExecuteCall(), DllPrepareCall(), FreeLibrary(), GetProcAddress(), GetLastError(), LoadLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Example // // // // // //

The example outlines how a Windows API function can be wrapped within an xHarbour function without reverting to xHarbour's extend API. The GetVolumeInformation() wrapper obtains only the volume name and serial number. Other information available from the WinAPI function is ignored. Note that the "out" parameters of the API must be passed by reference to DllCall(). #define DC_CALL_STD #define MAX_PATH

0x0020 260

PROCEDURE Main LOCAL cDrive := "D:\"

574

Function Reference

DllCall() LOCAL cVolName, cVolSerial cVolName := GetVolumeInformation( cDrive, @cVolSerial ) ? cVolName

// result: BACKUP

? cVolSerial RETURN

FUNCTION LOCAL LOCAL LOCAL

// result: 584C:2AE1

GetVolumeInformation( cVolume, cSerial ) cVolumeName := Replicate( Chr(0), MAX_PATH+1 ) nNameSize := Len( cVolumeName ) nResult

cSerial := U2Bin(0) nResult := DllCall( "Kernel32.dll" DC_CALL_STD "GetVolumeInformation" cVolume @cVolumeName nNameSize @cSerial 0 0 0 0

, , , , , , , , , ,

; // * C prototype * ; ; // DLL to call ; // calling vonvention ; // BOOL GetVolumeInformation( ; // LPCTSTR lpRootPathName , ; // LPTSTR lpVolumeNameBuffer , ; // DWORD nVolumeNameSize , ; // LPDWORD lpVolumeSerialNumber , ; // LPDWORD lpMaximumComponentLength , ; // LPDWORD lpFileSystemFlags , ; // LPTSTR lpFileSystemNameBuffer , ) // DWORD nFileSystemNameSize )

// format serial number as FFFF:FFFF cSerial := NumToHex( Bin2U(cSerial), 8 ) cSerial := Stuff( cSerial, 5, 0, ":" ) RETURN Left( cVolumeName, At( Chr(0), cVolumeName ) - 1 )

Function Reference

575

DllExecuteCall()

DllExecuteCall() Executes a DLL function via call template.

Syntax DllExecuteCall( , [] ) --> nResult

Arguments

This is a pointer to the template for calling the DLL function. It is returned from function DllPrepareCall().

This is a comma separated list of parameters which are passed to the DLL function to call.

Return The function returns the result of the executed DLL function as a numeric value.

Description Function DllExecuteCall() executes a DLL function using the call template as it is prepared by function DllPrepareCall(). The DllPrepareCall()/DllExecuteCall() way of calling a function in an external DLL is advantageous when the same DLL function must be executed many times. The call template is prepared once and contains all information required to execute the DLL function. If a DLL function needs to be called only once or a few times, it can be called directly via DllCall(). The overhead of preparing the call template can be avoided in such cases.

Info See also: Category: Source: LIB: DLL:

DllCall(), DllPrepareCall(), FreeLibrary(), GetProcAddress(), GetLastError(), LoadLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Example // // // //

The example implements two Windows API wrappers for conversion of Ansi strings to Unicode and vice versa. The call templates for DllExecuteCall() are created on the first function call and stored in STATIC variables. #define DC_CALL_STD

0x0020

PROCEDURE Main LOCAL cString, cWideString cString := "Hello World" cWideString := AnsiToWide( cString ) ? Len( cString ), cString ? Len( cWideString ), cWideString

576

Function Reference

DllExecuteCall() ? WideToAnsi( cWideString ) RETURN

FUNCTION AnsiToWide( cString ) STATIC pCallTemplate LOCAL nWideLen := 2 * ( Len( cString ) ) LOCAL cWideChar := Replicate( Chr(0), nWideLen ) LOCAL nRet IF pCallTemplate == NIL // create call template on first call pCallTemplate := DllPrepareCall( ; "Kernel32.dll", ; // external DLL DC_CALL_STD , ; // calling convention "MultiByteToWideChar" ) // external function ENDIF nRet := DllExecuteCall( pCallTemplate 0 0 cString -1 @cWideChar nWideLen RETURN cWideChar

, , , , , ,

; ; ; ; ; ; ; )

FUNCTION WideToAnsi( cWideChar ) STATIC pCallTemplate LOCAL nLen := Int( Len( cWideChar ) / 2 ) LOCAL cString := Replicate( Chr(0), nLen ) LOCAL nRet IF pCallTemplate == NIL // create call template on first call pCallTemplate := DllPrepareCall( ; "Kernel32.dll", ; // external DLL DC_CALL_STD , ; // calling convention "WideCharToMultiByte" ) // external function ENDIF nRet := DllExecuteCall( pCallTemplate 0 0 cWideChar -1 @cstring nLen 0 0 RETURN cString

Function Reference

, , , , , , , ,

; ; ; ; ; ; ; ; ; )

577

DllLoad()

DllLoad() Loads a DLL file into memory.

Syntax DllLoad( ) --> nDllHandle

Arguments

This is a character string holding the name of the DLL file to load into memory.

Return The function returns a numeric DLL handle > 0. If the DLL file cannot be loaded, the return value is zero.

Description Function DllLoad() is a synonym for function LoadLibrary(). Refer to LoadLibrary().

Info See also: Category: Source: LIB: DLL:

578

LoadLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Function Reference

DllPrepareCall()

DllPrepareCall() Creates a call template for an external DLL function.

Syntax DllPrepareCall( |, ; [] , ; | ) --> pCallTemplate

Arguments

A character string holding the name of the DLL file where the function is located. This is an external DLL, not created by xHarbour. If a character string is passed for , it must contain complete path information, unless the file is located in the current directory, or in the list of directories held in the SET PATH environment variable of the operating system.

Alternatively, the first parameter can be a numeric DLL handle as returned by function LoadLibrary().

The calling convention to use for the DLL function can optionally be specified. Constants are available for this parameter.

Calling conventions Constant

Value

Description

DC_CALL_CDECL DC_CALL_STD *) *) default

0x0010 0x0020

C calling convention (__cdecl) Standard convention for WinAPI (__stdcall)



This is a character string holding the symbolic name of the function to call. Unlike regular xHarbour functions, this function name is case sensitive.

Instead of the symbolic function name, the numeric ordinal position of the function inside the DLL file can be passed. This is, however, not recommended, since ordinal positions of functions may change between DLL versions.

Return The function returns a pointer to the call template for the specified DLL function.

Description Function DllPrepareCall() prepares a call template which contains all information required to invoke a DLL function, except for the parameters to pass. The call template is then passed along with the parameters to function DllExecuteCall() which executes the DLL function (see DllExecuteCall() for a complete example). Function Reference

579

DllPrepareCall()

The preparation of a call template is advantageous when a DLL function must be called many times, since the information assembled in the call template is the same for multiple DLL function calls. If a DLL function needs to be called only once or a few times, it can be executed via DllCall() since the extra overhead of the call template preparation is not justified in such case. Important: the call template must not be changed.

Info See also: Category: Source: LIB: DLL:

580

DllExecuteCall(), FreeLibrary(), GetProcAddress(), GetLastError(), LoadLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Function Reference

DllUnload()

DllUnload() Releases a dynamically loaded external DLL from memory.

Syntax DllUnload( ) --> lSuccess

Arguments

This is a numeric handle of the DLL to release as returned from LoadLibrary().

Return The function returns a logical value inidcating a successful operation.

Description Function DllUnload() is a synonym for FreeLibrary(). Refer to FreeLibrary().

Info See also: Category: Source: LIB: DLL:

Function Reference

FreeLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

581

DosError()

DosError() Sets or retrieves the last DOS error code.

Syntax DosError( [] ) --> nOsErrorCode

Arguments

This numeric parameter defines the return value for subsequent DosError() calls.

Return The function returns the last DOS error code as a numeric value.

Description The DosError() function returns an error code of the Disk Operating System (DOS) that is set when a disk, directory or file operation fails. This leads normally to a runtime error, so that DosError() is usually called within error handling routines to test if a DOS error has occured. DosError() retains its value until a new DOS error occurs, or a new return value is defined explicitely with . The return value of DosError() is set to zero after each successful DOS operation. The following table gives an overview of some DOS error codes together with their meaning.

Disk Operating System (DOS) error codes

582

Error

Description

1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19 20 21 22 23 24 25 26 27

Invalid function number File not found Path not found Too many open files (no handles left) Access denied Invalid handle Memory control blocks destroyed Insufficient memory Invalid memory block address Invalid environment Invalid format Invalid access code Invalid data Invalid drive was specified Attempt to remove the current directory Not same device No more files Attempt to write on write-protected media Unknown unit Drive not ready Unknown command Cyclic redundancy check (CRC) -- part of diskette is bad Bad request structure length Seek error Unknown media type Sector not found Function Reference

DosError() 28 29 30 31 32 33 34 35 36 38 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 80 82 83 84 85 86 87 88 89 90

Printer out of paper Write fault Read fault General failure Sharing violation Lock violation Invalid disk change FCB unavailable Sharing buffer overflow Unable to complete the operation Network request not supported Remote computer not listening Duplicate name on network Network path not found Network busy Network device no longer exists NETBIOS command limit exceeded System error, NETBIOS error Incorrect response from network Unexpected network error Incompatible remote adapter Print queue full Not enough space for print file Print file was cancelled Network name was denied Access denied Network device type incorrect Network name not found Network name limit exceeded NETBIOS session limit exceeded Sharing temporarily paused Network request not accepted Print or disk redirection is paused File exists Cannot make directory entry Fail on INT 24 Too many redirections Duplicate redirection Invalid password Invalid parameter Network data fault Function not supported by network Required system component not installed

Info See also: Category: Source: LIB: DLL:

BEGIN SEQUENCE, ErrorBlock(), FError(), TRY...CATCH Error functions vm\errorapi.c xhb.lib xhbdll.dll

Example // The example shows how to catch a "file not found" error // using DosError() within a TRY...CATCH error handling structure.

Function Reference

583

DosError() PROCEDURE Main LOCAL oError DosError(55)

// sets current DOS error code

TRY ? DosError()

// result: 55

USE xyz NEW

// create DOS error

CATCH oError IF DosError() == 2 ? "File not found:", oError:fileName QUIT ENDIF END RETURN

584

Function Reference

DoW()

DoW() Determines the numeric day of the week from a date.

Syntax DoW( ) --> nDayOfWeek

Arguments

The parameter must be a value of data type Date.

Return The function returns the numeric day of the week or 0 for an empty date.

Description DoW() calculates the numeric day of the week from a Date value. Weekdays are numbered from One to Seven, with Sunday being 1 and Saturday being 7.

Info See also: Category: Source: LIB: DLL:

CDow(), CtoD(), Date(), Day(), DtoC(), DtoS(), SET CENTURY, SET DATE, StoD(), Transform() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example illustrates CDoW() and Dow() return values. PROCEDURE Main LOCAL dDate := CtoD( "01/01/2006" ) ? CDoW( dDate ) ? DoW ( dDate ) ? CDoW( dDate+4 ) ? DoW ( dDate+4 ) RETURN

Function Reference

// result: Sunday // result: 1 // result: Thursday // result: 5

585

DtoC()

DtoC() Converts a Date value to a character string in SET DATE format.

Syntax DtoC( )

--> cDateString

Arguments

The parameter must be a value of data type Date.

Return The return value is a character string formatted in the current SET DATE format.

Description The function converts a Date value to a character string. The string is formatted according to the current SET DATE format. The default date format is "MM/DD/YY". Important: use DtoC() and its counterpart CtoD() with extreme care. The result of both functions depends on the current SET DATE and SET EPOCH format.

Info See also: Category: Source: LIB: DLL:

CtoD(), Date(), DtoS(), SET CENTURY, SET DATE, SET EPOCH, StoD(), Transform() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example creates a date format independent Date value and // outlines a common problem with date to string conversions. The // last CtoD() call yields a date in October instead of January. PROCEDURE Main LOCAL dDate := StoD( "20060110" ) // 10th of January, 2006 LOCAL cDate // use default date format ? cDate := DtoC( dDate ) // result: 01/10/06 SET DATE ITALIAN

// select Italian date format

? DtoC( dDate )

// result: 10-01-06

SET CENTURY ON SET EPOCH TO 2000 ? DtoC( dDate )

? CtoD( cDate ) RETURN

586

// result: 10-01-2006 // CAUTION: date format mismatch // result: 01-10-2006

Function Reference

DtoS()

DtoS() Converts a Date value to a character string in YYYYMMDD format.

Syntax DtoS( ) --> cYYYYMMDD

Arguments

The parameter must be a value of data type Date.

Return The return value is a character string in YYYYMMDD format. DtoS() returns Space(8) for an empty date.

Description This function converts a Date value to a character string that is independent from the settings SET CENTURY, SET DATE and SET EPOCH. Therefore, DtoS() and its counterpart StoD() are the recommended Date to Character string conversion functions, unless a Date value must be output in a country specific format. When Date fields are combined with Character fields in an index expression, use DtoS() to concatenate the Date field with the Character field. This ensures that the Date field is sorted in chronological order.

Info See also: Category: Source: LIB: DLL:

CtoD(), Date(), DtoC(), INDEX, StoD() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example illustrates sorting of date formatted character strings // and how it is influenced by the date format. PROCEDURE Main LOCAL aDate := { StoD( "20060209" ), ; StoD( "20060303" ), ; StoD( "20060106" ) } SET DATE TO ITALIAN

// dd-mm-yyyy

// using DtoC() ASort( aDate,,, {|d1,d2| DtoC( d1 ) < DtoC( d2 ) } ) AEval( aDate, {|d| QOut(Day(d), CMonth(d) ) } ) /* result: 3 March 6 January 9 February */

Function Reference

587

DtoS() // using DtoS() ASort( aDate,,, {|d1,d2| DtoS( d1 ) < DtoS( d2 ) } ) AEval( aDate, {|d| QOut(Day(d), CMonth(d) ) } ) /* result: 6 January 9 February 3 March */ RETURN

588

Function Reference

ElapTime()

ElapTime() Calculates the time elapsed between a start and an end time.

Syntax ElapTime( , ) --> cElapsedTime

Arguments

This is a Time() formatted character string containing the start time to use for the calculation. The time string must be coded using a 24h time format.

A time string containing the end time.

Return The function returns a time-formatted character string holding the duration of the time interval in the format hh:mm:ss.

Description This function returns a string that shows the difference between the starting time represented as and the ending time as . If the starting time is later than the ending time, the function assumes that the end time occured on the next day.

Info See also: Category: Source: LIB: DLL:

Days(), Time(), Secs(), Seconds() Date and time rtl\samples.c xhb.lib xhbdll.dll

Example // The example shows return values of ElapTime() PROCEDURE Main LOCAL cStartTime := "17:30:15" ? ElapTime( cStartTime, "21:45:30" )

// result: 04:15:15

? ElapTime( cStartTime, "07:45:30" ) RETURN

// result: 14:15:15

Function Reference

589

Empty()

Empty() Checks if the passed argument is empty.

Syntax Empty( ) -->

lIsEmpty

Arguments

An expression of any data type whose value is tested for being empty.

Return The function returns .T. (true) when the passed value is empty, otherwise .F. (false).

Description The function tests if an expression yields an empty value. The status "Empty" exists for all data types, except Code block Object and Pointer. It is commonly used to test if a user has entered data into an input field. The following table list empty values:

Data types and their empty values Data type

Valtype()

Description

Array Code block Character Date Hash Logical Memo Numeric Object Pointer NIL

A B C D H L M N O P U

Array with zero elements No empty value Null string and White space characters (CR/LF, Space(), Tabs) Null date (CTOD("")) Hash with zero elements False (.F.) Same as character The value zero No empty value No empty value NIL

Info See also: Category: Source: LIB: DLL:

Len(), Valtype() Logical functions rtl\empty.c xhb.lib xhbdll.dll

Example // The example lists common empty values and outlines few values // that could be considered empty, but which are not.

590

PROCEDURE Main ? Empty( NIL )

// result: .T.

? Empty( 0 )

// result: .T.

Function Reference

Empty() ? Empty( .F. )

// result: .T.

? Empty( CtoD("") )

// result: .T.

? Empty( "" ) ? Empty( "

// result: .T. // result: .T.

? ? ? ? ?

Empty( Empty( Empty( Empty( Empty(

" )

Chr( 0) Chr( 9) Chr(10) Chr(13) Chr(32)

) ) ) ) )

// // // // //

result: result: result: result: result:

.F. .T. .T. .T. .T.

? Empty( {} ) ? Empty( {0} )

// result: .T. // result: .F.

? Empty( {|| NIL } )

// result: .F.

? Empty( {=>} ) RETURN

Function Reference

// result: .T.

591

Eof()

Eof() Determines when the end-of-file is reached.

Syntax Eof() --> lIsEndOfFile

Return The function returns .T. (true) when the record pointer in a work area has reached the end of file, otherwise .F. (false).

Description The Eof() function indicates if the record pointer has reached the logical end-of-file mark during database navigation. The end-of-file mark is a state variable that exists for each work area. Eof() operates in the current work area unless it is used within an aliased expression. The Eof() state of a work area is evaluated each time the record pointer is moved with commands like SKIP, SEEK or LOCATE or their functional equivalents. When Eof() returns .T. (true), this value is retained until the record pointer is moved to a different record, or a new record is appended. Note that Eof() is always .T. (true) when a database has no records, and it returns always .F. (false) when a work area is not in use.

Info See also: Category: Source: LIB: DLL:

Bof(), DbSeek(), DbSkip(), DO WHILE, Found(), GO, LastRec(), LOCATE, RecNo(), SEEK, SKIP Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example illustrates the Eof() state of a work area during // physical and logical record pointer movement. #include "Ord.ch" PROCEDURE Main LOCAL nCount := 0 USE Customer INDEX ON Upper(LastName+FirstName) TO Cust01 ? Eof(), LastName

// result: .F. Alberts

// physical movement of record pointer GOTO 200 ? Eof(), nCount, Recno() // result: .F.

0

200

// logical movement of record pointer DO WHILE .NOT.EoF() SKIP nCount ++

592

Function Reference

Eof() ENDDO // Note: from record #10 we skipped 45 records // to hit end-of-file, and ended up at record #220 // That's because the database is indexed. ? EoF(), nCount, Recno() // result: .T. 220 ? EoF(), Empty(LastName) SKIP 0 ? EoF(), Empty(LastName)

225

// result: .T.

.T.

// result: .T.

.T.

SKIP -1 ? EoF(), LastName

// result: .F.

Waters

SET SCOPETOP TO "G" SET SCOPEBOTTOM TO "M"

// restrict logical navigation // restrict logical navigation

GO BOTTOM ? EoF(), LastName

// result: .F.

SKIP ? EoF(), LastName

// EoF reached due to scope // result: .T. (empty)

Miller

CLOSE Customer RETURN

Function Reference

593

ErrorBlock()

ErrorBlock() Sets or retrieves the error handling code block.

Syntax ErrorBlock( [] ) --> bLastErrorBlock

Arguments

An optional code block can be passed that replaces the current error handling code block. The code block receives as parameter an Error() object containing information about a runtime error.

Return The return value is the currently installed error handling code block.

Description The error code block is part of the runtime error handling system of xHarbour and can be retrieved or defined with the ErrorBlock() function. A default error code block is installed at program startup in the ErrorSys() routine. By default, the error code block is evaluated when a runtime error occurs ouside a TRY...CATCH control structure. An error object is filled with error information by the xHarbour runtime kernel and passed on to the error code block. The error code block can then call a user defined error handling routine, or pass the Error object on to the Break() function, which, in turn, passes the Error object on to the RECOVER option of the BEGIN SEQUENCE statement. If the error code block does not call Break(), its return value must be of logical data type to instruct the error handling system how to proceed with error handling. If .T. (true) is returned, the offending operation is retried, while .F. (false) instructs the error handling system to ignore the error and resume processing. Note: the error code block is part of xHarbour's Clipper compatible error handling system and not recommended to use in new applications. Instead, xHarbour's moder TRY...CATCH error handling control structure provides a modern and more flexible way for programming runtime error recovery.

Info See also: Category: Source: LIB: DLL:

BEGIN SEQUENCE, Break(), ErrorNew(), ErrorSys(), TRY...CATCH Error functions, Debug functions vm\errorapi.c xhb.lib xhbdll.dll

Examples // // // //

This example uses offensive error handling by assuming that index files required for a database exist. If they do not exist, they are created in the RECOVER section of the BEGIN SEQUENCE statement. PROCEDURE Main OpenCustomer()

594

Function Reference

ErrorBlock() ? "Files are open" ? "Program can start" RETURN

PROCEDURE OpenCustomer LOCAL oError, n LOCAL bError := ErrorBlock( {|e| Break(e) } ) FOR n := 1 TO 2 BEGIN SEQUENCE // regular code USE Customer NEW SHARED SET INDEX TO Cust01, Cust02 ErrorBlock( bError ) RECOVER USING oError // error handling code ErrorBlock( bError ) USE Customer NEW EXCLUSIVE INDEX ON CustNo TO Cust01 INDEX ON Upper(LastName+FirstName) TO Cust02 USE // go back to open DBF in SHARED mode LOOP ENDSEQUENCE EXIT NEXT RETURN // This example does the same as the previous one, except that // it uses TRY...CATCH instead of an error code block. PROCEDURE Main OpenCustomer() ? "Files are open" ? "Program can start" RETURN

PROCEDURE OpenCustomer LOCAL n FOR n:=1 TO 2 TRY // regular code USE Customer NEW SHARED SET INDEX TO Cust01, Cust02 CATCH // error recovery USE Customer NEW EXCLUSIVE INDEX ON CustNo TO Cust01 INDEX ON Upper(LastName+FirstName) TO Cust02 USE LOOP END

Function Reference

595

ErrorBlock() EXIT NEXT RETURN

596

Function Reference

ErrorLevel()

ErrorLevel() Sets the exit code of the xHarbour application.

Syntax ErrorLevel( [] ) --> nCurrentExitCode

Arguments

An optional numeric value in the range of 0 to 255 can be passed that replaces the current exit code of the xHarbour application.

Return The function returns a numeric value which is the current exit code of the xHarbour application.

Description The ErrorLevel() function defines or retrieves the exit code of the xHarbour application. The exit code can be viewed as the return value of the application that is passed to the calling process upon termination. Normally, the calling process is the operating system. When the xHarbour application ends regularly, the exit code is set to 0. If the application quits due to a runtime error, the default exit code is set to 1. The exit code can be queried in a batch file using the ERRORLEVEL command of the operating system. This way, regular and irregular program termination can be detected. ErrorLevel() allows for user-defined exit codes since numeric values in the range of 0 to 255 can be passed to the function. A user-defined exit code is retained until a new value is passed to ErrorLevel().

Info See also: Category: Source: LIB: DLL:

ErrorBlock(), ErrorSys(), Getenv(), QUIT Error functions, Debug functions vm\hvm.c xhb.lib xhbdll.dll

Example // // // // // //

This example consists of three files: MYSTART.BAT, a batch processing file executed by the operating system, and two PRG files containing the code for two xHarbour applications. The ErrorLevel() exit code of both applications is queried in the batch file to run both xHarbour applications as alternating processes when the user presses the Y key. @ECHO OFF REM This is the command file MYSTART.BAT :Start ECHO Main application module MyProgram.exe IF ERRORLEVEL 25 GOTO Reorg GOTO Exit :Reorg

Function Reference

597

ErrorLevel() ECHO Data reorganization module Reorganize.exe IF ERRORLEVEL 26 GOTO Start :Exit ECHO Application has ended REM *EOF* /* * Program: MyProgram.exe */ PROCEDURE Main ? "press to re-organize data" ? Inkey(0) IF Chr( LastKey() ) $ "yY" ErrorLevel( 25 ) ENDIF RETURN

/* * Program: Reorganize.exe */ PROCEDURE Main ? "Data re-organization is running." ? ? "press to re-start main program" ? Inkey(0) IF Chr( LastKey() ) $ "yY" ErrorLevel( 26 ) ENDIF RETURN

598

Function Reference

ErrorNew()

ErrorNew() Creates a new Error object and optionally fills it with data.

Syntax ErrorNew( [ ], [ ], [ ], [ ], [], { ], [ ], [ ], [ ]

; ; ; ; ; ; ; ; ) --> oError

Arguments

A character string that is assigned to oError:subSystem. Defaults to NIL.

A numeric value that is assigned to oError:genCode. Defaults to NIL.

A numeric value that is assigned to oError:subCode. Defaults to NIL.

A character string that is assigned to oError:operation. Defaults to NIL.

A character string that is assigned to oError:description. Defaults to NIL.

An array that is assigned to oError:args. Defaults to NIL.

A character string that is assigned to oError:modulName. Defaults to ProcFile(1).

A character string that is assigned to oError:procName. Defaults to ProcName(1).

A numeric value that is assigned to oError:procLine. Defaults to ProcLine(1).

Return The function returns the new Error object with the passed parameters assigned to instance variables.

Function Reference

599

ErrorNew()

Description ErrorNew() creates a new Error object and optionally assigns the parameters passed to instance variables of the object. The function is automatically called by the xHarbour runtime system when a runtime error occurs. User defined routines can create their own Error objects and fill them with error information. The Error object is then passed to the error code block (see ErrorBlock()) or to the Throw() function. Error objects are instances of the Error() class. Refer to that class for more information on creating user defined Error objects.

Info See also: Category: Header: Source: LIB: DLL:

Error(), ErrorBlock(), Throw(), TRY...CATCH Error functions, Object functions error.ch rtl\terror.prg xhb.lib xhbdll.dll

Example // refer to the Error() class for an Error object example

600

Function Reference

ErrorSys()

ErrorSys() Installs the default error code block.

Syntax ErrorSys( ) --> NIL

Arguments

A code block accepting one parameter must be passed. The code block must call the default error handling routine and pass the received parameter on to it.

Return The return value is always NIL.

Description ErrorSys() is an implicit INIT PROCEDURE called at startup of an xHarbour application. It installs the default error code block used for standard error handling. ErrorSys() is programmed in the ERRORSYS.PRG module and should not be called at runtime of an xHarbour application. To replace the default error code block, call the ErrorBlock() function. Since ErrorSys() is implicitely called it must be present in an xHarbour application. The only reason to program a user defined ErrorSys() routine is when the entire ERRORSYS.PRG module is replaced by a user-defined module.

Info See also: Category: Header: Source: LIB: DLL:

Function Reference

BEGIN SEQUENCE, Break(), Error(), ErrorBlock(), ErrorLevel(), Throw(), TRY...CATCH Error functions error.ch rtl\ errorsys.prg xhb.lib xhbdll.dll

601

Eval()

Eval() Evaluates a code block.

Syntax Eval( [, ] )

--> xReturn

Arguments

A code block to be evaluated

Any number of values to be passed as arguments to the code block.

Return The function returns the value of the last expression inside the code block.

Description This function evaluates the code block and passes on to it all parameters specified as the comma separated list . A code block can contain multiple, comma separated expressions that are executed from left to right. The value of the last expression executed in the code block is used as return value of Eval(). Code blocks are values that contain executable code. Normally, the xHarbour compiler creates the code associated with code blocks at compile time. It is possible, however, to create code blocks at runtime of an application. This is accomplished by the macro operator (&) which compiles a character string holding the syntax for a code block at runtime.

Info See also: Category: Source: LIB: DLL:

AEval(), AScan(), ASort(), DbEval(), FieldBlock() Code block functions, Indirect execution vm\evalhb.c xhb.lib xhbdll.dll

Example // The example outlines basic rules for code block usage. PROCEDURE Main LOCAL bBlock, cBlock bBlock := {|x| QOut(x) } Eval( bBlock, Date() )

// result: NIL (of QOut()) // displays: 02/08/06

bBlock := {|x,y| x + y } ? Eval( bBlock, 5, 17 )

602

// result: 22

Function Reference

Eval() ? Eval( bBlock, "A", "string" ) RETURN

Function Reference

// result: Astring

603

Exp()

Exp() Calculates the value of e raised by an exponent.

Syntax Exp( ) --> nAntiLogarithm

Arguments

A numeric expression used as exponent for e (2.71828...)

Return The function returns the numeric anti-logarithm of .

Description This function returns the value of e raised to the power of . It is the inverse function of Log(). Note that cannot be larger than 46. Otherwise, a numeric overflow is created.

Info See also: Category: Source: LIB: DLL:

Log(), SET DECIMALS, SET FIXED Mathematical functions, Numeric functions rtl\math.c xhb.lib xhbdll.dll

Example // The example shows return values of Exp() PROCEDURE Main SET DECIMALS TO 15 ? Exp(1) ? Exp(-1) ? Exp(46) ? Exp(46.1) RETURN

604

// // // //

result: result: result: result:

2.718281828459045 0.367879441171442 94961194206024470000.000000000000000 ************************************

Function Reference

FCharCount()

FCharCount() Counts the number of characters in a text file ignoring white space characters.

Syntax FCharCount( ) --> nCharCount

Arguments

This is a character string holding the name of the text file whose characters to count. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Return The function returns the number of non white space characters contained in a text file.

Description The function counts the characters in an ASCII text file but ignores white space characters. These are Tab (Chr(9)), Line Feed (Chr(10)), Carriage return (Chr(13)) and Blank space (Chr(32)).

Info See also: Category: Source: LIB: DLL:

FCreate(), FOpen(), FLineCount(), FParse(), FWordCount(), MemoLine(), MlCount() File functions, xHarbour extensions rtl\fparse.c xhb.lib xhbdll.dll

Example // The example displays the number of characters of // the example. PROCEDURE Main LOCAL cFileName := "FCharCount.prg" ? FCharCount( cFileName )

// result: 141

RETURN

Function Reference

605

FClose()

FClose() Closes a binary file.

Syntax FClose( ) --> lSuccess

Arguments

The numeric file handle returned from a previous call to FOpen() or FCreate().

Return The return value is .T. (true) when the file is successfully closed, otherwise .F. (false).

Description FClose() closes a file that is either newly created with FCreate() or opened with FOpen(). Both functions return a numeric file handle that must be passed to FClose() in order to close the open file. When the file is successfuly closed, all internal file buffers are permanently written to disk, and the function returns .T. (true). If the close operation fails, the return value is .F. (false). The reason for failure can then be queried by calling the FError() function.

Info See also: Category: Source: LIB: DLL:

FCreate(), FError(), FOpen(), FRead(), FSeek(), FWrite() File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // // // //

The example demonstrates how to create a new file, write some data to it and close it. If any operation fails, an appropriate error message is displayed along with the error code obtained from the operating system. #include "Fileio.ch" PROCEDURE Main LOCAL nFileHandle, cText nFileHandle := FCreate( "NewFile.txt", FC_NORMAL ) IF FError() 0 ? "Error while creatingg a file: ", FError() QUIT ENDIF cText := "New text for file" IF FWrite( nFileHandle, cText ) Len( cText ) ? "Error while writing a file: ", FError()

606

Function Reference

FClose() ENDIF IF .NOT. FClose( nFileHandle ) ? "Error while closing a file: ", FError() ELSE ? "File successfully created and closed" ENDIF RETURN

Function Reference

607

FCount()

FCount() Returns the number of fields in the current work area.

Syntax FCount() --> nFieldCount

Return The function returns a numeric value which is the number of field variables available in a work area. If a work area is not used, the return value is zero.

Description FCount() is used to determine how many fields, or field variables, exist in a work area. By default, the function operates in the current work area. Use an aliased expression to determine the number of fields in a different work area.

Info See also: Category: Source: LIB: DLL:

FIELD, FieldGet(), FieldName(), FieldType(), Type() File functions, Field functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows a typical programming pattern for FCount() where // an array is filled with the names and contents of all fields. PROCEDURE Main LOCAL aArray, n USE Customer NEW aArray := Array( FCount() ) FOR n := 1 TO FCount() aArray[n] := { FieldName(n), FieldGet(n) } NEXT AEval( aArray, {|a| QOut( Padr(a[1],10)+":",a[2] ) } ) USE RETURN

608

Function Reference

FCreate()

FCreate() Creates an empty binary file.

Syntax FCreate( , [] ) --> nFileHandle

Arguments

This is a character string holding the name of the file to create. It must include path and file extension. If the path is omitted from , the file is created in the current directory.

A numeric value specifying one or more attributes associated with the new file. #define constants from the FILEIO.CH file can be used for as listed in the table below:

Attributes for binary file creation Constant

Value Attribute

Description

FC_NORMAL *) FC_READONLY FC_HIDDEN FC_SYSTEM *) default attribute

0 1 2 4

Creates a normal read/write file Creates a read-only file Creates a hidden file Creates a system file

Normal Read-only Hidden System

Return The function returns a numeric file handle to be used later for writing data to the file using FWrite(). The return value is -1 when the operation fails. Use FError() to determine the cause of failure.

Description The low-level file function FCreate() creates a new file, or truncates an existing file to contain zero bytes. If the operation is successful, the return value must be preserved in a variable for accessing the file lateron. The file is left open in compatibility sharing mode and read/write access mode so that the creating application can write data to the file. The file attribute is set when the file is closed again. Any attribute restricting file access, like FC_READONLY, for example, becomes effective after the newly created file is closed.

Info See also: Category: Header: Source: LIB: DLL:

FClose(), FErase(), FError(), FOpen(), FRead(), FSeek(), FWrite(), HB_FTempCreate() File functions, Low level file functions FileIO.ch rtl\philes.c xhb.lib xhbdll.dll

Example // The example creates a new file, writes some data to it and closes it. // If file creation or data write fails, an error message is displayed

Function Reference

609

FCreate() // along with the error code obtained from the operating system. #include "Fileio.ch" PROCEDURE Main LOCAL nFileHandle, cText nFileHandle := FCreate( "NewFile.txt", FC_NORMAL ) IF FError() 0 ? "Error while creatingg a file:", FError() QUIT ENDIF cText := "Text for new file" IF FWrite( nFileHandle, cText ) Len( cText ) ? "Error while writing a file:", FError() ENDIF IF .NOT. FClose( nFileHandle ) ? "Error while closing a file:", FError() ELSE ? "File successfully created and closed" ENDIF RETURN

610

Function Reference

FErase()

FErase() Deletes a file from disk.

Syntax FErase( ) --> nSuccess

Arguments

This is a character string holding the name of the file to delete. It must include path and file extension. If the path is omitted from , the file is searched and deleted in the current directory.

Return The return value is 0 when the file is successfully deleted, or -1 on failure. Use function FError() to determine the cause of failure.

Description The low-level file function FErase() deletes a file from disk. The file must be closed before it can be deleted. Note that must include the entire path and file name. If no path is specified, the function searches only the current directory to delete the file. The setting SET DEFAULT and SET PATH are ignored by FErase().

Info See also: Category: Source: LIB: DLL:

CLOSE, ERASE, FClose(), FCreate(), FError(), FOpen(), FRead(), FRename(), FSeek(), FWrite(), RENAME File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // The example deletes all CDX index files found in the current // directory. #include "Directry.ch" PROCEDURE Main LOCAL aCdxFiles := Directory( "*.CDX" ) AEval( aCdxFiles, { |aFile| FErase( aFile[ F_NAME ] ) } ) RETURN

Function Reference

611

FError()

FError() Retrieves the error code of the last low-level file operation.

Syntax FError() --> nErrorCode

Return The function returns the error code of the last low-level file operation as a numeric value. If the last low-level file operation is successful, the return value is zero.

Description Low-level file operations work with file handles and include the functions FClose(), FCreate() , FErase(), FOpen(), FRead(), FReadStr(), FRename(), FSeek() and FWrite(). If any file operation performed by these functions fails, the error code obtained from the disk operating system is returned from function FError(). The function retains this value until a successful low-level file operation completes. Note: error codes for low-level file functions are a subset of error codes listed under DosError(). See DosError() for a description of the meaning of error codes.

Info See also: Category: Source: LIB: DLL:

DosError(), FClose(), FCreate(), FErase(), FOpen(), FRead(), FReadStr(), FRename(), FSeek(), FWrite() File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // See the example for FCreate()

612

Function Reference

FieldBlock()

FieldBlock() Creates a set/get code block for a field variable

Syntax FieldBlock( ) --> bFieldBlock

Arguments

A character string holding the name of the database field to be accessed by the returned code block.

Return The function returns a code block accessing the field variable , or NIL when an illegal parameter is passed. The code block accepts one parameter used to assign a value to the field variable.

Description The code block function FieldBlock() creates a code block which accesses a field variable in the current work area. When evaluated with no parameter, the code block retrieves (gets) the value of . If one parameter is passed, the corresponding value is assigned (is set) to the field variable. It is not necessary that a database is open when FieldBlock() is called. When the returned code block is passed to the Eval() function, however, the field variable must exist in the current work area. Note: The FieldBlock() code block can be evaluated in any work area that has the specified field variable, as long as the work area is current. That is, the code block is not bound to any particular work area but is evaluated always in the context of the current work area. Use function FieldWBlock() to create a set/get code block bound to a particular work area.

Info See also: Category: Source: LIB: DLL:

FieldGet(), FieldPut(), FieldWBlock(), MemvarBlock() Code block functions, Database functions rtl\fieldbl.prg xhb.lib xhbdll.dll

Example // The example creates a set/get block for the field variable // LASTNAME in the CUSTOMER database. The field variable is // first get and then set. PROCEDURE Main LOCAL bBlock := FieldBlock( "LastName" ) USE Customer // get field variable ? Eval( bBlock )

Function Reference

// result: Miller

613

FieldBlock() // set field variable EVal( bBlock, "MILLER" ) ? LastName

// result: MILLER

USE // unused work area ? Eval( bBlock ) RETURN

614

// result: runtime error

Function Reference

FieldDec()

FieldDec() Retrieves the number of decimal places of a field variable.

Syntax FieldDec( ) --> nDecimalPlaces

Arguments

A numeric value specifying the ordinal position of the field variable to query. Valid values are in the range from 1 to FCount().

Return The function returns a numeric value indicating the number of decimal places of the specified field variable.

Description FieldDec() retrieves a particular information available for field variables: the number of decimal places. This is only relevant for field variables of Numeric data type. All other field variables have no decimal places.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbFieldInfo(), DbStruct(), FieldLen(), FieldName(), FieldType() Field functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

615

FieldGet()

FieldGet() Retrieves the value of a field variable by its ordinal position.

Syntax FieldGet( ) --> xFieldValue

Arguments

A numeric value specifying the ordinal position of the field variable to query. Valid values are in the range from 1 to FCount().

Return The function returns the value of the field variable at the specified position, or NIL if does not fall into the valid range.

Description FieldGet() retrieves the value of a field variable by its ordinal position, rather than by its field name. The ordinal position is determined by the sequence of field declarations when a database file is created. Ordinal positions begin with 1 and end with FCount().

Info See also: Category: Source: LIB: DLL:

FieldBlock(), FieldName(), FieldPut(), FieldWBlock() Database functions, Field functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example calls FieldGet() in the current work area // and in a different work area using an aliased expression. PROCEDURE Main USE Customer ALIAS Cust ? FieldPos( "Lastname" ) ? FieldGet(3)

// current work area // result: 3 // result: Miller

SELECT 0 ? Used() ? FieldGet(3)

// new work area // result: .F. // result: NIL

? Cust->(FieldGet(3))

// aliased expression // result: Miller

CLOSE Cust RETURN

616

Function Reference

FieldLen()

FieldLen() Retrieves the number of bytes occupied by a field variable.

Syntax FieldLen( ) --> nFieldLength

Arguments

A numeric value specifying the ordinal position of the field variable to query. Valid values are in the range from 1 to FCount().

Return The function returns a numeric value indicating the number of bytes the specified field variable occupies in one record of the database file.

Description FieldLen() retrieves a particular information available for field variables: the number of bytes required to store the field variable in a database record. Note that the value of memo fields is stored in a separate file. A memo field variable occupies 4 or 10 bytes in a database record, depending on the RDD used.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbFieldInfo(), DbStruct(), FieldDec(), FieldName(), FieldType() Field functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

617

FieldName()

FieldName() Retrieves the name of a field variable by its ordinal position.

Syntax FieldName( ) --> cFieldName

Arguments

A numeric value specifying the ordinal position of the field variable to query. Valid values are in the range from 1 to FCount().

Return The function returns the name of the specified field variable as a character string, or a null string ("") if does not fall into the valid range.

Description FieldName() retrieves the name of a field variable by its ordinal position. The ordinal position is determined by the sequence of field declarations when a database file is created. Ordinal positions begin with 1 and end with FCount().

Info See also: Category: Source: LIB: DLL:

DbFieldInfo(), DbStruct(), FCount(), FieldDec(), FieldGet(), FieldLen(), FieldPos(), FieldPut(), FieldType(), Type(), Valtype() Database functions, Field functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example lists the names and values of all field variables // in the current work area. PROCEDURE Main LOCAL n USE Customer ALIAS Cust FOR n:=1 TO FCount() ? Padr(FieldName(n),10),":",FieldGet(n) NEXT CLOSE Cust RETURN

618

Function Reference

FieldPos()

FieldPos() Retrieves the ordinal position of a field variable by its name.

Syntax FieldPos( ) --> nFieldPos

Arguments

A character string holding the name of the field variable.

Return The function returns a numeric value indicating the ordinal position of the field variable in the work area. If the work area has no field variable with this name, the return value is zero.

Description FieldPos() accepts a field name as character string and retrieves from it the ordinal position of the field variable. This is the reverse functionality of function FieldName(). Both FieldPos() and FieldName() are used for programming generic database routines that work with unknown database structures.

Info See also: Category: Source: LIB: DLL:

DbFieldInfo(), FCount(), FieldDec(), FieldGet(), FieldLen(), FieldName(), FieldPut(), FieldType() Database functions, Field functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates a typical use for FieldPos(). PROCEDURE Main LOCAL cName USE Customer NEW ? cLast := FieldGet(FieldPos("LASTNAME")) // result: Miller ? FieldPos("LASTNAME")

// result: 3

USE RETURN

Function Reference

619

FieldPut()

FieldPut() Assigns a value to a field variable by its ordinal position.

Syntax FieldPut( , ) --> xAssigneValue

Arguments

A numeric value specifying the ordinal position of the field variable to assign a value to. must be in the range from 1 to FCount().

An expression whose value is assigned to the field variable. The data type of must match the data type of the field variable. Note that memo fields must be assigned character strings.

Return The function returns the value assigned to the specified field variable, or NIL if is outside the valid range.

Description FieldPut() assigns a value to a field variable by using its ordinal position, rather than its field name. The ordinal position is determined by the sequence of field declarations when a database file is created. Ordinal positions begin with 1 and end with FCount().

Info See also: Category: Source: LIB: DLL:

DbFieldInfo(), FieldDec(), FieldGet(), FieldLen(), FieldName(), FieldPos(), FieldType(), REPLACE Database functions, Field functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates various possibilities of // assigning a value to a field variable. PROCEDURE Main LOCAL cField := "LASTNAME" , cLastName := "Miller" USE Customer NEW ALIAS Cust Cust->LASTNAME := cLastName

// hard-coded assignment

? FieldPos( cField )

// result: 3

? FieldPut( 3, cLastName )

// result: Miller // aliased expression

620

Function Reference

FieldPut() Cust-> ( FieldPut( FieldPos(cField), cLastName ) ) USE RETURN

Function Reference

621

FieldType()

FieldType() Retrieves the data type of a field variable.

Syntax FieldType( ) --> cFieldType

Arguments

A numeric value specifying the ordinal position of the field variable to query. Valid values are in the range from 1 to FCount().

Return The function returns a single character indicating the data type of the specified field variable, or a null string ("") if is outside the valid range.

Description FieldType() retrieves a particular information available for field variables: its data type.

Info See also: Category: Source: LIB: DLL:

622

DbFieldInfo(), DbStruct(), FieldDec(), FieldLen(), FieldName() Field functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

FieldWBlock()

FieldWBlock() Creates a set/get code block for a field variable in a particular work area.

Syntax FieldWBlock( , ) --> bFieldWBlock

Arguments

A character string holding the name of the database field to be accessed by the returned code block.

is the numeric ordinal position of a work area to bind the code block to. Work areas are numbered from 1 to 65535.

Return The function returns a code block accessing the field variable in the work area , or NIL when an illegal parameter is passed. The code block accepts one parameter used to assign a value to the field variable.

Description The code block function FieldWBlock() creates a code block which accesses a field variable in the work area specified with . By this, the code block is bound to the work area. When evaluated with no parameter, the code block retrieves (gets) the value of in the particular work area. If one parameter is passed, the corresponding value is assigned (is set) to the field variable. It is not necessary that a database is open when FieldWBlock() is called. When the returned code block is passed to the Eval() function, however, the field variable must exist in the work area .

Info See also: Category: Source: LIB: DLL:

FieldBlock(), FieldGet(), FieldPut(), MemvarBlock() Code block functions, Database functions rtl\fieldbl.prg xhb.lib xhbdll.dll

Example // // // //

The example creates a set/get code block accessing work area #10. A database is opened in this work area, and an unused work area is selected as current to demonstrate that the code block is bound to work area #10. PROCEDURE Main1 LOCAL bBlock := FieldWBlock( "LastName", 10 ) SELECT 10 USE Customer ALIAS Cust

Function Reference

623

FieldWBlock() SELECT 0 ? Used()

// result: .F.

// get field variable ? Eval( bBlock )

// result: Miller

// set field variable EVal( bBlock, "Smith" ) ? Cust->LastName

// result: Smith

? Eval( bBlock )

// result: Smith

CLOSE ALL RETURN

624

Function Reference

File()

File() Checks for the existence of a file in the default directory or path

Syntax File( ) --> lExists

Arguments

This is a character string containing the file specification to search for. It can include the wildcard characters (* and ?) and/or drive and directory information. If a complete file name isgiven, it must include a file extension.

Return The function returns .T. (true) if a match is found for , otherwise .F. (false).

Description The File() function is used to check if a file exists that matches the file specification . When does not contain directory information, the function searches directories in the following order: 1.

the current directory.

2.

the directory set with SET DEFAULT.

3.

the directories listed in the SET PATH setting.

Directories defined with environment variables of the operating system are not searched for . In addition, hidden or system files are not recognized by File().

Info See also: Category: Source: LIB: DLL:

CurDir(), Directory(), IsDirectory(), SET DEFAULT, SET PATH File functions rtl\filehb.c xhb.lib xhbdll.dll

Example // The example shows the dependency between File() and the // SET PATH and SET DEFAULT settings. PROCEDURE Main ? File( "Customer.dbf" ) ? File( "\xhb\apps\data\Customerdbf")

// result: .F. // result: .T.

SET PATH TO \xhb\apps\data ? File( "Customer.dbf" )

// result: .T.

SET PATH TO SET DEFAULT TO \xhb\apps\data

Function Reference

625

File() ? File( "Customer.dbf" ) ? File( "*.cdx")

// result: .T. // result: .T.

RETURN

626

Function Reference

FileStats()

FileStats() Retrieves file information for a single file.

Syntax FileStats( , [@] , [@] , [@], [@], [@], [@]

; ; ; ; ; ; ) --> lSuccess

Arguments

This is a character string holding the name of the file to query. It must include path and file extension. If the path is omitted from , the file is searched in the current directory. @

If specified, must be passed by reference. It receives the file attributes of the file as a character string. @

If specified, must be passed by reference. It receives the file size of the file as a numeric value. @

If specified, must be passed by reference. It receives the creation date of the file as a date value. @

If specified, must be passed by reference. It receives the creation time of the file as a numeric value. The unit is "seconds elapsed since midnight". Use function TString() to convert this value to a "hh:mm:ss" formatted time string. @

If specified, must be passed by reference. It receives the last change date of the file as a date value. @

If specified, must be passed by reference. It receives the creation time of the file as a numeric value. The unit is "seconds elapsed since midnight".

Return The return value is .T. (true) when the information on the file could be retrieved, otherwise .F. (false) is returned.

Function Reference

627

FileStats()

Description Function FileStats() retrieves statistical information about a single file. It is more efficient than the Directory() function which retrieves the same information for a group of files and stores them in an array. FileStats(), in contrast, allows for "picking" desired information about a single file by passing the according parameters by reference to the function.

Info See also: Category: Source: LIB: DLL:

Directory(), FCreate(), HB_FSize() File functions, Low level file functions, xHarbour extensions rtl\filestat.c xhb.lib xhbdll.dll

Example // The example shows how to retrieve statistical information about // a single file, and how to convert the time values from Seconds // to a hh:mm:ss time formatted string. PROCEDURE Main LOCAL cFileName := LOCAL cFileAttr , LOCAL dCreateDate, LOCAL dChangeDate,

"FILESTATS.PRG" nFileSize nCreateTime nChangeTime

? FileStats( cFileName, @cFileAttr , @nFileSize , ; @dCreateDate, @nCreateTime, ; @dChangeDate, @nChangeTime ) ? "File statistiscs" ? "File Name :", cFileName ? "Attributes:", cFileAttr ? "File Size :", nFileSize ? "Created :", dCreateDate, TString( nCreateTime ) ? "Changed :", dChangeDate, TSTring( nChangeTime ) RETURN

628

Function Reference

FkLabel()

FkLabel() Returns a function key name.

Syntax FKLABEL( ) --> cKeyLabel

Arguments

A numeric value identifying a function key. It must be in the range of 1 to 40.

Return The function returns a character string containing the label of a function key, or a null string ("") when an invalid parameter is passed.

Description This function exists for compatibility reasons only and is not recommended to be used in new xHarbour programs.

Info See also: Category: Source: LIB: DLL:

Function Reference

FkMax() Keyboard functions rtl\fkmax.c xhb.lib xhbdll.dll

629

FkMax()

FkMax() Returns the number of available function keys.

Syntax FkMax() --> nFKeyCount

Return The function returns the number of available function keys.

Description This function exists for compatibility reasons only and is not recommended to be used in new xHarbour programs.

Info See also: Category: Source: LIB: DLL:

FkLabel() Keyboard functions rtl\fkmax.c xhb.lib xhbdll.dll

Example // The example lists the names of all function keys PROCEDURE Main LOCAL n ? FOR n:=1 TO FkMax() ?? "", FkLabel(n) IF n % 10 == 0 ? ENDIF NEXT RETURN

630

Function Reference

FLineCount()

FLineCount() Counts the lines in an ASCII text file.

Syntax FLineCount( ) --> nLineCount

Arguments

This is a character string holding the name of the text file whose lines to count. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Return The function returns the number of lines contained in as a numeric value. If the file does not exist or cannot be opened, the return value is zero.

Description FLineCount() is an optimized function for counting the lines in an ASCII text file fast and efficiently. It can be used in conjunction with HB_FReadLine() to extract single lines from an ASCII text file.

Info See also: Category: Source: LIB: DLL:

FileStats(), FCharCount(), FCreate(), FOpen(), FParse(), FWordCount(), HB_FReadLine(), MemoLine(), MlCount() File functions, xHarbour extensions rtl\fparse.c xhb.lib xhbdll.dll

Example // The example uses FLineCount() to determine the size of an // array used to collect all lines of a text file. PROCEDURE Main LOCAL cFileName LOCAL nCount LOCAL aLines LOCAL nFileHandle LOCAL nLine LOCAL cLine

:= := := := :=

"Test.txt" FLineCount( cFileName ) Array( nCount ) FOpen( cFileName ) 0

FOR EACH cLine IN aLines HB_FReadLine( nFileHandle, @cLine ) aLines[ ++nLine ] := cLine END FClose( nFileHandle ) ? Len( aLines ) AEval( aLines, {|c| QOut( c ) } ) RETURN

Function Reference

631

FLock()

FLock() Applies a file lock to an open, shared database.

Syntax FLock() --> lSuccess

Return The function returns .T. (true) when the entire file open in a work area is successfully locked, otherwise .F. (false).

Description The function FLock() is used when a database open in SHARED mode in a work area must be protected entirely from concurrent updates by other applications in a multi-user scenario. As long as an application has obtained a file lock with FLock(), other applications can read records from the file, but are excluded from updating any record in the file with new data. Therefore, file locks should be used with special care and should be released as soon as possible with DbUnlock(). Before a file lock is placed, it is recommended to consider whether or not the same protection could be achieved with one or multiple record locks. They are created with the Rlock() or DbRLock() functions and are by far less restrictive for network operations. Certain database updates, however, require an application to obtain a file lock, otherwise a safe operation is not guaranteed to complete. As a general rule, database operations that involve many records require a file lock, while those updating only one or few records can be achieved using record locks.

Commands requiring an FLock() Command

Protection

APPEND FROM DELETE (multiple records) RECALL (multiple records) REPLACE (multiple records) UPDATE ON

FLock() or USE...EXCLUSIVE FLock() or USE...EXCLUSIVE FLock() or USE...EXCLUSIVE FLock() or USE...EXCLUSIVE FLock() or USE...EXCLUSIVE

FLock() attempts to lock the database once only. If this attempt fails, the function returns .F. (false). Common reasons for failure are that another application has currently obtained a record lock or a file lock on the same database file.

Info See also: Category: Source: LIB: DLL:

DbRLock(), DbUnlock(), DbUnlockAll(), DbUseArea(), RLock(), SET EXCLUSIVE, UNLOCK, USE Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // This example uses FLock() to delete many records at once.

632

Function Reference

FLock() PROCEDURE Main USE Customer SHARED NEW IF FLock() DELETE FOR Year(Date())-Year(Cust->LastDate) > 5 DbUnlock() ELSE ? "Error: unable to lock file." ENDIF USE RETURN

Function Reference

633

FOpen()

FOpen() Opens a file on the operating system level.

Syntax FOpen( , []) --> nFileHandle

Arguments

This is a character string holding the name of the file to open. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

A numeric value specifying the open mode and access rights for the file. #define constants from the FILEIO.CH file can be used for as listed in the table below:

File open modes Constant

Value

Description

FO_READ *) FO_WRITE FO_READWRITE *) default

0 1 2

Open file for reading Open file for writing Open file for reading and writing

Constants that define the access or file sharing rights can be added to an FO_* constant. They specify how file access is granted to other applications in a network environment.

File sharing modes Constant

Value

Description

FO_COMPAT *) FO_EXCLUSIVE FO_DENYWRITE FO_DENYREAD FO_DENYNONE FO_SHARED *) default

0 16 32 48 64 64

Compatibility mode Exclusive use Prevent other applications from writing Prevent other applications from reading Allow others to read or write Same as FO_DENYNONE

Return The function returns a numeric file handle to be used later for accessing the file usi ng FRead() or FWrite(). The return value is -1 when the operation fails. Use FError() to determine the cause of failure.

Description The low-level file function FOpen() opens a file on the operating system level. The returned file handle must be preserved in a variable to be passed to other low-level file functions until the file is closed. Without the file handle, data cannot be written to or read from the file.

634

Function Reference

FOpen()

Open mode and sharing rights can be specified with . The default open and sharing mode grants shared read access to the application. FOpen() does not search the directories specified with SET PATH or SET DEFAULT. Therefore, the file name must be specified including directory information and extension. If no directory information is provided, FOpen() searches the file only in the current directory.

Info See also: Category: Header: Source: LIB: DLL:

FClose(), FCreate(), FError(), FRead(), FSeek(), FWrite() File functions, Low level file functions FileIO.ch rtl\philes.c xhb.lib xhbdll.dll

Example // The example implements a user-defined function that reads the // entire contents of a file into a memory variable using // low-level file functions: #include "FileIO.ch" PROCEDURE Main LOCAL cFile := "Fopen.prg" //"MyFile.txt" LOCAL cStream IF .NOT. ReadStream( cFile, @cStream ) IF FError() 0 ? "Error reading file:", FError() ELSE ? "File is empty" ENDIF ELSE ? "Successfully read", Len(cStream), "bytes" ENDIF RETURN FUNCTION ReadStream( cFile, cStream ) LOCAL nFileHandle := FOpen( cFile ) LOCAL nFileSize IF FError() 0 RETURN .F. ENDIF nFileSize := FSeek( cStream := Space( FSeek( nFileHandle, FRead( nFileHandle, FClose( nFileHandle RETURN ( FError() == 0

Function Reference

nFileHandle, 0, FS_END ) nFileSize ) 0, FS_SET ) @cStream, nFileSize ) ) .AND. .NOT. Empty( cStream ) )

635

Found()

Found() Checks if the last database search operation was successful

Syntax Found() --> lSuccess

Return The function returns .T. (true) when the last search operation in a work area was successful, otherwise .F. (false) is returned. The return value is always .F. (false), when a work area is unused.

Description The Found() function returns a status of a work area that indicates success of a search operation. Each work area has a Found status which is set when a search function or command is executed in a work area. The Found status is set to .T. (true) when a record matching a search condition is found. If the Found status is .T. (true), it is reset to .F. (false) when the record pointer is moved again. This most commonly used search function is DbSeek() which searches a value in an index. This search sets the Found status explicitely. If a work area is related to a parent work area via SET RELATION, the Found status of the child work area is implicitly set to .T. (true) when a record matches the relation expression.

Info See also: Category: Source: LIB: DLL:

DbSeek(), DbSetRelation(), Eof(), LOCATE, SEEK, SET RELATION, SET SOFTSEEK Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example illustrates return values of Found() // in different work areas. PROCEDURE Main USE Invoice NEW ALIAS Inv INDEX ON CustNo TO InvA SET INDEX TO InvA USE Customer ALIAS Cust INDEX ON Upper(LastName+FirstName) TO Cust01 SET INDEX TO Cust01 ? Alias() DbSeek( "BECKER" ) ? Found()

// result: CUST

? Inv->( Found() )

// result: .F.

// result: .T.

Inv->( DbSeek( Cust->CustNo ) ) ? Inv->( Found() ) // result: .T. ? Alias()

636

// result: CUST

Function Reference

Found() DbSkip() ? Found()

// result: .F.

? Inv->( Found() )

// result: .T.

CLOSE DATABASES RETURN

Function Reference

637

FParse()

FParse() Parses a delimited text file and loads it into an array.

Syntax FParse( , ) --> aTextArray

Arguments

This is a character string holding the name of the text file to load into an array. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

This is a single character used to parse a single line of text. It defaults to the comma.

Return The function returns a two dimensional array, or an empty array when the file cannot be opened.

Description Function FParse() reads a delimited text file and parses each line of the file at . The result of line parsing is stored in an array. This array, again, is collected in the returned array, making it a two dimensional array FParse() is mainly designed to read the comma-separated values (or CSV) file format, were fields are separated with commas and records with new-line character(s).

Info See also: Category: Source: LIB: DLL:

FCreate(), FOpen(), FCharCount(), FLineCount(), FParseEx(), FParseLine(), MemoLine(), MlCount() File functions, xHarbour extensions rtl\fparse.c xhb.lib xhbdll.dll

Example // The example reads a CSV file and displays its records // and field data PROCEDURE Main() LOCAL aText := FPparse( "Testdata.csv" ) LOCAL aRecord, cData FOR EACH aRecord IN aText // ? "Record #" + CStr( HB_EnumIndex() ), ": " FOR EACH cData IN aRecord ?? cData + " " NEXT NEXT

638

Function Reference

FParse() RETURN

Function Reference

639

FParseEx()

FParseEx() Parses a delimited text file and loads it into an array (optimized).

Syntax FParseEx( , [] ) --> aTextArray

Arguments

This is a character string holding the name of the text file to load into an array. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

This is a single character used to parse a single line of text. It defaults to the comma.

Return The function returns a two dimensional array, or an empty array when the file cannot be opened.

Description Function FParseEx() is a speed optimized version of FParse(). Refer to FParse() for more information.

Info See also: Category: Source: LIB: DLL:

640

FParse() File functions, xHarbour extensions rtl\fparse.c xhb.lib xhbdll.dll

Function Reference

FParseLine()

FParseLine() Parses one line of a delimited text and loads it into an array.

Syntax FParseLine( , []

) --> aTextFields

Arguments

This is a character string holding on line of delimited text.

This is a single character used to parse . It defaults to the comma.

Return The function returns a one dimensional array, or an empty array when an error occurs.

Description Function FParseLine() parses one line of delimited text at . The result is stored in a one dimensional array. FParseLine() is mainly designed to process the comma-separated values (or CSV) file format, were fields are separated with commas and records with new-line character(s). Note: function FParse() is available to process an entire CSV file.

Info See also: Category: Source: LIB: DLL:

FParse(), HB_FReadLine(), MemoLine() File functions, xHarbour extensions rtl\fparse.c xhb.lib xhbdll.dll

Example // The example parses one line of delimited text and displays // the resukt. Note that commas exist in the first and sixth // text field of the CSV formatted string. PROCEDURE Main() LOCAL cText, aData cText := '"Jones, Mr",Male,"Oklahoma","IL",20041231,"Director, President"' aData := FParseLine( cText ) FOR EACH cText IN aData ? LTrim( Str( HB_EnumIndex() ) ), cText NEXT ** Output // 1 Jones, Mr

Function Reference

641

FParseLine() // 2 // 3 // 4 // 5 // 6 RETURN

642

Male Oklahoma IL 20041231 Director, President

Function Reference

FRead()

FRead() Reads characters from a binary file into a memory variable.

Syntax FRead( , @, ) --> nBytesRead

Arguments

This is a numeric file handle returned from function FOpen() or FCreate().

A memory variable holding a character string must be passed by reference to FRead(). It must have at least characters.

This is a numeric value specifying the number of bytes to transfer from the file into the memory variable , beginning at the current file pointer position.

Return The function returns a numeric value indicating the number of bytes that are transfered from the file into the memory variable. If the return value is smaller the Len(), either the end of file is reached, or a file read error ocurred. This can be identified using function FError().

Description The low-level file function FRead() reads bytes from a file and copies them into a memory variable. To accomplish this, FRead() must receive a string buffer , large enough to receive the number of bytes specified with . Since the bytes are copied into a memory variable, the buffer variable must be passed by reference to FRead(). FRead() advances the file pointer by the number of bytes read and returns this number. When the end of file is reached, the file pointer cannot be advanced further, so that the return value is usually smaller than . Use FSeek() to reposition the file pointer without reading the file. If an error occurs during the operation, function FError() returns an error code indicating the cause of failure.

Info See also: Category: Source: LIB: DLL:

Bin2I(), Bin2L(), Bin2U(), Bin2W(), FClose(), FCreate(), FError(), FOpen(), FReadStr(), FSeek(), FWrite(), HB_FReadLine() File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // The example reads an entire file in blocks of 4096 bytes and fills // them into an array

Function Reference

643

FRead() #define BLOCK_SIZE

4096

PROCEDURE Main LOCAL cBuffer := Space( BLOCK_SIZE ) LOCAL nFileHandle := FOpen( "MyFile.log") LOCAL aBlocks := {} LOCAL nRead IF FError() 0 ? "Error opening file:", FERROR() QUIT ENDIF DO WHILE .T. nRead := FRead( nFileHandle, @cBuffer, BLOCK_SIZE ) IF nRead == BLOCK_SIZE AAdd( aBlocks, cBuffer ) ELSE // end of file reached AAdd( aBlocks, SubStr(cBuffer,nRead) ) EXIT ENDIF ENDDO FClose( nFileHandle ) ? Len( aBlocks ), "Blocks of", BLOCK_SIZE, "bytes read" RETURN

644

Function Reference

FReadStr()

FReadStr() Reads characters up to Chr(0) from a binary file.

Syntax FreadStr( , ) --> cString

Arguments

This is a numeric file handle returned from function FOpen() or FCreate().

This is a numeric value specifying the number of bytes to read from the file, beginning at the current file pointer position.

Return The function returns the bytes read from the file as a character string. If an error occurs, a null string ("") is returned.

Description The low-level file function FReadStr() reads bytes from an open file and returns them as a character string. The file pointer is advanced by the number of bytes read. The function reads all bytes up to the end of file, except Chr(0). The bytes up to the first Chr(0), but not including Chr(0), are returned.

Info See also: Category: Source: LIB: DLL:

Bin2I(), Bin2L(), Bin2U(), Bin2W(), FClose(), FCreate(), FError(), FOpen(), FRead(), FSeek(), FWrite(), HB_FReadLine() File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // The example reads a file using FReadStr() and FRead() and // compares the results. #include "Fileio.ch" PROCEDURE Main LOCAL cBuffer LOCAL nHandle nHandle := FCreate( "Testfile.txt", FC_NORMAL ) FWrite( nHandle , "xHarbour" + Chr(0) + "compiler" ) FClose( nHandle ) nHandle

:= FOpen( "Testfile.txt" , FO_READ )

? cBuffer := FReadStr( nHandle, 20 ) // result: xHarbour

Function Reference

645

FReadStr() ? Len( cBuffer )

// result: 8

FSeek(nHandle, 0, FS_SET )

// go to begin of file

cBuffer := Space( 20 ) ? FRead( nHandle, @cBuffer, 20 ) ? Trim( cBuffer ) ? Asc( cBuffer[9] )

// result: 17 // result: xHarbour compiler // result: 0

FClose( nHandle ) FErase( "Testfile.txt" ) RETURN

646

Function Reference

FreeLibrary()

FreeLibrary() Releases a dynamically loaded external DLL from memory.

Syntax FreeLibrary( ) --> lSuccess

Arguments

This is a numeric handle of the DLL to release as returned from LoadLibrary().

Return The function returns a logical value inidcating a successful operation.

Description Function FreeLibrary() releases a DLL previously loaded with LoadLibrary() from memory. Internally, the function decrements the load counter of the DLL with the handle to signal the operating system that the DLL is no longer required by the xHarbour application. Whether or not the DLL is actually removed from memory is controlled by the operating system, since the same DLL could be in use by multiple applications.

Info See also: Category: Source: LIB: DLL:

Function Reference

DllCall(), LibFree(), LoadLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

647

FRename()

FRename() Renames a file.

Syntax FRename( , ) --> nSuccess

Arguments

This is a character string holding the name of the file to rename. It must include path and file extension. The path can be omitted from when the file resides in the current directory.

This is a character string with the new file name including file extension. Drive and/or path are optional.

Return The function returns a numeric value. 0 indicates success and -1 is returned for failure. The cause of a failure can be determined using function FError()

Description The FRename() function changes the name of a file. The file is searched in the current directory only, unless a full qualified file name including drive and path is specified. Directories specified with SET DEFAULT and SET PATH are ignored by FRename(). If is specified as a full qualified file name and its directory differs from the one of , the source file is moved to the new directory and stored under the new file name. When the new file either exists or is currently open, FRename() aborts the operation. Use the File() function to test for the existence of . A file must be closed before attempting to rename it.

Info See also: Category: Source: LIB: DLL:

CLOSE, ERASE, FCReate(), FErase(), FError(), File(), RENAME File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // The example changes the name of an existing Log file // for archival purposes and creates a new Log file PROCEDURE Main LOCAL nLogs, nHandle IF File( "Logfile.txt" ) nLogs := 0

648

Function Reference

FRename() DO WHILE File( "Logfile." + Padl( nLogs, 3, "0" ) ) nLogs ++ IF nLogs > 999 nLogs := 0 EXIT ENDIF ENDDO IF FRename( "Logfile.txt", ; "Logfile." + Padl( nLogs, 3, "0" ) ) == -1 ? "Error renaming file:", FError() ENDIF ENDIF nHandle := FCreate( "Logfile.txt" ) IF FError() == 0 FWrite( nHandle, "Created: " + DtoS(Date()), 17 ) FClose( nHandle ) ENDIF RETURN

Function Reference

649

FSeek()

FSeek() Changes the position of the file pointer.

Syntax FSeek( , , [] ) --> nPosition

Arguments

This is a numeric file handle returned from function FOpen() or FCreate().

This is a numeric value specifying the number of bytes to move the file pointer. It can be a positive or negative number. Negative numbers move the file pointer backwards (towards the beginning of the file), positive values move it forwards. The value zero is used to position the file pointer exactly at the location specified with .

Optionally, the starting position from where to move the file pointer can be specified. #define constants are available in the FILEIO.CH file that can be used for .

Start positions for moving the file pointer Constant

Value

Description

FS_SET *) FS_RELATIVE FS_END *) default

0 1 2

Start at the beginning of the file Start at the current file pointer position Start at the end of the file

Return The function returns a numeric value. It is the new position of the file pointer, counted from the beginning of the file (position 0).

Description The low-level file function FSeek() moves the file pointer of an open file to a new position, without reading the contents of the file. The file pointer can be moved forwards (positive ) and backwards (negative ). It is not possible, however, to move the file pointer outside the boundaries of a file.

650

Function Reference

FSeek()

Info See also: Category: Header: Source: LIB: DLL:

FClose(), FCreate(), FError(), FOpen(), FRead(), FReadStr(), FWrite() File functions, Low level file functions FileIO.ch rtl\philes.c xhb.lib xhbdll.dll

Example // The example implements the user-defined function FSize() // which determines the size of a file using FSeek() #include "FileIO.ch" PROCEDURE Main LOCAL cFile := "MyFile.txt" ? FSize( cFile ) RETURN FUNCTION FSize( cFile ) LOCAL nHandle := FOpen( cFile ) LOCAL nSize := -1 IF FError() == 0 nSize := FSeek( nHandle, 0, FS_END ) FClose( nHandle ) ENDIF RETURN nSize

Function Reference

651

FWordCount()

FWordCount() Counts the words in a text file.

Syntax FWordCount( ) --> nWordCount

Arguments

This is a character string holding the name of the text file whose words to count. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Return The function returns the number of words contained in a text file.

Description The function counts the words in an ASCII text file. Words are recognized as sequences of characters delimited by blank spaces (Chr(32)).

Info See also: Category: Source: LIB: DLL:

652

FCharCount(), FLineCount() File functions, xHarbour extensions rtl\fparse.c xhb.lib xhbdll.dll

Function Reference

FWrite()

FWrite() Writes data to an open binary file.

Syntax FWrite( , , [] ) --> nBytesWritten

Arguments

This is a numeric file handle returned from function FOpen() or FCreate().

This is a character string to be written to the open file.

A numeric value specifying the number of bytes to write to the file, beginning with the first character of . It defaults to Len( ), i.e. all bytes of .

Return The function returns a numeric value which is the number of bytes written to the file. If the return value equals , the operation was succesful. Any value differeing from indicates failure, which can be identified using function FError().

Description The low-level file function FWrite() writes data provided in form of a character string into an open file. Data is written starting at the current position of the file pointer. The file pointer is advanced to a new position by the number of written bytes.

Info See also: Category: Source: LIB: DLL:

FClose(), FCreate(), FError(), FOpen(), FRead(), FReadStr(), FWrite() File functions, Low level file functions rtl\philes.c xhb.lib xhbdll.dll

Example // The example implements the user defined function WriteStream() // which writes an entire character string into a newly created file PROCEDURE Main LOCAL aDir := Directory() LOCAL cFiles := "" AEval( aDir, {|a| cFiles += a[1] + Chr(13)+Chr(10) } ) IF .NOT. WriteStream( "Files.txt", cFiles ) ? "Error writing file", FError() ENDIF RETURN FUNCTION WriteStream( cFile, cStream )

Function Reference

653

FWrite() LOCAL nHandle := FCreate( cFile ) IF FError() 0 RETURN .F. ENDIF FWrite( nHandle, cStream, Len(cStream) ) FClose( nHandle ) RETURN ( FError() == 0 )

654

Function Reference

GetCurrentThread()

GetCurrentThread() Retrieves the handle of the current thread.

Syntax GetCurrentThread() --> pThreadHandle

Return The function returns the handle of the thread that executes GetCurrentThread().

Description Function GetCurrentThread() is used to retrieve the thread handle of the current thread. Thread handles are created by function StartThread(). They are required for other multi-threading functions like JoinThread() or StopThread().

Info See also: Category: Source: LIB: DLL:

Function Reference

GetThreadID(), GetSystemThreadID(), HB_MutexCreate(), IsSameThread(), JoinThread(), StopThread(), ThreadSleep() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

655

GetDefaultPrinter()

GetDefaultPrinter() Retrieves the name of a computer's default printer.

Syntax GetDefaultPrinter() --> cPrinterName

Return The function returns a character string holding the name of the default printer.

Description This function serves informational purposes. It retrieves the name of the printer selected as default printer for the current user in the system configuration.

Info See also: Category: Source: LIB: DLL:

GetPrinters(), PrintFileRaw(), PrinterExists(), PrinterPortToName() Printer functions, xHarbour extensions rtl\tprinter.c xhb.lib xhbdll.dll

Example PROCEDURE Main() LOCAL cPrinter := GetDefaultPrinter() ? cPrinter RETURN

656

Function Reference

GetEnv()

GetEnv() Retrieves an operating system environment variable.

Syntax GetEnv( ) --> cString

Arguments

A character string with the name of the environment variable to retrieve. The name is not casesensitive.

Return The function returns the contents of the environment variable as a character string, or a null string ("") when the environment variable does not exist.

Description The GetEnv() function queries the environment variables defined for the operating system command shell that has started the xHarbour application. Environment variables are defined using the SET command of the command shell.

Info See also: Category: Source: LIB: DLL:

CurDir(), CurDrive(), File(), SET DEFAULT, SET PATH Environment functions rtl\gete.c xhb.lib xhbdll.dll

Example // The example retrieves some environment variables common for // a programming environment: PROCEDURE Main ? GetEnv( "INCLUDE" )

// SET INCLUDE=path

? GetEnv( "LIB" )

// SET LIB=path

? GetEnv( "COMSPEC" ) RETURN

// Command shell

Function Reference

657

GetLastError()

GetLastError() Retrieves the error code of the last dynamically called DLL function.

Syntax GetLastError() --> nErrorCode

Return The function returns the last error code that occurred with a DllCall() invoked DLL function.

Description GetLastError() is used when a Windows API function is invoked via DllCall(). Typically, a WinAPI function declared as BOOL returns 0 on failure. In this case, GetLastError() can be called to retrieve the error code for extended error information. The last error code can be set with function SetLastError().

Info See also: Category: Source: LIB: DLL:

658

DllCall(), LoadLibrary(), SetLastError() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Function Reference

GetNew()

GetNew() Creates a new Get object.

Syntax GetNew( [] , [] , , [] , [] , []

; ; ; ; ; ) --> oGet

Arguments

This is the numeric row coordinate on the screen where the Get object is displayed. It defaults to the return value of function Row(). is assigned to oGet:row.

This is the numeric column coordinate on the screen where the Get object is displayed. It defaults to the return value of function Col(). is assigned to oGet:col.

This is the data code block connecting a Get object with a variable holding the edited value (see description below). is assigned to oGet:block.

This is a character string holding the symbolic name of a memory variable of PRIVATE or PUBLIC scope. If the Get object should edit such a variable, is optional. defaults to an empty string ("") and is assigned to oGet:name.

This is a character string holding a PICTURE format. defaults to an empty string ("") and is assigned to oGet:picture.

This is a character string holding a color string of up to four color values. (refer to function SetColor() for color values). is assigned to oGet:colorSpec.

Return Function GetNew() returns a new, initialized Get object.

Description Function GetNew() is the functional equivalent of Get():new(). Refer to the description of the Get object.

Function Reference

659

GetNew()

Info See also: Category: Source: LIB: DLL:

660

Get() Object functions, UI functions rtl\tgetint.prg xhb.lib xhbdll.dll

Function Reference

GetPrinters()

GetPrinters() Retrieves information about available printers.

Syntax GetPrinters( [], [] ) --> aPrinterInfo

Arguments

The default value for is .F. (false). If set to .T. (true), the function includes port information in the returned array.

The default value for is .F. (false). If set to .T. (true), the function returns only information for local printers.

Return The function returns a one- or two-dimensional array. If is .F. (false), a one-dimensional array is returned. Each element contains a character string with the name of an available printer. If is .T., each element of the returned array is an array of four elements, holding character strings with additional printer information:

Array elements for additional printer information Element

Description

1 2 3 4

Printer name Port name Printer type (e.g. Local/Network) Printer driver

Description The GetPrinters() function obtains information about printers that are currently available. If it is called without arguments, the function returns the names of all available printers. The list can be reduced to local printers only by specifying .T. (true) for . Additional information about port and printer driver can be retrieved when is set to .T. (true)

Info See also: Category: Source: LIB: DLL:

GetDefaultPrinter(), PrintFileRaw(), PrinterExists(), PrinterPortToName() Printer functions, xHarbour extensions rtl\tprinter.c xhb.lib xhbdll.dll

Example // The example is a test program for Windows printing PROCEDURE Main LOCAL aPrinter, i

Function Reference

661

GetPrinters() CLS ? ? Set(_SET_DEVICE) aPrinter := GetPrinters() IF Empty( aPrinter ) ? '----- No Printers installed' QUIT ENDIF SET PRINTER TO ( GetDefaultPrinter() ) ? Set( _SET_PRINTER ) ? Set( _SET_PRINTFILE ) SET CONSOLE OFF SET PRINTER ON ? 'Default Printer' ? ? GetDefaultPrinter() ? ? 'Printers available' ?'-------------------' FOR x:= 1 TO Len( aPrinter ) ? aPrinter[i] NEXT x aPrinter:= GetPrinters( .T. ) ? ? 'Printers and Ports' ? '-------------------' FOR i:= 1 TO Len( aPrinter ) ? aPrinter[i,1],'on', aPrinter[i,2] NEXT EJECT SET PRINTER OFF SET CONSOLE ON SET PRINTER TO ? Set( _SET_PRINTER ) ? Set( _SET_DEVICE ) WAIT RETURN

662

Function Reference

GetProcAddress()

GetProcAddress() Retrieves the memory address of a function in a dynamically loaded DLL.

Syntax GetProcAddress( , ; | ) --> pAddress

Arguments

This is a numeric handle of the DLL that contains the DLL function. It is the return value of LoadLibrary().

This is a character string holding the symbolic name of the function to obtain the memory address for. Unlike regular xHarbour functions, this function name is case sensitive.

Instead of the symbolic function name, the numeric ordinal position of the function inside the DLL file can be passed.

Return The function returns the memory address of as a pointer. When the function cannot be found in the DLL, a null pointer is returned.

Description Function GetProcAddress() obtains the memory address of a DLL function after the DLL is loaded into memory with LoadLibrary(). The memory address of a function, also called function pointer, is sometimes required by API functions when they need to call other functions. Note: the pointer returned by GetProcAddress() cannot be used on the PRG code level but only on the C code level.

Info See also: Category: Source: LIB: DLL:

DllCall(), DllPrepareCall(), LoadLibrary() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Example // The example demonstrates case sensitivity of function names // with DLL functions. PROCEDURE Main LOCAL nDll := LoadLibrary( "Kernel32.dll" ) ? GetProcAddress( nDll, "MultiByteToWideChar" )

Function Reference

// result: 7c809cad

663

GetProcAddress() ? GetProcAddress( nDll, "MultibyteToWideChar" )

// result: 00000000

FreeLibrary( nDll ) RETURN

664

Function Reference

GetRegistry()

GetRegistry() Retrieves the value of a registry entry

Syntax GetRegistry( , , ) --> xRegValue

Arguments

This numeric parameter specifies the root entry in the Windows registry to search for a registry key. #define constants are available in the Winreg.ch file that can be used for . They begin the the prefix HKEY_.

This is a character string holding the search path in the registry to locate . The path must include a backslash as delimiter, if required, but may neither begin or end with a backslash.

This is a character string holding the name of the registry key to retrieve the value for. must be located underneath .

Return The function returns the value of the specified registry key or NIL if it does not exist within the given root entry and search path.

Description The function searches a key in the Windows registry beginning with the root , following the search path . If the key exists in , the value of is returned. If the key cannot be found, the return value is NIL.

Winreg.ch Winreg.ch adds quite some overhead to an application program by adding structure definitions. If this is not required, Winreg.ch does not need to be #included. GetRegistry() recognizes the following values for in addition to the HKEY_* #define constants:

Registry keys Registry Key

Equivalent value

HKEY_LOCAL_MACHINE HKEY_CLASSES_ROOT HKEY_CURRENT_USER HKEY_CURRENT_CONFIG HKEY_LOCAL_MACHINE HKEY_USERS

0 1 2 3 4 5

Note: on Windows NT, 2000, XP or later, the user may need certain security rights in order to be able to read the registry.

Function Reference

665

GetRegistry()

Info See also: Category: Header: Source: LIB: DLL:

QueryRegistry(), SetRegistry() Registry functions, xHarbour extensions Winreg.ch rtl\winreg.prg xhb.lib xhbdll.dll

Example // The example reads values from the registry as they exist // after an xHarbour Builder installation * #include "Winreg.ch" #define HKEY_CURRENT_USER

// not needed for this example 0

// use alternative #define constant

PROCEDURE Main LOCAL nHKey := HKEY_CURRENT_USER LOCAL cRegPath := "SOFTWARE\xHarbour.com\xHarbour Builder" ? GetRegistry( nHKey, cRegPath, "Edition" )

// result: Enterprise

? GetRegistry( nHKey, cRegPath, "rootdir" )

// result: C:\xhb

? GetRegistry( nHKey, cRegPath, "xhb build" ) // result: October 2006 RETURN

666

Function Reference

GetSystemThreadID()

GetSystemThreadID() Retrieves the numeric system Thread ID of a thread.

Syntax GetSystemThreadID( [] ) --> nSystemTID

Arguments

This the a handle of the thread to retrieve the system ID for. If omitted, the system thread ID of the current thread is retrieved.

Return The function returns the numeric ID of a thread as it is used by the operating system.

Description When a new thread is started, it gets assigned a unique numeric Thread ID (TID) by the operating system. The system TID of the current or a particular thread is returned by GetSystemThreadID(). It is mainly of informational use, since system TIDs are random generated. xHarbour's virtual machine maintains an additional TID which is sequentially generated. See function GetThreadID() for more information.

Info See also: Category: Source: LIB: DLL:

Function Reference

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), StartThread(), ThreadSleep() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

667

GetThreadID()

GetThreadID() Retrieves the numeric application Thread ID of a thread.

Syntax GetThreadID( [] ) --> nApplicationTID

Arguments

This the a handle of the thread to retrieve the ID for. If omitted, the thread ID of the current thread is retrieved.

Return The function returns the numeric ID of a thread as it is used by the xHarbour application.

Description Function GetThreadID() returns the numeric Thread ID (TID) as it is used by xHarbour's virtual machine. TIDs are unique and are generated sequentially. This guarantees the following conditions: 1.

the TID of the Main thread is always 1.

2.

the TID of the next thread created is larger than the TID of a previously created thread.

3.

if GetThreadID() returns the same TID for two s, both s refer to the same thread.

Note: if does not contain a valid thread handle, a runtime error is raised. Refer to function IsValidThread() to test the validity of a thread handle.

Info See also: Category: Source: LIB: DLL:

GetCurrentThread(), GetSystemThreadID(), HB_MutexCreate(), StartThread(), ThreadSleep() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Example // The example displays the application TID and system TID of // ten threads. PROCEDURE Main LOCAL i, aTID := {} DisplayTIDs() FOR i:=1 TO 9 StartThread( "GetTIDs", aTID ) NEXT WaitForThreads()

668

Function Reference

GetThreadID() AEval( aTID, {|c| QOut(c) } ) RETURN

PROCEDURE GetTIDs( aTID ) LOCAL th := GetCurrentThread() LOCAL cTID IF GetThreadID( th ) == 1 cTID := "Main thread : " ELSE cTID := "Child thread: " ENDIF cTID += " cTID += "

APP TID:" + Str( GetThreadID( th ), 5 ) SYS TID:" + Str( GetSystemThreadID( th ), 5 )

AAdd( aTID, cTID ) RETURN

Function Reference

669

HaaDelAt()

HaaDelAt() Removes a key/value pair from an associative array.

Syntax HaaDelAt( , ) --> NIL

Arguments

A variable referencing the associative array to remove a key/value pair from.

A numeric value specifying the ordinal position of the key/value pair to remove. It must be in the range between 1 and Len().

Return The function returns always NIL.

Description The function removes a key/value pair from the associative array by its ordinal position. If is outside the valid range, a runtime error is raised. Use function HaaGetPos() to determine the ordinal position of a key.

Info See also: Category: Source: LIB: DLL:

Array(), HaaGetKeyAt(), HaaGetValueAt(), HaaSetValueAt(), Hash(), HSetAACompatibility() Associative arrays, Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example creates an associative array and deletes // the third key/value pair. PROCEDURE Main LOCAL hArray := Hash() HSetAACompatibility( hArray, .T. ) hArray[ hArray[ hArray[ hArray[ hArray[

"One" ] "Two" ] "Three"] "Four" ] "Five" ]

:= := := := :=

10 20 30 40 50

? hArray[ 3 ] ? hArray["Four"]

// result: 30 // result: 40

HaaDelAt( hArray, 3 )

670

Function Reference

HaaDelAt() ? hArray[ 3 ] ? hArray["Four"] RETURN

Function Reference

// result: 40 // result: 40

671

HaaGetKeyAt()

HaaGetKeyAt() Retrieves the key from an associative array by its ordinal position.

Syntax HaaGetKeyAt( , ) --> xKey

Arguments

A variable referencing the associative array to retrieve a key from.

A numeric value specifying the ordinal position of the key/value pair to query. It must be in the range between 1 and Len().

Return The function returns the key at position in the associative array .

Description This function retrieves the key from the associative array at position . If is outside the valid range, a runtime error is raised. Use function HaaGetPos() to determine the ordinal position of a key. The keys are inserted into the associative array by their sorting order and cannot be moved or changed.

Info See also: Category: Source: LIB: DLL:

Array(), HaaGetValueAt(), HaaSetValueAt(), Hash(), HSetAACompatibility() Associative arrays, Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example demonstrates that keys are collected in an // associative array by their sorting order. PROCEDURE Main LOCAL hArray := Hash() HSetAACompatibility( hArray, .T. ) hArray[ hArray[ hArray[ hArray[ hArray[

672

"One" ] "Two" ] "Three"] "Four" ] "Five" ]

:= := := := :=

10 20 30 40 50

? HGetKeyAt( hArray, 1 ) ? HGetKeyAt( hArray, 5 )

// result: Five // result: Two

? hArray[1]

// result: 10

Function Reference

HaaGetKeyAt() ? hArray[5] RETURN

Function Reference

// result: 50

673

HaaGetPos()

HaaGetPos() Retrieves the ordinal position of a key in an associative array.

Syntax HaaGetPos( , ) --> nPos

Arguments

A variable referencing the associative array to search a key in.

This is the key to search for in .

Return The function returns the ordinal position of in the associative array , or 0 if the key is not present.

Description This function is mostly used to check if a key is present in an associative array. If the return value is greater than zero, the key exists. The return value can then be passed on to function HaaGetValueAt() to retrieve the associated value. This is more efficient than using the key a second time for retrieving the value.

Info See also: Category: Source: LIB: DLL:

Array(), HaaGetKeyAt(), HaaGetRealPos(), HaaGetValueAt(), HaaSetValueAt(), Hash(), HSetAACompatibility() Associative arrays, Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example creates an associative array and retrieves values // from it using a function and array notation. PROCEDURE Main LOCAL hArray := Hash() HSetAACompatibility( hArray, .T. ) hArray[ hArray[ hArray[ hArray[ hArray[

"One" ] "Two" ] "Three"] "Four" ] "Five" ]

:= := := := :=

10 20 30 40 50

? HaaGetPos( hArray, "Four" ) ? HaaGetPos( hArray, "Five" ) ? HaaGetPos( hArray, "Six" )

674

// result: 4 // result: 5 // result: 0

Function Reference

HaaGetPos() ? HaaGetValueAt( hArray, 4 ) ? HaaGetValueAt( hArray, 5 ) ? hArray[4] ? hArray[5] RETURN

Function Reference

// result: 40 // result: 50 // result: 40 // result: 50

675

HaaGetRealPos()

HaaGetRealPos() Retrieves the sort order of a key in an associative array.

Syntax HaaGetRealPos( , ) --> nSortOrder

Arguments

A variable referencing the associative array to search a key in.

A numeric value specifying the ordinal position of the key/value pair to query. It must be in the range between 1 and Len().

Return The function returns a numeric value representing the sort order of in the associative array , or 0 if the key does not exist.

Description Keys are internally held in an associative array by their sorting order. Function HaaGetRealPos() is used to determine this sorting order of a key in an associative array. The ordinal position of a key is returned by HaaGetPos().

Info See also: Category: Source: LIB: DLL:

Array(), HaaGetKeyAt(), HaaGetPos(), HaaGetValueAt(), HaaSetValueAt(), Hash(), HGetVaaPos(), HSetAACompatibility() Associative arrays, Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example outlines the difference of the ordinal position // of a key and its sorting order in an associative array PROCEDURE Main LOCAL hArray := Hash(), i, nReal HSetAACompatibility( hArray, .T. ) hArray[ hArray[ hArray[ hArray[ hArray[

"One" ] "Two" ] "Three"] "Four" ] "Five" ]

:= := := := :=

10 20 30 40 50

FOR i:=1 TO Len( hArray ) ? i, HGetKeyAt( hArray, i ) NEXT

676

Function Reference

HaaGetRealPos() ** // // // // //

Output: 1 Five 2 Four 3 One 4 Three 5 Two

FOR i:=1 TO Len( hArray ) nReal := HaaGetRealPos( hArray, i ) ? nReal, HGetKeyAt( hArray, nReal ) NEXT ** Output: // 3 One // 5 Two // 4 Three // 2 Four // 1 Five RETURN

Function Reference

677

HaaGetValueAt()

HaaGetValueAt() Retrieves the value from an associative array by its ordinal position.

Syntax HaaGetValueAt( , ) --> xValue

Arguments

A variable referencing the associative array to retrieve a value from.

A numeric value specifying the ordinal position of the value to retrieve. It must be in the range between 1 and Len().

Return The function returns the value at position in the associative array .

Description This function retrieves the value from the associative array at position . If is outside the valid range, a runtime error is raised. Use function HaaGetPos() to determine the ordinal position of a key/value pair. Values of key/value pairs can be changed by specifying the key for an 4associative array and assigning a new value, or by using function HaaSetValueAt() which accepts the ordinal position of the value to change.

Info See also: Category: Source: LIB: DLL:

Array(), HaaGetKeyAt(), HaaGetPos(), HaaSetValueAt(), Hash(), HSetAACompatibility() Associative arrays, Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example outlines the possibilities of retrieving // values from an associative array. PROCEDURE Main LOCAL hArray := Hash() HSetAACompatibility( hArray, .T. ) hArray[ hArray[ hArray[ hArray[ hArray[

678

"One" ] "Two" ] "Three"] "Four" ] "Five" ]

:= := := := :=

10 20 30 40 50

Function Reference

HaaGetValueAt() ? HaaGetValueAt( hArray, 1 ) ? HaaGetValueAt( hArray, 5 )

// result: 10 // result: 50

? hArray[1] ? hArray[5]

// result: 10 // result: 50

? hArray["One"] ? hArray["Five"] RETURN

Function Reference

// result: 10 // result: 50

679

HaaSetValueAt()

HaaSetValueAt() Changes the value in an associative array by its ordinal position.

Syntax HaaSetValueAt( , , ) --> NIL

Arguments

A variable referencing the associative array to change a value in.

A numeric value specifying the ordinal position of the value to change. It must be in the range between 1 and Len().

is the new value to assign at position in .

Return The function returns always NIL.

Description This function changes the value of the associative array at position . If is outside the valid range, a runtime error is raised. Use function HaaGetPos() to determine the ordinal position of a key/value pair.

Info See also: Category: Source: LIB: DLL:

Array(), HaaGetKeyAt(), HaaGetPos(), HaaGetValueAt(), Hash(), HSetAACompatibility() Associative arrays, Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example outlines the possibilities of changing // values in an associative array. PROCEDURE Main LOCAL hArray := Hash() HSetAACompatibility( hArray, .T. ) hArray[ hArray[ hArray[ hArray[ hArray[

"One" ] "Two" ] "Three"] "Four" ] "Five" ]

:= := := := :=

10 20 30 40 50

HaaSetValueAt( hArray, 1, 100 )

680

Function Reference

HaaSetValueAt() hArray["Two"] := 200 hArray[3] := 300 ? hArray["One"] ? HaaGetValueAt( hArray, 2 ) ? hArray[3] RETURN

Function Reference

// result: 100 // result: 200 // result: 300

681

HAllocate()

HAllocate() Pre-allocates memory for a large hash.

Syntax HAllocate( , ) --> NIL

Arguments

A variable referencing an empty hash to pre-allocate memory for.

A numeric value specifying the number of key/value pairs to reserve memory for.

Return The function returns always NIL.

Description The function is used to pre-allocate memory for an empty hash or to reduce its pre-allocated size. When the number of key/value pairs to collect in a hash is approximately known in advance, it can be useful to pre-allocate memory for it so that the time to grow a hash and allocate memory for it is reduced to a minimum. To reduce memory pre-allocated in excess, call HAllocate() with a small value for . The function is provided in case huge hashes must be built and performance is at stake. Normally, the partitioning of hashes using HSetPartition() is more effective in creating large hashes.

Info See also: Category: Source: LIB: DLL:

682

Hash(), HSetPartition() Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Function Reference

HardCR()

HardCR() Replaces soft carriage returns with hard CRs in a character string.

Syntax HardCR( ) --> cConvertedString

Arguments

A character string to be converted.

Return The function returns with all soft carriage returns converted to hard carriage returns.

Description Soft carriage returns (Chr(141)+Chr(10)) are inserted into a string by MemoEdit() when a line wraps during editing. The string returned from MemoEdit() retains soft carriage returns and is usually stored in a memo field. When such a string must be printed or displayed with another function than MemoEdit(), it is necessary to replace soft carriage returns with hard carriage returns (Chr(13)+Chr(10)) since soft carriage returns are not interpreted as end of line characters. Note: when a memo field is output using a proportional font, use MemoTran() to replace soft carriage returns with a space character.

Info See also: Category: Source: LIB: DLL:

?|??, @...SAY, MemoTran(), StrTran() Character functions, Memo functions rtl\hardcr.c xhb.lib xhbdll.dll

Example // The example displays a memo field previously formatted with the // automatic word wrapping of MemoEdit(). PROCEDURE Main USE Customer NEW ? HardCR( Customer->Notes ) USE RETURN

Function Reference

683

Hash()

Hash() Creates a new hash.

Syntax Hash( [, [, , ] ] ) --> hHash

Arguments ..

is the key value associated with in the hash. The key value is usually of data type Character, but may be a Date or Numeric value. ..

is a value in the hash which can be accessed through its key value .

Return The function returns a new hash, populated with the specified key/value pairs. If no parameter is passed, an empty hash is returned. If the function is called with an odd number of arguments, or key values are specified which are not of data type Character, Date or Numeric, the return value is NIL.

Description Hash variables are usually initialized within a variable declaration using the literal Hash operator \{=>\}. The Hash() function is equivalent to this operator and allows for creating hashes programmatically outside a variable declaration. Hashes can be populated with key/value pairs by passing an even number of parameters to the function. Data representing the key values must be of orderable data types which restricts them to the data types C, D and N.

Info See also: Category: Source: LIB: DLL:

{=>}, HAllocate(), HClone(), HCopy(), HGet(), HDel(), HEval(), HSet(), HSetCaseMatch(), HGetPartition() Hash functions, xHarbour extensions vm\hash.c xhb.lib xhbdll.dll

Example // The example creates hashes using the literal hash operator // and the Hash() function. PROCEDURE Main LOCAL hHash1 := { "OPT1" => 10, "OPT2" => 20 } LOCAL hHash2, hHash3 hHash2 := Hash( "OPT2", 200, "OPT3", 300, "OPT4", 400 ) hHash3 := hHash1 + hHash2

684

Function Reference

Hash() ? ValToPrg( hHash3 ) // { "OPT1" => 10, "OPT2" => 200, "OPT3" => 300, "OPT4" => 400 } RETURN

Function Reference

685

HB_AExpressions()

HB_AExpressions() Parses a character string into an array of macro expressions.

Syntax HB_AExpressions( ) --> aMacroExpressions

Arguments

This is a character string holding a list of macro expressions.

Return The function returns a one dimensional array holding in its elements individual macro expressions.

Description Function HB_AExpressions() parses a character string, extracts from it single macro expressions and collects them in the returned array. If the string contains multiple expressions, they must be comma separated.

Info See also: Category: Source: LIB: DLL:

& (macro operator), HB_MacroCompile(), HB_VmExecute() Indirect execution, xHarbour extensions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example parses a string holding three macro expressions. The // the individual macro expressions are displayed and then compiled. PROCEDURE Main( ... ) LOCAL cMacro, aExpr PRIVATE nNum := 10 PRIVATE aName := { "xHarbour" } cMacro := "PCount(),(Valtype(nNum)=='N' .AND. nNum>0), aName[1]" aExpr

:= HB_AExpressions( cMacro )

AEval( aExpr, {|c| QOut(c) } ) ** Output: // PCount() // (Valtype(nNum)=='N' .AND. nNum>0) // aName[1] FOR EACH cMacro IN aExpr ? &cMacro NEXT ** Output: // 0

686

Function Reference

HB_AExpressions() // .F. // xHarbour RETURN

Function Reference

687

HB_AnsiToOem()

HB_AnsiToOem() Converts a character string from the ANSI to the OEM character set.

Syntax HB_AnsiToOem( ) --> cOEM_String

Arguments

A character string holding characters from the ANSI character set.

Return The function returns a string converted to the OEM character set.

Description The function converts all characters of to the corresponding characters in the MSDOS (OEM) character set. Both character sets differ in characters whose ASCII values are larger than 127. If a character in the ANSI string does not have an equivalent in the OEM character set, it is converted to a similar character of the OEM character set. In this case, it may not be possible to reverse the ANSI => OEM conversion with function HB_OemToAnsi(). Note: all databases created with Clipper store their data using the OEM character set. Displaying data in xHarbour console applications occurs with the OEM character set. Data display in xHarbour GUI applications is done with the Windows ANSI character set.

Info See also: Category: Source: LIB: DLL:

HB_OemToAnsi(), HB_SetCodePage() Conversion functions, xHarbour extensions rtl\oemansi.c xhb.lib xhbdll.dll

Example // // // //

The example demonstrates the effect of ANSIOEM conversion using a character string where the conversion is not reversible. The character string contains characters used for line graphics in DOS. #include "Box.ch" PROCEDURE Main LOCAL cOEM1 := B_SINGLE LOCAL cANSI := HB_OemToAnsi( B_SINGLE ) LOCAL cOEM2 := HB_ANsiToOem( cANSI ) DispBox(10, 10, 20, 20, cOEM1 ) @ Row(), COl() SAY "OEM1" DispBox(10, 30, 20, 40, cANSI )

688

Function Reference

HB_AnsiToOem() @ Row(), COl() SAY "ANSI" DispBox(10, 50, 20, 60, cOEM2 ) @ Row(), COl() SAY "OEM2" @ MaxROw()-1, 0 WAIT RETURN

Function Reference

689

HB_AParams()

HB_AParams() Collects values of all parameters passed to a function, method or procedure.

Syntax HB_AParams() --> aValues

Return The function returns an array holding the values of all parameters passed.

Description Function HB_AParams() provides a convenient way of collecting all parameters passed to a function, method or procedure with one function call in an array.

Info See also: Category: Source: LIB: DLL:

PCount(), PValue(), Valtype() Debug functions, Environment functions, xHarbour extensions "" xhb.lib xhbdll.dll

Example // The example demonstrates how an unknown number of command line // arguments passed to an xHarbour application can be processed. PROCEDURE Main( ... ) LOCAL aArg := HB_AParams() LOCAL cArg FOR EACH cArg IN aArg DO CASE CASE Upper( cArg ) IN ("-H/H-?/?") ? "Help requested" CASE .NOT. cArg[1] IN ( "-/" ) ?? " argument:", cArg CASE Upper( cArg ) IN ("-X/X") ? "Execution requested" OTHERWISE ? "Unknown:", cArg ENDCASE NEXT RETURN

690

Function Reference

HB_ArgC()

HB_ArgC() Returns the number of command line arguments.

Syntax HB_ArgC() --> nArgCount

Return The function returns the number of command line arguments.

Description When an xHarbour application is started, it can be passed arguments from the command line which are received by the initial routine of the application. HB_ArgC() determines this number of arguments. The contents of command line arguments can be retrieved with function HB_ArgV().

Info See also: Category: Source: LIB: DLL:

HB_ArgV(), PCount(), PValue() Debug functions, Environment functions, xHarbour extensions rtl\cmdarg.c xhb.lib xhbdll.dll

Example // // // //

The example outlines the difference between PCount() and HB_ArgC(). Command line arguments can be retrieved in the start routine with PCount()/PValue(), or anywhere in a program with HB_ArgC()/HB_ArgV() PROCEDURE Main( ... ) LOCAL i FOR i:=1 TO PCount() ? i, PValue(i) NEXT ? "-----------" Test() RETURN

PROCEDURE Test LOCAL i FOR i:=1 TO HB_ArgC() ? i, HB_ArgV(i) NEXT RETURN

Function Reference

691

HB_ArgCheck()

HB_ArgCheck() Checks if an internal switch is set on the command line.

Syntax HB_ArgCheck( ) --> lExists

Arguments

This is a character string holding the symbolic name of the internal command line switch to check.

Return The function returns .T. (true) when the xHarbour application is started with set on the command line, otherwise .F. (false) is returned.

Description An xHarbour application can be started with regular and internal command line switches, or arguments. Internal switches are prefixed with two slashes, while regular switches are not prefixed. HB_ArgCheck() tests only the existence of prefixed switches. Note: use function HB_ArgString() to retrieve the value of an internal command line switch.

Info See also: Category: Source: LIB: DLL:

HB_ArgC(), HB_ArgV(), HB_ArgString(), PCount(), PValue() Debug functions, Environment functions, xHarbour extensions vm\cmdarg.c xhb.lib xhbdll.dll

Example // The example tests for the existence of the command line switch TEST. // The result is only true, when the program is started as follows // (the command line switch is case insensitive): // // c:\xhb\test.exe //TEST // c:\xhb\test.exe //test PROCEDURE Main( ... ) ? HB_ArgCheck( "TEST" ) RETURN

692

Function Reference

HB_ArgString()

HB_ArgString() Retrieves the vale of an internal switch set on the command line.

Syntax HB_ArgString( ) --> cValue | NIL

Arguments

This is a character string holding the symbolic name of the internal command line switch to check.

Return The function returns the value of the commad line switch as a character string. If is not used at program invocation, the return value is NIL. When it has no value, a null string ("") is returned.

Description An xHarbour application can be started with regular and internal command line switches, or arguments. Internal switches are prefixed with two slashes, while regular switches are not prefixed. HB_ArgString() retrieves the value of prefixed switches. Note: use function HB_ArgString() to retrieve the value of an internal command line switch.

Info See also: Category: Source: LIB: DLL:

HB_ArgC(), HB_ArgCheck(), HB_ArgV(), PCount(), PValue() Debug functions, Environment functions, xHarbour extensions vm\cmdarg.c xhb.lib xhbdll.dll

Example // The example retrieves the value of the command line switch TEST. // The value is displayed, when the program is started as follows // (the command line switch is case insensitive): // // c:\xhb\test.exe //TEST10 // c:\xhb\test.exe //test10 PROCEDURE Main( ... ) ? HB_ArgString( "TEST" ) ? HB_ArgString( "TEST1" ) ? HB_ArgString( "TEST2" )

// result: 10 // result: 0 // result: NIL

RETURN

Function Reference

693

HB_ArgV()

HB_ArgV() Retrieves the value of a command line argument.

Syntax HB_ArgV( ) --> cArgValue

Arguments

This is a numeric value indicating the ordinal position of the command line argument to check. The value zero is

Return The function returns the value of the command line argument at position passed to thexHarbour application as a character string. If is larger than HB_ArgC(), a null string ("") is returned.

Description HB_ArgV() is used to retrieve the contents of command line arguments passed to an xHarbour application when it is started. The values are retrieved by their ordinal position and are returned as character strings. To ordinal position zero has a special meaning: it retrieves the name of xHarbour application.

Info See also: Category: Source: LIB: DLL:

HB_ArgC(), HB_ArgCheck(), HB_ArgString(), PCount(), PValue() Debug functions, Environment functions, xHarbour extensions rtl\cmdarg.c xhb.lib xhbdll.dll

Example // The example implements the user-defined function AppName() // which builds the application name upon initial call and // returns it with or without complete path. PROCEDURE Main( ... ) ? AppName() ? AppName(.T.) RETURN FUNCTION AppName( lFullName ) STATIC scAppName IF scAppName == NIL // path information scAppName := CurDrive() + ":\" + CurDir() + "\" scAppName += HB_ArgV(0)

// EXE file name

IF .NOT. ".exe" IN Lower( scAppName ) scAppName += ".exe" ENDIF

694

Function Reference

HB_ArgV() ENDIF IF Valtype( lFullName ) "L" lFullName := .F. ENDIF IF .NOT. lFullName RETURN SubStr( scAppName, RAt( "\", scAppName ) + 1 ) ENDIF RETURN scAppName

Function Reference

695

HB_ArrayId()

HB_ArrayId() Returns a unique identifier for an array or an object variable.

Syntax HB_ArrayId( | ) --> pID

Arguments

This is an array to retrieve a unique identifier for.

Alternatively, an object can be passedThis is an array to retrieve a unique identifier for.

Return The function returns a pointer value (Valtype()=="P") of the passed array or object. If neither an array nor an object is passed, a null pointer is returned.

Description Function HB_ArrayID() is provided for debug purposes and returns a unique value for the passed array or object. If two variables hold arrays or objects, and HB_ArrayId() returns the same value for both variables, they reference the same array or object. Note: the returned identifier is only valid during one program invocation. It cannot be used for identifying persistent data between multiple program invocations.

Info See also: Category: Source: LIB: DLL:

696

Array(), HBObject(), HB_ThisArray() Array functions, Debug functions, Object functions, xHarbour extensions vm\arrayshb.c xhb.lib xhbdll.dll

Function Reference

HB_ArrayToStructure()

HB_ArrayToStructure() Converts an array to a binary C structure.

Syntax HB_ArrayToStructure( , ; , ; [] ) --> cBinaryStructure

Arguments

This is an an array holding the values of the structure members to convert to binary.

The C-data types to convert each element of to must be specified as a one dimensional array of the same length as . #define constants must be used for . The following constants are available in the Cstruct.ch file:

Constants for C-data types Constant

C-data type

CTYPE_CHAR CTYPE_UNSIGNED_CHAR CTYPE_CHAR_PTR CTYPE_UNSIGNED_CHAR_PTR CTYPE_SHORT CTYPE_UNSIGNED_SHORT CTYPE_SHORT_PTR CTYPE_UNSIGNED_SHORT_PTR CTYPE_INT CTYPE_UNSIGNED_INT CTYPE_INT_PTR CTYPE_UNSIGNED_INT_PTR CTYPE_LONG CTYPE_UNSIGNED_LONG CTYPE_LONG_PTR CTYPE_UNSIGNED_LONG_PTR CTYPE_FLOAT CTYPE_FLOAT_PTR CTYPE_DOUBLE CTYPE_DOUBLE_PTR CTYPE_VOID_PTR CTYPE_STRUCTURE CTYPE_STRUCTURE_PTR

char unsigned char char * unsigned char* short unsigned short short * unsigned short * int unsigned int int * unsigned int * long unsigned long long * unsigned long * float float * double double * void * struct struct *



Optionally, the byte alignment for C-structure members can be specified. By default, the members are aligned at an eight byte boundary. Note that Windows API functions require a four byte alignment for structures.

Function Reference

697

HB_ArrayToStructure()

Return The function returns a character string holding the values of structure members in binary form.

Description Function HB_ArrayToStructure() converts an array into a binary string representation of a C structure. The returned string contains the values of structure members in binary form and can be passed to external API functions via DllCall(). If the structure is an "out" parameter of the API function, it must be passed by reference and can be converted back to an array using HB_StructureToArray(). HB_ArrayToStructure() is appropriate for simple structures. It is recommended to declare a structure class using typedef struct when a structure is complex, e.g. when it is a nested structure.

Info See also: Category: Header: Source: LIB: DLL:

C Structure class, HB_StructureToArray(), pragma pack(), (struct), typedef struct C Structure support, xHarbour extensions cstruct.ch vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example simulates the POINT structure which has only two members. // An array of two elements represents a point with an x and y coordinate. // The array is converted to a binary structure of 8 bytes. #include "Cstruct.ch" PROCEDURE Main LOCAL aMember := { 100, 200 } LOCAL aTypes := { CTYPE_LONG, CTYPE_LONG } LOCAL nAlign := 4 LOCAL cBinary cBinary := HB_ArrayToStructure( aMember, aTypes, nAlign ) ? Len( cBinary )

// result: 8

? Bin2L( Left( cBinary, 4 ) )

// result: 100

? Bin2L( Right( cBinary, 4 ) ) RETURN

698

// result: 200

Function Reference

HB_ATokens()

HB_ATokens() Splits a string into tokens based on a delimiter.

Syntax HB_ATokens( , [] , [] , []

; ; ; ) --> aTokens

Arguments

This is a character string which is tokenized based on the value of .

A single character can be specified as delimiter used to tokenize the string . It defaults to a blank space (Chr(32)).

This parameter defaults to .F. (false). When it is set to .T. (true), all portions of enclosed in single or double quotes are not searched for .

The parameter is only relevant when is .T. (true). When is also .T. (true), only portion sof enclosed in double quotes are not searched for .

Return The function returns an array of character strings.

Description HB_ATokens() function splits into substrings, based on the value of . The delimiter is removed from and the resulting substrings are collected in an array, which is returned. If is .T. (true), a quoted substring within is not split if it contains the delimiter sign. If the value of is .F. (false), which is the default, the quoted substring will be split, regardless of the quotes. The argument specifies if both the double and single quote signs are interpreted as a quote sign (.F.) or only the double quote is recognized as a quote sign (.T.).

Info See also: Category: Source:

At(), IN, Left(), Rat(), Right(), SubStr() Array functions, Character functions vm\arrayshb.c

Example // The example displays the result of HB_ATokens() using different // combinations for and

Function Reference

699

HB_ATokens() PROCEDURE Main LOCAL cString := [This\'_is\'_a_tok"e_n"ized_string] LOCAL aTokens := {} LOCAL i aTokens := HB_ATokens( cString, "_", .F., .F. ) FOR i := 1 TO Len( aTokens ) ? aTokens[i] NEXT // Result: array with 6 elements // This\' // is\' // a // tok"e // n"ized // string aTokens := HB_ATokens( cString, "_", .T., .F. ) FOR i := 1 TO Len( aTokens ) ? aTokens[i] NEXT // Result: array with 4 elements // This\'_is\' // a // tok"e_n"ized // string aTokens := HB_ATokens( cString, "_", .T., .T. ) FOR i := 1 TO Len( aTokens ) ? aTokens[i] NEXT // Result: array with 5 elements // This\' // is\' // a // tok"e_n"ized // string RETURN

700

Function Reference

HB_AtX()

HB_AtX() Locates a substring within a character string based on a regular expression.

Syntax HB_AtX( , , [], [@] , [@]

; ; ; ; ) --> cFoundString

Arguments

This is a character string holding the search pattern as a literal regular expression. Alternatively, the return value of HB_RegExComp() can be used.

This is the character string being searched for a matching substring.

This parameter defaults to .T. (true) so that a case sensitive search is performed. Passing .F. (false) results in a case insensitive search. @

If passed by reference, gets assigned a numeric value indicating the start position of the found substring in . When there is no match, is set to zero. @

If passed by reference, gets assigned a numeric value indicating the length of the found substring in . When there is no match, is set to zero.

Return The function returns the first substring contained in that matches the regular expression . If no match is found, the return value is NIL.

Description Function HB_AtX() searches a character string for matching regular expression and returns the found substring. It is a simple pattern matching function which searches and extracts only the first occurance of a substring and optionally returns its position and size in the searched string when and are passed by reference.

Function Reference

701

HB_AtX()

Info See also: Category: Source: LIB: DLL:

At(), HB_RegEx(), HB_RegExAll(), HB_RegExSplit(), RAt(), SubStr() Character functions, Regular expressions, xHarbour extensions rtl\regex.c xhb.lib xhbdll.dll

Example // The example extracts an eMail address from a text string. // The search is case insensitive although the RegEx defines // charcater classes only with upper case letters. PROCEDURE Main LOCAL cRegEx := "[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}" LOCAL cText := "Send your request to [email protected] " + ; "for more information" LOCAL cEmail, nStart, nLen cEmail := HB_AtX( cRegEx, cText, .F., @nStart, @nLen ) ? cEmail ? nStart ? nLen RETURN

702

// result: [email protected] // result: 22 // result: 17

Function Reference

HB_BackGroundActive()

HB_BackGroundActive() Queries and/or changes the activity of a single background task.

Syntax HB_BackGroundActive( [, ] ) --> lOldActive

Arguments

This is the numeric task handle as returned by HB_BackGroundAdd().

This is an optional logical value used to change the activity of a background task. Passing .T. (true) activates the background task, and .F. (false) deactivates it.

Return The function returns the previous activation state of a background task as a logical value.

Description Function HB_BackGroundActive() queries and optionally changes the activation state of a single background task. If the task handle, as returned from HB_BackGroundAdd(), is valid, the previous value for the activation state is returned. If an invalid task handle is passed, the return value is NIL.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_BackGroundAdd(), HB_BackGroundDel(), HB_BackGroundReset(), HB_BackGroundRun(), HB_BackGroundTime(), HB_IdleAdd() Background processing, xHarbour extensions rtl\bkgtsks.c xhb.lib xhbdll.dll

703

HB_BackGroundAdd()

HB_BackGroundAdd() Adds a new background task.

Syntax HB_BackGroundAdd( , [], [] ) --> nTaskHandle

Arguments

This is a codeblock that will be executed in the background.

This is a numeric value specifying the number of milliseconds after which the task is executed. The default value is zero,which means that the background task is executed each time background processing is invoked.

The default value of is .T. (true) causing being checked for immediate background activation. Passing .F. (false) adds the task to the internal task list but does not execute it until it is activated with HB_BackGroundActive().

Return The function returns a numeric task handle that must be preserved for other background processing functions, such as HB_BackGroundDel().

Description Function HB_BackGroundAdd() adds the passed codeblock to the list of background tasks that will be executed concurrently to the main program. There is no limit for the number of background tasks. Background task processing must be activated using the command SET BACKGROUND TASKS ON. Background tasks are processed sequentially until a SET BACKGROUND TASKS OFF is issued or an idle state is encountered. The idle state is the state of the xHarbour virtual machine (VM) when it waits for user input from the keyboard or the mouse. The VM enters idle state during Inkey() calls. All applications that do not use Inkey() function calls can signal the idle state with a call to the HB_IdleState() function. Note: to avoid interruption of background processing during idle states, an idle task must be defined like HB_IdleAdd( \{||HB_BackGroundRun()\} ). An alternative for background tasks is provided with threads. Refer to function StartThread() for running parts of an application simultaneously in multiple threads.

704

Function Reference

HB_BackGroundAdd()

Info See also: Category: Source: LIB: DLL:

HB_BackGroundActive(), HB_BackGroundDel(), HB_BackGroundReset(), HB_BackGroundRun(), HB_BackGroundTime(), HB_ExecFromArray(), HB_IdleAdd(), StartThread() Background processing, xHarbour extensions rtl\bkgtsks.c xhb.lib xhbdll.dll

Example // // // //

The example uses a regular background task to display the time once in a second while MemoEdit() is active. To ensure continuous display while MemoEdit() waits for user input, an idle task is defined which enforces background task processing. PROCEDURE Main LOCAL nTask, nIdle DispOutAtSetPos( .F. ) SET BACKGROUND TASKS ON nIdle := HB_IdleAdd( {|| HB_BackGroundRun() } ) nTask := HB_BackGroundAdd( {|| ShowTime() }, 1000 ) MemoEdit( MemoRead( "Test.prg" ), 1, 0, MaxRow()-2, MaxCOl() ) HB_BackGroundDel( nTask ) HB_IdleDel( nIdle ) RETURN

PROCEDURE ShowTime() DispoutAt( MaxRow(), MaxCol()-7, Time() ) RETURN

Function Reference

705

HB_BackGroundDel()

HB_BackGroundDel() Removes a background task from the internal task list.

Syntax HB_BackGroundDel( ) --> bAction

Arguments

This is the numeric task handle as returned by HB_BackGroundAdd().

Return The function returns the code block assoiated with the task handle, or NIL if an invalid task handle is specified.

Description Function HB_BackGroundDel() removes the task associated with the passed task handle from the internal list of background tasks. The task handle must be a value returned by a previous call to the HB_BackGroundAdd() function. If the specified task exists, it is deactivated and the associated code block is returned.

Info See also: Category: Source: LIB: DLL:

706

HB_BackGroundActive(), HB_BackGroundAdd(), HB_BackGroundReset(), HB_BackGroundRun(), HB_BackGroundTime(), HB_ExecFromArray() Background processing, xHarbour extensions rtl\bkgtsks.c xhb.lib xhbdll.dll

Function Reference

HB_BackGroundReset()

HB_BackGroundReset() Resets the internal counter of background tasks.

Syntax HB_BackGroundReset() --> NIL

Return The return value is always NIL.

Description Function HB_BackGroundReset() resets the internal counter identifying the next background task to be executed to 1. As a result, the next cycle for background processing starts with the first task defined.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_BackGroundActive(), HB_BackGroundAdd(), HB_BackGroundDel(), HB_BackGroundRun(), HB_BackGroundTime() Background processing, xHarbour extensions rtl\bkgtsks.c xhb.lib xhbdll.dll

707

HB_BackGroundRun()

HB_BackGroundRun() Enforces execution of one or all background tasks.

Syntax HB_BackGroundRun( [] ) --> NIL

Arguments

This is the numeric task handle as returned by HB_BackGroundAdd(). If omitted, all background tasks are executed.

Return The return value is always NIL.

Description Function HB_BackGroundRun() executes a single background task defined with , or all tasks from the internal task list when no task handle is specified. The function can be used to enforce execution of background tasks during regular program execution or during idle states of a program. Note: HB_BackGroundRun() executes the task specified with immediately, even if the wait interval defined for this task has not elapsed, or if the task is not active.

Info See also: Category: Source: LIB: DLL:

708

HB_BackGroundActive(), HB_BackGroundAdd(), HB_BackGroundDel(), HB_BackGroundReset(), HB_BackGroundTime(), HB_IdleAdd() Background processing, xHarbour extensions rtl\bkgtsks.c xhb.lib xhbdll.dll

Function Reference

HB_BackGroundTime()

HB_BackGroundTime() Queries or changes the wait interval in milliseconds after which the task is executed.

Syntax HB_BackGroundTime( ( [, ] ) --> nOldInterval

Arguments

This is the numeric task handle as returned by HB_BackGroundAdd().

This is an optional numeric value specifying the time interval in milliseconds a background task should wait between two execution cycles. When set to zero, a background task is invoked each time the internal task list is checked for background execution.

Return The function returns the previous wait interval of the background task as a numeric value. If an invalid task handle id passed, the return value is NIL.

Description Function HB_BackGroundTime() queries or changes the number of milliseconds after which the task is executed. Normally, the time interval is defined with the second parameter of HB_BackGroundAdd().

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_BackGroundActive(), HB_BackGroundAdd(), HB_BackGroundDel(), HB_BackGroundReset(), HB_BackGroundRun() Background processing, xHarbour extensions rtl\bkgtsks.c xhb.lib xhbdll.dll

709

HB_BitAnd()

HB_BitAnd() Performs a bitwise AND operation with numeric integer values.

Syntax HB_BitAnd( , ) --> nResult

Arguments

Two numeric integer values must be passed. If numbers with decimal fractions or values of other data types are specified, a runtime error is generated. Function Int() can be used to make sure both parameters are integer values.

Return The function returns a numeric value. It is the result of the bitwise AND operation with both parameters.

Description The function performs bitwise AND operation with two integer values. It compares individual bits of both values at the same position. If bits at the same position are set in both values, the bit at this position is also set in the return value.

Info See also: Category: Source: LIB: DLL:

710

& (bitwise AND), HB_BitIsSet(), HB_BitNot(), HB_BitOr(), HB_BitXOr() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Function Reference

HB_BitIsSet()

HB_BitIsSet() Checks if a bit is set in a numeric integer value.

Syntax HB_BitIsSet( , ) --> lBitIsSet

Arguments

This is a numeric integer value to check for set bits.

This numeric parameter specifies the position of the bit to test. The least significant bit has position zero, so that the range for is 0 to 31 on a 32-bit operating system.

Return The function returns .T. (true) when the bit is set at the specified position, otherwise .F. (false).

Description Function HB_BitIsSet() tests individual bits of a numeric integer value. This allows, for example, to encode multiple status variables in a single numeric value and detect different values from a single memory variable, or to build the binary character representation for an integer number.

Info See also: Category: Source: LIB: DLL:

HB_BitReset(), HB_BitSet(), HB_BitShift() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Example // The example implements function Num2Bit() which creates // a characters string consisting of "0" and "1" PROCEDURE Main() ? Num2Bit( 1 ) ? Num2Bit( 64 ) ? Num2Bit( 1234 ) ? Num2Bit( 12345678 ) RETURN FUNCTION LOCAL LOCAL LOCAL LOCAL

// // // //

result: result: result: result:

0000000000000001 0000000001000000 0000010011010010 00000000101111000110000101001110

Num2Bit( nNumber ) nInt := Int( nNumber ) nLen := IIf( Abs(nInt) > 2^15, 31, 15 ) cBin := Replicate( "0", nLen+1 ) nPos

FOR nPos := 0 TO nLen IF HB_BitIsSet( nInt, nPos ) cBin[ nLen-nPos+1 ] := "1" ENDIF

Function Reference

711

HB_BitIsSet() NEXT RETURN cBin

712

Function Reference

HB_BitNot()

HB_BitNot() Performs a bitwise OR operation with a numeric integer value.

Syntax HB_BitNot( ) --> nResult

Arguments

A numeric integer value must be passed. If a number with decimal fraction or a value of other data types is specified, a runtime error is generated. Function Int() can be used to make sure the parameter is an integer value.

Return The function returns a numeric value. It is the result of the bitwise NOT operation with the bits of the parameter.

Description The function performs bitwise NOT operation with the bits of the passed parameter. That is, all bits are inverted.

Info See also: Category: Source: LIB: DLL:

HB_BitAnd(), HB_BitIsSet(), HB_BitOr(), HB_BitXOr() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Example // The example shows the result of a bitwise NOT operation PROCEDURE Main LOCAL i FOR i := -5 TO 5 ? i, HB_BitNot(i) NEXT ** Output // // // // // // // // // // // RETURN

Function Reference

-5 -4 -3 -2 -1 0 1 2 3 4 5

4 3 2 1 0 -1 -2 -3 -4 -5 -6

713

HB_BitOr()

HB_BitOr() Performs a bitwise OR operation with numeric integer values.

Syntax HB_BitOr( , ) --> nResult

Arguments

Two numeric integer values must be passed. If numbers with decimal fractions or values of other data types are specified, a runtime error is generated. Function Int() can be used to make sure both parameters are integer values.

Return The function returns a numeric value. It is the result of the bitwise OR operation with both parameters.

Description The function performs bitwise OR operation with two integer values. It compares individual bits of both values at the same position. If bits at the same position are set in either value, the bit at this position is also set in the return value. The bit in the return value is not set when the bits of both values at this position are not set.

Info See also: Category: Source: LIB: DLL:

714

| (bitwise OR), HB_BitAnd(), HB_BitIsSet(), HB_BitNot(), HB_BitXOr() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Function Reference

HB_BitReset()

HB_BitReset() Sets a bit in a numeric integer value to 0.

Syntax HB_BitReset( , ) --> nResult

Arguments

This is a numeric integer value.

This numeric parameter specifies the position of the bit to set to 0. The least significant bit has position zero, so that the range for is 0 to 31 on a 32-bit operating system.

Return The function returns the integer number where the specified bit is set to 0.

Description Function HB_BitReset() sets a single bit of a numeric integer to 0. If the bit at position is not set in , the result has the same value, otherwise its value is different.

Info See also: Category: Source: LIB: DLL:

HB_BitIsSet(), HB_BitSet(), HB_BitShift() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Example // The example displays the result of HB_BitReset() with the // help of a user defined function Num2Bit(). The bit sequence // and the numeric value resulting from the operation is shown. PROCEDURE Main LOCAL nInt := 4567 LOCAL n, i ? "Original :", " ", Num2Bit( nInt ), LTrim(Str(nInt)) ? FOR i:= 0 TO 7 n := HB_BitReset( nInt, i ) ? "Reset Bit:", LTrim(Str(i)), Num2Bit( n ), LTrim(Str(n)) NEXT ** output // Original :

11010111 4567

// Reset Bit: 0 11010110 4566 // Reset Bit: 1 11010101 4565 // Reset Bit: 2 11010011 4563

Function Reference

715

HB_BitReset() // Reset // Reset // Reset // Reset // Reset RETURN

FUNCTION LOCAL LOCAL LOCAL LOCAL

Bit: Bit: Bit: Bit: Bit:

3 4 5 6 7

11010111 11000111 11010111 10010111 01010111

4567 4551 4567 4503 4439

Num2Bit( nNumber ) nInt := Int( nNumber ) nLen := 7 cBin := Replicate( "0", nLen+1 ) nPos

FOR nPos := 0 TO nLen IF HB_BitIsSet( nInt, nPos ) cBin[ nLen-nPos+1 ] := "1" ENDIF NEXT RETURN cBin

716

Function Reference

HB_BitSet()

HB_BitSet() Sets a bit in a numeric integer value to 1.

Syntax HB_BitSet( , ) --> nResult

Arguments

This is a numeric integer value.

This numeric parameter specifies the position of the bit to set to 1. The least significant bit has position zero, so that the range for is 0 to 31 on a 32-bit operating system.

Return The function returns the integer number where the specified bit is set to 1.

Description Function HB_BitSet() sets a single bit of a numeric integer to 1. If the bit at position is set in , the result has the same value, otherwise its value is different.

Info See also: Category: Source: LIB: DLL:

HB_BitIsSet(), HB_BitReset(), HB_BitShift() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Example // The example displays the result of HB_BitSet() with the // help of a user defined function Num2Bit(). The bit sequence // and the numeric value resulting from the operation is shown. PROCEDURE Main LOCAL nInt := 45678 LOCAL n, i ? "Original:", " ", Num2Bit( nInt ), LTrim(Str(nInt)) ? FOR i:= 0 TO 7 n := HB_BitSet( nInt, i ) ? "Set Bit: ", LTrim(Str(i)), Num2Bit( n ), LTrim(Str(n)) NEXT ** output // Original: // Set Bit: // Set Bit: // Set Bit:

Function Reference

01101110 45678 0 01101111 45679 1 01101110 45678 2 01101110 45678

717

HB_BitSet() // Set // Set // Set // Set // Set RETURN

FUNCTION LOCAL LOCAL LOCAL LOCAL

Bit: Bit: Bit: Bit: Bit:

3 4 5 6 7

01101110 01111110 01101110 01101110 11101110

45678 45694 45678 45678 45806

Num2Bit( nNumber ) nInt := Int( nNumber ) nLen := 7 cBin := Replicate( "0", nLen+1 ) nPos

FOR nPos := 0 TO nLen IF HB_BitIsSet( nInt, nPos ) cBin[ nLen-nPos+1 ] := "1" ENDIF NEXT RETURN cBin

718

Function Reference

HB_BitShift()

HB_BitShift() Shifts bits in a numeric integer value.

Syntax HB_Bitshift( , ) --> nResult

Arguments

This is a numeric integer value.

This numeric integer value specifies how far to shift bits. When a negative number is passed, bits are shifted to the right. A positive value shifts bits to the left.

Return The function returns a numeric value. It is the result of the bit-shift operation.

Description Function HB_BitShift() shifts the bits of a numeric integer to the left or the right, depending on the sign of . A shift operation involves all bits of . When the bits are shifted one place to the left, the most significant, or highest, bit is discarded and the least significant (or lowest) bit is set to 0. When the bits are shifted one place to the right, the lowest bit is discarded and the highest bit is set to 0. A numeric value has 32 bits on a 32 bit operating system.

Info See also: Category: Source: LIB: DLL:

, HB_BitIsSet(), HB_BitReset(), HB_BitSet() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

Example // // // //

The example displays the result of bit-shift operations to the left and the right with the aid of a user defined function Num2Bit(). Note that the initial integer has only one bit set. This bit "drops off" when shifted 3 places to the right. PROCEDURE Main LOCAL nInt := 4 LOCAL i, n ? "Original:", " ", Num2Bit( nInt ), Str( nInt, 4 ) ? FOR i:= -3 TO 3 n := HB_BitShift( nInt, i ) ? "Shifted :", Str(i,2), Num2Bit( n ), Str( n, 4 ) NEXT

Function Reference

719

HB_BitShift() ** output // Original: // Shifted // Shifted // Shifted // Shifted // Shifted // Shifted // Shifted RETURN

FUNCTION LOCAL LOCAL LOCAL LOCAL

00000100

: -3 00000000 : -2 00000001 : -1 00000010 : 0 00000100 : 1 00001000 : 2 00010000 : 3 00100000

4 0 (bit dropped off) 1 2 4 8 16 32

Num2Bit( nNumber ) nInt := Int( nNumber ) nLen := 7 cBin := Replicate( "0", nLen+1 ) nPos

FOR nPos := 0 TO nLen IF HB_BitIsSet( nInt, nPos ) cBin[ nLen-nPos+1 ] := "1" ENDIF NEXT RETURN cBin

720

Function Reference

HB_BitXOr()

HB_BitXOr() Performs a bitwise XOR operation with numeric integer values.

Syntax HB_BitXOr( , ) --> nResult

Arguments

Two numeric integer values must be passed. If numbers with decimal fractions or values of other data types are specified, a runtime error is generated. Function Int() can be used to make sure both parameters are integer values.

Return The function returns a numeric value. It is the result of the bitwise XOR operation with both parameters.

Description The function performs bitwise XOR operation with two integer values. It compares individual bits of both values at the same position. The bit at the same position is set in the return value, when both integer values have the bit set differently at the same position. If both integers have the same bit set or not set, i.e. when both bits are the same, the corresponding bit in the return value is not set.

Info See also: Category: Source: LIB: DLL:

Function Reference

^^ (bitwise XOR), HB_BitAnd(), HB_BitIsSet(), HB_BitNot(), HB_BitOr() Bitwise functions, xHarbour extensions rtl\hbBitf.c xhb.lib xhbdll.dll

721

HB_BuildDate()

HB_BuildDate() Retrieves the formatted build date of the xHarbour compiler

Syntax HB_BuildDate() --> cDateTime

Return The function returns a character string formatted as "MMM dd yyyy hh:mm:ss" where "MMM" is the abbreviated month name, "dd" is the day, "yyyy" is the year and "hh:mm:ss" is the time.

Description FUnction HB_BuildDate() is used to retrieve a formatted date and time string of the day, the xHarbour compiler was built.

Info See also: Category: Source: LIB: DLL:

HB_BuildInfo(), HB_Compiler(), Os(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\version.c xhb.lib xhbdll.dll

Example PROCEDURE Main ? HB_BuildDate() RETURN

722

Function Reference

HB_BuildInfo()

HB_BuildInfo() Retrieves build information of the xHarbour compiler.

Syntax HB_BuildInfo( ) -->

cBuildInfo

Arguments

This is a numeric value indicating the information to retrieve. #define constants are listed in the Hbver.ch file that can be used for .

Return The function returns the requested build information. The data type of the return value depends on .

Description Function HB_BuildInfo() is used to retrieve information about the current build of the xHarbour compiler. The following information is returned depending on the #define constant used for :

Build information for the xHarbour compiler Constant

Value

Valtype() Description

_HB_VER_MAJOR _HB_VER_MINOR _HB_VER_REVISION _HB_VER_LEX _HB_VER_AS_STRING _HB_PCODE_VER _HB_VER_COMPILER _HB_VER_PLATFORM _HB_VER_BUILD_DATE _HB_VER_BUILD_TIME _HB_VER_LENTRY _HB_VER_CHLCVS _HB_VER_C_USR _HB_VER_L_USR _HB_VER_PRG_USR _HB_EXTENSION

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

N N N C C N C C C C C C C C C L

_HB_C52_UNDOC

17

L

_HB_C52_STRICT

18

L

_HB_COMPAT_C53

19

L

_HB_COMPAT_XPP

20

L

_HB_COMPAT_VO

21

L

Major version number Minor version number Revision number Lex version Complete version as character string Version number of PCode engine Version of C compiler Platform xHarbour is running on Date xHarbour was built Time xHarbour was built Last entry in CVS ChangeLog file Revision of last entry in CVS Reserved Reserved Reserved #define HB_EXTENSION is used for current build #define HB_C52_UNDOC is used for current build #define HB_C52_STRICT is used for current build #define HB_COMPAT_C53 is used for current build #define HB_COMPAT_XPP is used for current build #define HB_COMPAT_VO is used for current build

Function Reference

723

HB_BuildInfo() _HB_COMPAT_FLAGSHIP

22

L

_HB_COMPAT_FOXPRO

23

L

_HB_COMPAT_DBASE

24

L

_HB_HARBOUR_OBJ_GENERATION _HB_HARBOUR_STRICT_ANSI_C _HB_CPLUSPLUS _HB_HARBOUR_YYDEBUG _HB_SYMBOL_NAME_LEN _HB_MULTITHREAD _HB_VM_OPTIMIZATION _HB_LANG_ID _HB_ARRAY_MODE _HB_CREDITS

25 26 27 28 29 30 31 32 33 34

L L L L N L N C N A

#define HB_COMPAT_FLAGSHIP is used for current build #define HB_COMPAT_FOXPRO is used for current build #define HB_COMPAT_DBASE is used for current build Reserved Reserved Reserved Reserved Maximum length of symbolic variable names Multi-threading is supported Optimization level of Virtual Machine Language ID of language used for build Reserved Credits to xHarbour developers

Info See also: Category: Header: Source: LIB: DLL:

HB_BuildDate(), HB_Compiler(), Os(), Os_VersionInfo() Environment functions, xHarbour extensions hbver.ch rtl\version.c xhb.lib xhbdll.dll

Example // The example displays build information of the xHarbour compiler // and the operating system #include "hbver.ch" PROCEDURE Main CLS ? "Compiler:", HB_BuildInfo( _HB_VER_AS_STRING ) ? ? "Operating System:", HB_BuildInfo( _HB_VER_PLATFORM ) RETURN

724

Function Reference

HB_CheckSum()

HB_CheckSum() Calculates the checksum for a stream of data using the Adler32 algorithm.

Syntax HB_CheckSum( ) --> nAdler32

Arguments

This is a character string to calulate the checksum for.

Return The function returns the calculated checksum as a numeric value.

Description HB_CheckSum() implements the Adler32 algorithm for calculating the checksum of a character string. This algorithm computes faster than the algorithm of the HB_CRC32() function, but is less reliable, especially for short data streams. The following table compares the speed of checksum algorithms available in xHarbour

Algorithm comparison Function

Algorithm

Relative Speed

HB_CheckSum() HB_CRC32() HB_MD5()

Adler 32 bit CRC 32 bit MD5 128 bit

1.00 1.46 4.51

Info See also: Category: Source: LIB: DLL:

HB_CRC32(), HB_MD5() Checksum functions, xHarbour extensions rtl\hbchksum.c xhb.lib xhbdll.dll

Example // // // // //

The example calculates the checksum for two character strings. Note that if the example is compiled, it will display a different checksum for cString2 than shown in the example. The result changes the checksum of the file "Checksum.prg" PROCEDURE Main LOCAL cString1 := "Hello world" LOCAL cString2 := Memoread( "Checksum.prg" ) ? HB_CheckSum( cString1 )

// result:

413140028.00

? HB_CheckSum( cString2 )

// result: 1460748119.00

RETURN

Function Reference

725

HB_CmdArgArgV()

HB_CmdArgArgV() Returns the first command line argument (EXE file name).

Syntax HB_CmdArgArgV() --> cExeFile

Return The function returns the first command line argument as a character string.

Description Function HB_CmdArgArgV() queries the command line and returns the first argument. It is the name of the EXE file as entered by the user. Note that the file name may not include the ".exe" extension or directory information.

Info See also: Category: Source: LIB: DLL:

726

HB_ArgC(), HB_ArgCheck(), HB_ArgV(), PCount(), PValue() Debug functions, Environment functions, xHarbour extensions vm\cmdarg.c xhb.lib xhbdll.dll

Function Reference

HB_Compiler()

HB_Compiler() Retrieves the version of the C compiler shipped with xHarbour.

Syntax HB_Compiler() --> cCompilerVersion

Return The function returns a character string holding the name and version of the C compiler shipped with xHarbour.

Description Function HB_Compiler() is used to retrieve information about the C compiler shipped with xHarbour. The C compiler is an integral part of xHarbour and produces OBJ files.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_BuildDate(), HB_BuildInfo(), Os(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\version.c xhb.lib xhbdll.dll

727

Hb_CRC32()

Hb_CRC32() Calculates the checksum for a stream of data using the CRC 32 algorithm.

Syntax HB_CRC32( ) --> nCRC32

Arguments

This is a character string to calulate the checksum for.

Return The function returns the calculated checksum as a numeric value.

Description HB_CRC32() implements the CRC32 algorithm (Cyclic Redundancy Code) for calculating the checksum of a character string. This algorithm computes faster than the algorithm of the HB_MD5() function, but is less reliable. The following table compares the speed of checksum algorithms available in xHarbour:

Algorithm comparison Function

Algorithm

Relative Speed

HB_CheckSum() HB_CRC32() HB_MD5()

Adler 32 bit CRC 32 bit MD5 128 bit

1.00 1.46 4.51

Info See also: Category: Source: LIB: DLL:

728

HB_CheckSum(), HB_MD5() Checksum functions, xHarbour extensions rtl\hbcrc32.c xhb.lib xhbdll.dll

Function Reference

HB_Crypt()

HB_Crypt() Encrypts a character string.

Syntax HB_Crypt( , ) --> cEncryptedString

Arguments

This is a character string to encrypt.

This is a character string holding the encryption key.

Return The function returns the encrypted character string.

Description Function HB_Crypt() encrypts a character string using the encryption key . The key should have at least six characters and cannot be longer than 512 characters. The returned encrypted string can be decrypted by passing it to function HB_Decrypt() along with the same encryption key.

Info See also: Category: Source: LIB: DLL:

HB_Decrypt() Character functions, Conversion functions, xHarbour extensions rtl\hbcrypt.c xhb.lib xhbdll.dll

Example // The example shows how to encrypt a decrypt a character string. PROCEDURE Main LOCAL cText := "Hello world" LOCAL cKey := "xHarbour" LOCAL cCipher cCipher := HB_Crypt( cText, cKey ) ? cCipher ? HB_Decrypt( cCipher, cKey ) RETURN

Function Reference

729

HB_Decrypt()

HB_Decrypt() Decrypts an encrypted character string.

Syntax HB_Decrypt( , ) --> cString

Arguments

This is a previously encrypted character string to decrypt.

This is a character string holding the encryption key.

Return The function returns the decrypted character string.

Description Function HB_Decrypt() decrypts a character string previousle encrypted with function HB_Crypt(). A successful decryption requires the same key as used for encrypting the unencrypted string.

Info See also: Category: Source: LIB: DLL:

730

HB_Crypt() Character functions, Conversion functions, xHarbour extensions rtl\hbcrypt.c xhb.lib xhbdll.dll

Function Reference

HB_DeSerialize()

HB_DeSerialize() Converts a binary string back to its original data type.

Syntax HB_DeSerialize( ) --> xValue

Arguments

This is a character string returned from HB_Serialize().

Return The function returns the value previously converted by HB_Serialize().

Description HB_DeSerialize() reverses the result of HB_Serialize(), i.e. the binary string representation of a value is converted back to its original data type and returned.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_RestoreBlock(), HB_Serialize(), RESTORE, SAVE Conversion functions, xHarbour extensions rtl\hbserial.prg xhb.lib xhbdll.dll

731

HB_EnumIndex()

HB_EnumIndex() Returns the current ordinal position of a FOR EACH iteration.

Syntax HB_EnumIndex() --> nIteration

Return The function returns a numeric value. It is the ordinal position of the current item within a FOR EACH control structure.

Description Function HB_EnumIndex() is only used within a FOR EACH control structure. It returns a numeric value which can be viewed as the "loop counter" of the FOR EACH statement. HB_EnumIndex() identifies the ordinal position of the item that is currently processed by FOR EACH.

Info See also: Category: Source: LIB: DLL:

FOR, FOR EACH, HB_QSelf(), HB_QWith() Control structures, Environment functions, xHarbour extensions vm\hvm.c xhb.lib xhbdll.dll

Example // // // //

The example compares a regular FOR..NEXT loop with a FOR EACH loop. FOR..NEXT uses a loop counter while FOR EACH does not. Instead, the "loop counter" is retrieved with function HB_EnumIndex(). PROCEDURE Main LOCAL aArray1 := { "A", "B", "C" } LOCAL aArray2 := { "a", "b", "c" } LOCAL i, cValue CLS ? "FOR loop" FOR i:=1 TO Len( aArray1 ) ? i, aArray1[i] IF i == 3 AAdd( aArray1, "D" ) ENDIF NEXT ? ? "FOR EACH loop" FOR EACH cValue IN aArray2 ? HB_EnumIndex(), cValue IF HB_EnumIndex() == 3

732

Function Reference

HB_EnumIndex() AAdd( aArray2, "d" ) ENDIF NEXT RETURN

Function Reference

733

HB_Exec()

HB_Exec() Executes a function, procedure or method from its pointer.

Syntax HB_Exec( , [NIL, ] ) --> xResult or HB_Exec( , , [ ] ) --> xResult

Arguments

This is a pointer to a function or procedure to execute. It can be obtained with the functionreference operator or the HB_FuncPtr() function. If such a pointer is used, the second parameter must be NIL.

This is a pointer to an object's method to execute. It can be obtained with the HB_ObjMsgPtr() function. If such a pointer is used, the second parameter must be an object.

This is an object whose method is executed.

An optional list of parameters can be specified. They are passed to the function, method or procedure when executed.

Return HB_Exec() returns the result of the executed function, method or procedure.

Description Function HB_Exec() accepts as first parameter a pointer to a function, procedure or method. If a function/procedure pointer is used, the second parameter must be NIL. In case of a method pointer, the second parameter must be an object. All other optional parameters are passed on to the executed function, procedure or method. A pointer is a special data type in xHarbour and is of Valtype()=="P". It represents the memory address of a function, procedure or method. If a memory address is known, the corresponding routine can be executed without the need of looking up the symbolic name. This can lead to performance advantages.

734

Function Reference

HB_Exec()

Info See also: Category: Source: LIB: DLL:

@(), Eval(), HB_ExecFromArray(), HB_FuncPtr(), HB_ObjMsgPtr() Indirect execution, Pointer functions, xHarbour extensions vm\eval.c xhb.lib xhbdll.dll

Example // The example uses a function pointer of a built-in function and // a method pointer to a user-defined class for HB_Exec(). #include "hbclass.ch" PROCEDURE Main LOCAL oObject LOCAL pPointer := ( @QOut() ) // displays "Hello World" HB_Exec( pPointer, NIL, "Hello", "World" ) oObject := Test():new( "xHarbour" ) pPointer := HB_ObjMsgPtr( oObject, "display" ) // displays five times "xHarbour" HB_Exec( pPointer, oObject, 5 ) RETURN

CLASS Test PROTECTED: DATA name EXPORTED: METHOD init CONSTRUCTOR METHOD display ENDCLASS METHOD init( cName ) CLASS Test ::name := cName RETURN self METHOD display( nTimes ) CLASS Test LOCAL i IF nTimes == NIL nTimes := 1 ENDIF FOR i:=1 TO nTimes QOut( ::name ) NEXT RETURN self

Function Reference

735

HB_ExecFromArray()

HB_ExecFromArray() Executes a function, procedure or method indirectly.

Syntax HB_ExecFromArray( ) --> xResult HB_ExecFromArray( || ; [,] ) --> xResult HB_ExecFromArray( , | ; [,] ) --> xResult

Arguments

This is a one dimensional array whose first one or two elements contain executable data while all following elements are passed as parameters to the executable portion of the array. See details in the description.

This is a code block to be executed. It receives the values stored in the array as parameters, if specified.

This is a character string holding the symbolic name of a function or procedure to be executed. The values stored in the array are passed as parameters, if specified.

This is a pointer to a function or procedure to be executed. It can be obtained using function HB_FuncPtr(). The values stored in the array are passed as parameters, if specified.

If the first parameter is an object (Valtype()=="O"), the second parameter specifies the method to call for the object.

This is a character string holding the symbolic name of the method to be executed. The values stored in the array are passed as parameters, if specified.

This is a pointer to a method to be executed. It can be obtained using function HB_ObjMsgPtr(). The values stored in the array are passed as parameters to the method, if specified.

An optional, one dimensional array can be specified. Its elements are passed as parameters to a code block, function, method or procedure.

Return The function returns the return value of the executed code. 736

Function Reference

HB_ExecFromArray()

Description Function HB_ExecFromArray() is used for indirect execution of program code in xHarbour. The function can be called in different ways and accepts parameters of different data types, the first of which must contain an executable value, or item. Depending on the data type of an executable item, HB_ExecFromArray() uses different approaches for execution:

Paremeters and data types of executable items 1st param.

2nd param.

3rd param.

Description

Array Character string Code block Pointer Object Object

NIL Character string Pointer

NIL Executable array is processed NIL Macro operator executes function or procedure NIL Eval() executes code block NIL HB_Exec() executes function call Macro operator executes method of object HB_Exec() executes method of object

The following notes explain how HB_ExecFromArray() works depending on the data type of the first parameter passed:

Array When an array is passed as first parameter, it must be a so called "executable array". This is a one dimensional array whose first element contains an "executable item". An executable item can be of Valtype()=="C" (symbolic name of function or procedure to execute), Valtype()=="B" (code block to execute) or Valtype()=="P" (pointer to function or procedure to execute). The following elements of the executable array are passed as parameters to the executable item. If the executable item is of Valtype()=="O" (object), the second element of the executable array must contain either a character string specifying the name of the method to call, or it must be a pointer to a method obtained with HB_ObjMsgPtr(). All other values stored in the third to the last element of the executable array are passed as parameters to the object's method.

Character string When the first parameter is a character string, it must contain the symbolic name of a function or procedure which is visible at runtime. HB_ExecFromArray() uses the macro operator to call the corresponding function or procedure. The second parameter can be optionally a one dimensional array. Its elements are passed as parameters to the function or procedure.

Code block When the first parameter is a code block, the optional second parameter can be a one dimensional array whose elements are passed as parameters to the code block. It is executed with the Eval() function.

Pointer When the first parameter is a pointer, it must be obtained with the function-reference operator or the HB_FuncPtr() function. The optional second parameter contains the parameters to pass to the corresponding function or procedure. It is executed with HB_Exec().

Object When the first parameter is an object, the second parameter must be one of 1.

character string containing the symbolic name of a method to execute

2.

pointer to a method otained with HB_ObjMsgPtr()

Function Reference

737

HB_ExecFromArray()

The optional third parameter contains the parameters to pass to the corresponding method.

Info See also: Category: Source: LIB: DLL:

@(), {|| }, {}, Array(), Eval(), HB_Exec(), HB_FuncPtr(), HB_ObjMsgPtr() Indirect execution, Pointer functions, xHarbour extensions vm\eval.c xhb.lib xhbdll.dll

Examples // The example demonstrates various calls to HB_ExecFromArray() using // an executable array, code block, function name and pointer. PROCEDURE Main LOCAL cFunc := "QOUT" LOCAL pFunc := HB_FuncPtr( cFunc ) LOCAL aExec := { cFunc, "Hello", "World" } // executable array with function name HB_ExecFromArray( aExec ) // output: Hello World // function pointer and parameter array HB_ExecFromArray( pFunc, { "Hi", "there" } ) // output: Hi there // function name and parameter array ? HB_ExecFromArray( "CDOW", { Date() } ) // output: wednesday // executable array with code block and parameter bBlock := {|d| Year(d) } aExec := { bBlock, Date() } ? HB_ExecFromArray( aExec )

// output: 2006

RETURN // This example uses an object for HB_ExecFromArray() and // demonstrates possibilities of calling a method. #include "hbclass.ch" PROCEDURE Main LOCAL pMethod, oObject LOCAL aExec, bBlock // function name and no parameters oObject := HB_ExecFromArray( "NumStat" ) // executable array with object, method name and parameters aExec := { oObject, "set", 1, 2, 3, 4, 5 } HB_ExecFromArray( aExec ) // executable array with code block and parameter bBlock := {|o| o:total() } aExec := { bBlock, oObject } ? HB_ExecFromArray( aExec )

738

// result: 15

Function Reference

HB_ExecFromArray() // executable array with object, method pointer and no parameters pMethod := HB_ObjMsgPtr( oObject, "average" ) aExec := { oObject, pMethod } ? HB_ExecFromArray( aExec ) // code block and parameter array ? HB_ExecFromArray( bBlock, { oObject } ) RETURN

// result:

3

// result: 15

CLASS NumStat PROTECTED: DATA numbers DATA count EXPORTED: METHOD set METHOD average METHOD total ENDCLASS

METHOD set( ... ) CLASS NumStat ::numbers := HB_AParams() ::count := Len( ::numbers ) RETURN self

METHOD average CLASS NumStat RETURN ::total() / ::count

METHOD total CLASS NumStat LOCAL nTotal := 0 LOCAL nNumber FOR EACH nNumber IN ::numbers nTotal += nNumber NEXT RETURN nTotal

Function Reference

739

HB_FNameMerge()

HB_FNameMerge() Composes a file name from individual components.

Syntax HB_FNameMerge( [] , ; [] , ; [] ) --> cResult

Arguments

This is a character string holding the path component for a file.

This is a character string holding the name component for the file.

This is a character string holding the file extension.

Return The function returns a character string containing all components passed to the function. When no parameter is passed, an empty string ("") is returned.

Description Function HB_FNameMerge() is used to build a full qualified file name from individual components. They can be obtained by calling HB_FNameSplit().

Info See also: Category: Source: LIB: DLL:

CurDir(), CurDrive(), Directory(), File(), HB_FNameSplit() Character functions, File functions, xHarbour extensions rtl\fnsplit.c xhb.lib xhbdll.dll

Example // The function splits a full qualified file name and // merges different components PROCEDURE Main LOCAL cString := "C:\xhb\source\data\test.dbf" LOCAL cPath, cFileName, cExtension HB_FNameSplit( cString, @cPath, @cFileName, @cExtension ) ? HB_FNameMerge( , cFileName, cExtension ) // result: test.dbf ? HB_FNameMerge( cPath, cFileName ) // result: C:\xhb\source\data\test RETURN

740

Function Reference

HB_FNameSplit()

HB_FNameSplit() Splits a file name into individual components.

Syntax HB_FNameSplit( , [@] , [@] , [@]

; ; ; ) --> NIL

Arguments

This is a character string to split into different components of a file name. @

If specified, must be passed by reference. It receives the path component for a file as a character string. @

If specified, must be passed by reference. It receives the name component for a file as a character string. @

If specified, must be passed by reference. It receives the file extension as a character string.

Return The function returns always NIL. The components of a file name are assigned to the parameters passed by reference.

Description Function HB_FNameSplit() is used to split a full qualified file name into individual components. They can be merged later with function HB_FNameMerge().

Info See also: Category: Source: LIB: DLL:

CurDir(), CurDrive(), Directory(), File(), HB_FNameMerge() Character functions, File functions, xHarbour extensions rtl\fnsplit.c xhb.lib xhbdll.dll

Example // The function splits a full qualified file name and // displays the result PROCEDURE Main LOCAL cString := "C:\xhb\source\data\test.dbf" LOCAL cPath, cFileName, cExtension

Function Reference

741

HB_FNameSplit() ? HB_FNameSplit( cString, @cPath, @cFileName, @cExtension ) ? cPath ? cFileName ? cExtension

// result: C:\xhb\source\data\ // result: test // result: .dbf

RETURN

742

Function Reference

HB_FReadLine()

HB_FReadLine() Extracts the next line from a text file.

Syntax HB_FReadLine( , @ , [], []

; ; ; ) --> nReturn

Arguments

This is a numeric file handle returned from function FOpen(). @

A memory variable that must be passed by reference to HB_FReadLine(). It receives the character string read from the text file. does not need to be initialized.

The parameter is optional. It is either a character string containing the end-of-line characters, or an array of character strings, each element of which contains end-of-line characters. The default value for is Chr(13)+Chr(10) (Carriage return, Line feed).

This is an optional numeric value specifying the maximum line length the function searches for the next . The default value is 4096.

Return The function returns 0 when the next text line is read from the file. A value not equal zero is returned when no more lines are available to read.

Description HB_FReadLine() is an efficient extraction routine for getting the next available line from an ASCII text file. It differs from FReadStr() in allowing a programmer to define the end-of-line character(s) HB_FReadLine() should recognize. Also, the maximum length of a line to search for the next end-ofline character(s) can be specified. The default value of 4096 is sufficient for most common text files.

Info See also: Category: Source: LIB: DLL:

FOpen(), FClose(), FCreate(), FReadStr(), MemoLine(), MemoRead() Low level file functions, xHarbour extensions rtl\fnsplit.c xhb.lib xhbdll.dll

Example // The example demonstrates an efficient way of loading single lines // from an ASCII file into an array.

Function Reference

743

HB_FReadLine() PROCEDURE Main LOCAL cFileName := "HB_FReadLine.prg" LOCAL aLines := {} LOCAL nFileHandle := FOpen( cFileName ) LOCAL cLine DO WHILE HB_FReadLine( nFileHandle, @cLine ) == 0 AAdd( aLines, cLine ) ENDDO // Add the last line AAdd( aLines, cLine ) FClose( nFileHandle ) ? Len( aLines ) AEval( aLines, {|c| QOut( c ) } ) RETURN

744

Function Reference

HB_FSize()

HB_FSize() Returns the size of a file in bytes.

Syntax HB_FSize( ) --> nFileSize

Arguments

This is a character string holding the name of the file to query. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Return The function returns a numeric value indicating the size of the file in bytes. If the file does not exist, the return value is 0.

Description Function HB_FSize() is used to determine the size of a single file in bytes. Note that the return value of this function is 0 for an existing file with no contents and for a none existing file. Use function File() to check for the existence of a file.

Info See also: Category: Source: LIB: DLL:

Directory(), FileStats(), FCreate(), FOpen() Low level file functions, xHarbour extensions rtl\fssize.c xhb.lib xhbdll.dll

Example // The example displays the size of a single file PROCEDURE Main LOCAL cFileName := "HB_FSize.prg" ? HB_FSize( cFileName ) RETURN

Function Reference

745

HB_FTempCreate()

HB_FTempCreate() Creates and opens a temporary file.

Syntax HB_FTempCreate( [] , [] , [], [@]

; ; ; ) --> nFileHandle

Arguments

This is an optional character string specifying the directory where to create the temporary file. It defaults to the operating system variable SET TEMP or SET TMP. Operating system variables can be queried with function GetEnv().

This is an optional character string of three characters specifying the prefix to use for the name of the temporary file. It defaults to the string "xht".

This is an optional numeric value defining how to create and open the temporary file. See function FCreate() for a description of . @

If specified, must be passed by reference. It receives the file name of the created temporary file as a character string.

Return The function returns a numeric value > 0 when the temporary file is successfully created. This is the file handle of the created temporary file.

Description Function HB_FTempCreate() creates a temporary file and opens it. The return value is the file handle of the temporary file. It can be used with low level file functions, such as FWrite() to store data in the file. Temporary files are often required in an application. HB_FTempCreate() guarantees that the file name of the newly created file is unique, so that no existing file will be overwritten. To obtain the file name of the temporary file, parameter must be passed by reference. It can then later be passed to function FErase() in order to remove the temporary file from disk.

746

Function Reference

HB_FTempCreate()

Info See also: Category: Source: LIB: DLL:

FCreate(), FErase(), FWrite(), GetEnv() File functions, Low level file functions, xHarbour extensions rtl\fstemp.c xhb.lib xhbdll.dll

Example // The example implements a user defined function that creates // a temporary file and returns its file name. The temporary // file is then erased. PROCEDURE Main LOCAL cTempFile := TempFileName() ? cTempFile

// result: C:\temp\xht93.tmp

FErase( cTempFile ) RETURN

FUNCTION TempFileName() LOCAL nFileHandle LOCAL cFileName nFileHandle := HB_FTempCreate( ,,, @cFileName ) IF nFileHandle > 0 FClose( nFileHandle ) ENDIF RETURN cFileName

Function Reference

747

HB_FuncPtr()

HB_FuncPtr() Obtains the pointer to a function or procedure.

Syntax HB_FuncPtr( ) --> pFuncPointer

Arguments

This is a character string holding the symbolic name of an xHarbour function, or a declared userdefined FUNCTION or PROCEDURE.

Return The return value is a pointer to or NIL, when the symbolic name of the function or procedure does not exist at runtime.

Description Function HB_FuncPtr() retrieves the pointer to an xHarbour function or a user -defined FUNCTION or PROCEDURE whose symbolic name must exist at runtime. Pointers to STATIC declared functions and procedures cannot be obtained at runtime. A function pointer is the memory address of a function or procedure. It can be used with HB_Exec() or HB_ExecFromArray() to execute a function from its pointer. This is similar to embedding a function call within a code block and passing the block to the Eval() function. A code block can contain multiple function calls. If only one function is to be executed indirectly, a function pointer along with HB_Exec() or HB_ExecFromArray() is faster than code block execution. The advantage of a function pointer is that the dynamic lookup of the symbolic function name can be avoided once the pointer is obtained. This can improve the performance of time critical functions considerably when they must be called very often.

Info See also: Category: Source: LIB: DLL:

748

@(), HB_Exec(), HB_ExecFromArray(), HB_ObjMsgPtr() Indirect execution, xHarbour extensions vm\hvm.c xhb.lib xhbdll.dll

Function Reference

HB_GCAll()

HB_GCAll() Scans the memory and releases all garbage memory blocks.

Syntax HB_GCAll( [] ) --> NIL

Arguments

Passing .T. (true) enforces a complete garbage collection, even if there are only few memory objects to collect. If is omitted, or set to .F. (false), the garbage collector is not invoked when there is little or no garbage to collect.

Return The return value is always NIL.

Description xHarbour's garbage collector is normally invoked automatically during idle states. An idle state is the state of the xHarbour virtual machine (VM) when it waits for user input from the keyboard or the mouse. The VM enters idle state during Inkey() calls. All applications that do not use Inkey() function calls can signal the idle state with a call to the HB_IdleState() function. Alternatively, garbage collection can be enforced programmatically with HB_GCAll(.T.). This can be advantageous when there is massive use of memory during a loop, for exemple, that includes no user input and no idle state is signalled.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_GCStep(), HB_IdleState(), Memory() Debug functions, Environment functions, xHarbour extensions vm\garbage.c xhb.lib xhbdll.dll

749

HB_GCStep()

HB_GCStep() Invokes the garbage collector for one collection cycle.

Syntax HB_GCStep() --> NIL

Return The return value is always NIL.

Description Function HB_GCStep() invokes the garbage collector for one garbage collection cycle, thus allowing for incremental garbage collection. Refer to HB_GCAll() for more information on the garbage collector.

Info See also: Category: Source: LIB: DLL:

750

HB_GCAll(), Memory() Debug functions, Environment functions, xHarbour extensions vm\garbage.c xhb.lib xhbdll.dll

Function Reference

HB_IdleAdd()

HB_IdleAdd() Adds a background task for being executed during idle states.

Syntax HB_IdleAdd( ) --> nTaskHandle

Arguments

This is a codeblock that will be executed during idle states. The code block receives no parameters when executed.

Return The function returns a numeric task handle that must be preserved for other idle processing functions, such as HB_IdleDel().

Description Function HB_IdleAdd() adds the passed codeblock to the list of background tasks that will be executed when the main program enters an idle state. There is no limit for the number of idle tasks. The idle state is the state of the xHarbour virtual machine (VM) when it waits for user input from the keyboard or the mouse. The VM enters idle state during Inkey() calls. All applications that do not use Inkey() function calls can signal the idle state with a call to the HB_IdleState() function. Note: tasks for regular background processing are created with function HB_BackGroundAdd(). An alternative for background tasks is provided with threads. Refer to function StartThread() for running parts of an application simultaneously in multiple threads.

Info See also: Category: Source: LIB: DLL:

HB_BackGroundAdd(), HB_IdleDel(), HB_IdleState(), HB_IdleSleepMSec(), StartThread() Background processing, xHarbour extensions rtl\idle.c xhb.lib xhbdll.dll

Example // This example halts the program for 10 seconds with the Inkey() // function. A message is continuously displayed until either // a key is pressed or 10 seconds have elapsed. PROCEDURE Main LOCAL nCounter := 10 CLS DispOutAtSetPos( .F. ) nTask := HB_IdleAdd( {|| DispMsg( --nCounter ) } ) ? "Test program for idle state" ?

Function Reference

751

HB_IdleAdd() ? InKey( 10 ) HB_IdleDel( nTask ) ? ? "Program resumes" RETURN

PROCEDURE DispMsg( nCounter ) LOCAL cMsg cMsg := "Program resumes in " cMsg += Ltrim( Str(nCounter) ) cMsg += " seconds unless you press a key" DispoutAt( Row(), Col(), cMsg ) Hb_IdleSleep( 1 ) RETURN

752

Function Reference

HB_IdleDel()

HB_IdleDel() Removes a task from the list of idle tasks.

Syntax HB_IdleDel( ) --> bAction

Arguments

This is the numeric task handle as returned by HB_IdleAdd().

Return The function returns the code block assoiated with the task handle, or NIL if an invalid task handle is specified.

Description Function HB_IdleDel() removes the task associated with the passed task handle from the internal list of idle tasks. The task handle must be a value returned by a previous call to the HB_IdleAdd() function. If the specified task exists, it is deactivated and the associated code block is returned.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_BackGroundAdd(), HB_IdleAdd(), HB_IdleState(), HB_IdleSleepMSec() Background processing, xHarbour extensions rtl\idle.c xhb.lib xhbdll.dll

753

HB_IdleReset()

HB_IdleReset() Resets the internal counter of idle tasks.

Syntax HB_IdleReset() --> NIL

Return The return value is always NIL.

Description Function HB_IdleReset() resets the internal counter identifying the next idle task to be executed to 1. As a result, the next cycle for idle processing starts with the first task defined.

Info See also: Category: Source: LIB: DLL:

754

HB_BackGroundAdd(), HB_IdleAdd(), HB_IdleDel(), HB_IdleState() Background processing, xHarbour extensions rtl\idle.c xhb.lib xhbdll.dll

Function Reference

HB_IdleSleep()

HB_IdleSleep() Halts idle task processing for a number of seconds.

Syntax HB_IdleSleep( ) --> NIL

Arguments

This is a numeric value specifying the number of seconds to wait until idle task processing resumes.

Return The return value is always NIL.

Description Function HB_IdleSleep() defines a time interval in seconds during which idle task processing is paused. Idle tasks are executed again after seconds have elapsed.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_BackGroundAdd(), HB_IdleAdd(), HB_IdleState(), HB_IdleSleepMSec() Background processing, xHarbour extensions rtl\idle.c xhb.lib xhbdll.dll

755

HB_IdleSleepMSec()

HB_IdleSleepMSec() Queries or changes the default time interval for idle task processing.

Syntax HB_IdleSleepMSec( [] ) --> nOldInterval

Arguments

This is a numeric value specifying the time interval to wait between the execution of idle tasks. The unit is 1/1000th of a second (milliseconds). The default value is 20.

Return The function returns the previous wait interval for idle tasks as a numeric value.

Description Function HB_IdleSleepMSec() queries or changes the number of milliseconds after which the next idle task is executed. This allows for fine tuning idle task processing and to optimize CPU usage on multiuser systems, such as Terminal Server, where a minimum amount of idle task processing is desirable.

Info See also: Category: Source: LIB: DLL:

756

HB_IdleAdd(), HB_IdleDel(), HB_IdleState(), HB_IdleSleepMSec() Background processing, xHarbour extensions rtl\idle.c xhb.lib xhbdll.dll

Function Reference

HB_IdleState()

HB_IdleState() Signals an idle state.

Syntax HB_IdleState() --> NIL

Return The return value is always NIL.

Description Function HB_IdleState() is used to explicitely signal an idle state while the program is not wating for user input. The function requests garbage collection and executes a single idle task defined with the codeblock passed to the HB_IdleAdd() function. Each call to HB_IdleState() function evaluates the next idle task in the order of task creation.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_GCAll(), HB_IdleAdd(), HB_IdleDel(), HB_IdleSleepMSec() Background processing, xHarbour extensions rtl\idle.c xhb.lib xhbdll.dll

757

HB_IsArray()

HB_IsArray() Tests if the value returned by an expression is an array.

Syntax HB_IsArray( ) --> lIsArray

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is an array, otherwise .F. (false) is returned.

Description Function HB_IsArray() is used to test if a variable contains an array or if the result of an expression is of data type Array. The function can be used as a replacement for the expression: Valtype()=="A".

Info See also: Category: Source: LIB: DLL:

758

HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_IsBlock()

HB_IsBlock() Tests if the value returned by an expression is a Code block.

Syntax HB_IsBlock( ) --> lIsCodeblock

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is a code block, otherwise .F. (false) is returned.

Description Function HB_IsBlock() is used to test if a variable contains a code block or if the result of an expression is of data type Code block. The function can be used as a replacement for the expression: Valtype()=="B".

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_IsArray(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

759

HB_IsByRef

HB_IsByRef Tests if a parameter is passed by reference.

Syntax HB_IsByRef( @ ) --> lIsByReference

Arguments

is the symbolic name of any parameter passed to a function, method or procedure.

Return The function returns .T. (true) if the variable is passed by reference, otherwise .F. (false) is returned.

Description Function HB_IsByRef() is used to test if a variable is passed by reference to a function, method or procedure. This requires to pass by reference to HB_IsByRef(). If is not passed by reference to HB_IsByRef(), a runtime error is raised.

Info See also: Category: Source: LIB: DLL:

HB_IsArray(), HB_IsBlock(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Example // The example demonstrates how to test if a variable is // passed by reference to a subroutine. PROCEDURE Main LOCAL cMsg := "Hello World" LOCAL dDate:= Date() Test( cMsg, @dDate ) RETURN PROCEDURE Test( p1, p2 ) ? "First parameter is " IF HB_IsByRef( @p1 ) ?? "passed by reference" ELSE ?? "not passed by reference" ENDIF ? "Second parameter is "

760

Function Reference

HB_IsByRef IF HB_IsByRef( @p2 ) ?? "passed by reference" ELSE ?? "not passed by reference" ENDIF RETURN

Function Reference

761

HB_IsDate()

HB_IsDate() Tests if the value returned by an expression is a Date.

Syntax HB_IsDate( ) --> lIsDate

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is of data type Date, otherwise .F. (false) is returned.

Description Function HB_IsDate() is used to test if a variable contains a date value or if the result of an expression is of data type Date. The function can be used as a replacement for the expression: Valtype()=="D".

Info See also: Category: Source: LIB: DLL:

762

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_IsHash()

HB_IsHash() Tests if the value returned by an expression is a Hash.

Syntax HB_IsHash( ) --> lIsHash

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is of data type Hash, otherwise .F. (false) is returned.

Description Function HB_IsHash() is used to test if a variable contains a hash value or if the result of an expression is of data type Hash. The function can be used as a replacement for the expression: Valtype()=="H".

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

763

HB_IsLogical()

HB_IsLogical() Tests if the value returned by an expression is a logical value.

Syntax HB_IsLogical( ) --> lIsLogical

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is of data type Logical, otherwise .F. (false) is returned.

Description Function HB_IsLogical() is used to test if a variable contains a logical value or if the result of an expression is of data type Logical. The function can be used as a replacement for the expression: Valtype()=="L".

Info See also: Category: Source: LIB: DLL:

764

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_IsMemo()

HB_IsMemo() Tests if the value returned by an expression is a Memo value.

Syntax HB_IsMemo( ) --> lIsMemo

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is of data type Memo, otherwise .F. (false) is returned.

Description Function HB_IsMemo() is used to test if a variable contains a memo value or if the result of an expression is of data type Memo. The function can be used as a replacement for the expression: Valtype()=="M".

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

765

HB_IsNIL()

HB_IsNIL() Tests if the value returned by an expression is NIL.

Syntax HB_IsNIL( ) --> lIsNIL

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is NIL, otherwise .F. (false) is returned.

Description Function HB_IsNIL() is used to test if a variable contains the value NIL or if the result of an expression is of undefined data type. The function can be used as a replacement for the expression: Valtype()=="U".

Info See also: Category: Source: LIB: DLL:

766

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_IsNull()

HB_IsNull() Tests if the value returned by an expression is empty.

Syntax HB_IsNull( ) --> lIsNull

Arguments

This is an expression of data type Array, Character or Hash. If a value of a different data type is passed, a runtime error is raised.

Return The function returns .T. (true) if the value returned by is an empty array, character string or hash, otherwise .F. (false) is returned.

Description Function HB_IsNull() is used to test if a variable contains an empty value of data type Array, Character or Hash. The function can be used as a replacement for the expression: Len()==0.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

767

HB_IsNumeric()

HB_IsNumeric() Tests if the value returned by an expression is a numeric value.

Syntax HB_IsNumeric( ) --> lIsNumeric

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is of data type Numeric, otherwise .F. (false) is returned.

Description Function HB_IsNumeric() is used to test if a variable contains a numeric value or if the result of an expression is of data type Numeric. The function can be used as a replacement for the expression: Valtype()=="N".

Info See also: Category: Source: LIB: DLL:

768

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsLogical(), HB_IsHash(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsObject(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_IsObject()

HB_IsObject() Tests if the value returned by an expression is an object.

Syntax HB_IsObject( ) --> lIsObject

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is an object, otherwise .F. (false) is returned.

Description Function HB_IsObject() is used to test if a variable contains an object or if the result of an expression is of data type Object. The function can be used as a replacement for the expression: Valtype()=="O".

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsLogical(), HB_IsHash(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsPointer(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

769

HB_IsPointer()

HB_IsPointer() Tests if the value returned by an expression is a pointer.

Syntax HB_IsPointer( ) --> lIsPointer

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is a pointer, otherwise .F. (false) is returned.

Description Function HB_IsPointer() is used to test if a variable contains a pointer or if the result of an expression is of data type Pointer. The function can be used as a replacement for the expression: Valtype()=="P".

Info See also: Category: Source: LIB: DLL:

770

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsLogical(), HB_IsHash(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_IsRegExString()

HB_IsRegExString() Checks if a character string is a compiled regular expression.

Syntax HB_IsRegExString( ) --> lIsRegExComp

Arguments

is a character string to test.

Return The function returns .T. (true) if the passed string is a compiled regular expression, otherwise .F. (false) is returned.

Description All regular expression functions and operators can process character strings containing literal regular expressions or compiled regular expressions. A literal regular expression can be compiled with HB_RegExComp() to speed up pattern matching. HB_IsRegExString() detects if a character string is a compiled regular expression.

Info See also: Category: Source:

Function Reference

HAS, HB_RegEx(), HB_RegExComp(), LIKE Regular expressions, xHarbour extensions rtl\regex.c

771

HB_IsString()

HB_IsString() Tests if the value returned by an expression is a character string.

Syntax HB_IsString( ) --> lIsString

Arguments

This is an expression of any data type.

Return The function returns .T. (true) if the value returned by is a character string, otherwise .F. (false) is returned.

Description Function HB_IsString() is used to test if a variable contains a character string or if the result of an expression is of data type Character. The function can be used as a replacement for the expression: Valtype()=="C".

Info See also: Category: Source: LIB: DLL:

772

HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsLogical(), HB_IsHash(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsString(), Type(), Valtype() Debug functions, Logical functions, xHarbour extensions rtl\valtype.c xhb.lib xhbdll.dll

Function Reference

HB_KeyPut()

HB_KeyPut() Puts an inkey code into the keyboard buffer.

Syntax HB_KeyPut( ) --> NIL

Arguments

This is a numeric Inkey() code to add to the keyboard buffer. #define constants from the file Inkey.ch can be used for . The numeric value Zero is ignored.

Return The return value is always NIL.

Description Function HB_KeyPut() extends the KEYBOARD command and allows for adding numeric Inkey() codes to the keyboard buffer whose values are outside the range of 1 to 255. HB_KeyPut() adds to the keyboard buffer without removing pending keys from the buffer. The function can add only one Inkey() code at a time. To add multiple key codes, the function must be called repeatedly.

Info See also: Category: Header: Source: LIB: DLL:

KEYBOARD, CLEAR TYPEAHEAD, Inkey() Keyboard functions inkey.ch rtl\inkey.c xhb.lib xhbdll.dll

Example // The example outlines the difference between the KEYBOARD command // and HB_KeyPut() with an Inkey() code greater than 255 #include "Inkey.ch" PROCEDURE Main ? K_ALT_PGDN

// result: 417

KEYBOARD Chr( K_ALT_PGDN ) ? Inkey() ? Asc( Chr( K_ALT_PGDN ) )

// result: 161 // result: 161

HB_KeyPut( K_ALT_PGDN ) ? Inkey()

// result: 417

RETURN

Function Reference

773

HB_LangSelect()

HB_LangSelect() Queries or changes the current national language .

Syntax HB_LangSelect( [] ) --> cOldLanguageID

Arguments

This is a character string identifying the national language to select as current (see table below).

Return The function returns a character string identifying the national language selected before the function is called.

Description Function HB_LangSelect() queries and optionally changes the current national language used for functions returning constant character strings. Functions CDoW() or CMonth() are examples where return values differ by the national language. By default, the English language is selected. In order to change the language, the corresponding module must be linked. That is, the symbolic names of the national languages to be available at runtime must be REQUESTed. When the language module is linked, the language can be changed at runtime by passing the language identifier to HB_LangSelect(). The following table lists the REQUEST symbols and language identifiers available in xHarbour. Note that the code page must be set correctly with HB_SetCodePage() for the national languages as well.

National language support in xHarbour Language name Basque Belorussian Belorussian Bulgarian Bulgarian Catalan Chinese Simplified

Code page

850 866 Windows-1251 DOS-MIK Windows-1251 850 936 for ZH, ZH-CN, ZH-SG Chinese Traditional 950 for ZH-HK, ZH-TW Croatian 1250 Croatian 437 Croatian 852 Croatian ISO-8859-2 Czech 852 Czech ISO-8859-2 Czech Kamenickych Czech 1250 Dutch 850 774

REQUEST symbol

Source file

HB_LANG_EU HB_LANG_BY866 HB_LANG_BYWIN HB_LANG_BGMIK HB_LANG_BGWIN HB_LANG_CA HB_LANG_ZHGB

"EU" "BY866" "BYWIN" "BGMIK" "BGWIN" "CA" "ZHGB"

msgeu.c msgby866.c msgbywin.c msgbgmik.c msgbgwin.c msgca.c msgzhgb.c

HB_LANG_ZHB5

"ZHB5"

msgzhb5.c

HB_LANG_HR1250 HB_LANG_HR437 HB_LANG_HR852 HB_LANG_HRISO HB_LANG_CS852 HB_LANG_CSISO HB_LANG_CSKAM HB_LANG_CSWIN HB_LANG_NL

"HR1250" "HR437" "HR852" "HRISO" "CS852" "CSISO" "CSKAM" "CSWIN" "NL"

msghr1250.c msghr437.c msghr852.c msghriso.c msgcs852.c msgcsiso.c msgcskam.c msgcswin.c msgnl.c Function Reference

HB_LangSelect() English Esperanto French Galician German German WIN Hebrew - Dos Hebrew - Windows Hungarian Hungarian Hungarian Icelandic Indonesian Italian Korean Lithuanian Polish Polish Polish Polish Portuguese Romanian Russian Russian Russian Serbian Serbian Serbian Slovenian Slovenian Slovenian Spanish Spanish WIN Ukrainian Ukrainian Ukrainian

437 850 850 850 850 ANSI 862 Windows-1255 852 CWI-2 Windows-1 850 437 437 949 Windows-1257 852 ISO-8859-2 Mazowia 1250 850 852 866 KOI-8 Windows-1251 Latin II 852 ISO-8859-2 Windows-1251 Latin II 852 ISO-8859-2 1250 850 ANSI 866 KOI-8U Windows-1251

HB_LANG_EN HB_LANG_EO HB_LANG_FR HB_LANG_GL HB_LANG_DE HB_LANG_DEWIN HB_LANG_HE862 HB_LANG_HEWIN HB_LANG_HU852 HB_LANG_HUCWI HB_LANG_HUWIN HB_LANG_IS850 HB_LANG_ID HB_LANG_IT HB_LANG_KO HB_LANG_LT HB_LANG_PL852 HB_LANG_PLISO HB_LANG_PLMAZ HB_LANG_PLWIN HB_LANG_PT HB_LANG_RO HB_LANG_RU866 HB_LANG_RUKOI8 HB_LANG_RUWIN HB_LANG_SR852 HB_LANG_SRISO HB_LANG_SRWIN HB_LANG_SL852 HB_LANG_SLISO HB_LANG_SLWIN HB_LANG_ES HB_LANG_ESWIN HB_LANG_UA866 HB_LANG_UAKOI8 HB_LANG_UAWIN

"EN" "EO" "FR" "GL" "DE" "DEWIN" "HE862" "HEWIN" "HU852" "HUCWI" "HUWIN" "IS850" "ID" "IT" "KO" "LT" "PL852" "PLISO" "PLMAZ" "PLWIN" "PT" "RO" "RU866" "RUKOI8" "RUWIN" "SR852" "SRISO" "SRWIN" "SL852" "SLISO" "SLWIN" "ES" "ESWIN" "UA866" "UAKOI8" "UAWIN"

msgen.c msgeo.c msgfr.c msggl.c msgde.c msgdewin.c msghe862.c msghewin.c msghu852.c msghucwi.c msghuwin.c msgis850.c msgid.c msgit.c msgko.c msgltwin.c msgpl852.c msgpliso.c msgplmaz.c msgplwin.c msgpt.c msgro.c msgru866.c msgrukoi.c msgruwin.c msgsr852.c msgsriso.c msgsrwin.c msgsl852.c msgsliso.c msgslwin.c msges.c msgeswin.c msgua866.c msguakoi.c msguawin.c

Info See also: Category: Source: LIB: DLL:

HB_AnsiToOem(), HB_OemToAnsi(), HB_SetCodePage() Language specific, xHarbour extensions rtl\langapi.c, lang\msg*.c xhb.lib xhbdll.dll

Example // The example shows the result of CDoW() depending // on the selected national language REQUEST HB_LANG_ES REQUEST HB_LANG_IT

// Spanish language // Italian language

PROCEDURE Main ? HB_LangSelect() ? Cdow( Date() )

Function Reference

// result: EN // result: Friday

775

HB_LangSelect() ? HB_LangSelect( "ES" ) ? HB_LangSelect() ? CdoW( Date() )

// result: EN // result: ES // result: Viernes

? HB_LangSelect( "IT" ) ? HB_LangSelect() ? CdoW( Date() )

// result: ES // result: IT // result: Venerdì

RETURN

776

Function Reference

HB_LibDo()

HB_LibDo() Executes a function located in a dynamically loaded xHarbour DLL.

Syntax HB_LibDo( [, ] ) --> xResult

Arguments

This is a character string holding the symbolic name of the function or procedure to execute.

The values of all following parameters specified in a comma separated list are passed on to the DLL function.

Return The function returns the result of the called DLL function.

Description Function HB_LibDo() is used to execute functions located in DLL files created by the xHarbour compiler and linker. This applies to DLL files loaded dynamically at runtime with function LibLoad(). If a DLL file is bound statically at link time, a DLL function can be called directly. HB_LibDo() looks up the symbolic function name and passes the values of to it. The return value of HB_LibDo() is the result of . If cannot be found, a runtime error is generated. Important: the EXE file loading the xHarbour DLL with LibLoad() must be created for DLL usage for HB_LibDo() to work properly (compiler switch -usedll, linker switch /DLL).

Info See also: Category: Source: LIB: DLL:

DllCall(), LibLoad(), LoadLibrary() DLL functions, xHarbour extensions vm\dynlibhb.c xhb.lib xhbdll.dll

Example // The example consists of two file. The first is compiled to an EXE // and the second to a DLL. Function SayHello() resides in the DLL // and is called from the EXE. /* -----------------------------------------------------------// File: DYNDLL.PRG // Compile and link as EXE for DLL usage // e.g. XBuild -usedll dyndll.exe dyndll.prg // ---------------------------------------------------------- */ PROCEDURE Main LOCAL pDLL

Function Reference

777

HB_LibDo() ? Type( "SayHello()" ) // result is "U" because the function SayHello() // does not exist

? pDLL := LibLoad( "dyndll1.dll" ) // result is a pointer to the loaded DLL

? Type( "SayHello()" ) // result is "UI" because function SayHello() // exists now (in loaded DLL)

? HB_LibDo( "SayHello" ) // result is: 1 // displays : Hello from DLL

? HB_LibDo( "SayHello", "Called via HB_LibDo()" ) // result is: 2 // displays : Called via HB_LibDo()

? &("SayHello")( "Called via Macro operator" ) // result is: 3 // displays : Called via Macro operator // // NOTE: // This is the fastest way of calling a DLL function: // // The macro operator "&" looks up the function symbol. // The execution operator "()" calls the function and // passes parameter(s) on to it

? LibFree( pDll ) // result is .T., DLL is successfully unloaded

? Type( "SayHello()" ) // result is "U" because the function SayHello() // does not exist anymore RETURN

/* -----------------------------------------------------------// File: DYNDLL1.PRG // Compile and link as DLL // e.g. XBuild dyndll1.dll dyndll.prg // ---------------------------------------------------------- */ FUNCTION SayHello( cText ) STATIC nCalls := 0 IF cText == NIL cText := "Hello from DLL" ENDIF ? cText RETURN ++nCalls

778

Function Reference

HB_MacroCompile()

HB_MacroCompile() Compiles a macro string into a PCode sequence.

Syntax HB_MacroCompile( ) --> cPCode

Arguments

This is a character string holding a macro expression to compile.

Return The function returns a characters string holding the PCode sequences of the compiled macro expression.

Description Function HB_MacroCompile() accepts a character string and compiles it into a PCode sequence. This, again, is a character string holding executable code, which is executed by passing it to function HB_VMExecute(). If is not a valid macro expression, a runtime error is raised.

Info See also: Category: Source: LIB: DLL:

& (macro operator), Eval(), HB_VMExecute() Indirect execution, xHarbour extensions vm\macro.c xhb.lib xhbdll.dll

Example // // // // //

The example outlines two possibilities of calling a function indirectly via macro expression. The first compiles a macro to PCode, and the second creates a code block with the macro operator. Note that functions that are only included in macro expressions should be REQUESTed to make sure they are linked. REQUEST QOut, Time PROCEDURE Main LOCAL cMacro := "QOut( Time() )" LOCAL cPCode := HB_MacroCompile( cMacro ) LOCAL bBlock := &( "{||" + cMacro + "}" ) HB_VMExecute( cPCode ) EVal( bBlock ) RETURN

Function Reference

779

HB_MD5()

HB_MD5() Calculates a message digest for a stream of data using the MD5 algorithm.

Syntax HB_MD5( ) --> cMD5

Arguments

This is a character string to calulate the message disgest for.

Return The function returns a character string of 32 characters which is the message digest of .

Description HB_MD5() is a cryptographic hash function wich accepts a variable length character string (or message) as input, and produces a fixed length string as output, also known as Message Digest or Digital Fingerprint. The algorithm used is the MD5 algorithm.

Info See also: Category: Source: LIB: DLL:

HB_CheckSum(), HB_CRC32(), HB_MD5File() Checksum functions, xHarbour extensions rtl\hbmd5.c xhb.lib xhbdll.dll

Example // The example displays the message digest of severeal character // strings, including null string. PROCEDURE Main ? HB_MD5("")

// result: d41d8cd98f00b204e9800998ecf8427e

? HB_MD5("a")

// result: 0cc175b9c0f1b6a831c399e269772661

? HB_MD5("abc")

// result: 900150983cd24fb0d6963f7d28e17f72

? HB_MD5("message digest") // result: f96b697d7cb7938d525a2f31aaf161d0 RETURN

780

Function Reference

HB_MD5File()

HB_MD5File() Calculates a message digest for a file using the MD5 algorithm.

Syntax HB_MD5File( ) --> cMD5

Arguments

This is a character string holding the name of the file to process. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Return The function returns a character string of 32 characters which is the message digest of the file specified.

Description HB_MD5File() does the same as HB_MD5() but processes an entire file rather than a character string. The result is the message digest of the file which can be used to detect if the file is changed.

Info See also: Category: Source: LIB: DLL:

HB_CheckSum(), HB_CRC32(), HB_MD5() Checksum functions, xHarbour extensions rtl\hbmd5.c xhb.lib xhbdll.dll

Example // The example implements a simple command line tool that // displays the MD5 message digest of a file. PROCEDURE Main( cFileName ) IF PCount() > 0 .AND. File( cFileName ) ? HB_MD5File( cFileName ) ELSE ? "Usage: MD5File " ENDIF RETURN

Function Reference

781

HB_MultiThread()

HB_MultiThread() Checks if an application is created for multi-threading.

Syntax HB_MultiThread() --> lIsMultiThread

Return The functions returns .T. when the application supports multiple threads, otherwise .F. (false) is returned.

Description The function is used to check if an application is created with the multi-thread enabled libraries of xHarbour. This is accomplished with the -mt compiler switch. Note: the multi-threading capabilities require additional code to be linked and create a larger executable than a single-threaded application.

Info See also: Category: Source: LIB: DLL:

782

StartThread() Multi-threading functions, xHarbour extensions rtl\hvm.c xhb.lib xhbdll.dll

Function Reference

HB_MutexCreate()

HB_MutexCreate() Creates a Mutex.

Syntax HB_MutexCreate() --> pMutexHandle

Return The function returns a handle to the created Mutex.

Description Function HB_MutexCreate() creates a Mutex and returns a handle to it. A Mutex (the name comes from MUTual EXclusion) is a complex data structure required in multi-threaded programming to protect memory resources from concurrent access by multiple threads. There are two distinct programming techniques applied in Mutex usage: Locks and Notifications. No matter which technique is used, a Mutex is only required when at least two threads access the same memory resources or execute the same program code simultaneously. If this is not the case, a Mutex is not required.

Mutex lock A Mutex can be locked with HB_MutexLock(). The first thread calling this function obtains a lock on the Mutex and can proceed with program execution. Any subsequent thread calling HB_MutexLock() with the same Mutex is suspended by the operating system until the Mutex lock is freed by the locking thread with a call to HB_MutexUnlock(). When the locking thread calls HB_MutexLock() again with the same Mutex, the lock counter is increased and the thread proceeds. HB_MutexUnlock() must then be called as many times as HB_MutexLock() to reset the lock counter to zero for releasing the Mutex lock. Mutex locking/unlocking is always done in the same thread. A thread holding a lock prevents other threads from executing the same, Mutex protected, program code simultaneously.

Mutex notification Mutex notifications provide some sort of communication protocol between two threads. This is accomplished by the functions Notify() and Subscribe(). Both functions must operate on the same Mutex but are called in two different threads. If, for example, thread "A" subscribes to a Mutex, it is suspended by the operating system until a second thread "B" notifies the Mutex. When thread "B" calls Notify(), the suspended thread "A" "wakes up" and resumes program execution. The Subscribe()/Notify() protocol allows for controlling the execution of a thread "A" by a second thread "B".

Function Reference

783

HB_MutexCreate()

Info See also: Category: Source: LIB: DLL:

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), Notify(), StartThread(), Subscribe() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Examples Mutex locking // // // // // // // // // //

The example demonstrates how a routine that is safe for single-threaded applications can be made safe for a multi-threaded application by means of a Mutex. The two routines ShowTIDs_ST() and ShowTIDs_MT() differ only in Mutex usage. The output of ShowTIDs_ST() is totally scrambled and differs from one program invocation to the next when running simultaneously in ten threads. The Mutex protected routine ShowTIDs_MT(), in contrast, produces always the same, proper output when executed by multiple threads. GLOBAL pMutex PROCEDURE Main LOCAL i CLS ? ? "--- Unsafe operation ----" FOR i:=1 TO 10 StartThread( "ShowTIDs_ST" ) NEXT WaitForThreads() pMutex := HB_MutexCreate() ? ? "---- Safe operation -----" FOR i:=1 TO 10 StartThread( "ShowTIDs_MT" ) NEXT WaitForThreads() RETURN

PROCEDURE ShowTIDs_ST() LOCAL cTID ? "APP TID:" , Str( GetThreadID(), 5 ) ?? " SYS TID:", Str( GetSystemThreadID(), 5 ) RETURN

PROCEDURE ShowTIDs_MT() LOCAL cTID HB_MutexLock( pMutex )

784

Function Reference

HB_MutexCreate() ? "APP TID:" , Str( GetThreadID(), 5 ) ?? " SYS TID:", Str( GetSystemThreadID(), 5 ) HB_MutexUnlock( pMutex ) RETURN

Mutex notification // // // // // // // // // // // //

The example demonstrates the technique of Mutex notification. Ten threads are started in the FOR...NEXT loop and immediately suspended in procedure GetTIDs by subscribing to the Mutex. All threads are then notified with NotifyAll() and collect their thread IDs in an array which is finally displayed. The result of the example is not predictable since the operating system schedules the threads for execution on its own behalf. I.e. the example produces different output each time it is started. Note that the Mutex is held in a GLOBAL variable to be visible when child threads Subscribe() to the Mutex. GLOBAL pMutex PROCEDURE Main LOCAL i, aTID := {}, pThread, aThread := {} pMutex := HB_MutexCreate() FOR i:=1 TO 10 pThread := StartThread( "GetTIDs", aTID ) AAdd( aThread, pThread ) NEXT NotifyAll( pMutex ) ThreadSleep( 100 ) AEval( aTID, {|c| QOut(c) } ) RETURN

PROCEDURE GetTIDs( aTID ) LOCAL cTID // A thread waits infinitely until notification Subscribe( pMutex ) cTID := "APP TID:" + Str( GetThreadID(), 5 ) cTID += " SYS TID:" + Str( GetSystemThreadID(), 5 ) AAdd( aTID, cTID ) RETURN

Function Reference

785

HB_MutexLock()

HB_MutexLock() Obtains a permanent lock on a Mutex.

Syntax HB_MutexLock( ) --> lSuccess

Arguments

This is the handle of the Mutex to lock. It is the return value of HB_MutexCreate().

Return The function returns .T. (true) when the Mutex is locked, and .F. (false) when an error occurs.

Description Function HB_MutexLock() locks the Mutex for the current thread. If the Mutex is already locked by another thread, the current thread is suspended. That is, HB_MutexLock() waits infinitely and returns only when a lock is obtained. If the infinite wait period is not desired, a thread can call HB_MutexTryLock() to check if the Mutex can be locked, or HB_MutexTimeoutLock(), to restrict the wait period to a specified amount of time. A locked Mutex must be unlocked with HB_MutexUnlock() to grant other threads access to the Mutex protected program code. Refer to function HB_MutexCreate() for more information on Mutexes.

Info See also: Category: Source: LIB: DLL:

786

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexTimeoutLock(), HB_MutexTryLock(), HB_MutexUnlock(), JoinThread(), Notify(), StartThread(), Subscribe() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Function Reference

HB_MutexTimeoutLock()

HB_MutexTimeoutLock() Tries to obtain a lock on a Mutex with timeout.

Syntax HB_MutexTimeoutLock( , ; ) --> lSuccess

Arguments

This is the handle of the Mutex to lock. It is the return value of HB_MutexCreate().

A numeric value specifying the maximum period of time to wait before the function returns when a lock cannot be obtained. The unit for this timeout period is 1/1000th of a second. If is omitted, the thread waits infinitely, i.e. the function does not return until a lock is obtained.

Return The function returns .T. (true) when the Mutex is locked within the timeout period, and .F. (false) when no lock is obtained.

Description The function works like HB_MutexLock() but accepts as second parameter a timeout value. The function returns when either a lock is obtained on the Mutex, or the timeout period has expired. The return value indicates if the current thread has obtained the lock.

Info See also: Category: Source: LIB: DLL:

Function Reference

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexTimeoutLock(), HB_MutexTryLock(), HB_MutexUnlock(), Notify(), StartThread(), Subscribe() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

787

HB_MutexTryLock()

HB_MutexTryLock() Tries to obtain a permanent lock on a Mutex.

Syntax HB_MutexTryLock( ) --> lSuccess

Arguments

This is the handle of the Mutex to lock. It is the return value of HB_MutexCreate().

Return The function returns .T. (true) when the Mutex is locked, otherwise .F. (false).

Description The function works like HB_MutexLock() but does not wait when the Mutex is currently locked. Instead, it returns .F. (false) so that the current thread continues to run. If .T. (true) is returned, the current thread has obtained a Mutex lock, which must be unlocked later with HB_MutexUnlock().

Info See also: Category: Source: LIB: DLL:

788

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), HB_MutexTimeoutLock(), HB_MutexUnlock(), Notify(), StartThread(), Subscribe() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Function Reference

HB_MutexUnlock()

HB_MutexUnlock() Unlocks a Mutex.

Syntax HB_MutexUnlock( ) --> NIL

Arguments

This is the handle of the Mutex to unlock. It is the return value of HB_MutexCreate().

Return The function returns always NIL.

Description Function HB_MutexUnlock() releases a lock previously set with HB_MutexLock(), HB_MutexTimeoutLock() or HB_MutexTryLock(). A Mutex must be unlocked in the same thread that has obtained a lock. Refer to HB_MutexCreate() for more information on Mutexes.

Info See also: Category: Source: LIB: DLL:

Function Reference

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), HB_MutexTimeoutLock(), HB_MutexTryLock(), Notify(), StartThread(), Subscribe() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

789

HB_ObjMsgPtr()

HB_ObjMsgPtr() Retrieves the pointer to a method.

Syntax HB_ObjMsgPtr( , ) --> nMethodPointer

Arguments

This is an object whose method pointer is retrieved.

This is a character string holding the symbolic name of the method to retrieve the pointer for.

Return The function returns a pointer to the method of the object , or NIL, if the object does not have the specified method.

Description Function HB_ObjMsgPtr() retrieves the pointer to a method of an object. A pointer is the memory address of a method. It can be used with HB_Exec() or HB_ExecFromArray() to execute a method from its pointer. This is similar to embedding a method call within a code block and passing the block to the Eval() function. A code block can contain multiple method calls. If only one method is to be executed indirectly, a method pointer along with HB_Exec() or HB_ExecFromArray() is faster than code block execution. The advantage of a method pointer is that the dynamic lookup of the symbolic method name can be avoided once the pointer is obtained. This can improve the performance of time critical methods considerably when they must be called very often.

Info See also: Category: Source: LIB: DLL:

@(), CLASS, HB_Exec(), HB_ExecFromArray(), HB_FuncPtr(), METHOD (Declaration) Indirect execution, xHarbour extensions vm\classes.c xhb.lib xhbdll.dll

Example // The example compares indirect method execution using // a method pointer and a code block. #include "hbclass.ch" PROCEDURE Main LOCAL oObject := Test():new( "xHarbour" ) LOCAL pPointer := HB_ObjMsgPtr( oObject, "display" ) LOCAL bBlock := {|o| o:display() } HB_Exec( pPointer, oObject )

790

Function Reference

HB_ObjMsgPtr() Eval( bBlock, oObject ) RETURN

CLASS Test PROTECTED: DATA name EXPORTED: METHOD init CONSTRUCTOR METHOD display ENDCLASS METHOD init( cName ) CLASS Test ::name := cName RETURN self METHOD display CLASS Test QOut( ::name ) RETURN self

Function Reference

791

HB_OemToAnsi()

HB_OemToAnsi() Converts a character string from the OEM to the ANSI character set.

Syntax HB_OemToAnsi( ) --> cANSI_String

Arguments

A character string holding characters from the OEM character set.

Return The function returns a string converted to the ANSI character set.

Description The function converts all characters of to the corresponding characters in the Windows ANSI character set. Both character sets differ in characters whose ASCII values are larger than 127. If a character in the OEM string does not have an equivalent in the ANSI character set, it is converted to a similar character of the ANSI character set. In this case, it may not be possible to reverse the OEM => ANSI conversion with function HB_AnsiToOem(). Note: all databases created with Clipper store their data using the OEM character set. Displaying data in xHarbour console applications occurs with the OEM character set. Data display in xHarbour GUI applications is done with the Windows ANSI character set.

Info See also: Category: Source: LIB: DLL:

HB_AnsiToOem(), HB_SetCodePage() Conversion functions, xHarbour extensions rtl\oemansi.c xhb.lib xhbdll.dll

Example // See the example for function HB_AnsiToOem()

792

Function Reference

HB_OsNewLine()

HB_OsNewLine() Returns the end-of-line character(s) to use with the current operating system.

Syntax HB_OsNewLine() --> cEndOfLine

Return The function returns a character string containing the end-of-line character(s).

Description HB_OsNewLine() returns a character string containing the character(s) required to move the screen cursor or print head to the start of a new line. The string will hold either Chr(10) or Chr(13)+Chr(10).

Info See also: Category: Source: LIB: DLL:

Function Reference

Chr(), Os(), OutStd(), OutErr(), SET EOL Environment functions, xHarbour extensions rtl\console.c xhb.lib xhbdll.dll

793

HB_QSelf()

HB_QSelf() Retrieves the self object during method execution.

Syntax HB_QSelf() --> self

Return The function returns the self object while methods are being executed. Outside the context of methods, the return value is NIL.

Description Function HB_QSelf() returns the self object in the context of method execution. This is only rquired when methods are implemented with a FUNCTION or PROCEDURE statement rather than a METHOD statement. Functions or procedures can serve as method implementation when a method of a class is redefined using EXTEND CLASS...WITH METHOD. Note: when HB_QSelf() is called outside the body of a method implementation, the return value is always NIL. Code blocks cannot retrieve the self object with HB_QSelf(). To access the self object within a code block, self must either be embedded in the code block, or it must be passed as a code block parameter.

Info See also: Category: Source: LIB: DLL:

794

CLASS, EXTEND CLASS...WITH METHOD, HB_QWith() Object functions, xHarbour extensions vm\hvm.c xhb.lib xhbdll.dll

Function Reference

HB_QWith()

HB_QWith() Retrieves the with object during WITH OBJECT execution.

Syntax HB_QWith() --> oObject | NIL

Return The function returns the with object while the WITH OBJECT statement is executed. Outside this statement, the return value is NIL.

Description Function HB_QWith() returns the with object in the context of the WITH OBJECT statement. All abbreviated messages within the WITH OBJECT .. END block are addressed to the with object.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_QSelf(), HB_SetWith(), WITH OBJECT Object functions, xHarbour extensions vm\hvm.c xhb.lib xhbdll.dll

795

HB_Random()

HB_Random() Generates a random number between two boundaries.

Syntax HB_Random( [] ) --> nRandomNumber or HB_Random( , ) --> nRandomNumber

Arguments

is a numeric value specifying the upper boundary of the random number generator. It defaults to 1.

is a numeric value specifying the lower boundary of the random number generator. It defaults to 0. Note that the first parameter is only interpreted as lower boundary when two parameters are passed.

Return The function returns a random numeric value with two decimal digits, limited by the two boundaries.

Description This function generates a random number between two boundaries. The boundary values are excluded from the range. When only one boundary is passed to the function, it is considered the maximum boundary. The minimum boundary, in that case, is zero. When no boundaries are passed, the function returns a number between 0.00 and 1.00. Note Use function HB_RandomInt() to generate random integer values.

Info See also: Category: Source: LIB: DLL:

HB_RandomInt(), HB_RandomSeed() Numeric functions, Random generator, xHarbour extensions rtl\hbrandom.c xhb.lib xhbdll.dll

Example // The example demonstrates the three possibilities of generating // random numbers with HB_Random(). PROCEDURE Main // Random number between 0.01 and 0.99 ? HB_Random() // Random number between 0.01 and 9.99 ? HB_Random(10) // Random number between 8.01 and 9.99

796

Function Reference

HB_Random() ? HB_Random(8,10) RETURN

Function Reference

797

HB_RandomInt()

HB_RandomInt() Generates a random integer number between two boundaries.

Syntax HB_RandomInt( [] ) --> nRandomInteger or HB_RandomInt( , ) --> nRandomInteger

Arguments

is a numeric value specifying the upper boundary of the random number generator. It defaults to 1.

is a numeric value specifying the lower boundary of the random number generator. It defaults to 0. Note that the first parameter is only interpreted as lower boundary when two parameters are passed.

Return The function returns a random integer value, limited by the two boundaries.

Description This function generates a random number between two boundaries. The boundary values are included in the range. When only one boundary is passed to the function, it is considered the maximum boundary. The minimum boundary, in that case, is zero. When no boundaries are passed, the function returns 0 or 1. Note Use function HB_Random() to generate random numeric values with two decimals.

Info See also: Category: Source: LIB: DLL:

HB_Random(), HB_RandomSeed() Numeric functions, Random generator, xHarbour extensions rtl\hbrandom.c xhb.lib xhbdll.dll

Example // The example demonstrates the three possibilities of generating // random numbers with HB_RandomInt(). PROCEDURE Main // Random creation of 0 and 1 ? HB_Random() // Random number between 0 and 10 ? HB_Random(10) // Random number between 8 and 10

798

Function Reference

HB_RandomInt() ? HB_Random(8,10) RETURN

Function Reference

799

HB_RandomSeed()

HB_RandomSeed() Sets the seed for generating random numbers.

Syntax HB_RandomSeed( [] ) --> NIL

Arguments

A numeric value used as seed for generating the random numbers returned by HB_Random() and HB_RandomInt().

Return The function returns always NIL.

Description This function sets the seed value for generating random numbers with HB_Random() and HB_RandomInt(). When a seed value is specified for the random number generator, it produces the same series of random numbers with each program invocation. This is useful for debugging purposes. Calling the function without an argument resets the seed so that HB_Random() and HB_RandomInt() generate different series of random numbers each time a program is executed.

Info See also: Category: Source: LIB: DLL:

HB_Random(), HB_RandomInt() Numeric functions, Random generator, xHarbour extensions rtl\hbrandom.c xhb.lib xhbdll.dll

Example // The example generates two stings holding random upper case characters // from A to Z. The first string is the same, each time the example is // executed, while the second differs between program invocations. PROCEDURE Main LOCAL i, cStr1 := Space(10), cStr2 := Space(10) HB_RandomSeed(7) FOR i:=1 TO Len( cStr1 ) cStr1[i] := HB_RandomInt(65,90) NEXT ? HB_RandomSeed() FOR i:=1 TO Len( cStr2 ) cStr2[i] := HB_RandomInt(65,90) NEXT ? cStr1

800

Function Reference

HB_RandomSeed() ? cStr2 RETURN

Function Reference

801

HB_ReadIni()

HB_ReadIni() Reads an INI file from disk.

Syntax HB_ReadIni( , [] , [], []

; ; ; ) --> hIniData

Arguments

This is a character string holding the name of the INI file to open. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

This parameter defaults to .T. (true) causing the function to return a case sensitive Hash(). When set to .F. (false), the returned hash is case insensitive.

This is a character string holding the delimiter(s) recognized as separating character bewteen key and value within the INI file. Bydefault, the characters ":", "=" and "|" are recognized.

This parameter defaults to .T. (true) so that a [MAIN] section is automatically added to the resulting hash. All key/value pairs appearing at the beginning of the INI file outside a [section] are assigned to the hash key "MAIN".

Return The function returns two dimensional hash holding sections and key/value pairs of each section inth e INI file. When the file does not exist, the return value is NIL.

Description Function HB_ReadIni() reads an INI file and loads the data into a two dimensional Hash, which is returned. INI files are commonly used for configuration data of applications. They are comfortable to use since they can be created and/or changed with a regular ASCII editor. The basic feature of an INI file is that it organizes data in key/value pairs which can be divided into sections: ; comment line: this is the auto-MAIN section mainKey1=mainvalue1 # inline comment mainKey2=mainvalue2 [SECTION1] sectionKey1=valueA sectionKey2=valueB [SECTION2]

802

Function Reference

HB_ReadIni() sectionKey1=valueC sectionKey2=valueD

INI file sections are named. The names are enclosed in square brackets in the INI file and are used as keys in the Hash returnd by HB_ReadIni(). The value of each [section] key is, again, a hash, making the return value a two-dimensional hash. The hashes in the second dimension contain the key=value pairs of each [section] of the INI file. The example above shows two key=value entries at the beginning of the INI file which are not part of a named [section]. By default, HB_ReadIni() assigns such entries to the hash key named "MAIN".

Info See also: Category: Source: LIB: DLL:

FOpen(), FRead(), Hash(), HB_SetIniComment(), HB_WriteIni() File functions, xHarbour extensions rtl\hbini.prg xhb.lib xhbdll.dll

Example // The example uses the INI file discussed in the function // description and creates from it a case sensitive Hash. // The key values of different sections are displayed. PROCEDURE Main LOCAL hIniData := HB_ReadIni( "test.ini" ) ? Valtype( hIniData["MAIN"] ) ? Valtype( hIniData["SECTION1"] )

// result: H // result: H

? hIniData["MAIN"]["mainKey2"]

// result: mainvalue2

? hIniData["SECTION1"]["sectionKey1"] // result: valueA ? hIniData["SECTION1"]["sectionKey2"] // result: valueB ? hIniData["SECTION2"]["sectionKey1"] // result: valueC ? hIniData["SECTION2"]["sectionKey2"] // result: valueD RETURN

Function Reference

803

HB_RegEx()

HB_RegEx() Searches a string using a regular expression

Syntax HB_RegEx( , , [], []

; ; ; ) --> aMatches

Arguments

This is a character string holding the search pattern as a literal regular expression. Alternatively, the return value of HB_RegExComp() can be used.

This is the character string being searched for a match.

This parameter defaults to .T. (true) so that a case sensitive search is performed. Passing .F. (false) results in a case insensitive search.

This parameter defaults to .F. (false).

Return The function returns an array filled with the found substrings matching the regular expression. If no match is found, the return value is NIL.

Description Function HB_RegEx() searches a character string using a regular expression and co llects matching substrings in an array, which is returned. The first element of the returned array contains the whole match, while subsequent elements contain the portions of the whole match that comply with the regular expression. If the result in the first element does not match further, the returned array has one element only. Note: the xHarbour Regular Expressions (RegEx) engine is using the PCRE implementation http://www.pcre.org/. Regular Expressions is a very powerful language specifically designed to analyze and match text patterns. The subject of RegEx is well beyond the scope of this documentation, and has been covered by many dedicated books. For a comprehensive description of RegEx in general, and PCRE in specific, please review http://www.pcre.org/. A good introduction and tutorial on RegEx can also be found at http://www.regular-expressions.info/.

804

Function Reference

HB_RegEx()

Info See also: Category: Source: LIB: DLL:

HAS, HB_AtX(), HB_RegExAll(), HB_RegExComp(), HB_RegExSplit(), LIKE Character functions, Regular expressions, xHarbour extensions rtl\regex.c xhb.lib xhbdll.dll

Examples // The example extracts a time from a text string by searching // two pairs of digits separated by a colon. PROCEDURE Main LOCAL cRegEx := "[0-9]{2}:[0-9]{2}" LOCAL cText := "Departure is at 18:45h from London airport" LOCAL aResult aResult := HB_RegEx( cRegEx, cText ) AEval( aResult, {|c| QOut(c) } ) ** Output: // 18:45 RETURN // The example matches an ISO formatted date string and displays // the whole match and sub-matches. PROCEDURE Main LOCAL cRegEx := "([0-9]{4})[-/]([0-9]{1,2})[-/]([0-9]{1,2})" LOCAL aDates := { "2006-9-28", ; "2006/10/1", ; "2006-123-1" } LOCAL cDate, aMatch FOR EACH cDate IN aDates ? ? "Matching: ", cDate aMatch := HB_RegEx( cRegEx, cDate ) IF aMatch == NIL ? "No match" ELSEIF Len( aMatch ) == 1 ? "Matched:", aMatch[1] ELSEIF Len( aMatch ) > 1 ? "Whole match:", aMatch[1] ? "Sub matches: " AEVal( aMatch,{|c| QQOut( '"'+ c +'" ') }, 2 ) ENDIF NEXT ** // // // // // // //

Output: Matching: 2006-9-28 Whole match: 2006-9-28 Sub matches: "2006" "9" "28" Matching: 2006/10/1 Whole match: 2006/10/1 Sub matches: "2006" "10" "1"

Function Reference

805

HB_RegEx() // // Matching: // No match RETURN

806

2006-123-1

Function Reference

HB_RegExAll()

HB_RegExAll() Parses a string and fills an array with parsing information.

Syntax HB_RegExAll( , , [], [] , [] , [] , []

; ; ; ; ; ; ) --> aAllRegexMatches

Arguments

This is a character string holding the search pattern as a literal regular expression. Alternatively, the return value of HB_RegExComp() can be used.

This is the character string being searched for a match.

This parameter defaults to .T. (true) so that the resulting compiled regular expression performs a case sensitive search. Passing .F. (false) results in a case insensitive search.

This parameter defaults to .F. (false).

This is a numeric value indicating the maximum number of matches to return. The default value is zero which returns all matches.

This parameter is numeric and specifies the type of match to return. It defaults to zero which means that the function returns the whole match and sub-matches, if any. The value 1 instructs the function to return only whole matches, 2 means the first sub-match in the whole match, 3 is the second sub-match in the whole match, and so forth.

This parameter defaults to .T. (true) so that only matched substrings are included in the returned array. When passing .F. (false) the array includes the numeric start and end positions of the substrings found in .

Return The function returns an array filled with the found substrings matching the regular expression. If no match is found, the return value is NIL. The array is two dimensional when is .T. (default), and three dimensional when is set to .F. (false).

Function Reference

807

HB_RegExAll()

Description Function HB_RegExAll() searches a character string using a regular expression and collects matching substrings in an array, which is returned. The array is two dimensional when is .T. (true), which is the default. The first column of the array contains whole matches, while subsequent columns contain sub-matches found in the whole match. When is .F. (false), the numeric start and end positions of the matched substrings are determined in addition and the result is a three dimensional array of the following structure: aMatch := ; { ; { ; { , { , { , } , ; { ; { , { , { , } ; }

, }, ; , }, ; , }, ;

, }, ; , }, ; , }, ;

The example program outlines the possible return values of HB_RegExAll() in detail.

Info See also: Category: Source: LIB: DLL:

HAS, HB_AtX(), HB_RegEx(), HB_RegExComp(), HB_RegExSplit(), LIKE Character functions, Regular expressions, xHarbour extensions rtl\regex.c xhb.lib xhbdll.dll

Examples // The example demonstrates the return values of HB_RegExAll() by // matching a text that contains 4 ISO formatted dates. PROCEDURE Main LOCAL cRegEx := "([0-9]{4})[-/]([0-9]{1,2})[-/]([0-9]{1,2})" LOCAL cText := "Our shop is closed from 2006/10/25 to 2006/11/1 " + ; "and 2006/12/24 to 2007/1/3" LOCAL aMatch, i, j CLS ? "Text to match:" ? cText ? ? "Matching without positions" ? ? "All matches and sub-matches" aMatch := HB_RegExAll( cRegEx, cText ) AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) WAIT CLS ? "Text to match:" ? cText ? ? "Matching with positions"

808

Function Reference

HB_RegExAll() ? ? "One whole match" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "First sub-match of one whole match" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "Second sub-match of one whole match" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "Third sub-match of one whole match" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "Two whole matches" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "First sub-match of two whole matches" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "Second sub-match of two whole matches" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "Third sub-match of two whole matches" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "All whole matches" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } ) ? ? "All first sub-matches" aMatch := HB_RegExAll( cRegEx, cText, .T., AEval( aMatch, {|a| QOut(ValToPrg(a)) } )

.T., 1, 1, .F. )

.T., 1, 2, .F. )

.T., 1, 3, .F. )

.T., 1, 4, .F. )

.T., 2, 1, .F. )

.T., 2, 2, .F. )

.T., 2, 3, .F. )

.T., 2, 4, .F. )

.T., 0, 1, .F. )

.T., 0, 2, .F. )

WAIT CLS ? "Text to match:" ? cText ? ? "All whole matches including sub-matches" aMatch := HB_RegExAll( cRegEx, cText,,,,, .F. ) FOR i:=1 TO Len( aMatch ) ? FOR j:=1 TO Len( aMatch[i] ) IF j == 1 ? "Whole match" ELSE ? "- sub-match" ENDIF ?? " found:", aMatch[i,j,1] ?? " Start:", aMatch[i,j,2] ?? " End:" , aMatch[i,j,3] NEXT

Function Reference

809

HB_RegExAll() NEXT RETURN // // // //

The example locates the opening and closing tags in an HTML or XML file and displays them along with their positions. Note that the end position of opening tags is found with the At() function since opening HTML and XML tags may include attributes. PROCEDURE Main LOCAL cText := Memoread( "Test.htm" ) LOCAL cRegEx := " lIsWhiteSpaceChar

Arguments

A character string to check for its first character.

Return The function returns .T. (true) when the leftmost character of a string is a white-space character, otherwise .F. (false).

Description The function is used to check if a string begins with a white-space character. It returns .T. (true) when the first character is a white-space character, and .F. (false) when it begins with any other character.

Info See also: Category: Source: LIB: DLL:

IsAlNum(), IsAlpha(), IsAscii(), IsCntrl(), IsDigit(), IsGraph(), IsLower(), IsPrint(), IsSpace(), IsUpper(), IsXDigit(), Lower(), Upper() Character functions, xHarbour extensions rtl\is.c xhb.lib xhbdll.dll

Example // The example collects all white-space characters in a string // and displays their ASCII values. PROCEDURE Main LOCAL i, aSpace := {} FOR i := 0 TO 255 IF IsSpace( Chr(i) ) AAdd( aSpace, i ) ENDIF NEXT AEval( aSpace, {|n| QOut(n) } ) // result: // 9 // 10 // 11 // 12 // 13 // 32 RETURN

Function Reference

NIL

Return The return value is always NIL.

Description Function KillAllThreads() is provided for "emergency recovery", such as dead locks between threads, and may only be called in the main thread of an xHarbour application. The function sends a thread termination request to the operating system for all threads but the main thread, and returns immediately. It does not guarantee that threads have actually terminated when the function returns. Use WaitForThreads() to make sure all threads have terminated. Important: if a call to KillAllThreads() becomes necessary, the program logic of the multi-threading application should be carefully revised. It is an indication for an error in the usage of multiple threads.

Info See also: Category: Source: LIB: DLL:

918

HB_MutexCreate(), KillThread(), StartThread(), StopThread(), ThreadSleep(), WaitForThreads() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Function Reference

KillThread()

KillThread() Kills a running thread.

Syntax KillThread( ) --> NIL

Arguments

This is the handle of the thread to terminate. A thread handle is returned from function StartThread().

Return The return value is always NIL.

Description Function KillThread() is provided for "emergency recovery", such as dead locks between threads. The function sends a thread termination request to the operating system for the specified thread and returns immediately. It does not guarantee that the thread has actually terminated when the function returns. Use JoinThread() to make sure the thread has terminated. Important: if a call to KillThread() becomes necessary, the program logic of the multi-threading application should be carefully revised. It is an indication for an error in the usage of multiple threads. To stop a thread from outside, use StopThread(). StopThread() works synchronously while KillThread() works asynchronously.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_MutexCreate(), JoinThread(), KillAllThreads(), StartThread(), StopThread(), ThreadSleep() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

919

L2bin()

L2bin() Converts a numeric value to a signed long binary integer (4 bytes).

Syntax L2Bin( ) --> cInteger

Arguments

A numeric value in the range of -(2^31) to +(2^31) - 1.

Return The function returns a four-byte character string representing a 32-bit signed long binary integer .

Description L2Bin() is a binary conversion function that converts a numeric value (Valtype()=="N") to a four-byte binary number (Valtype()=="C"). The range for the numeric return value is determined by a signed long integer. If is outside this range, a runtime error is raised. L2bin() is the inverse function of Bin2L().

Info See also: Category: Source: LIB: DLL:

Asc(), Bin2I(), Bin2L(), Bin2U(), Bin2W(), Chr(), I2Bin(), U2Bin(), W2Bin() Binary functions, Conversion functions rtl\binnum.c xhb.lib xhbdll.dll

Example // The example demonstrates return values of L2Bin(). PROCEDURE Main LOCAL c c := L2Bin(0) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 0 0 0 c := L2Bin(1) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 1 0 0 0 c := L2Bin(-1) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 255 255 255 255 c := L2Bin(256) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 1 0 0

920

Function Reference

L2bin() c := L2Bin(-256) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 255 255 255 c := L2Bin(2147483647) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 255 255 255 127 c := L2Bin(-2147483648) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 0 0 128 RETURN

Function Reference

921

LastKey()

LastKey() Returns the last Inkey() code retrieved.

Syntax LastKey( [] ) --> nLastInkeyCode

Arguments

A numeric value specifying the type of events LastKey() should retrieve. #define constants from INKEY.CH must be used for . They are listed below:

Constants for Constant

Value

Events returned by LastKey()

INKEY_MOVE INKEY_LDOWN INKEY_LUP INKEY_RDOWN INKEY_RUP INKEY_MMIDDLE INKEY_MWHEEL INKEY_KEYBOARD INKEY_ALL

1 2 4 8 16 32 64 128 255

Mouse pointer moved Left mouse button pressed Left mouse button released Right mouse button pressed Right mouse button released Middle mouse button pressed Mouse wheel turned Key pressed All events are returned

IF is omitted, the current SET EVENTMASK setting is used. If this is not issued, LastKey() returns only keyboard events.

Return The function returns a numeric value identifying the last keyboard or mouse event retrieved by the Inkey() function.

Description The LastKey() function returns the last keyboard or mouse event that was removed from the internal input buffers by the Inkey() function. LastKey() retains its value until the next pending key stroke or mouse event is removed from the internal input buffers by Inkey(). This way, the last Inkey code does not need to be preserved in a variable that must be passed to sub-routines for processing user input. Instead, user input can be queried with LastKey() until the next Inkey() call is made. If only a subset of the Inkey codes is required, LastKey() can be passed a parameter that filters Inkey codes retrieved from Inkey(). Only Inkey codes matching are returned from LastKey(). Note: the file INKEY.CH contains numerous symbolic #define constants that identify different key strokes or mouse input. It is recommended to use #define constants for prosessing Inkey codes, rather than using their numeric values.

922

Function Reference

LastKey()

Info See also: Category: Header: Source: LIB: DLL:

Chr(), Inkey(), KEYBOARD, NextKey() Keyboard functions, Mouse functions Inkey.ch rtl\inkey.c xhb.lib xhbdll.dll

Example // // // //

In this example, all possible user input is recognized by the Inkey() function. LastKey(), however, reports only key strokes and a left button click. Other mouse input is ignored by LastKey(). #include "Inkey.ch" PROCEDURE Main LOCAL nEvent CLS ?? "Waiting for events (press ESC to quit)" SET EVENTMASK TO INKEY_ALL DO WHILE Lastkey() K_ESC nEvent := Inkey(0) nEvent := LastKey( INKEY_KEYBOARD + INKEY_LUP ) IF nEvent == 0 LOOP ENDIF @ 0, 0 CLEAR TO 1, MaxCol() IF nEvent >= K_MINMOUSE // display current mouse cursor position @ 0,1 SAY "Mouse Row:" ?? MRow() @ 1,1 SAY "Mouse Col:" ?? MCol() ELSE @ 0,1 SAY "Key Code:" ?? nEvent ENDIF ENDDO RETURN

Function Reference

923

LastRec()

LastRec() Returns the number of records available in a work area .

Syntax LastRec() --> nRecords

Return The function returns the number of records available in a work area as a numeric value. If the work area is not used or if a database is empty, the return value is zero.

Description The LastRec() function returns the number of records available in a work area. It is the actual number of physical records stored in a database file, not the number of records that a logically visible in a work area. Logical visibility of records can be reduced with SET FILTER, SET DELETED or SET SCOPE so that the number of records that are accessible during database navigation can be less than the number of records reported by LastRec().

Info See also: Category: Source: LIB: DLL:

COUNT, Eof(), OrdKeyCount(), RecCount(), RecNo() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example illustrates LastRec() usage with and without // alias operator PROCEDURE Main USE Customer USE Invoice

ALIAS Cust NEW ALIAS Inv NEW

? Alias() ? LastRec() ? Cust->(LastRec())

// result: INV // result: 12233 // result: 5612

CLOSE ALL RETURN

924

Function Reference

Left()

Left() Extracts characters from the left side of a string

Syntax Left( , ) --> cSubString

Arguments

A character string to extract a substring from.

A numeric value specifying the number of characters to extract from the left side of .

Return The function returns a character string containing Min( , Len() ) characters.

Description The character function Left() extracts a substring from the left side of . The returned substring contains the first characters. If is larger than Len(), the return value is a copy of . Left() is an abbreviated form of SubStr( , 1, ) and has a counterpart Right(), which extracts a substring from the right side of a string.

Info See also: Category: Source: LIB: DLL:

At(), HB_ATokens(), LTrim(), RAt(), Right(), RTrim(), Stuff(), SubStr() Character functions rtl\left.c xhb.lib xhbdll.dll

Example // The example illustrates return values of function Left() PROCEDURE Main ? CDoW(Date()) ? Left( CDoW(Date()), 3)

// result: Friday // result: Fri

? Time() ? Left( Time(), 5)

// result: 14:45:12 // result: 14:45

? Left("xHarbour", 7) RETURN

// result: xHarbou

Function Reference

925

Len()

Len() Returns the number of items contained in an array, hash or string

Syntax Len( | | ) --> nCount

Arguments

An array whose number of elements is determined.

A character string whose number of characters is determined.

A hash whose number of key/value pairs is determined.

Return The function returns the number of items stored in the passed parameter as a numeric value. When the passed parameter is empty (contains no items), the return value is zero.

Description The function Len() accepts parameters of three different data types: Array, Character string and Hash. It returns the number of items stored in the passed parameter.

Return value of Len() Data type

Description

Array Character string Hash

Number of array elements in first dimension Number of characters Number of key/value pairs

The return value is zero, when an array has no elements, a string has no characters or a hash has no key/value pair.

Info See also: Category: Source: LIB: DLL:

Array(), Empty(), Hash(), LenNum(), LTrim(), RTrim() Array functions, Character functions, Hash functions rtl\len.c xhb.lib xhbdll.dll

Example // The example shows return values of Len() with different data types PROCEDURE Main LOCAL aArray := Directory( "*.prg" ) LOCAL cString := "Hello World"

926

Function Reference

Len() LOCAL hHash

:= { "A" => 1, "B" => 2, "C" => 3, "D" => 4 }

? "Array :" , Len( aArray ) ? "String:" , Len( cString ) ? "Hash :" , Len( hHash ) RETURN

Function Reference

// result: 217 // result: 11 // result: 4

927

LenNum()

LenNum() Returns the number of characters a numeric value needs for display.

Syntax LenNum( ) --> nLength

Arguments

A numeric value.

Return The function returns a numeric value. It is the number of characters required to display the numeric value, including the decimal point.

Description LenNum() is a utility function that calculates the number of characters a numeric value needs for display. It is an abbreviation for the expression Len( LTrim( Str( ) ) ).

Info See also: Category: Source: LIB: DLL:

Len(), Str(), LTrim() Numeric functions, xHarbour extensions rtl\lennum.c xhb.lib xhbdll.dll

Example // The example shows various results of LenNum() PROCEDURE Main ? LenNum( 1 ) ? LenNum( 10 ) ? LenNum( 100 ) ? LenNum( 1000 ) ? LenNum( 10.1 ) ? LenNum( 100.12 ) ? LenNum( 1000.123 ) ? LenNum( ? LenNum( ? LenNum( ? LenNum( RETURN

928

0.1 ) 0.01 ) 0.001 ) 0.0001 )

// // // //

result: result: result: result:

1 2 3 4

// result: 4 // result: 6 // result: 8 // // // //

result: result: result: result:

3 4 5 6

Function Reference

LibFree()

LibFree() Releases a dynamically loaded xHarbour DLL from memory.

Syntax LibFree( ) --> lSuccess

Arguments

This is the pointer of the DLL to release as returned from LibLoad().

Return The function returns a logical value indicating a successful operation.

Description Function LibFree() releases a DLL previously loaded with LibLoad() from memory. When the function is successful, it returns .T. (true) and the pointer of the xHarbour DLL can no longer be used.

Info See also: Category: Source: LIB: DLL:

Function Reference

HB_LibDo(), LibLoad(), FreeLibrary() DLL functions, xHarbour extensions vm\dynlibhb.c xhb.lib xhbdll.dll

929

LibLoad()

LibLoad() Loads an xHarbour DLL file into memory.

Syntax LibLoad( ) --> pDLL

Arguments

This is a character string holding the name of the xHarbour DLL file to load into memory. It must contain complete path information, unless the file is located in the current directory, or in the list of directories held in the SET PATH environment variable of the operating system.

Return The function returns a pointer to the DLL file. If the DLL file cannot be loaded, or does not exist, the return value is a null pointer.

Description The LibLoad() function loads a DLL file created by xHarbour at runtime of an application into memory. All symbolic names of the functions residing in the DLL are added to the symbol table of the application. These functions can then be invoked via HB_LibDo() or by using the macro operator. Refer to function HB_LibDo() for an extensive example on the possibilities of invoking functions within a dynamically loaded DLL. Note: function LoadLibrary() is available to load DLLs at runtime which are not created by xHarbour.

Info See also: Category: Source: LIB: DLL:

930

HB_LibDo(), LibFree(), LoadLibrary() DLL functions, xHarbour extensions vm\dynlibhb.c xhb.lib xhbdll.dll

Function Reference

LoadLibrary()

LoadLibrary() Loads an external DLL file into memory.

Syntax LoadLibrary( ) --> nDllHandle

Arguments

This is a character string holding the name of the DLL file to load into memory. It must contain complete path information, unless the file is located in the current directory, or in the list of directories held in the SET PATH environment variable of the operating system.

Return The function returns a numeric DLL handle > 0. If the DLL file cannot be loaded, or does not exist, the return value is zero.

Description The LoadLibrary() function loads a DLL file at runtime of an xHarbour application into memory that is not created with xHarbour. Functions residing in this DLL can then be invoked via DllCall() by passing the returned DLL handle. If the DLL is already in use by other applications, LoadLibrary() does not load the DLL a second time, but increments the load counter of the DLL. This signals the operating system that the xHarbour application requires the DLL in addition to other applications. When the DLL is no longer required, the DLL handle should be freed with FreeLibrary(). Note: function LibLoad() is available to load a DLL cerated with xHarbour.

Info See also: Category: Source: LIB: DLL:

DllCall(), FreeLibrary(), GetProcAddress(), LibLoad() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Example // // // // // // //

The example shows a recomended use of LoadLibrary() when DLL handles are required during the entire lifetime of an xHarbour application. The DLL is loaded in an INIT PROCEDURE and the DLL handle is available via a GLOBAL variable. This way, the DLL handle can be used in different API wrappers that invoke WinAPI functions within the same DLL. The example implements two wrappers for converting normal Ansi strings to wide character string (Unicode) and vice versa. #define DC_CALL_STD

0x0020

GLOBAL gKernel32DLL INIT PROCEDURE InitDlls

Function Reference

931

LoadLibrary() gKernel32DLL := LoadLibrary( "Kernel32.dll" ) RETURN EXIT PROCEDURE FreeDlls FreeLibrary( gKernel32DLL ) RETURN

PROCEDURE Main LOCAL cString, cWideString cString := "Hello World" cWideString := AnsiToWide( cString ) ? Len( cString ), cString ? Len( cWideString ), cWideString ? WideToAnsi( cWideString ) RETURN

FUNCTION LOCAL LOCAL LOCAL

AnsiToWide( cString ) nWideLen := 2 * ( Len( cString ) ) cWideChar := Replicate( Chr(0), nWideLen ) nRet

nRet := ; DllCall( gKernel32DLL DC_CALL_STD "MultiByteToWideChar" 0 0 cString -1 @cWideChar nWideLen RETURN cWideChar

FUNCTION LOCAL LOCAL LOCAL

; ; ; ; ; ; ; ; )

WideToAnsi( cWideChar ) nLen := Int( Len( cWideChar ) / 2 ) cString := Replicate( Chr(0), nLen ) nRet

nRet := ; DllCall( gKernel32DLL DC_CALL_STD "WideCharToMultiByte" 0 0 cWideChar -1 @cstring nLen 0 0 RETURN cString

932

, , , , , , , ,

, , , , , , , , , ,

; ; ; ; ; ; ; ; ; ; )

Function Reference

Log()

Log() Calculates the natural logarithm of a numeric value.

Syntax Log( ) --> nNaturalLog

Arguments

A numeric value greater than zero.

Return The function returns the natural logarithm of as a numeric value.

Description The mathematical function Log() calculates the natural logarithm for a mumeric value. The natural logarithm is based on the Euler number 2.7183... which is usually abbreviated as "e". The inverse function of Log() is Exp().

Info See also: Category: Source: LIB: DLL:

Exp(), SET DECIMALS, SET FIXED Mathematical functions, Numeric functions rtl\math.c xhb.lib xhbdll.dll

Example // The example shows results of function Log() PROCEDURE Main SET DECIMALS TO 5 ? Log(10) ? Log(100)

// result: 2.30259 // result: 4.60517

? Log(1) ? Exp(Log(1)) RETURN

// result: 0.00000 // result: 1.00000

Function Reference

933

Lower()

Lower() Converts a character string to lowercase.

Syntax Lower( ) --> cLowerCaseString

Arguments

A character string to convert to lowercase letters.

Return The return value is a character string containing only lowercase letters.

Description The character function Lower() copies the passed string, replaces all uppercase letters with lowercase letters and returns the result. It is related to function Upper() wich converts a string to uppercase letters. Both functions are used for case-insensitive string routines.

Info See also: Category: Source: LIB: DLL:

IsLower(), IsUpper(), Upper() Character functions rtl\strcase.c xhb.lib xhbdll.dll

Example // The example demonstrates various results of LOWER() PROCEDURE Main ? Lower( "xHARbOUR" ) ? Lower( "123 ABC - def" )

// result: xharbour // result: 123 abc - def

RETURN

934

Function Reference

LTrim()

LTrim() Removes leading white-space characters from a character string.

Syntax LTrim( ) --> cTrimmedString

Arguments

A character string which is copied without leading white-space characters.

Return The function returns a copy of without white-spaces at the beginning of the string.

Description LTrim() is used for formatting character strings whose first characters consist of white-space characters (Chr(9),Chr(10),Chr(13),(Chr(32)). The function creates a copy of but ignores white spaces at the beginning of the input string.

Info See also: Category: Source: LIB: DLL:

AllTrim(), IsSpace(), PadC() | PadL() | PadR(), RTrim(), Str(), SubStr() Character functions rtl\trim.c xhb.lib xhbdll.dll

Example // The example shows various results of function LTrim(). #define CRLF #define TAB #define SPACE

Chr(13)+Chr(10) Chr(9) Chr(32)

PROCEDURE Main LOCAL cStr := TAB+SPACE+CRLF+" xHarbour" ? Len( cStr ) ? Asc( cStr )

// result: 13 // result: 9

? Len( LTrim( cStr ) ) ? Asc( LTrim( cStr ) )

// result: // result:

? Str(5) ? Len( Str(5) ) ? LTrim( Str(5) )

// result: // result: 10 // result: 5

8 120 5

RETURN

Function Reference

935

LUpdate()

LUpdate() Returns the last modification date of a database open in a work area.

Syntax LUpdate() --> dLastChange

Return The function returns the date of the last change applied to a database fiel open in a work area. If the work area is unused, an empty date is returned.

Description LUpdate() returns the date of the last change applied to a database file in a work area. This information is stored in the header of a database file and is only updated when the file is closed.

Info See also: Category: Source: LIB: DLL:

DbInfo(), FCount(), FieldName(), Header(), LastRec(), RecSize() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The function illustrates that the last modification date // is only updated when a database file is closed. PROCEDURE Main USE Customer ALIAS Cust NEW EXCLUSIVE ? DtoS(Date()) ? DtoS(LUpdate())

// result: 20060324 // result: 20060103

REPLACE Cust->LastNamet WITH "Miller" ? DtoS(LUpdate())

// result: 20060103

CLOSE Cust USE Customer NEW ? DtoS(LUpdate())

// result: 20060324

CLOSE ALL RETURN

936

Function Reference

MakeDir()

MakeDir() Creates a new directory.

Syntax MakeDir( ) --> nOSError

Arguments

A character expression specifying the directory to create. The directory can be specified relative to the current directory, or absolute, including a drive letter followed by a colon.

Return The function returns a numeric value representing the operating system error code (DOS error). A value of 0 indicates a successful operation.

Description The function attempts to create the directory specified with . If this operation fails, the function returns the OS error code indicating the reason for failure. See the FError() function for a description of OS errors. Note that cannot contain subdirectories more than one level deep.

Info See also: Category: Source: LIB: DLL:

DirChange(), DirRemove(), DiskChange(), DiskName(), FError(), IsDisk() Directory functions, File functions rtl\dirdrive.c xhb.lib xhbdll.dll

Example // The example demonstrates how to create nested sub-directories // in the current directory PROCEDURE Main LOCAL i, j, aSubDir, cSubDir, nError LOCAL aNewDir := { ; "payments\salaries" , ; "payments\purchases" , ; "customer\marketing" , ; "customer\orders" , ; "customer\support" } FOR i:=1 TO Len( aNewDir ) cSubDir := CurDrive()+ ":\" + CurDir() + "\" aSubDir := HB_ATokens( aNewDir[i], "\" ) FOR j:=1 TO Len( aSubDir ) cSubDir += aSubDir[j] + "\" nError := MakeDir( cSubDir )

Function Reference

937

MakeDir() IF nError == 0 ? "Directory", cSubDir, "successfully created" ELSEIF nError == 5 ? "Directory", cSubDir, "exists already" ELSE ? "Error for", cSubDir, LTrim( Str( nError ) ) ENDIF NEXT j NEXT i RETURN

938

Function Reference

Max()

Max() Returns the larger value of two Numerics or Dates.

Syntax Max( , ) --> nLargerNumber Max( , ) --> dLargerDate

Arguments and

Two numeric values to be compared. and

Two Date values to be compared.

Return The function returns the larger value of the two arguments.

Description The function compares two numeric or two Date values and returns the larger value of both. Max() is used to normalize values against a limit. The inverse function is Min().

Info See also: Category: Source: LIB: DLL:

Min() Numeric functions, Date and time rtl\minmax.c xhb.lib xhbdll.dll

Example // The example uses Max() to identify the maximum length of a string within // a set of character strings for formatted console output PROCEDURE Main LOCAL aLabel LOCAL dDate LOCAL cTime LOCAL nPad

:= := := :=

{ "Day", "Hour", "Minutes", "Seconds" } Date() Time() 0

AEval( aLabel, {|c| nPad := Max( nPad, Len(c) ) } ) ? ? ? ?

PadL( PadL( PadL( PadL(

aLabel[1], aLabel[2], aLabel[3], aLabel[4],

nPad nPad nPad nPad

), ), ), ),

dDate SubStr( cTime, 1, 2 ) SubStr( cTime, 4, 2 ) SubStr( cTime, 7, 2 )

RETURN

Function Reference

939

MaxCol()

MaxCol() Determines the rightmost column position of the screen buffer.

Syntax MaxCol() --> nColumn

Return The function returns the ordinal position of the rightmost column in a console window as a numeric value.

Description MaxCol() determines the maximum number of columns in a console window in which characters can be displayed. The leftmost column has number zero, the rightmost column has number MaxCol().

Info See also: Category: Source: LIB: DLL:

Col(), MaxRow(), Row(), SetMode() Screen functions rtl\maxrow.c xhb.lib xhbdll.dll

Example // In this example, a box is drawn and column numbers are displayed // using a different color for every 10th column position. PROCEDURE Main LOCAL i @ 0, 0 TO 2, MaxCol() DOUBLE FOR i:=1 TO MaxCol()-1 IF i % 10 > 0 @ Row(), Col() SAY Str(i%10,1) COLOR "N/BG" ELSE @ Row(), Col() SAY Str(i/10,1) COLOR "GR+/BG" ENDIF NEXT @ 4, 0 CLEAR RETURN

940

Function Reference

MaxRow()

MaxRow() Determines the bottom row position of the screen buffer.

Syntax MaxRow() --> nRow

Return The function returns the ordinal position of the bottom row in a console window as a numeric value.

Description MaxRow() determines the maximum number of rows in a console window in which characters can be displayed. The top row has number zero, the bottom row has number MaxRow().

Info See also: Category: Source: LIB: DLL:

Col(), MaxCol(), Row(), SetMode() Screen functions rtl\maxrow.c xhb.lib xhbdll.dll

Example // The function changes the screen buffer, or console window size, // and displays the size of the screen buffer. PROCEDURE Main LOCAL nRow := MaxRow(), nCol := MaxCol() CLS SetMode( 25, 80 ) ? MaxRow(), MaxCol(), ScreenBufferSize() WAIT SetMode( 50, 80 ) ? MaxRow(), MaxCol(), ScreenBufferSize() WAIT SetMode( 50, 135 ) ? MaxRow(), MaxCol(), ScreenBufferSize() WAIT SetMode( nRow+1, nCol+1 ) RETURN FUNCTION ScreenBufferSize RETURN 2 * ( 1 + MaxRow() ) * ( 1 + MaxCol() )

Function Reference

941

MCol()

MCol() Determines the screen column position of the mouse cursor.

Syntax MCol() --> nMouseCol

Return The function returns the column position of the mouse cursor as a numeric value.

Description MCol() is used in full screen or console window applications to determine the current screen column position of the mouse cursor. The leftmost column has number zero, while the rightmost column has number MaxCol(). Note to obtain proper mouse input from the user, function Inkey() should be called including mouse events.

Info See also: Category: Source: LIB: DLL:

Inkey(), MDblClk(), MHide(), MLeftDown(), MRightDown(), MRow(), MSetCursor(), MShow(), SET EVENTMASK Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Example // The example changes the event mask for Inkey() to ALL events // and displays the mouse cursor position when the left button is pressed. #include "Inkey.ch" PROCEDURE Main LOCAL nEvent, nRow, nCol, cPos CLS MShow() ? "Click with left mouse button (press ESC to quit)" SET EVENTMASK TO INKEY_ALL DO WHILE Lastkey() K_ESC nEvent := Inkey(0) IF nEvent == K_LBUTTONDOWN nRow := MRow() nCol := MCol() cPos := LTrim( Str(nRow) ) + "," + LTrim( Str(nCol) ) // display current mouse cursor position @ nRow, nCol SAY cPos ENDIF ENDDO RETURN

942

Function Reference

MDblClk()

MDblClk() Determines the double-click interval for the mouse.

Syntax MDblClk( [] ) --> nMilliSeconds

Arguments

A numeric value specifying the interval in milliseconds between two mouse button clicks for being recognized as a double-click.

Return The return value is the double-click interval present before the function is called.

Description The function MDblClk() exists for compatibility reasons only and is not recommended to use. Mouse properties are nowadays set via the operating system configuration.

Info See also: Category: Source: LIB: DLL:

Function Reference

MCol(), MRow() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

943

MemoEdit()

MemoEdit() Displays and/or edits character strings and memo fields in text mode.

Syntax MemoEdit( [] , [] , [] , [] , [] , [] , [] , [] , [] , [], [], [], []

; ; ; ; ; ; ; ; ; ; ; ; ) --> cTextBuffer

Arguments

A character string to be copied to the text buffer. The text buffer is displayed by MemoEdit() and can be edited by the user. The default value is an empty string ("").

A numeric value indicating the screen coordinate for the top row of the MemoEdit() display rectangle. The default value is 0.

A numeric values indicating the screen coordinate for the left column of the MemoEdit() display rectangle. The default value is 0.

A numeric value indicating the screen coordinate for the bottom row of the MemoEdit() display rectangle. The default value is MaxRow().

A numeric values indicating the screen coordinate for the right column of the MemoEdit() display rectangle. The default value is MaxCol().

The default value is .T. (true), indicating that a user can edit the text buffer maintained by MemoEdit(). If .F. (false) is passed, MemoEdit() displays the characater string within the boundaries of its display rectangle. The user can scroll the displayed text but cannnot edit the text buffer.

A character string holding the name of a user defined function. The function must be visible in the entire application, i.e. it must not be declared as STATIC FUNCTION. allows for modifying the standard edit behavior of MemoEdit() (see description below). 944

Function Reference

MemoEdit()

As an alternative, the value .F. (false) can be passed for . This causes MemoEdit() to display in the specified rectangle and return immediately. The passed string can neither be scrolled nor edited.

A numeric value specifying the number of characters that can appear in a single line of the text buffer. The default value is - . If a single text line in the text buffer contains more than characters, the text line is word wrapped. If is specified as being larger than - of the display rectangle, and the user navigates the text cursor to a column position beyond the coordinates of the MemoEdit() rectangle, the displayed text is scrolled horizontally.

A numeric value specifying the number of spaces a Tab character (Chr(9)) contained in should be replaced with in the displayed text buffer. The default value is 3 spaces.

A numeric value specifying the first text buffer row to be displayed in the top screen row of the display rectangle. The default value is 1.

A numeric value specifying the first text buffer column to be displayed in the left screen column of the display rectangle. The default value is 0.

A numeric value specifying the row offset for initial positioning of the edit cursor. The default value is 0, i.e. the edit cursor is displayed in the first row of the display rectangle.

A numeric value specifying the column offset for initial positioning of the edit cursor. The default value is , i.e. the edit cursor is displayed in the specified column of the display rectangle, which is the first column, by default.

Return The return value of MemoEdit() depends on the key a user pressed to terminate the function. Alt+W When the user pressed the key combination Alt+W (K_ALT_W), the edited text buffer is returned as a character string. Esc

When the user pressed the Escape key (K_ESC), the return value is a copy of .

Description MemoEdit() is a function for editing character strings, or memo fields, in console windows or full screen applications. The function provides a character oriented user interface and processes user input for editing text. Similar to AChoice() and DbEdit(), MemoEdit() employs a standard behaviour that can be configured by a user defined function . Altough MemoEdit() is equipped with an extensive parameter profile, it is simple to use since all parameters are optional. The simplest form of using MemoEdit() is given by this line of code: cText := MemoEdit()

Function Reference

945

MemoEdit()

Assigning the return value of MemoEdit() to a memory variable invokes the standard text editing behaviour of the function, i.e. the entire console window, or screen, is used for displaying the internal text buffer. The edited text is assigned to a memory variable when the user terminates text editing by pressing Alt+W. If text editing is ended with the Escape key, MemoEdit() returns an unchanged copy of . It is important to understand that the user edits only the internal text buffer. This internal buffer is filled with a copy of parameter , if specified. All other parameters for row and column coordinates change the default (initial) display of the rectangle where text is displayed and can be edited by the user. Whether or not MemoEdit() exposes standard or user-configured text editing behavior depends on the parameter , which is a character string containing the name of a user defined function.

MemoEdit() without user function In its standard behavior, MemoEdit() processes the keys listed in the following table:

Standard key processing of MemoEdit() Key

Description

Navigation in the text buffer Up (Ctrl+E) Down (Ctrl+X) Left (Ctrl+S) Right(Ctrl+D) Ctrl+Left (Ctrl+A) Ctrl+Right (Ctrl+F) Home End Ctrl+Home Ctrl+End PgUp PgDn Ctrl+PgUp Ctrl+PgDn

Go to previous line Go to next line Go to previous character Go to next character Go to previous word Go to next word Go to begin-of-line Go to end-of-line Go to first displayed line Go to last displayed line Go to previous page Go to next page Go to first line Go to last line

Editing the text buffer Printable characters Return Delete Backspace Tab Ctrl+Y Ctrl+T Ctrl+B Ctrl+V (Ins) Alt+W Esc

Insert character Begin a new paragraph Delete character at cursor Delete character to left of cursor Insert tab character or spaces Delete the current line Delete word right Reformat paragraph Toggle insert/overstrike mode Terminate editing with changes Terminate editing without changes

Keys are grouped into the tasks navigation within the text buffer and editing it. MemoEdit() supports insert and overstrike modes, which is toggled by the Ins key. An automatic word wrap is applied to the text buffer when the number of characters entered in the current text line exceeds the value for parameter . This word wrap is marked in the text buffer with a so called "Soft carriage return" (Chr(141)) which indicates the end-of-line, not the end-of-paragraph. The latter is marked in 946

Function Reference

MemoEdit()

the text when the user presses the Return key. This inserts a "Hard carriage return" (Chr(13)) into the text buffer. Note that "Soft carriage returns" remain in the text returned my MemoEdit(). When this text is output to a printer, or processed otherwise, it may be necessary to replace "Soft carriage returns" with blank spaces or "Hard carriage returns". The functions HardCR(), MemoTran() or StrTran() can be used to accomplish this.

MemoEdit() with user function If a user function is specified, the standard editing behavior of MemoEdit() becomes configurable. For this, MemoEdit() distinguishes non-configurable keys from key-exceptions. The function applies its default action to the text buffer, when non-configurable keys are pressed. The user function is called for keys that yield an exception, and the return value of the user function instructs MemoEdit() how to process such a key. If there are no more keys pending in the keyboard buffer, the user function is called once again. As a consequence, the user function is called during different MemoEdit() modes. The user function receives three numeric values from MemoEdit(): the current MemoEdit() mode, the current row, and the current column of the text buffer. #define constants are available in MEMOEDIT.CH that identify the different modes of MemoEdit().

MemoEdit() modes Constant

Mode

Description

ME_IDLE ME_UNKEY ME_UNKEYX ME_INIT

0 1 2 3

MemoEdit() is idle, all keys are processed Unknown key, text buffer is unaltered Unknown key, text buffer is altered Initialization mode

ME_INIT

The user function is called for the first time when MemoEdit() is invoked. At this point, MemoEdit() is initializing its text buffer and has not displayed it yet. The return value of the user function can be used at this stage to initialize word wrapping or the scrolling mode of MemoEdit() (see ME_TOGGLEWRAP and ME_TOGGLESCROLL in the table further down). The user function is called repeatedly in the initialization stage of MemoEdit() until the value ME_DEFAULT (0) is returned. After this, the text buffer is displayed and MemoEdit() continues key processing according to . That is, if is .F. (false), the user can scroll the text but cannot edit it.

ME_UNKEY This mode tells the user function that a configurable (unknown) key is pressed and the text buffer is not altered, yet. The return value of the user function instructs MemoEdit() how to treat a configurable key. Use function LastKey() to obtain the Inkey code of such key.

Configurable keys of MemoEdit()

Function Reference

Key

Default key processing

Ctrl+Y Ctrl+T Ctrl+B Ctrl+V (Ins) Alt+W Esc

Delete the current line Delete word right Reformat paragraph Toggle insert/overstrike mode Terminate editing with changes Terminate editing without changes

947

MemoEdit()

Returning ME_DEFAULT (0) from the user function for a configurable key instructs MemoEdit() to perform its default action. A different return value causes a different action, thus redefines the key (return values from the user function are explained further down). ME_UNKEYX The same as ME_UNKEY, but the text buffer is altered. ME_IDLE

There are no more keys avalable in the keyboard buffer for processing. MemoEdit() calls the user function once in this situation and enters a wait state afterwards, until a new key is pressed. This mode is usually used to update row and column numbers on the screen if this information is presented to the user.

The second parameter passed to the user function is the current row in the text buffer. Rows are numbered beginning with 1. The third parameter passed to the user function is the current column in the text buffer. Columns are numbered beginning with 0. During the modes ME_INIT, ME_UNKEY and ME_UNKEYX, the return value of the user function instructs MemoEdit() what action to take for the pressed key. There are several #define constants available in MEMOEDIT.CH for this purpose.

Return values for the MemoEdit() user function Constant

Value

Description

ME_DEFAULT ME_UNKEY ME_IGNORE ME_DATA ME_TOGGLEWRAP ME_TOGGLESCROLL ME_WORDRIGHT ME_BOTTOMRIGHT

0 1-31 32 33 34 35 100 101

Perform default action Process requested action corresponding to key code Ignore unknown key Treat unknown key as data Toggle word wrap mode Toggle scroll mode Perform word-right operation Perform bottom-right operation

Info See also: Category: Header: Source: LIB: DLL:

HardCR(), MemoLine(), MemoRead(), MemoTran(), MemoWrit(), StrTran() Character functions, Memo functions, UI functions inkey.ch, memoedit.ch rtl\memoedit.prg xhb.lib xhbdll.dll

Example // // // //

The example implements a simple file editor using MemoEdit() with user function. The user function displays status information and configures the Alt+S (Save) and Alt+C (Cancel) as termination keys #include "Inkey.ch" #include "Memoedit.ch" STATIC slChanged := .F. PROCEDURE Main( cFileName ) LOCAL cScreen LOCAL cText := ""

948

Function Reference

MemoEdit() SAVE SCREEN TO cScreen SET SCOREBOARD OFF SetCancel( .F. ) CLS IF .NOT. Empty( cFileName ) .AND. File( cFileName ) cText := MemoRead( cFileName ) ENDIF @ 0, 0 TO MaxRow(), MaxCol() DOUBLE cText := MemoEdit( cText, ; 1, 1 , ; MaxRow()-1, MaxCol()-1, ; .T., "USERFUNC" ) IF .NOT. Empty( cFileName ) .AND. ; File( cFileName ) .AND. ; slChanged .AND. ; Alert( "Save changes?", { "Yes", "No" } ) == 1 // remove "soft carriage return/line feeds" cText := StrTran( cText, Chr(141)+Chr(10), " " ) // save file MemoWrit( cFileName, cText ) ENDIF RESTORE SCREEN FROM cScreen RETURN

FUNCTION LOCAL LOCAL LOCAL

UserFunc( nMode, nRow, nCol ) nKey := LastKey() nRet := ME_DEFAULT cInfo := ""

DO CASE CASE nMode == ME_INIT Set( _SET_INSERT, .F. )

// start in overstrike mode

CASE nMode == ME_IDLE IF nKey > 31 .AND. nKey < 256 slChanged := .T. ENDIF cInfo := "[row: " + LTrim(Str(nRow)) cInfo += " col: " + LTrim(Str(nCol))+"]" cInfo += Chr(205)+Chr(205) IF Set( _SET_INSERT ) cInfo += "[Ins]" ELSE cInfo += "[Ovr]" ENDIF IF slChanged cInfo += Chr(205)+Chr(205)+"[Chg]" ENDIF @ MaxRow(), 2 SAY cInfo + Replicate(Chr(205),6)

Function Reference

949

MemoEdit() CASE nMode == ME_UNKEY .OR. nMode == ME_UNKEYX // buffer is changed slChanged := ( nMode == ME_UNKEYX ) DO CASE CASE nKey IN { K_ALT_W, K_CTRL_W, K_ESC } nRet := ME_IGNORE // ignore default termination keys CASE nKey == K_ALT_S nRet := K_ALT_W CASE nKey == K_ALT_C nRet := K_ESC slChanged := .F. ENDCASE

// Save with Alt+S

// Cancel with Alt+C

ENDCASE RETURN nRet

950

Function Reference

MemoLine()

MemoLine() Extracts a line of text from a formatted character string or memo field.

Syntax MemoLine( , [] , [] , [] , [] , [], [@]

; ; ; ; ; ; ) --> cTextLine

Arguments

A character string or memo field to extract a text line from. It can be a formatted text string that includes Tab and Hard/Soft carriage return characters.

A numeric value specifying the number of characters per extracted line. It is usually a value between 4 and 254. If is larger than 254 characters, parameter must be set to .T. (true). The default value for is 79.

A numeric value specifying the line number to extract. It defaults to 1.

A numeric value specifying the number of blank spaces the Tab character should be expanded to. It defaults to 4 blank spaces.

A logical value indicating if word wrapping should be applied to when lines are extracted. The default value is .T. (true), resulting in extracted text lines that contain whole words only. When a word does not fit entirely to the end of the extracted text line, it is wrapped to the next text line. Passing .F. (false) for this parameter turns word wrapping off so that only lines ending with a hard carriage return are extracted.

This parameter defaults to .F. (false). It must be set to .T. (true) when text lines of more than 254 characters should be extracted. @

A numeric value specifying the first character in to begin with extracting text lines. It defaults to 1. If passed by reference, receives the starting position of the next line that can be extracted from in a repeated call to MemoLine(). This improves the speed of MemoLine() considerably when multiple lines are extracted from text of more than 64 kB.

Function Reference

951

MemoLine()

Return The function returns a character string of characters. If is .T. (true) and the extracted line does not end with a complete word, the line is filled with blank spaces up to the length of . If is .F. (false), the returned string contains characters and a next call to MemoLine() extracts characters following the next hard carriage return. If is larger than the number of lines contained in , an empty string ("") is returned.

Description MemoLine() is used to extract single text lines from a formatted text string that may include Tab characters (Chr(9)), Soft carriage returns (Chr(141)) or Hard carriage returns (Chr(13)). Multiple lines are usually extracted within a FOR..NEXT loop whose upper boundary is determined by the total number of text lines in a string, as reported by function MLCount(). If multiple lines are extracted, it is strongly recommended to pass by reference to MemoLine(), initializing the parameter with 1. This improves the speed of text extraction considerably. note: when text lines extracted with MemoLine() are displayed, they have only the same length if a fixed-size font is used for display.

Info See also: Category: Source: LIB: DLL:

FLineCount(), HB_FReadLine(), MemoEdit(), MemoRead(), MemoWrit(), MLCount(), MLPos() Character functions, Memo functions rtl\txtline.c xhb.lib xhbdll.dll

Example // The example demonstrates MemoLine() usage for extracting all lines // of a text file. The difference of using line numbers versus using // line offsets is outlined. PROCEDURE Main( cFileName ) LOCAL nLineLen := 60 LOCAL nTabSize := 8 LOCAL lWrap := .T. LOCAL i, imax, cText, cLine, nOffSet, nTextLen LOCAL t1, t2, t3 IF Empty( cFileName ) .OR. .NOT. File( cFileName ) ? "No file specified" QUIT ENDIF cText := MemoRead( cFileName ) t1 := Seconds() imax := MLCount( cText, nLineLen, nTabSize, lWrap ) FOR i:=1 TO imax cLine := MemoLine( cText, nLineLen, i, nTabSize, lWrap ) NEXT t2 := Seconds() // This example shows the use of the parameter.

952

Function Reference

MemoLine() // Note that the line number does not change, but the starting // position in the text to begin extracting a line nTextLen := Len( cText ) nOffSet := 1 i := 0 DO WHILE nOffSet cString

Arguments

This is a character string holding the name of the file to read. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Return The function returns the entire contents of file as a character string. If the file is not found, an empty string ("") is returned.

Description MemoRead() provides the fastest way of reading the entire contents of a file from disk and assign it to a memory or field variable. The function searches a file only in the current directory, if is not a full qualified file name. The settings of SET PATH and SET DEFAULT are ignored. The file is opened as read-only and in shared mode. If this fails due to another process having obtained exclusive access to the file, or if the file is not found, the return value is an empty string ("").

Info See also: Category: Source: LIB: DLL:

MemoEdit(), MemoLine(), MemoWrit(), REPLACE Character functions, Memo functions rtl\memofile.c xhb.lib xhbdll.dll

Example // See the examples of function MemoEdit() or MemoLine() for // a usage scenario of MemoRead()

954

Function Reference

Memory()

Memory() Returns memory statistics.

Syntax Memory( ) --> nMemoryUsage

Arguments

A numeric value must be passed to identify the memory to query. The following table lists #define constants listed in HBMemory.ch that can be used for .

Constants for memory statistics Constant

Value

Description

HB_MEM_CHAR HB_MEM_BLOCK HB_MEM_RUN HB_MEM_VM HB_MEM_FM HB_MEM_FMSEGS HB_MEM_SWAP HB_MEM_CONV HB_MEM_EMSUSED HB_MEM_USED HB_MEM_USEDMAX HB_MEM_STACKITEMS HB_MEM_STACK HB_MEM_STACK_TOP HB_MEM_LIST_BLOCKS

0 1 2 3 101 102 103 104 105 1001 1002 1003 1004 1005 1006

Free Variable Space (KB) Largest String (KB) RUN Memory (KB) Virtual Memory (KB) Fixed Memory/Heap (KB) Segments in Fixed Memory/Heap Free Swap Memory (KB) Free Conventional (KB) Used Expanded Memory (KB) Memory used (bytes) Maximum memory used (bytes) Total items on the stack Total memory size used by the stack (bytes) Total items currently on the stack List all allocated blocks

Return The function returns a numeric value indicating usage of the specified memory.

Description The function is used to obtain values for current memory usage. The type of memory to use must be specified with #define constants. Not all memory types are supported on all platforms. If a memory type cannot be queried, the return value is zero. Memory() can give only a "snapshot" of current memory usage while the function is being executed. The memory usage may have changed when the function returns due to the activity of xHarbour's garbage collector.

Function Reference

955

Memory()

Info See also: Category: Header: Source: LIB: DLL:

956

GetEnv(), HB_GCAll() Debug functions, Environment functions, xHarbour extensions hbmemory.ch vm\fm.c xhb.lib xhbdll.dll

Function Reference

MemoTran()

MemoTran() Replaces "carriage return/line feed" pairs in a character string.

Syntax MemoTran( , ; [], ; [] ) --> cNewString

Arguments

A character string or memo field to replace carriage return/line feed pairs in.

A single character used to replace hard carriage return/line feed pairs with. It defaults to a semicolon (;).

A single character used to replace soft carriage return/line feed pairs with. It defaults to a blank space.

Return The function returns a copy of where all carriage return / line feed pairs are replaced.

Description The function replaces hard and soft carriage return/line feed pairs with single characters in a memo field or a character string. A hard carriage return is Chr(13), while a soft carriage return is Chr(141). The latter is inserted into a text string by function MemoEdit() when automatic word wrap is set to .T. (true).

Info See also: Category: Source: LIB: DLL:

Function Reference

HardCR(), MemoEdit(), StrTran() Character functions, Memo functions rtl\mtran.c xhb.lib xhbdll.dll

957

MemoWrit()

MemoWrit() Writes a character string or a memo field to a file.

Syntax MemoWrit( , ) --> lSuccess

Arguments

This is a character string holding the name of the file to create. It must include path and file extension. If the path is omitted from , the file is created in the current directory.

A character string to be written to the file .

Return The function returns .T. (true) when the string could be written to the file , otherwise .F. (false) is returned.

Description MemoWrit() creates a file, writes the character string to it, and closes the file. If the file exists already, it is overwritten without warning. When the file cannot be created, the return value is .F. (false). Note: the function writes an end-of-file marker (Chr(26)) to the created file. That means, the file created by MemoWrit() contains one byte more than the input string . This must be taken into consideration if the file is later read using MemoRead().

Info See also: Category: Source: LIB: DLL:

FCreate(), FWrite(), MemoEdit(), MemoRead() Character functions, Memo functions rtl\memofile.c xhb.lib xhbdll.dll

Example // The example contains the shortest possible source code of // a complete text file editor (8 lines of code). PROCEDURE Main( cFileName ) IF Empty( cFileName ) ? "No file name specified" QUIT ENDIF MemoWrit( cFileName, MemoEdit( MemoRead( cFilename ) ) ) RETURN

958

Function Reference

MemVarBlock()

MemVarBlock() Creates a set/get code block for a dynamic memory variable.

Syntax MemVarBlock( ) --> bMemVarBlock

Arguments

A character string holding the name of a dynamic memory variable (PRIVATE or PUBLIC).

Return The function returns a set/get code block that accesses the memory variable . If the variable does not exist, the return value is NIL.

Description The function creates a code block accessing a dynamic memory variable, i.e. a variable of PRIVATE or PUBLIC scope. The code block accepts one parameter. If a parameter is passed, its value is assigned to the variable . Evaluating the code block without a parameter returns the value of the variable.

Info See also: Category: Source: LIB: DLL:

FieldBlock(), FieldWBlock() Code block functions rtl\memvabl.prg xhb.lib xhbdll.dll

Example // The example creates two code blocks accessing a PRIVATE // and a PUBLIC variable. PROCEDURE Main MEMVAR cPrivate, cPublic LOCAL bMemVar1 , bMemVar2 PUBLIC cPublic := "PUBLIC" PRIVATE cPrivate := "PRIVATE" bMemVar1 := MemVarBlock( "cPublic" ) bMemVar2 := MemVarBlock( "cPrivate" ) ? Eval( bMemVar1 ) ? Eval( bMemVar2 )

// result: PUBLIC // result: PRIVATE

? Eval( bMemVar1, "Hello" ) ? Eval( bMemVar2, "World" )

// result: Hello // result: World

? cPublic ? cPrivate RETURN

Function Reference

// result: Hello // result: World

959

MenuModal()

MenuModal() Activates the menu system represented by a TopBarMenu object.

Syntax MenuModal( , [], [] , [] , [] , [] , [

; ; ; ; ; ; ) --> nMenuItemID

Arguments

This is a TopBarMenu() object to activate.

This is a numeric value indicating the ordinal position of the first menu item to be selected when the menu is activated.

This is a numeric value specifying the screen row for displaying messages assigned to the instance variable :message of menu items. The range for is between 0 and MaxRow().

This is a numeric value specifying the left screen coordinate for displaying menu messages. Usually, is set to the value 0.

This is a numeric value specifying the right screen coordinate for displaying menu messages. Usually, is set to the value of MaxCol().

The parameter is an optional character string defining the color for the message to display. It defaults to SetColor().

Optionally, a GetList array can be passed when the menu is activated during READ.

Return The function returns the ordinal position of the selected menu item. If the user cancels menu selection with the Esc key, the return value is zero.

Description Function MenuModal() is provided for compatibility reasons. It calls method :modal() of the object and returns this method's result. 960

Function Reference

MenuModal()

Info See also: Category: Source: LIB: DLL:

Function Reference

READ, TopBarMenu() Get system, UI functions rtl\ttopbar.prg xhb.lib xhbdll.dll

961

MHide()

MHide() Hides the mouse cursor.

Syntax MHide() --> NIL

Return The function returns always NIL.

Description The function MHide() exists for compatibility reasons only and is not recommended to use. Hiding the mouse cursor is only relevant when an application runs in full screen mode. Use function MSetCursor() for hiding/displaying the mouse cursor in such an application.

Info See also: Category: Source: LIB: DLL:

962

MShow(), MSetCursor() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Function Reference

Min()

Min() Returns the smallerr value of two Numerics or Dates.

Syntax Min( , ) --> nSmallerNumber Min( , ) --> dSMallerDate

Arguments and

Two numeric values to be compared. and

Two Date values to be compared.

Return The function returns the smaller value of the two arguments.

Description The function compares two numeric or two Date values and returns the smaller value of both. Min() is used to normalize values against a limit. The inverse function is Max().

Info See also: Category: Source: LIB: DLL:

Max() Numeric functions, Date and time rtl\minmax.c xhb.lib xhbdll.dll

Example // // // //

The example compares elements of two arrays of different length. The limit for the loop counter is determined with function Min(). Array elements containing same values are collected in a result array. PROCEDURE Main LOCAL aArray1 := {"A", "B", "C", "D" } LOCAL aArray2 := {"D", "B", "C" } LOCAL aResult := {} LOCAL i, imax imax := Min( Len( aArray1 ), Len( aArray2 ) ) FOR i:=1 TO imax IF aArray1[i] == aArray2[i] AAdd( aResult, aArray1[i] ) ENDIF NEXT ? ValToPrg( aResult ) RETURN

Function Reference

// result: { "B", "C" }

963

MLCount()

MLCount() Counts the number of lines in a character string or memo field

Syntax MLCount( , [] , [] , [] , []

; ; ; ; ) --> nLineCount

Arguments

A character string or memo field to be counted. It can be a formatted text string that includes Tab and Hard/Soft carriage return characters.

A numeric value specifying the number of characters per line. It is usually a value between 4 and 254. If is larger than 254 characters, parameter must be set to .T. (true). The default value for is 79.

A numeric value specifying the number of blank spaces the Tab character should be expanded to. It defaults to 4 blank spaces.

A logical value indicating if word wrapping should be applied to when lines are counted. The default value is .T. (true), resulting in text lines being counted that contain whole words only. When a word does not fit entirely to the end of a text line, it is wrapped to the next text line. Passing .F. (false) for this parameter turns word wrapping off so that only lines ending with a hard carriage return are counted.

This parameter defaults to .F. (false). It must be set to .T. (true) when text lines of more than 254 characters should be counted.

Return The function returns the number of lines contained in when it is formatted according to the parameters , and .

Description MLCount() is used in conjunction with MemoLine() that extracts single lines of text from a formatted text string or memo field. MLCount() determines the total number of lines that can be extracted from .

964

Function Reference

MLCount()

Info See also: Category: Source: LIB: DLL:

MemoLine(), MemoTran(), MLPos() Memo functions, Character functions rtl\txtline.c xhb.lib xhbdll.dll

Example // Refer to function MemoLine() for a usage example of MLCount()

Function Reference

965

MLCToPos()

MLCToPos() Determines the position of a single character in a formatted text string or memo field.

Syntax MLCToPos( , ; [], ; [], ; [], ; [], ; [] , ; []) --> nPosition

Arguments

A character string or memo field to scan. It can be a formatted text string that includes Tab and Hard/Soft carriage return characters.

A numeric value specifying the number of characters per text line. It is usually a value between 4 and 254. If is larger than 254 characters, parameter must be set to .T. (true). The default value for is 79.

A numeric value specifying the text row, or line number, to find a character in. Text lines are counted beginning with 1, which is also the default value for .

A numeric value specifying the column within the text row to find a character in. Columns are counted beginning with 0, which is also the default value for .

A numeric value specifying the number of blank spaces the Tab character should be expanded to. It defaults to 4 blank spaces.

A logical value indicating if word wrapping should be applied to when lines are scanned. The default value is .T. (true), resulting in text lines that contain whole words only. When a word does not fit entirely to the end of the scanned text line, it is wrapped to the next text line. Passing .F. (false) for this parameter turns word wrapping off so that only lines ending with a hard carriage return are scanned.

This parameter defaults to .F. (false). It must be set to .T. (true) when text lines of more than 254 characters should be scanned.

Return The function returns the position of the character in that is located in the text row and column . Position counting starts with 1. 966

Function Reference

MLCToPos()

Description MLCToPos() calculates the position of a single character in a formatted text string, based on row and column position. Row and column positions are compatible with the parameters MemoEdit() passes to its user function. The return value of MLCToPos(), in contrast, is compatible with the SubStr() function, so that substrings can be extracted from a formatted character string.

Info See also: Category: Source: LIB: DLL:

MemoEdit(), MLCount(), MLPos(), MPosToLC(), SubStr() Character functions, Memo functions rtl\mlcount.c xhb.lib xhbdll.dll

Example // This example determines the byte position of line 3, column 6 // when the text string is formatted with 10 characters per line: PROCEDURE Main LOCAL cString LOCAL cLine LOCAL nLineLen LOCAL i, imax

:= := := :=

"The quick brown fox jumps over the lazy dog" "" 10 MLCount( cString, nLineLen )

? '"' + cString + '"' ? FOR i:=1 TO imax cLine := MemoLine( cString, nLineLen, i ) ? '"' + cLine + '"' NEXT // Output so far: // "The quick brown fox jumps over the lazy dog" // // "The quick " // "brown fox " // "jumps over" // "the lazy " // "dog " ? i := MLCtoPos( cString, nLineLen, 3, 6, 0) // result: 27 ? SubStr( cString, i, nLineLen ) // result: over the l RETURN

Function Reference

967

MLeftDown()

MLeftDown() Determines the status of the left mouse button.

Syntax MLeftDown() --> lLeftButtonIsPressed

Return MLeftDown() returns .T. (true) if the left mouse button is pressed when the function is called, otherwise .F. (false) is returned.

Description MLeftDown() is used in full screen or console window applications to determine the current status of the left mouse button.

Info See also: Category: Source: LIB: DLL:

968

Inkey(), MDblClk(), MHide(), MRightDown(), MRow(), MShow(), SET EVENTMASK Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Function Reference

MlPos()

MlPos() Determines the starting position of a line in a formatted character string or memo field.

Syntax MlPos( , [ , [] , [] , [] , []

; ; ; ; ; ) --> nPosition

Arguments

A character string or memo field to scan. It can be a formatted text string that includes Tab and Hard/Soft carriage return characters.

A numeric value specifying the number of characters per text line. It is usually a value between 4 and 254. If is larger than 254 characters, parameter must be set to .T. (true). The default value for is 79.

A numeric value specifying the text row, or line number, to find the starting position for. Text lines are counted beginning with 1, which is also the default value for .

A numeric value specifying the number of blank spaces the Tab character should be expanded to. It defaults to 4 blank spaces.

A logical value indicating if word wrapping should be applied to when lines are scanned. The default value is .T. (true), resulting in text lines that contain whole words only. When a word does not fit entirely to the end of the scanned text line, it is wrapped to the next text line. Passing .F. (false) for this parameter turns word wrapping off so that only lines ending with a hard carriage return are scanned.

This parameter defaults to .F. (false). It must be set to .T. (true) when text lines of more than 254 characters should be scanned.

Return The function returns the starting position of the text line having number in . Position counting starts with 1.

Description MLPos() is used similar to MLCToPos() for finding an exact byte position in a formatted text string. MlPos() ingnores column positions within a text line and searches only for the beginning of a line of text. Function Reference

969

MlPos()

Info See also: Category: Source: LIB: DLL:

MemoLine(), MemoTran(), MLCount(), MLCToPos(), MPosToLC() Character functions, Memo functions rtl\mlpos.c xhb.lib xhbdll.dll

Example // This example determines the starting position of the 4th line // when the text string is formatted with 10 characters per line: PROCEDURE Main LOCAL cString LOCAL cLine LOCAL nLineLen LOCAL i, imax

:= := := :=

"The quick brown fox jumps over the lazy dog" "" 10 MLCount( cString, nLineLen )

? '"' + cString + '"' ? FOR i:=1 TO imax cLine := MemoLine( cString, nLineLen, i ) ? '"' + cLine + '"' NEXT // Output so far: // "The quick brown fox jumps over the lazy dog" // // "The quick " // "brown fox " // "jumps over" // "the lazy " // "dog " ? ? i := MLPos( cString, nLineLen, 4 ) // result: 32 ? SubStr( cString, i, nLineLen ) // result: the lazy d RETURN

970

Function Reference

Mod()

Mod() Calculates the modulus of two numbers.

Syntax Mod( , ) --> nRemainder

Arguments

This is the numeric dividend of the division operation.

This is the numeric divisor of the division operation.

Return The function returns the numeric remainder of a division of by .

Description Function Mod() exists for compatibility reasons only. It is superseeded by the modulus operator.

Info See also: Source: LIB: DLL:

Function Reference

% operator rtl\mod.c xhb.lib xhbdll.dll

971

Month()

Month() Extracts the numeric month number from a Date value.

Syntax Month( ) --> nMonth

Arguments

This is an expression returning a value of data type Date.

Return The function returns the numeric month number of . When is an empty date, the function returns zero.

Description This function is used to extract the numeric month from a Date value.

Info See also: Category: Source: LIB: DLL:

CMonth(), Day(), DoW(), Year() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example shows results of the function Month() PROCEDURE Main ? Date() ? Month( Date() ) ? Month( Date() + 7 )

// result: 02/25/06 // result: 2 // result: 3

RETURN

972

Function Reference

MPosToLC()

MPosToLC() Calculates row and column position of a character in a formatted string or memo field.

Syntax MPosToLC( , ; [], ; [], ; [], ; [] , ; []) --> { nTextRow, nTextCol }

Arguments

A character string or memo field to scan. It can be a formatted text string that includes Tab and Hard/Soft carriage return characters.

A numeric value specifying the number of characters per text line. It is usually a value between 4 and 254. If is larger than 254 characters, parameter must be set to .T. (true). The default value for is 79.

A numeric value indicating the position of the character in . The default value is 1.

A numeric value specifying the number of blank spaces the Tab character should be expanded to. It defaults to 4 blank spaces.

A logical value indicating if word wrapping should be applied to when lines are scanned. The default value is .T. (true), resulting in text lines that contain whole words only. When a word does not fit entirely to the end of the extracted text line, it is wrapped to the next text line. Passing .F. (false) for this parameter turns word wrapping off so that only lines ending with a hard carriage return are scanned.

This parameter defaults to .F. (false). It must be set to .T. (true) when text lines of more than 254 characters should be extracted.

Return The function returns an array of two elements. The first element contains the row in the text where the character at position is located, and the second element is the column number.

Description MPosToLC() calculates the row and column position of a single character in a formatted text string, based on its byte position. Row and column positions are compatible with the parameters MemoEdit() passes to its user function. That is, rownumbersing begins with 1 and columns are numbered beginning with 0. Function Reference

973

MPosToLC()

Info See also: Category: Source: LIB: DLL:

MemoEdit(), MLCToPos(), MLPos() Character functions, Memo functions rtl\mpostolc.c xhb.lib xhbdll.dll

Example // This example determines the text row and column of the character // at position 36, when the text is formatted with 10 characters per line: PROCEDURE Main LOCAL cString LOCAL aLines LOCAL nLineLen LOCAL i, imax LOCAL aRowCol

:= := := :=

"The quick brown fox jumps over the lazy dog" {} 10 MLCount( cString, nLineLen )

? '"' + cString + '"' ? FOR i:=1 TO imax AAdd( aLines, MemoLine( cString, nLineLen, i ) ) ? '"' + aLines[i] + '"' NEXT // Output so far: // "The quick brown fox jumps over the lazy dog" // // "The quick " // "brown fox " // "jumps over" // "the lazy " // "dog " ? SubStr( cString, 36 )

// result: lazy dog

aRowCol := MPosToLC( cString, nLineLen, 36 ) ? aRowCol[1], aRowCol[2]

// result:

? SubStr( aLines[aRowCol[1]], 1+aRowCol[2] ) RETURN

974

4

4

// result: lazy

Function Reference

MPresent()

MPresent() Determines if a mouse is available.

Syntax MPresent() --> lMouseIsPresent

Return The function returns .T. (true) when a mouse is present, otherwise the return value is .F. (false).

Description The function tests the presence of a mouse. It is a compatibility function for text mode and full screen applications.

Info See also: Category: Source: LIB: DLL:

Function Reference

MRestState(), MSaveState(), MSetCursor() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

975

MRestState()

MRestState() Restores a previously saved state of the mouse.

Syntax MRestState( ) --> NIL

Arguments

This must be a character string previously returned from function MSaveState().

Return The function always returns NIL.

Description The function restores settings of the mouse that are previously saved with a call to MSaveState(). It is a compatibility function for text mode and full screen applications.

Info See also: Category: Source: LIB: DLL:

976

MPresent(), MSaveState(), MSetCursor() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Function Reference

MRightDown()

MRightDown() Determines the status of the left mouse button.

Syntax MRightDown() --> lRightButtonIsPressed

Return MRightDown() returns .T. (true) if the right mouse button is pressed when the function is called, otherwise .F. (false) is returned.

Description MRightDown() is used in full screen or console window applications to determine the current status of the right mouse button.

Info See also: Category: Source: LIB: DLL:

Function Reference

Inkey(), MDblClk(), MHide(), MLeftDown(), MRow(), MShow(), SET EVENTMASK Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

977

MRow()

MRow() Determines the screen row position of the mouse cursor.

Syntax MRow() --> nMouseRow

Return The function returns the row position of the mouse cursor as a numeric value.

Description MRow() is used in full screen or console window applications to determine the current screen row position of the mouse cursor. The top screen row has number zero, while the bottom screen row has number MaxRow(). Note to obtain proper mouse input from the user, function Inkey() should be called including mouse events.

Info See also: Category: Source: LIB: DLL:

Inkey(), MCol(), MDblClk(), MHide(), MLeftDown(), MRightDown(), MSetCursor(), MShow(), SET EVENTMASK Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Example // The example changes the event mask for Inkey() to ALL events // and displays the mouse cursor position when the left button is pressed. #include "Inkey.ch" PROCEDURE Main LOCAL nEvent, nRow, nCol, cPos CLS MShow() ? "Click with left mouse button (press ESC to quit)" SET EVENTMASK TO INKEY_ALL DO WHILE Lastkey() K_ESC nEvent := Inkey(0) IF nEvent == K_LBUTTONDOWN nRow := MRow() nCol := MCol() cPos := LTrim( Str(nRow) ) + "," + LTrim( Str(nCol) ) // display current mouse cursor position @ nRow, nCol SAY cPos ENDIF ENDDO RETURN

978

Function Reference

MSaveState()

MSaveState() Saves the current state of the mouse.

Syntax MSaveState() --> cSavedState

Return The function returns the current mouse state encoded in a binary character string.

Description MSaveState() is used in text mode and console window applications to save the current settings of the mouse. This includes the screen position of the mouse cursor, its visibility and boundaries. The return value can be passed to function MRestState() to restore the saved state.

Info See also: Category: Source: LIB: DLL:

Function Reference

MPresent(), MRestState(), MSetCursor() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

979

MSetBounds()

MSetBounds() Sets restricting boundaries for the mouse cursor.

Syntax MSetBounds( [], [], [], [] ) --> NIL

Arguments

A numeric value indicating the screen coordinate for the top boundary of the restricting rectangle. The default value is 0.

A numeric value indicating the screen coordinate for the left boundary of the restricting rectangle. The default value is 0.

A numeric value indicating the screen coordinate for the bottm boundary of the restricting rectangle. The default value is MaxRow().

A numeric value indicating the screen coordinate for the right boundary of the restricting rectangle. The default value is MaxCol().

Return The function always returns NIL.

Description The function restricts mouse cursor movement to the rectangle defined with the passed parameters. If no parameter is passed to MSetBounds(), the function releases all boundaries set. MSetBound() is a compatibility function for text mode and full screen applications.

Info See also: Category: Source: LIB: DLL:

980

MPresent(), MRestState(), MSaveState(), MSetCursor() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Function Reference

MSetCursor()

MSetCursor() Determines the visibility of the mouse cursor.

Syntax MSetCursor( [] ) --> lPreviousSetting

Arguments

A logical value can be passed. .T. (true) makes the mouse cursor visible and .F. (false) hides it.

Return The function returns a logical value indicating the visibility of the mouse cursor before MSetCursor() is called.

Description MSetCursor() is used to change the visibility of the mouse cursor. This is only relevant for full screen text mode applications that use SaveScreen() for saving and the screen buffer. The mouse cursor must be hidden before SaveScreen() is called.

Info See also: Category: Source: LIB: DLL:

Function Reference

MPresent(), MRestState(), MSaveState(), MSetBounds(), SetMouse() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

981

MSetPos()

MSetPos() Moves the mouse cursor to a new position on screen.

Syntax MSetPos( , ) --> NIL

Arguments

A numeric value between 0 and MaxRow() specifying the new row position of the mouse cursor.

A numeric value between 0 and MaxCol() specifying the new columnn position of the mouse cursor.

Return The return value is always NIL.

Description MSetPos() is used in full screen or console window applications to move the mouse cursor to a new position on the screen. It is a compatibility function.

Info See also: Category: Source: LIB: DLL:

982

MCol(), MRow(), MSetBounds(), MSetCursor(), SetMouse() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

Function Reference

MShow()

MShow() Displays the mouse cursor.

Syntax MShow() --> NIL

Return The function returns always NIL.

Description The function MShow() exists for compatibility reasons only and is not recommended to use. Displaying the mouse cursor is only relevant when an application runs in full screen mode. Use function MSetCursor() for hiding/displaying the mouse cursor in such an application.

Info See also: Category: Source: LIB: DLL:

Function Reference

MHide(), MSetCursor() Mouse functions rtl\mouseapi.c xhb.lib xhbdll.dll

983

NetErr()

NetErr() Determines if a database command has failed in network operation.

Syntax NetErr( [] ) --> lIsNetworkError

Arguments

An optional logical value that sets the global status for errors which may occur with database operations in a network.

Return The function returns .T. (true) if a database could not be opened or a new record could not be created during concurrent access in a network. Otherwise, the return value is .F. (false).

Description NetErr() is a function used to detect database errors that may occur with the commands USE, USE...EXCLUSIVE or APPEND BLANK when a database is concurrently accessed by multiple applications in a network. The function maintains a status variable indicating such errors. The status variable is set by xHarbour's default error handling system in following situations:

Possible NetErr() conditions Failed command

Description

USE USE...EXCLUSIVE APPEND BLANK

USE EXCLUSIVE is issued by another process USE or USE EXCLUSIVE is issued by another process LastRec()+1 is locked with FLock() or Rlock() by another process

NetErr() returns .T. (true) if a database command failed due to these conditions.

Info See also: Category: Source: LIB: DLL:

APPEND BLANK, DbAppend(), DbRLock(), DbUseArea(), FLock(), NetName(), RLock(), USE Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example illustrates the situations where NetErr() is used // to detect possible database access errors in a network: PROCEDURE Main USE Customer ALIAS Cust NEW EXCLUSIVE IF .NOT. NetErr() INDEX ON CustID TO Cust01 INDEX ON Upper(LastName+FirstName) TO Cust02 USE

984

Function Reference

NetErr() ELSE ? "File cannot be opened exclusively" ENDIF USE Customer ALIAS Cust SHARED NEW IF .NOT. NetErr() SET INDEX TO Cust01, Cust02 ELSE ? "File is exclusively used by another process" ENDIF IF Select( "Cust" ) > 0 SELECT Cust APPEND BLANK IF .NOT. NetErr() REPLACE CustID WITH "X087" , ; Name WITH "Miller" ELSE ? "Record is currently locked by another process" ENDIF ENDIF RETURN

Function Reference

985

NetName()

NetName() Retrieves the current user name or the computer name.

Syntax NetName( [] ) --> cComputerName | cUserName

Arguments

If is set to .T. (true), the function returns the user account name, otherwise it returns the computer name.

Return The function returns a character string containing either the computer name or the user name. If this information cannot be retrieved, an empty string ("") is returned.

Description NetName() serves informational purposes and is used when different users log into the same computer, or when multiple computers run the same application in a network.

Info See also: Category: Source: LIB: DLL:

986

Os(), Version() Environment functions, Network functions rtl\net.c xhb.lib xhbdll.dll

Function Reference

NextKey()

NextKey() Returns the next pending key or mouse event.

Syntax NextKey( [] ) --> nNextInkeyCode

Arguments

A numeric value specifying the type of events NextKey() should retrieve. #define constants from INKEY.CH must be used for . They are listed below:

Constants for Constant

Value

Events returned by NextKey()

INKEY_MOVE INKEY_LDOWN INKEY_LUP INKEY_RDOWN INKEY_RUP INKEY_MMIDDLE INKEY_MWHEEL INKEY_KEYBOARD INKEY_ALL

1 2 4 8 16 32 64 128 255

Mouse pointer moved Left mouse button pressed Left mouse button released Right mouse button pressed Right mouse button released Middle mouse button pressed Mouse wheel turned Key pressed All events are returned

IF is omitted, the current SET EVENTMASK setting is used. If this is not issued, NextKey() returns only keyboard events.

Return The function returns a numeric value identifying the next keyboard or mouse event that can be retrieved by the Inkey() function.

Description The NextKey() function returns the next keyboard or mouse event that is pending in the internal input buffers to be retrieved by the Inkey() function. NextKey() does not remove events from the input buffers and does not update the LastKey() value. This way, the input buffers can be polled without actually removing an event. If only a subset of the Inkey codes is required, NextKey() can be passed a parameter that filters Inkey codes. Only Inkey codes matching are returned from NextKey(). Note: the file INKEY.CH contains numerous symbolic #define constants that identify different key strokes or mouse input. It is recommended to use #define constants for prosessing Inkey codes, rather than using their numeric values.

Function Reference

987

NextKey()

Info See also: Category: Source: LIB: DLL:

Inkey(), KEYBOARD, LastKey(), SET EVENTMASK, SET TYPEAHEAD Keyboard functions, Mouse functions rtl\inkey.c xhb.lib xhbdll.dll

Example // In the example, two characters are stuffed into the keyboard buffer // and the results of Inkey(), LastKey() and NextKey() are shown #include "Inkey.ch" PROCEDURE Main KEYBOARD "19" ? Chr( NextKey() ) ? Chr( LastKey() )

// result: 1 // result: Chr(0)

? Chr( Inkey() ) ? Chr( LastKey() )

// result: 1 // result: 1

? Chr( NextKey() ) ? Chr( LastKey() )

// result: 9 // result: 1

? Chr( Inkey() ) ? Chr( LastKey() ) ? Chr( NextKey() ) RETURN

988

// result: 9 // result: 9 // result: Chr(0)

Function Reference

Notify()

Notify() Resumes a single thread blocked by a particular Mutex.

Syntax Notify( , [] ) --> NIL

Arguments

This is the handle of the Mutex to notify. It is the return value of HB_MutexCreate().

Optionally, an arbitrary value can be passed as second parameter. It defines the return value of Subscribe() and, thus, is passed to the thread that is blocked by the Mutex.

Return The function returns always NIL.

Description Function Notify() sends a notification to the next thread having subscribed to a Mutex. The second parameter defines the return value for the function Subscribe() being executed in a second thread. If more than one thread have subscribed to the Mutex , the operating system selects the thread to resume exexuting program code. It is not possible to notify a particular thread waiting for a Mutex.

Info See also: Category: Source: LIB: DLL:

Function Reference

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), NotifyAll(), StartThread(), Subscribe(), SubscribeNow() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

989

NotifyAll()

NotifyAll() Resumes all threads blocked by a particular Mutex.

Syntax NotifyAll( ) --> NIL

Arguments

This is the handle of the Mutex to notify. It is the return value of HB_MutexCreate().

Return The function returns always NIL.

Description Function NotifyAll() sends a nodification to all threads having subscribed for a Mutex. As a result, all threads waiting for a notification on resume program excution.

Info See also: Category: Source: LIB: DLL:

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), Notify(), StartThread(), Subscribe(), SubscribeNow() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Example // // // //

The example starts 5 threads which are suspended immediately after being started by Subscribe(). When the Main thread has created the threads, they are resumed after a key stroke. The Main thread then waits for the end of all threads before the program terminates. PROCEDURE Main LOCAL i, imax := 5 LOCAL pMutex := HB_MutexCreate() CLS FOR i:=1 TO imax StartThread( "RunInThread", pMutex, 2*i ) ThreadSleep( 50 ) NEXT WAIT "Press a key to notify all threads..." NotifyAll( pMutex ) WaitForThreads() RETURN

990

Function Reference

NotifyAll() PROCEDURE RunInThread( pMutex, nRow ) LOCAL nCol @ nRow, 0 SAY "Thread #" + LTrim( Str(GetThreadID()) ) nCol := Col() Subscribe( pMutex ) DO WHILE nCol < MaxCol() DispoutAt( nRow, ++nCol, "-" ) ThreadSleep(10) ENDDO RETURN

Function Reference

991

NumButtons()

NumButtons() Returns the number of mouse buttons.

Syntax NumButtons() --> nButtonCount

Return The function returns the number of mouse buttons available.

Description NumButtons() is used to determine how many buttons a mouse is equipped with.

Info See also: Category: Source: LIB: DLL:

992

MSetCursor(), SetMouse() Mouse functions rtl\mousex.c xhb.lib xhbdll.dll

Function Reference

NumToHex()

NumToHex() Converts a numeric value or a pointer to a Hex string.

Syntax NumToHex( |, []) --> cHexString

Arguments |

The first parameter is eiher a numeric value or a pointer to convert to hexadecimal notation.

An optional numeric value specifying the length of the return string.

Return The function returns a character string holding the passed value in hexadecimal notation.

Description NumToHex() converts a numeric value or a pointer to a Hex formatted character string. It converts only integer values. If a number has a decimal fraction, it is ignored. The reverse function is HexToNum().

Info See also: Category: Source: LIB: DLL:

CStr(), HexToNum(), HexToStr(), StrToHex(), StrZero(), Transform() Numeric functions, Conversion functions, xHarbour extensions rtl\hbhex2n.c xhb.lib xhbdll.dll

Example // The example demonstrates return values of NumToHex() PROCEDURE Main() ? NumToHex( 1 ) ? NumToHex( 128 )

// result: 1 // result: 80

? NumToHex( 1 , 4 ) ? NumToHex( 128, 4 )

// result: 0001 // result: 0080

? NumToHex( -128 ) ? NumToHex( -1 )

// result: FFFFFFFFFFFFFF80 // result: FFFFFFFFFFFFFFFF

? NumToHex( -1 , 4 )

// result: FFFF

? NumToHex( SQrt(2) ) RETURN

Function Reference

// result: 1

993

OrdBagExt()

OrdBagExt() Retrieves the default extension for index files.

Syntax OrdBagExt() --> cFileExtension

Return The function returns the default extension for index files used by the default RDD as a character string.

Description OrdBagExt() returns the extension for index files used by the RDD that opens a database in the current work area. Different RDDs maintain different default file extensions. They are used when an index file is created and the file name is specified without extension. Note: OrdBagExt() does not return the file extension of an open index.

Info See also: Category: Source: LIB: DLL:

DbTableExt(), DbOrderInfo(), OrdBagName(), OrdCreate(), OrdFor(), OrdKey(), OrdName(), OrdNumber(), RddName() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example displays default index file extensions of two // RDDs available in xHarbour. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFNTX" ? OrdBagExt()

// result: .ntx

USE VfpCust VIA "DBFCDX" ? OrdBagExt()

// result: .cdx

CLOSE ALL RETURN

994

Function Reference

OrdBagName()

OrdBagName() Retrieves the file name of an open index.

Syntax OrdBagName( [ | ] ) --> cIndexFilename

Arguments

A numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

Return The function returns the name of the index file that contains the specified index as a character string. If no parameter is passed, the function returns the file name of the controlling index. If no index file is open, an empty string ("") is returned.

Description OrdBagName() retrieves the name of the index file in which an index is stored. The index can be specified by its numeric ordinal position, or by its symbolic name specified with the TAG option of the INDEX command.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), OrdBagExt(), OrdCreate(), OrdFor(), OrdKey(), OrdName(), OrdNumber(), RddName() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example lists results of OrdBagName() using two different RDDs. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFNTX" SET INDEX TO Cust01, Cust02 ? ? ? ?

OrdBagName() OrdBagName(1) OrdBagName(2) OrdBagName(3)

Function Reference

// // // //

result: result: result: result:

Cust01.ntx Cust01.ntx Cust02.ntx (empty string)

995

OrdBagName() USE Invoice VIA "DBFCDX" SET INDEX TO Invoice ? ? ? ?

OrdName() , OrdName(1), OrdName(2), OrdName(3),

OrdBagName() OrdBagName(1) OrdBagName(2) OrdBagName(3)

// // // //

result: result: result: result:

InvNo Invoice.cdx InvNo Invoice.cdx Custno Invoice.cdx (empty string)

CLOSE ALL RETURN

996

Function Reference

OrdCondSet()

OrdCondSet() Sets the conditions for index creation.

Syntax OrdCondSet( [] , [] , [] , [], [] , [] , [] , [] , [] , [] , [] , [] , [] , [] , [] , [] , [] , []

; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ) --> lSuccess

Arguments

A character string holding the FOR expression for the index to create. This string is stored in the index file header and can later be retrieved using the OrdFor() function. Pass an empty string ("") if the index is created without a FOR condition. The FOR expression cannot exceed 250 characters in length. RDDs that do not support a FOR condition when creating indexes generate a runtime error when this parameter is used.

A code block specifying the FOR expression, or NIL if no FOR expression is used. The code block expression must be identical with the expression specified as a character string . The code block is evaluated for all records in the current work area. Those records where yields .T. (true) are included in the index.

If .T. (true) is passed, all records in the current work area are indexed. The default value is .F. (false) so that the scope for indexing can be narrowed with the parameters or .

A code block containing a logical expression, or NIL if no WHILE condition is used. The index creation continues while the code block returns .T. (true). Index creation is terminated as soon as yields .F. (false). changes the default scope to . The code block is only used during index creation and not stored in the index file.

Function Reference

997

OrdCondSet()

A code block that is evaluated every records. It is normally used to inform the user about indexing progress and must return a logical value. The indexing operation continues as long as Eval() returns .T. (true). The operation is stopped when Eval() returns .F. (false).

This is a numeric value specifying the number of records to index before the code block is called. The default value is 0, so that is called for every record.

This is a numeric value specifying the record number to begin the index creation with. The default value is 0, i.e. indexing begins with the first record.

A numeric value restricting the number of records to evaluate during index creation to . The default value is 0, i.e. there is no restriction.

A numeric value specifying the record number of a single record to add to the index. The default value is 0, i.e. the single record scope is ignored.

If .T. (true) is passed, only the records from to the end of file are processed. Passing .F. (false) processes all records. The default value is .T. (true).

The default value for is .F. (false), resulting in records being added to the index in ascending order. If .T. (true) is passed, a descending index is created.

This parameter is reserved for future use.

If .T. (true) is passed, an index is created in addition to open indexes. The default value is .F. (false) causing all indexes open in the work area being closed before the new index is created.

Passing .T. (true) for instructs the RDD to use the current logical order of records for navigating the database during index creation. The logical order is determined by the controlling index and the OrdScope() restriction. The default value is .F. (false) so that the records in the current work area are evaluated in physical order.

If .T. (true) is passed, only an empty index is created that is custom built. Index entries must be added or deleted explicitely using functions OrdKeyAdd() and OrdKeyDel(). RDDs that support custom indexes do not add or delete keys automatically. The default value is .F. (false).

998

Function Reference

OrdCondSet()

The parameter is only relevant when is specified. Normally, the FOR condition is optimized. Passing .T. (true) suppresses optimization. The default value is .F. (false).

Passing .T. (true) for instructs the RDD to recognize a filter condition active the current work area that is set with SET FILTER or SET DELETED. In this case, filtered records are not included in the index. The default value is .F. (false) so that a filter condition is not recognized during index creation.

If .T. (true) is passed, the index file is created in EXCLUSIVE file access mode. The default value is .F. (false) so that the index file is created in SHARED mode.

Return The function returns .T. (true) if the conditions for index creation are set, otherwise .F. (false) is returned.

Description The OrdCondSet() function specifies the conditions for index creation in the current work area. The conditions override default values and remain active until an index is created. This is accomplished with function OrdCreate(). Consequently OrdCondSet() is immediately followed by a call to OrdCreate(). It is recommended to specify index creation conditions using the INDEX command. This command is preprocessed to OrdCondSet() and OrdCreate(). INDEX is much more comfortable to use for specifying the numerous function parameters.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbOrderInfo(), INDEX, OrdCreate() Index functions, Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

999

OrdCount()

OrdCount() Determines the number of indexes open in a work area.

Syntax OrdCount( [] ) --> nOpenIndexes

Arguments

This is a character string with the name of the file that stores the indexes. When the file extension is omitted, it is determined by the database driver that manages the file.

Return The function returns the number of open indexes stored in . If this parameter is omitted, the return value is the total number of indexes open in a work area.

Description The function delivers information about the number of indexes open in a work area, or indexes stored in a particular index file. It can be used as loop counter limit when information about all open indexes is collected.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), OrdCreate(), OrdKey(), OrdNumber() Index functions, Database functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows a user defined function which collects information // about open indexes in all work areas. FUNCTION LOCAL LOCAL LOCAL LOCAL

AllOrders() nArea := Select() aWorkArea := {} aOrders := {} i, imax, j, jmax

SELECT 0 imax := Select() - 1 FOR i:=1 TO imax DbSelectArea( i ) jmax := OrdCount() aOrders := Array( jmax ) AAdd( aWorkArea, { Alias(), aOrders } ) FOR j:=1 TO jmax aOrders[j] := { OrdBagName(j), OrdName(j) , ; OrdKey(j) , OrdCustom(j) }

1000

Function Reference

OrdCount() NEXT NEXT DbSelectArea( nArea ) RETURN aWorkArea

Function Reference

1001

OrdCreate()

OrdCreate() Creates a new index.

Syntax OrdCreate( , [], , , []

; ; ; ; ) --> NIL

Arguments

This is a character string with the name of the file that stores the new index. When the file extension is omitted, it is determined by the database driver that creates the file.

This is a character string holding the symbolic name of the index to create in an index file. It is analogous to the alias name of a work area. Support for depends on the RDD used to create the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

This is a character expression which describes the index expression in textual form. The expression is evaluated for the records in the current work area. The return value of determines the logical order of records when the index is the controlling index. The data type of the index may be Character, Date, Numeric or Logical. The maximum length of an index expression and its value is determined by the replaceable database driver used to create the index.

It is the same like but is specified as a code block that can be evaluated. If omitted, the code block is created from .

If the optional parameter is set to .T. (true), it suppresses inclusion of records that yield duplicate index values. When an index value exists already in an index, a second record resulting in the same index value is not added to the index. When is omitted, the current SET UNIQUE setting is used as default.

Return The function returns NIL.

Description The index function OrdCreate() creates an index for the database open in the current work area. Use an aliased expression to create an index in a different work area. Indexes are created by the RDD used to open the database, according to the conditions specified with function OrdCondSet(). If the RDD does not support multiple indexes per index file (DBFNTX, for example) an existing index file is overwritten. If multiple indexes are supported by an 1002

Function Reference

OrdCreate()

RDD (DBFCDX, for example) and is open, a new index is added to the file. If exists already in the list of open indexes, it is replaced with a new index having the expression . During index creation, the code block is evaluated for each record of the work area and its return value is added to the index. When index creation is complete, the new index becomes the controlling index. As a result, records are viewed in logical index order and no longer in physical order.

Info See also: Category: Source: LIB: DLL:

DbCreateIndex(), DbOrderInfo(), INDEX, OrdCondSet(), OrdListAdd(), OrdListClear(), Set() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indexes in one index file. REQUEST Dbfcdx PROCEDURE Main USE Customer ALIAS Cust NEW VIA "DBFCDX" OrdCreate( "Customer", "ID" , "CUSTNO" ) OrdCreate( "Customer", "NAME", "Upper(LastName+FirstName)" ) OrdListClear() OrdListAdd( "Customer" ) ? OrdNumber() ? OrdName() ? OrdKey()

// result: 1 // result: ID // result: CUSTNO

? ? ? ?

// // // //

OrdSetfocus( "NAME" ) OrdNumber() OrdName() OrdKey()

result: result: result: result:

ID 2 NAME Upper(LastName+FirstName)

CLOSE Cust RETURN

Function Reference

1003

OrdCustom()

OrdCustom() Determines if an index is a custom index.

Syntax OrdCustom( [ | ], ; [] , ; [] ) --> lOldCustomFlag

Arguments

This is a character string holding the symbolic name of the index to query. It is analogous to the alias name of a work area. Support for depends on the RDD used to create the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

Optionally, a numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

A logical value can be passed for . It changes the custom flag of the index. When .T. (true) is specified, the index becomes a custom index that is not automatically updated by the RDD. Passing .F. (false) removes the custom flag.

Return The function returns the custom flag set before the function is called.

Description The OrdCustom() function is used to determine if an index is a custom built index, or changes the custom flag of an index at runtime. Custom built indexes are not automatically updated by the RDD. Instead, index keys must be added to or removed from an index programmatically using OrdKeyAdd() or OrdKeyDel().

Info See also: Category: Source: LIB: DLL:

1004

DbOrderInfo(), INDEX, OrdCondSet(), OrdDescend(), OrdKeyAdd(), OrdKeyDel() Database functions, Index functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

OrdDescend()

OrdDescend() Determines the navigational order of a work area.

Syntax OrdDescend( [ | ], ; [] , ; [] ) --> lOldDescendFlag

Arguments

This is a character string holding the symbolic name of the index to query. It is analogous to the alias name of a work area. Support for depends on the RDD used to create the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

Optionally, a numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

A logical value can be passed for . It changes the descend flag of the index. When .T. (true) is specified, the navigational order in the current work area is set to descending, .F. (false) sets the navigational order to ascending.

Return The function returns the descend flag set before the function is called.

Description The function OrdDescend() is used to change the descend flag dynamically at runtime. The navigational order in a work area can be changed from ascending to descending and back without having to create a corresponding index. When .T. (true) is passed to the function, the navigational order is reversed, i.e. all functions and commands which move the record pointer are reversed.

Descending navigation Function

Description

Bof() Eof() DbSkip( 1 ) DbSkip(-1 ) DbGoTop() DbGoBottom()

Returns .T. when the last record is reached. Returns .T. when the first record is reached. Moves the record pointer to the previous record. Moves the record pointer to the next record. Moves the record pointer to the last record. Moves the record pointer to the first record.

Function Reference

1005

OrdDescend()

Note: the function changes the descending flag at runtime only. It does not change the actual index file.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), INDEX, OrdCondSet(), OrdCustom() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates an ascending index and demonstrates // the effect when the navigational order is reversed. PROCEDURE Main USE Customer INDEX ON Upper(Lastname+Firstname) TO Cust01 GO TOP ? LastName GO BOTTOM ? LastName

// result: Waters

OrdDescend( ,, .T. )

// change navigational order

SKIP -1 ? Bof()

// skipping backwards from the last // record hits begin of file. // result: .T.

GO BOTTOM ? Eof() ? LastName

// result: .F. // result: Alberts

SKIP ? Eof()

// Result: .T.

GO TOP ? LastName

// result: Waters

// result: Alberts

USE RETURN

1006

Function Reference

OrdDestroy()

OrdDestroy() Deletes an index from an index file.

Syntax OrdDestroy( [, ] ) --> NIL

Return The function always returns NIL.

Description OrdDestroy() deletes an open index and removes it from an index file. If the index file contains only one index, the file is erased from disc. When the controlling index is removed, no index is active after OrdDestroy() returns and the database is navigated in physical order. Function OrdNumber() returns 0 in that case, although other indexes may be open. Use OrdSetFocus() to activate another index.

Info See also: Category: Source: LIB: DLL:

DELETE TAG, OrdCreate() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indexes and destroys the controlling // index. PROCEDURE Main USE Customer OrdCreate( "Customer1", "ID" , "CUSTNO" ) OrdCreate( "Customer2", "NAME", "Upper(LastName+FirstName)" ) OrdSetFocus( "ID" ) ? OrdNumber() ? OrdName() ? OrdKey()

// result: 1 // result: ID // result: CUSTNO

? OrdSetfocus( "NAME" )

// result: ID

? OrdName() ? OrdNumber() ? OrdKey()

// result: NAME // result: 2 // result: Upper(LastName+FirstName)

OrdDestroy( "NAME" ) ? OrdNumber() ? OrdName() ? OrdKey()

// result: 0 // result: (empty string) // result: (empty string)

USE RETURN

Function Reference

1007

OrdFindRec()

OrdFindRec() Searches a record number in the controlling index.

Syntax OrdFindRec( , [] ) --> lFound

Arguments

This is a numeric value specifying the phyiscal record number to find in the controlling index. Physical record numbers are in the range of 1 to Lastrec().

This parameter defaults to .F. (false) causing OrdFindRec() to begin the search with the first record included in the controlling index. When .T. (true) is passed, the function begins the search with the current record.

Return The function returns .T. (true) if a record is found in the controlling index that has the record number , otherwise .F. (false) is returned.

Description OrdFindRec() searches a record number in the controlling index. It is similar to DbSeek(), which searches an index key. If OrdFindRec() finds the record number in the controlling index, it positions the record pointer on the found record, and Function Found() returns .T. (true) until the record pointer is moved again. In addition, both functions, BoF() and EoF() return .F. (false). When a matching record number is not found, the record pointer is positioned on the "ghost record" (Lastrec()+1), and the function Found() returns .F. (false), while Eof() returns .T. (true).

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), DbSeek(), OrdKeyGoto(), OrdKeyVal(), OrdWildSeek() Database functions, Index functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example navigates the record pointer via the controlling index // using physical and logical record numbers, REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" INDEX ON Upper(LastName) TAG NAME TO Cust01 OrdFindRec( 1 ) ? Lastname, Recno(), OrdKeyNo()

1008

// Physical first record // result: Miller 1 15

Function Reference

OrdFindRec() OrdFindRec( LastRec() ) ? Lastname, Recno(), OrdKeyNo()

// Physical last record // result: Smith 22 19

OrdKeyGoto( 1 ) ? Lastname, Recno(), OrdKeyNo()

// Logical first record // result: Alberts 20

1

OrdKeyGoto( OrdKeyCount() ) ? Lastname, Recno(), OrdKeyNo()

// Logical last record // result: Waters 15

22

OrdFindRec( -1 ) ? Lastname, Recno(), OrdKeyNo()

// Non-existent record // result: 23

0

? Bof(), Eof(), Found() USE RETURN

Function Reference

// result: .T.

.T.

.F.

1009

OrdFor()

OrdFor() Retrieves the FOR expression of an index.

Syntax OrdFor( [|][,] ) --> cForExpression

Arguments

A numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

Return The function returns a character string holding the FOR condition of the specified index. If the index is created without FOR condition, or if no index is open an empty string ("") is returned. If no parameter is passed to OrdFor(), the function returns the FOR condition of the controlling index.

Description OrdFor() returns the FOR expression of an index as a character string. It is similar to OrdKey() which returns the index key expression.

Info See also: Category: Source: LIB: DLL:

1010

DbOrderInfo(), INDEX, OrdCondSet(), OrdCreate(), OrdKey(), OrdName(), OrdNumber() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

OrdIsUnique()

OrdIsUnique() Retrieves the UNIQUE flag of an index.

Syntax OrdIsUnique( [|][,] ) --> lUniqueFlag

Arguments

A numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

Return The function returns the UNIQUE flag of the specified index as a logical value. If no index is open, the function returns .F. (false). If no database is open, a runtime error is created.

Description OrdIsUnique() queries the UNIQUE flag of an index. This flag is stored in the index file header and is set upon index creation with the INDEX command.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbOrderInfo(), INDEX, OrdCondSet(), OrdCreate(), OrdFor(), OrdKey(), OrdName() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

1011

OrdKey()

OrdKey() Returns the key expression of an index.

Syntax OrdKey( [|][,] ) --> cIndexKey

Arguments

A numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

Return The function returns the key expression of the specified index as a character string. If no parameters are passed, the index key of the controlling index is returned. If no index is open, the return value is an empty string ("").

Description OrdKey() returns the index key expression of an index as a character string. It is similar to OrdFor() which returns the FOR expression of the index.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), INDEX, IndexKey(), OrdCreate(), OrdFor(), OrdKeyCount(), OrdKeyNo(), OrdKeyVal(), OrdName(), OrdNumber() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indexes and displays their key expressions PROCEDURE Main USE Customer OrdCreate( "Customer1", "ID" , "CUSTNO" ) OrdCreate( "Customer2", "NAME", "Upper(LastName+FirstName)" )

1012

Function Reference

OrdKey() OrdSetFocus( "ID" ) ? OrdKey()

// result: CUSTNO

OrdSetfocus( "NAME" ) ? OrdName() ? OrdNumber() ? OrdKey()

// result: NAME // result: 2 // result: Upper(LastName+FirstName)

? OrdKey(1) ? OrdKey( "NAME" )

// result: CUSTNO // result: Upper(LastName+FirstName)

USE RETURN

Function Reference

1013

OrdKeyAdd()

OrdKeyAdd() Adds an index key to a custom built index.

Syntax OrdKeyAdd( [|], ; [] , ; [] ) --> lSuccess

Arguments

A numeric value specifying the ordinal position of the custom index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open custom index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the custom index. It is only required when multiple index files are open that contain indexes having the same .

This is the index value to be added to the index for the current record. It must be of the same data type as the value returned by the index expression. If omitted, is obtained by evaluating the index expression with the data of the current record.

Return The function returns .T. (true) if the current record is successfully included in the index, otherwise .F. (false) is returned.

Description OrdKeyAdd() is used to build a custom index whose entries are programmatically added and deleted. Custom built indexes are not automatically updated by the RDD but are initially empty. OrdKeyAdd() adds the current record to the custom index and OrdKeyDel() removes it. It is possible to add multiple index values to the index for the same record, so that the same record is found when different search values are passed to DbSeek(). If no parameters are passed, OrdKeyAdd() evaluates the index expresssion with the data of the current record to obtain . The record is added to the index when it matches the FOR condition and scoping restrictions, if they are defined. When is specified, it must have the same data type as the value of the expression &(OrdKey()). OrdKeyAdd() fails if the record pointer is positioned on Eof(), if the specified index is not a custom index, or if the specified index does not exist. 1014

Function Reference

OrdKeyAdd()

This is important when the custom index is the controlling index. Since a custome index is initially empty, relative database navigation with SKIP positions the record pointer always at Eof(). To include records to a controlling custom index, they must be physically navigated to using DbGoto(). The recommended way of creating a custom index is to use a non-custom index as the controlling index, skip through the database and specify for OrdListAdd() when the current record meets the conditions for being included in the custom index.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), DbGoto(), INDEX, OrdKey(), OrdKeyDel(), OrdKeyVal() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // // // // // //

The example shows two approaches for building a custom index. In the first approach, the controlling index is a regular index which allows for relative database navigation. The second approach uses the custome index as controlling index and requires absolute database navigation. The first five logical records and physical records are added to the custome index. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" INDEX ON Upper(LastName+FirstName) TAG NAME TO Cust01 INDEX ON Upper(LastName+FirstName) TAG NAMESET TO Cust01t CUSTOM // relative navigation with non-custom index OrdSetFocus( "NAME" ) GO TOP FOR i:=1 TO 5 OrdKeyAdd( "NAMESET" ) SKIP NEXT GO TOP Browse() // absolute navigation with custom index OrdSetFocus( "NAMESET" ) FOR i:=1 TO 5 DbGoto( i ) OrdKeyAdd( "NAMESET" ) NEXT GO TOP Browse() USE RETURN

Function Reference

1015

OrdKeyCount()

OrdKeyCount() Retrieves the total number of keys included in an index.

Syntax OrdKeyCount( [|][,] ) --> nKeyCount

Arguments

A numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

Return The function returns the number of keys included in the specified index. If no parameter is passed, the controlling index is used. If the specified index does not exist, a runtime error is generated.

Description The function counts the index keys present in the specified index. For this, it recognizes a possible FOR condition and/or scope set with OrdScope(). If no FOR condition and no scope is defined for the index, the return value of OrdKeyCount() is identical with LastRec(), which returns the physical number of records in a work area. Scopes and FOR conditions restrict the logical visibility of records, so that OrdKeyCount() represents the number of records that can be navigated to using SKIP. This information is especially required for programming scroll bars in browse views.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), DbGoto(), DbSkip(), LastRec(), OrdKeyGoto(), OrdKeyNo(), OrdScope() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example compares return values of LastRec() and OrdKeyCount() // when the logical visibility of records is unrestricted vs. restricted // with OrdScope().

1016

Function Reference

OrdKeyCount() #include "Ord.ch" PROCEDURE Main USE Customer INDEX ON Upper(LastName+Firstname) ? LastRec() ? OrdKeyCount()

TAG Name TO Cust01

// result: 225 // result: 225

OrdScope( TOPSCOPE , "E" ) OrdScope( BOTTOMSCOPE, "G" ) ? LastRec() ? OrdKeyCount()

// result: 225 // result: 13

USE RETURN

Function Reference

1017

OrdKeyDel()

OrdKeyDel() Removes an index key from a custom built index.

Syntax OrdKeyDel( [|], ; [] , ; [] ) --> lSuccess

Arguments

A numeric value specifying the ordinal position of the custom index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the open custom index can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the custom index. It is only required when multiple index files are open that contain indexes having the same .

This is the index value to be added to the index for the current record. It must be of the same data type as the value returned by the index expression. If omitted, is obtained by evaluating the index expression with the data of the current record.

Return The function returns .T. (true) if the current record is successfully removed from the index, otherwise .F. (false) is returned.

Description OrdKeyDel() is used in conjunction with OrdKeyAdd() to maintain a custom built index programmatically. Custom built indexes are not automatically updated by the RDD but are initially empty. OrdKeyDel() removes the current record from a custom index, if it is included in the specified index. If no parameters are passed, OrdKeyDel() evaluates the index expresssion with the data of the current record to obtain . The record is removed from the index when it is found. OrdKeyDel() fails if the record pointer is positioned on Eof(), if the specified index is not a custom index, if the specified index does not exist, or if the current record is not included in the custom index.

1018

Function Reference

OrdKeyDel()

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), DbGoto(), INDEX, OrdKey(), OrdKeyAdd(), OrdKeyVal() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates a regular and a custom index holding five // index keys. The last index key is removed from the custom index. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" INDEX ON Upper(LastName) TAG NAME TO Cust01 INDEX ON Upper(LastName) TAG NAMESET TO Cust01 CUSTOM OrdSetFocus( "NAME" ) GO BOTTOM ? OrdKeyVal()

// result: WATERS

GO TOP FOR i:=1 TO 5 OrdKeyAdd( "NAMESET" ) SKIP NEXT OrdSetFocus( "NAMESET" ) GO BOTTOM ? OrdKeyVal()

// result: CHAUCER

? OrdKeyDel( "NAMESET" ) ? OrdKeyVal()

// result: NIL

USE RETURN

Function Reference

1019

OrdKeyGoTo()

OrdKeyGoTo() Moves the record pointer to a logical record number.

Syntax OrdKeyGoTo( ) --> lSuccess

Arguments

This is a numeric value specifying the logical record number to move the record pointer to. Logical record numbers are in the range of 1 to OrdKeyCount() and depend on the controlling index.

Return The function returns .T. (true) if the record pointer is successfully positioned on the specified logical record number, otherwise .F. (false) is returned.

Description The function OrdKeyGoTo() moves the record pointer based on its logical record number, which can be retrieved using function OrdKeyNo(). The logical record number represents the position of a record in the controlling index, while the physical record number Recno() represents a record's position in the database. Physical record movement is accomplished using function DbGoTo().

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), DbGoto(), LastRec(), OrdFindRec(), OrdKeyNo(), OrdKeyRelPos(), OrdKeyCount(), RecNo() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example outlines the difference between physical and logical // record pointer movement. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" INDEX ON Upper(LastName) TAG NAME TO Cust01

1020

DbGoto( 1 ) ? Lastname, Recno(), OrdKeyNo()

// Physical first record // result: Miller 1 15

DbGoto( LastRec() ) ? Lastname, Recno(), OrdKeyNo()

// Physical last record // result: Smith 22 19

OrdKeyGoto( 1 ) ? Lastname, Recno(), OrdKeyNo()

// Logical first record // result: Alberts 20

1

Function Reference

OrdKeyGoTo() OrdKeyGoto( OrdKeyCount() ) ? Lastname, Recno(), OrdKeyNo()

// Logical last record // result: Waters 15

22

USE RETURN

Function Reference

1021

OrdKeyNo()

OrdKeyNo() Returns the logical record number of the current record.

Syntax OrdKeyNo( [|], [] ) --> nOrdKeyNo

Arguments

This is a character string holding the symbolic name of the index to query. It is analogous to the alias name of a work area. Support for depends on the RDD used to create the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

Optionally, a numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

Return The function returns the logical record number of the current record as a numeric value. Logical record numbers are in the range of 1 to OrdKeyCount() and depend on the controlling index. If the current record is not included in the index, the return value is zero.

Description OrdKeyNo() is used to determine the logical record number of the current record. The logical record number represents the position of a record in the controlling index, while the physical record number Recno() represents a record's position in the database. Physical record movement is accomplished using function DbGoTo(), while logical record pointer movement is done with OrdKeyGoTo().

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), INDEX, OrdKey(), OrdKeyCount(), OrdKeyGoTo(), OrdKeyRelPos(), OrdListAdd(), OrdNumber(), OrdScope(), Recno() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example outlines the difference between physical and logical // record numbers in an indexed database without and with scope. #include "Ord.ch"

1022

Function Reference

OrdKeyNo() PROCEDURE Main USE Customer INDEX ON Upper(LastName+Firstname)

TAG Name TO Cust01

? LastRec() ? OrdKeyCount()

// result: 225 // result: 225

GO TOP ? Recno() ? OrdKeyNo()

// result: // result:

GO BOTTOM ? Recno() ? OrdKeyNo()

// result: 123 // result: 225

15 1

OrdScope( TOPSCOPE , "E" ) OrdScope( BOTTOMSCOPE, "G" ) ? LastRec() ? OrdKeyCount()

// result: 225 // result: 13

GO TOP ? Recno() ? OrdKeyNo()

// result: // result:

GO BOTTOM ? Recno() ? OrdKeyNo()

// result: 207 // result: 13

87 1

USE RETURN

Function Reference

1023

OrdKeyRelPos()

OrdKeyRelPos() Returns or sets the relative position of the current record.

Syntax OrdKeyRelPos( [] ) --> nRelativePosition

Arguments

Optionally, a numeric value between 0 and 1 can be passed. It specifies the relative position to move the record pointer to.

Return The function returns a value between 0.0 and 1.0 (inclusive), which is the relative position of the current record.

Description The function is used to obtain the relative position of the record pointer, or to move it to a relative position. The relative position is specified as a value between 0 and 1. The return value multiplied with 100 is the relative position of the record pointer in percent of all records. It can be used to visualize the record pointer position with a scroll bar. OrdKeyRelPos() can be used with both, indexed and non-index databases. If a controlling index is active, the function returns the relative position of the current record within the controlling index. If a scope is set for the controlling index using OrdScope(), the number of visible records is taken into account. Filter conditions that limit the logical visibility of records are ignored. Note that the relative psoition returned by OrdKeyRelPos() is only an estimate whose accuracy grows with the number of records.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), OrdKeyCount(), OrdKeyGoTo(), OrdScope(), Recno() Database functions, Index functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates the relative position of the first/last // physical/logical record in an indexed database. PROCEDURE Main USE Customer INDEX ON Upper(LastName) SET DECIMALS TO 4

1024

GO TOP ? Lastname, OrdKeyRelPos()

// Logical first record // result: Alberts 0.0227

DbGoto( 1 )

// Physical first record

Function Reference

OrdKeyRelPos() ? Lastname, OrdKeyRelPos()

// result: Miller

0.6591

GO BOTTOM ? Lastname, OrdKeyRelPos()

// Logical last record // result: Waters 0.9773

DbGoto( LastRec() ) ? Lastname, OrdKeyRelPos()

// Physical last record // result: Smith 0.8864

RETURN

Function Reference

1025

OrdKeyVal()

OrdKeyVal() Retrieves the index value of the current record from the controlling index.

Syntax OrdKeyVal() --> xIndexValue

Return The function returns the index value of the current record. The retu rn value is NIL if the current record is not included in the controlling index or if there is no controlling index.

Description The function retrieves the index value for the current record from the index file holding the controlling index, not from the database file. This can be advantageous when an index expression is comprised of multiple fields. Their values can be assigned to a memory variable with one function call, rather than accessing multiple field variables individually.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), INDEX, IndexKey(), OrdCreate(), OrdFor(), OrdKey(), OrdKeyNo(), OrdName(), OrdNumber() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example uses the index value to display Lastname and Firstname // instead of field variables. PROCEDURE Main LOCAL cName USE Customer INDEX ON Upper( LastName + FirstName ) TO Cust01 ? FieldPos( "FirstName" ) ? FieldPos( "MiddleName" ) ? FieldPos( "LastName" )

// result: 2 // result: 3 // result: 4

? FieldLen( 2 ) ? FieldLen( 4 )

// result: 20 // result: 20

cName := OrdKeyVal() ? Trim( Right(cName, 20)), Trim( Left(cName,20) ) USE RETURN

1026

Function Reference

OrdListAdd()

OrdListAdd() Opens and optionally activates a new index in a work area.

Syntax OrdListAdd( ) --> NIL

Arguments

is a character string with the name of the file containing the index(es) to add to the list of open indexes in a work area. The file name can be specified including path information and extension. When the file extension is omitted, it is determined by the database driver that opened the database file in the work area.

Return The function always returns NIL.

Description OrdListAdd() opens an index file in a used work area and adds all contained indexes to the list of open indexes. If is the first index file opened in the work area, the first index stored in the file becomes the controlling index and the record pointer is moved to the first logical record. If there is a controlling index already active when OrdListAdd() is called, both, record pointer and controlling index, remain unchanged.

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), DbCreateIndex(), DbReindex(), DbSetOrder(), OrdCreate(), OrdListClear(), OrdListRebuild(), SET INDEX Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows the effect of OrdListAdd() when an index is opened // a first index in a work area vs. the situation when an additional index // is opened. PROCEDURE Main USE Customer INDEX ON Upper( LastName ) TO Cust01 INDEX ON Upper( FirstName ) TO Cust02 // reopening the database closes all indexes USE Customer ? Recno(), LastName // result: 1

Miller

OrdListAdd( "Cust01" ) ? Recno(), LastName

// result: 20

Alberts

OrdListAdd( "Cust02" ) ? Recno(), LastName

// result: 20

Alberts

Function Reference

1027

OrdListAdd() USE RETURN

1028

Function Reference

OrdListClear()

OrdListClear() Closes all indexes open in a work area.

Syntax OrdListClear() --> NIL

Return The function always returns NIL.

Description OrdListClear() closes all indexes open in a work area. When indexes are closed, database records can only be navigated in their physical order, since a logical order is no longer present.

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), OrdListAdd(), OrdListRebuild() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indexes and demonstrates the effect of // closing the indexes with OrdListClear() PROCEDURE Main USE Customer INDEX ON Upper( FirstName ) TO Cust01 INDEX ON Upper( LastName ) TO Cust02 USE Customer ? Recno(), LastName, Firstname

// result:

1

Miller

Irene

// result: // result:

1 9

Feldman

Allen

? OrdCount() ? Recno(), LastName, Firstname

// result: 2 // result: 20

Alberts

Cathy

OrdListClear() ? OrdCount() ? Recno(), LastName, Firstname

// result: 0 // result: 20

Alberts

Cathy

OrdListAdd( "Cust01" ) ? OrdCount() ? Recno(), LastName, Firstname OrdListAdd( "Cust02" ) OrdSetFocus( "Cust02" ) DbGoTop()

USE RETURN

Function Reference

1029

OrdListRebuild()

OrdListRebuild() Rebuilds all indexes open in the current work area

Syntax OrdListRebuild() --> NIL

Return The function always returns NIL.

Description OrdListRebuild() is used to reorganize all indexes open in the current work area. Use function OrdCreate() to reorganize a single index.

Info See also: Category: Source: LIB: DLL:

DbClearIndex(), DbCreateIndex(), DbSetIndex(), DbSetOrder(), INDEX, OrdCreate(), OrdListAdd(), OrdListClear(), REINDEX Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example opens a database along with two index files. All indexes // stored in the index files are rebuild. PROCEDURE Main USE Customer SET INDEX TO Cust01, Cust02 OrdListRebuild() USE RETURN

1030

Function Reference

OrdName()

OrdName() Returns the symbolic name of an open index by its ordinal position.

Syntax OrdName( [] [,] ) --> cIndexName

Arguments

A numeric value specifying the ordinal position of the index open in a work area. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index. The default value is 0.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same name.

Return The function returns the index name at position in the list of open indexes as a character string. If no parameters are passed, the index name of the controlling index is returned. If no index is open, the return value is an empty string ("").

Description OrdName() returns the symbolic name of an index as a character string. The name is specified with the TAG option of the INDEX command when the index is created. The reverse function of OrdName() is OrdNumber() which returns the ordinal position of an open index by its symbolic name.

Info See also: Category: Source: LIB: DLL:

Alias(), INDEX, OrdFor(), OrdKey(), OrdNumber() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indexes in one index file and displays. // various information about the open indexes. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" INDEX ON Upper(LastName+FirstName) TAG NAME INDEX ON CustID TAG ID

TO Cust01 TO Cust01

? OrdName() ? OrdKey()

// result: ID // result: CustID

? OrdSetfocus( "NAME" )

// result: ID

Function Reference

1031

OrdName() ? OrdName() ? OrdKey() ? OrdName(1) ? OrdName(2) USE RETURN

1032

// result: NAME // result: Upper(LastName+FirstName) // result: NAME // result: ID

Function Reference

OrdNumber()

OrdNumber() Returns the ordinal position of an open index by its symbolic name.

Syntax OrdNumber( [][, ] ) --> nOrder

Arguments

This is a character string holding the symbolic name of the index whose ordinal position is searched. It is analogous to the alias name of a work area. Support for depends on the RDD used to create the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same symbolic name.

Return The function returns a numeric value specifying the ordinal position of the index . Indexes are numbered in the sequence of opening, beginning with 1. If no parameter is passed, the ordinal position of the controlling index is returned. If no index is open, or if the name does not exist, the return value is zero.

Description OrdNumber() returns the ordinal position of an index based on its symbolic name. The name is specified with the TAG option of the INDEX command when the index is created. The reverse function of OrdNumber() is OrdName() which returns the symbolic name of an open index by its ordinal position.

Info See also: Category: Source: LIB: DLL:

Alias(), INDEX, OrdFor(), OrdKey(), OrdName() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indexes in one index file and displays. // various information about the indexes. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" ? OrdNumber()

// result: 0

INDEX ON Upper(LastName+FirstName) TAG NAME INDEX ON CustID TAG ID

Function Reference

TO Cust01 TO Cust01

1033

OrdNumber() ? OrdNumber() ? OrdKey()

// result: 2 // result: CustID

? OrdNumber( "NAME" ) ? OrdKey( "NAME" )

// result: 1 // result: Upper(LastName+FirstName)

USE RETURN

1034

Function Reference

OrdScope()

OrdScope() Defines the top and/or bottom scope for navigating in the controlling index.

Syntax OrdScope( , [] ) --> xOldValue

Arguments

The parameter is a numeric value identifying the top or bottom scope to set or clear. #define constants are available in Ord.ch that can be used for .

#define constants for Constant

Value

Description

TOPSCOPE BOTTOMSCOPE

0 1

Specifies the top scope Specifies the bottom scope



The parameter is specifies the value to be used as top or bottom boundary for the scope of the controlling index. The value must be of the same data type as the the value of the index expression, or it can be a code block that returns a value of this data type. If is omitted or the value NIL is passed explicitely for , a previously defined top or bottom scope is cleared.

Return The function returns the value for the top or bottom scope that is defined before the function is called.

Description The OrdScope() function defines or clears the top and bottom scope for indexed database navigation. The top and bottom scope values define the range of values valid for navigating the record pointer within the controlling index. Top and bottom scope value are inclusive, i.e. they are part of the resulting subset of records. They can be defined as constant values or as code blocks. When code blocks are used for top and/or bottom scope, they must return a value having the data type of the index expression. The scope code blocks are evaluated during database navigation, so that scope boundaries can change dynamically while the record pointer is moved. When a scope is set, the GO TOP command is equivalent to DbSeek( ), while GO BOTTOM is the same as DbSeek( , .F., .T. ). Attempting to move the record pointer before the top scope value does not change the record pointer but causes function BoF() to return .T. (true). When the record pointer is moved beyond the bottom scope value, it is advanced to the ghost record (Lastrec()+1) and function EoF() returns .T. (true). Note: The current scope settings can be queried without altering them using function DbOrderInfo(). Function Reference

1035

OrdScope()

Info See also: Category: Header: Source: LIB: DLL:

DbOrderInfo(), OrdCondSet(), OrdKey(), SET RELATION, SET SCOPE Database functions, Index functions Ord.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates evaluation of scope code blocks while a // database is browsed. Although the code blocks return constant values, // they could return the result of a function call as well. #include "Ord.ch" PROCEDURE Main USE Customer INDEX ON Upper(LastName+Firstname) TO Cust01 OrdScope( TOPSCOPE

, {|| Tone(1000), "E" } )

OrdScope( BOTTOMSCOPE, {|| Tone(500), "K" } ) Browse() RETURN

1036

Function Reference

OrdSetFocus()

OrdSetFocus() Sets focus to the controlling index in a work area

Syntax OrdSetFocus( [|], ; [] ) --> cOldIndexName

Arguments

A numeric value specifying the ordinal position of the index open in a work area to select as the controling index. Indexes are numbered in the sequence of opening, beginning with 1. The value zero identifies the controlling index.

Alternatively, a character string holding the symbolic name of the index to select can be passed. It is analogous to the alias name of a work area. Support for depends on the RDD used to open the index. Usually, RDDs that are able to maintain multiple indexes in one index file support symbolic index names, such as DBFCDX, for example.

is a character string with the name of the file that stores the index. It is only required when multiple index files are open that contain indexes having the same .

Return The function returns the symbolic name of the controlling index that is selected before the function is called. If no index is open, the return value is an empty string ("").

Description The OrdSetFocus() function selects an index open in a work area as the "controlling" index. Many indexes can be open in a work area, but only one index can have focus. This index determines the logical order how records stored in a database can be accessed and/or are visible in the current work area. If an open index is specified with or , this index is becomes the controlling index and the returnvalue is the name of the previous controlling index. Calling OrdSetFocus() without a parameter yields the current controlling index.

Function Reference

1037

OrdSetFocus()

Info See also: Category: Source: LIB: DLL:

Alias(), DbSetOrder(), INDEX, OrdFor(), OrdKey(), OrdName(), OrdNumber(), SET INDEX Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example creates two indees in one index file and displays // the result of OrdSetFocus(). The contents of the first logical // records resulting from both indexes illustrates the index change. REQUEST DbfCdx PROCEDURE Main USE Customer VIA "DbfCdx" INDEX ON Upper( LastName ) TAG Last TO Customer INDEX ON Upper( FirstName ) TAG First TO Customer ? OrdSetFocus()

// result: FIRST

DbGotop() ? Lastname, Firstname

// result: Feldman

? OrdSetFocus(1)

// result: FIRST

DbGotop() ? Lastname, Firstname

// result: Alberts

? OrdSetFocus( "First" )

// result: LAST

DbGotop() ? Lastname, Firstname

// result: Feldman

Allen

Cathy

Allen

USE RETURN

1038

Function Reference

OrdSetRelation()

OrdSetRelation() Defines a scoped relation between child work area and parent work area.

Syntax OrdSetRelation( | , ; , ; [] )

--> NIL

Arguments

The numeric ordinal position of the child work area to relate to the current work area.

Optionally, the child work area can be specified as a character string holding the symbolic alias name of the child work area.

A code block containing the relation expression.

The relation expression in form of a character string.

Return The function always returns NIL.

Description The function OrdSetRelation() creates a relation between the current work area (parent) and a secondary work area (Child) specified with or . The relation is scoped in the child work area, i.e. when the child area is selected as the current work area, only those records matching the expression can be navigated to. All other records are not visible. OrdSetRelation() is identical with DbSetRelation() when the fourth parameter of this function is set to .T. (true). Refer to DbSetRelation() for more information on creating links between parent and child work areas.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbSetRelation() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

1039

OrdSkipRaw()

OrdSkipRaw() Moves the record pointer via the controlling index.

Syntax OrdSkipRaw( [] ) --> NIL

Arguments

This is a numeric value indicating the number of records to move the record pointer within the controlling index. Positive values for move the record pointer forwards (towards the last logical record), negative values move it backwards. The default value is 1, i.e. calling OrdSkipRaw() with no parameter advances the record pointer to the next logical record.

Return The return value is always NIL.

Description OrdSkipRaw() moves the record pointer using information from the controlling index only, and ignores any filter condition set with SET DELETED or SET FILTER. All records included in the controlling index can be navigated to with OrdSkipRaw(). Use function DbSkip() when a filter condition should be recognized for record pointer movement.

Info See also: Category: Source: LIB: DLL:

DbSkip(), DbOrderInfo(), OrdKeyCount(), OrdKeyGoTo(), OrdScope(), Recno() Database functions, Index functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates movement of the record pointer using // DbSkip() versus OrdSkipRaw(). Note that Bof() returns .F. // with OrdSkipRaw() although the filter condition is not met. PROCEDURE Main USE Customer INDEX ON Upper(LastName) TO Cust01 ? Bof(), Lastname

// result:

.F.

Alberts

SET FILTER TO Lastname >= "K" GO TOP ? Bof(), Lastname

// result:

.F.

Keller

DbSkip( -1 ) ? Bof(), Lastname

// result:

.T.

Keller

OrdSkipRaw( -1 )

1040

Function Reference

OrdSkipRaw() ? Bof(), Lastname

// result:

.F.

Henreid

USE RETURN

Function Reference

1041

OrdSkipUnique()

OrdSkipUnique() Navigates to the next or previous record that has another index value.

Syntax OrdSkipUnique( [] ) --> lSuccess

Arguments

This parameter specifies the direction to move the record pointer. If is a negative numeric value, the record pointer is moved up (towards the begin of file). If is NIL, 0 or a positive numeric value, the record pointer is moved down (towards the end of file).

Return The function returns .T. (true) when the record pointer is moved to the next/previous record having a different index value.

Description OrdSkipUnique() navigates the record pointer in an indexed database as if the UNIQUE flag was set for the controlling index. If the controlling index is a regular index without the UNIQUE flag, it may contain identical index values for multiple records of the database. As a result, records that have duplicate index values can be navigated to with DbSkip(). If logical database navigation should ignore records having duplicate index values, function OrdSkipUnique() can be used. This function navigates the record pointer from the current record to the first/previous record whose index value differs from the current one. When OrdSkipUnique() is used for record pointer movement, the visibility of record s is the same as if an INDEX is created with the UNIQUE flag.

Info See also: Category: Source: LIB: DLL:

DbOrderInfo(), INDEX, OrdCreate(), OrdDescend(), OrdIsUnique() Database functions, Index functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // // // // //

The example creates a database and fills it with data from the string "cNames", thus creating duplicate index keys. The database is scanned from the first to the last record, but the next record is navigated to using OrdSkipUnique(). As a result, only four records of 14 show up in the result array. PROCEDURE Main LOCAL i, aResult LOCAL cNames := "AADDDDDCCCBBBB" LOCAL aStruct := { {"NAME", "C", 10, 0 } } // create database and index DbCreate( "TEST.DBF", aStruct )

1042

Function Reference

OrdSkipUnique() USE Test EXCLUSIVE INDEX ON Name TO Test // fill database using string data FOR i:=1 TO Len( cNames ) APPEND BLANK REPLACE FIELD->NAME WITH Replicate( cNames[i], 3 ) NEXT // collect result of OrdSkipUnique() navigation // in array "aResult" GO TOP aResult := Array(0) DO WHILE .NOT. Eof() AAdd( aResult, Trim( FIELD->NAME ) ) OrdSkipUnique() ENDDO // Length of input data ? Len( cNames ) ? LastRec()

// result: 14 // result: 14

// Length of output data ? Len( aResult )

// result: 4

AEVal( aResult, {|c| QOut(c) } ) // // // // //

output: AAA BBB CCC DDD

USE RETURN

Function Reference

1043

OrdWildSeek()

OrdWildSeek() Searches a value in the controlling index using wild card characters.

Syntax OrdWildSeek( , ; [] , ; [] ) --> lFound

Arguments

This is a character string to search in the controlling index. It may include the wild card characters "?" and "*". The question mark matches a single character, while the asterisk matches one or more characters.

This parameter defaults to .F. (false) causing OrdWildSeek() to begin the search with the first record included in the controlling index. When .T. (true) is passed, the function begins the search with the current record.

If .T. (true) is passed, OrdWildSeek() searches towards the begin of file. The default value is .F. (false), i.e. the function searches towards the end of file.

Return The function returns .T. (true) if a record matching is found in the controlling index, otherwise .F. (false) is returned.

Description OrdWildSeek() searches a character string that may include wild card characters in the controlling index. This allows for collecting subsets of records based on an approximate search string. Records matching the search string are found in the controlling index, and the record pointer is positioned on the found record. When a matching record is found, the function Found() returns .T. (true) until the record pointer is moved again. In addition, both functions, BoF() and EoF() return .F. (false). If the searched value is not found, OrdWildSeek() positions the record pointer on the "ghost record" (Lastrec()+1), and the function Found() returns .F. (false), while Eof() returns .T. (true). The SET SOFTSEEK setting is ignored by OrdWildSeek().

1044

Function Reference

OrdWildSeek()

Info See also: Category: Source: LIB: DLL:

DbSeek(), LOCATE, OrdFindRec(), OrdKeyGoto(), WildMatch() Database functions, Index functions, xHarbour extensions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example uses two wildcard search strings to show // possible search results of OrdWildSeek() PROCEDURE Main LOCAL aCust := {} USE Customer INDEX ON Upper(LastName) TO Cust01 DO WHILE OrdWildSeek( "*MAN?", .T. ) AAdd( aCust, FIELD->Lastname ) ENDDO AEval( aCust, {|c| QOut(c) } ) // Found records: // Dormann // Feldman GO TOP aCust := {} DO WHILE OrdWildSeek( "*EL*", .T. ) AAdd( aCust, FIELD->Lastname ) ENDDO AEval( aCust, {|c| QOut(c) } ) // Found records: // Feldman // Hellstrom // Keller // Reichel USE RETURN

Function Reference

1045

Os()

Os() Returns the name of the operating system.

Syntax OS() --> cOsName

Return The function returns a character string holding the operating system name.

Description Os() is an informational function used to query the name of the operating system an xHarbour application is running on.

Info See also: Category: Source: LIB: DLL:

1046

Getenv(), HB_BuildDate(), HB_BuildInfo(), Os_IsWinXP(), Version() Environment functions rtl\version.c xhb.lib xhbdll.dll

Function Reference

Os_IsWin2000()

Os_IsWin2000() Checks if the application is running on Windows 2000.

Syntax Os_IsWin2000() --> lIsWin2000

Return The function returns .T. (true) if the application runs on Windows 2000, otherwise .F. (false) is returned.

Description Os_IsWin2000() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1047

Os_IsWin2000_Or_Later()

Os_IsWin2000_Or_Later() Checks if the application is running on Windows version 2000 or later

Syntax Os_IsWin2000_Or_Later() --> lIsWin2000_Or_Later

Return The function returns .T. (true) if the application runs on Windows version 2000 or later, otherwis e .F. (false) is returned.

Description Os_IsWin2000_Or_Later() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

1048

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

Function Reference

Os_IsWin2003()

Os_IsWin2003() Checks if the application is running on Windows 2003.

Syntax Os_IsWin2003() --> lIsWin2003

Return The function returns .T. (true) if the application runs on Windows 2003, otherwise .F. (false) is returned.

Description Os_IsWin2003() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWinXP(), Os_IsWin2000(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1049

Os_IsWin95()

Os_IsWin95() Checks if the application is running on Windows 95.

Syntax Os_IsWin95() --> lIsWin95

Return The function returns .T. (true) if the application runs on Windows 95, otherwise .F. (false) is returned.

Description Os_IsWin95() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

1050

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

Function Reference

Os_IsWin98()

Os_IsWin98() Checks if the application is running on Windows 98.

Syntax Os_IsWin98() --> lIsWin98

Return The function returns .T. (true) if the application runs on Windows 98, otherwise .F. (false) is returned.

Description Os_IsWin98() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1051

Os_IsWin9X()

Os_IsWin9X() Checks if the application is running on a Windows 9x platform.

Syntax Os_IsWin9X() --> lIsWin9X

Return The function returns .T. (true) if the application runs on a Windows 9x platform, otherwise .F. (false) is returned. The 9x platform includes Windows 95, 98 and ME.

Description Os_IsWin9x() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows platform.

Info See also: Category: Source: LIB: DLL:

1052

Os(), Os_IsWinNT(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

Function Reference

Os_IsWinME()

Os_IsWinME() Checks if the application is running on Windows ME.

Syntax Os_IsWinME() --> lIsWinME

Return The function returns .T. (true) if the application runs on Windows ME, otherwise .F. (false) is returned.

Description Os_IsWinME() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1053

Os_IsWinNT()

Os_IsWinNT() Checks if the application is running on a Windows NT platform.

Syntax Os_IsWinNT() --> lIsWinNT

Return The function returns .T. (true) if the application runs on a Windows NT platform, otherwise .F. (false) is returned. The NT platform includes Windows NT, 2000, XP and 2003 Server.

Description Os_IsWin95() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows platform.

Info See also: Category: Source: LIB: DLL:

1054

Os(), Os_IsWin9x(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

Function Reference

Os_IsWinNT351()

Os_IsWinNT351() Checks if the application is running on Windows NT 3.51.

Syntax Os_IsWinNT351() --> lIsWinNT351

Return The function returns .T. (true) if the application runs on Windows NT 3.51, otherwise .F. (false) is returned.

Description Os_IsWinNT351() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1055

Os_IsWinNT4()

Os_IsWinNT4() Checks if the application is running on Windows NT 4.0.

Syntax Os_IsWinNT4() --> lIsWinNT40

Return The function returns .T. (true) if the application runs on Windows NT 4.0, otherwise .F. (false) is returned.

Description Os_IsWinNT4() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

1056

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWin2000(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

Function Reference

Os_IsWinVista()

Os_IsWinVista() Checks if the application is running on Windows Vista.

Syntax Os_IsWinVISTA() --> lIsWinVista

Return The function returns .T. (true) if the application runs on Windows Vista, otherwise .F. (false) is returned.

Description Os_IsWinVista() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWinXP(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1057

Os_IsWinXP()

Os_IsWinXP() Checks if the application is running on Windows XP.

Syntax Os_IsWinXP() --> lIsWinXP

Return The function returns .T. (true) if the application runs on Windows XP, otherwise .F. (false) is returned.

Description Os_IsWinXP() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

1058

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWin2000(), Os_IsWin2003(), Os_IsWtsClient(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

Function Reference

Os_IsWtsClient()

Os_IsWtsClient() Checks if the application is running on a Windows Terminal Server client.

Syntax Os_IsWtsClient() --> lIsWtsClient

Return The function returns .T. (true) if the application runs on a Windows Terminal Server client, otherwise .F. (false) is returned.

Description Os_IsWtsClient() belongs to a group of environment functions that test if an xHarbour application is running on a particular Windows operating system version.

Info See also: Category: Source: LIB: DLL:

Function Reference

Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWinXP(), Os_IsWin2000(), Os_IsWin2003(), Os_VersionInfo() Environment functions, xHarbour extensions rtl\winos.prg xhb.lib xhbdll.dll

1059

Os_VersionInfo()

Os_VersionInfo() Retrieves specific version information about the operating system.

Syntax Os_VersionInfo() --> aVersionInfo

Return The function returns a one-dimensional array with five elements holding version information data of the operating system. If the operating system does not provide version information, the return value is NIL.

Description The elements of the returned array contain the following data

Version information array Element

Description

1

Major version number 3 = Windows NT 3.51 4 = Windows 95, 98, ME or NT 4.0 5 = Windows 2000, XP, 2003 Server Minor version number 0 = Windows 95 10 = Windows 98 90 = Windows Me 51 = Windows NT 3.51 0 = Windows NT 4.0 0 = Windows 2000 1 = Windows XP 2 = Windows Server 2000 Build number of the operating system Platform identifier 0 = VER_PLATFORM_WIN32s 1 = VER_PLATFORM_WIN32_WINDOWS 2 = VER_PLATFORM_WIN32_NT Service Pack number or additional information about the OS

2

3 4

5

Info See also: Category: Source: LIB: DLL:

HB_BuildInfo(), Os(), Os_IsWinNT(), Os_IsWin9X(), Os_IsWin95(), Os_IsWin98(), Os_IsWinME(), Os_IsWinNT351(), Os_IsWinNT4(), Os_IsWinXP(), Os_IsWin2000(), Os_IsWin2003(), Os_IsWtsClient(), Version() Environment functions, xHarbour extensions rtl\winos.prg xhbdll.lib xhbdll.dll

Example // The example lists the version information of the operating system

1060

Function Reference

Os_VersionInfo() PROCEDURE Main AEval( OS_VersionInfo(), RETURN

Function Reference

{|x| QOut(x)} )

1061

OutErr()

OutErr() Writes values to the standard error device.

Syntax OutErr( ) --> NIL

Arguments

This is a comma separated list of expressions whose values are output.

Return The return value is always NIL.

Description OutErr() evaluates and writes the resulting values to the standard error device. This allows for collecting output in a file when program output is redirected on the command line to the error device (c:\xhb\program.exe 2> logfile.txt). OutErr() works identical as OutStd() except for using a different output channel.

Info See also: Category: Source: LIB: DLL:

DispOut(), OutStd() Output functions rtl\console.c xhb.lib xhbdll.dll

Example // The examlple illustrates how output sent to the standard devices // STDOUT and STDERR can be redirected into two different files. To // run the example, use this command line syntax: // // c:\xhb\Test.exe > regular.txt 2> error.txt PROCEDURE Main OutStd( "Regular log info", Date(), Time() ) OutErr( "Error log info", Date(), Time() ) RETURN

1062

Function Reference

OutStd()

OutStd() Writes values to the standard output device.

Syntax OutStd( ) --> NIL

Arguments

This is a comma separated list of expressions whose values are output.

Return The return value is always NIL.

Description OutStd() evaluates and writes the resulting values to the standard output device. This allows for collecting output in a file when program output is redirected on the command line to the error device (c:\xhb\program.exe > logfile.txt). Note: if an xHarbour console application does not require sophisticated screen output, the commands ? and ?? can be replaced with OutStd() by including the file SIMPLEIO.CH.

Info See also: Category: Source: LIB: DLL:

DispOut(), FWrite(), OutErr(), QOut() | QQOut() Output functions rtl\console.c xhb.lib xhbdll.dll

Example // The examlple illustrates how output sent to the standard devices // STDOUT and STDERR can be redirected into two different files. To // run the example, use this command line syntax: // // c:\xhb\Test.exe > regular.txt 2> error.txt PROCEDURE Main OutStd( "Regular log info", Date(), Time() ) OutErr( "Error log info", Date(), Time() ) RETURN

Function Reference

1063

PadC() | PadL() | PadR()

PadC() | PadL() | PadR() Pads values of data type Character, Date and Numeric with a fill character.

Syntax PadC( , , [] ) --> cPaddedString PadL( , , [] ) --> cPaddedString PadR( , , [] ) --> cPaddedString

Arguments

An expression yielding a Character, Date or Numeric value.

A numeric value indicating the length of the returned string.

A single character used to pad the value of with. It defaults to a space character (Chr(32)).

Return The function returns a character string of characters. It contains the value of padded with . If the value of contains more than characters, the value in the returned string is truncated to characters.

Description PadC(), PadL(), and PadR() are conversion functions that convert the value of an expression to a character string, padded with a fill character. The functions accept for values of data type Character, Date and Numeric. PadC() The fill character is added on the left and the right side, so that the value of appears centered in the result string. PadL() The fill character is added on the left side, so that the value of appears right justified in the result string. PadL() The fill character is added on the right side, so that the value of appears left justified in the result string. Note: function Pad() is a synonym for PadR().

1064

Function Reference

PadC() | PadL() | PadR()

Info See also: Category: Source: LIB: DLL:

Alltrim(), LTrim(), RTrim(), StrTran(), Stuff(), SubStr() Character functions, Conversion functions rtl/pad.c, rtl/padc.c, rtl/padl.c, rtl/padr.c xhb.lib xhbdll.dll

Example // The example shows the results of creating padded character strings PROCEDURE Main ? PadC( "xHarbour", 12, "_" ) ? PadL( "xHarbour", 12, "_" ) ? PadR( "xHarbour", 12, "_" ) ? "0x" + PadL( 2, 4, "0" ) RETURN

Function Reference

// result: __xHarbour__ // result: ____xHarbour // result: xHarbour____ // result: 0x0002

1065

PCol()

PCol() Returns the column position of the print head.

Syntax PCol() --> nColumn

Return The function returns a numeric value indicating the current column position of the print head.

Description PCol() reports the current column position of the print head when console output is directed to the printer after SET DEVICE TO PRINTER or SET PRINTER ON is issued. During printer output, PCol() maintains an internal counter which is initialized with zero. The counter is incremented by 1 for each character sent to the printer, and reset to zero when a form feed occurs with the EJECT command, or when a carriage return character (Chr(13)) is sent to the printer. The function increments the counter for all characters, including printer control characters, or escape sequences, that do not print. If a control character is sent to the printer, the current print head position must be saved using PCol() and PRow(), and restored with SetPrc(). Note that PCol() cannot be used with proportional fonts.

Info See also: Category: Source: LIB: DLL:

?|??, @...SAY, Col(), EJECT, IsPrinter(), PadC() | PadL() | PadR(), PRow(), QOut() | QQOut(), Row(), SET DEVICE, SET PRINTER, SetPrc() Environment functions rtl\console.c xhb.lib xhbdll.dll

Example // The example prints a telephone list from an address database. PROCEDURE Main LOCAL nPageSize := 60 LOCAL nCurPage := 0 LOCAL nCurLine := 99 USE Customer SET DEVICE TO PRINTER DO WHILE .NOT. EoF() IF nCurLine > nPageSize EJECT nCurLine := 1 nCurPage ++ @ nCurLine, 60 SAY "Page: " + LTrim(Str(nCurPage)) nCurLine += 2 ENDIF @ nCurLine, 0 SAY Trim(FIELD->LastName)+"," @ nCurLine, PCol() + 1 SAY Trim(FIELD->FirstName)

1066

Function Reference

PCol() @ nCurLine, 40

SAY FIELD->PHONE PICTURE "@R (999) 999-9999"

SKIP nCurLine++ ENDDO SET DEVICE TO SCREEN CLOSE Customer RETURN

Function Reference

1067

PCount()

PCount() Returns the number of passed parameters.

Syntax PCount() --> nParamCount

Return The function returns a numeric value indicating the number of parameters passed to a function, procedure or method.

Description PCount() reports the number of parameters passed to a called function, procedure or method. Note that if parameters are omitted in a call, they are initialized with NIL in the called routine. PCount() reports the last parameter passed to a called routine (see the example).

Info See also: Category: Source: LIB: DLL:

FUNCTION, HB_ArgC(), PValue(), PROCEDURE, Valtype() Debug functions, Environment functions vm\pcount.c xhb.lib xhbdll.dll

Example // The example shows the result of PCount() when a function is // called with different numbers of parameters. Omitted parameters // are implicitely passed as NIL values. PROCEDURE Main ? Test()

// result: 0

? Test( "A" ) ? Test( NIL )

// result: 1 // result: 1

? ? ? ? ?

Test( "A", "B" ) Test( "A", ) Test( "A", NIL ) Test( , "B" ) Test( , )

// // // // //

result: result: result: result: result:

2 2 2 2 2

? Test( "A", "B", "C" ) ? Test( "A", , "C" ) ? Test( , , "C" ) ? Test( , , NIL ) ? Test( , , ) RETURN

// // // // //

result: result: result: result: result:

3 3 3 3 3

FUNCTION Test RETURN PCount()

1068

Function Reference

PrinterExists()

PrinterExists() Checks if a particular printer is installed.

Syntax PrinterExists( ) --> lInstalled

Arguments

This is a character string holding the name of a printer to check.

Return The function returns .T. (true) if the specified printer is installed, otherwise .F. (false) is returned.

Description This function checks whether a particular printer is installed or not. The printer name is case sensitive and must be spelled in the exact same way as listed in the control panel.

Info See also: Category: Source: LIB: DLL:

GetPrinters(), GetDefaultPrinter(), IsPrinter(), PrinterPortToName() Printer functions, xHarbour extensions rtl\tprinter.c xhb.lib xhbdll.dll

Example // The example outlines case sensitivity of printer names. PROCEDURE Main() ? PrinterExists( "HP LaserJet 1200 Series PCL" ) // result: .T. ? PrinterExists( "HP LASERJET 1200 SERIES PCL" ) // result: .F. RETURN

Function Reference

1069

PrinterPortToName()

PrinterPortToName() Retrieves the name of the printer connected to a printer port.

Syntax PrinterPortToName( ) --> cPrinterName

Arguments

This is a character string holding the port name where a printer is connected to.

Return The function returns a character string holding the name of a printer, or an empty string ("") if the port name does not exist or no printer is connected to the specified port.

Description Function PrinterPortToName() retrieves the name of the printer which is connected to the port . The port name must be specified including the colon, like "LPT1:".

Info See also: Category: Source: LIB: DLL:

GetPrinters(), GetDefaultPrinter(), IsPrinter(), PrinterExists() Printer functions, xHarbour extensions rtl\tprinter.c xhb.lib xhbdll.dll

Example // The example queries the printer ports LPT1: to LPT5: and // lists the names of connected printers PROCEDURE Main() LOCAL aPrinters := {} LOCAL i, cPrinter, cPort FOR i:=1 TO cPort cPrinter IF .NOT. AAdd( ENDIF NEXT

5 := "LPT" + LTrim( Str(i) ) + ":" := PrinterPortToName( cPort ) Empty( cPrinter ) aPrinters, { cPort, cPrinter } )

IF Empty( aPrinters ) ? "No printer found" ELSE AEval( aPrinters, {|a| Qout( a[1], a[2] ) } ) ENDIF RETURN

1070

Function Reference

PrintFileRaw()

PrintFileRaw() Prints a file to a Windows printer in RAW mode.

Syntax PrintFileRaw( , ; , ; [] ) --> nErrorCode

Arguments

This is a character string holding the name of the printer to use for printing.

The file to print must be specified as a character string, including path and extension. If the path is omitted, the file is searched in the current directory.

This is an optional character string which appears as print job description in the spooler. It defaults to .

Return The function returns zero on success or a value less than zero on error. See the example for error codes.

Description Function PrintFileRaw() prints a file to a Windows printer in RAW mode. This restricts file types for printing to enhanced metafiles (EMF), ASCII text, and raw data, which includes all printer specific file types such as PostScript and PCL. The file is sent to the Windows spooler which processes the print job. The function returns zero when the file is successfully transferred to the spooler. Note that this is no guarantee for a printout. If the physical printer is out of paper, for example, the spooler reports an error to the user. This type of failure cannot be detected by PrintFileRaw().

Info See also: Category: Source: LIB: DLL:

GetPrinters(), GetDefaultPrinter(), PrinterExists(), PrinterPortToName() Printer functions, xHarbour extensions rtl\tprinter.c xhb.lib xhbdll.dll

Example // The example prints a file in RAW mode and demonstrates // the possible return values of PrintFileRaw(). PROCEDURE Main() LOCAL cPrinter LOCAL cFile LOCAL nResult LOCAL cMsg

Function Reference

:= := := :=

GetDefaultPrinter() "MyFile.Txt" -1 "PrintFileRaw(): "

1071

PrintFileRaw() CLS IF Empty( cPrinter ) ? "No default printer found" QUIT ENDIF nResult := PrintFileRaw( cPrinter, cFile, "Test for PrintFileRaw()" ) SWITCH nResult CASE -1 cMsg += "Invalid parameters passed to function" CASE -2 cMsg += "WinAPI OpenPrinter() call failed" CASE -3 cMsg += "WinAPI StartDocPrinter() call failed" CASE -4 cMsg += "WinAPI StartPagePrinter() call failed" CASE -5 cMsg += "WinAPI malloc() of memory failed" CASE -6 cMsg += "File " + cFile + " not found" DEFAULT cMsg += cFile + " PRINTED OK!!!" END

; EXIT ; EXIT ; EXIT ; EXIT ; EXIT ; EXIT

? cMsg RETURN

1072

Function Reference

ProcFile()

ProcFile() Determines the current PRG source code file.

Syntax ProcFile( [] ) --> cPrgFilename

Arguments

This is a numeric value >= 0 indicating the call stack position of the currently executed routine whose source code file should be returned. The default value is zero, which indicates the currently executed routine.

Return The function returns a character string holding the name of the PRG file in which the queried routine is implemented. If is larger than the number of entries in the call stack, or if the file name is not included as debug information in the linked executable file, an empty string is returned ("").

Description ProcFile() is a debug function used to determine the PRG file name in which a routine activated in the call stack is implemented. It is mainly used in conjunction with error handling routines that identify the location of runtime errors. See function ErrorBlock() for a discussion of error handling.

Info See also: Category: Source: LIB: DLL:

ErrorBlock(), ProcLine(), ProcName() Debug functions, xHarbour extensions vm\proc.c xhb.lib xhbdll.dll

Example // The example implements a user defined function that collects call stack // information in an array. FUNCTION GetCallStack() LOCAL aStack := {} LOCAL nStack := 1 // Skip the GetCallStack() function in the result DO WHILE .NOT. Empty( ProcName(nStack) ) AAdd( aStack, { ProcFile(nStack), ProcName(nStack), ProcLine(nStack) } nStack ++ ENDDO RETURN aStack

Function Reference

1073

ProcLine()

ProcLine() Determines the current line number executed in a PRG source code file.

Syntax ProcLine( [] ) --> nPrgLineNumber

Arguments

This is a numeric value >= 0 indicating the call stack position of the currently executed routine whose source code line number should be returned. The default value is zero, which indicates the currently executed routine.

Return The function returns a numeric value indicating the line number in the PRG source code file that is currently being executed. If is larger than the number of entries in the call stack, or if the executable is created with the /l compiler switch, the return value is zero.

Description ProcLine() is a debug function used to determine the line in the PRG source code file that is currently being executed. It is mainly used in conjunction with error handling routines that identify the location of runtime errors. See function ErrorBlock() for a discussion of error handling.

Info See also: Category: Source: LIB: DLL:

ErrorBlock(), ProcFile(), ProcName() Debug functions vm\proc.c xhb.lib xhbdll.dll

Example // The example implements a user defined function that collects call stack // information in an array. FUNCTION GetCallStack() LOCAL aStack := {} LOCAL nStack := 1 // Skip the GetCallStack() function in the result DO WHILE .NOT. Empty( ProcName(nStack) ) AAdd( aStack, { ProcFile(nStack), ProcName(nStack), ProcLine(nStack) } nStack ++ ENDDO RETURN aStack

1074

Function Reference

ProcName()

ProcName() Determines the symbolic name of the currently executed function, method or procedure.

Syntax ProcName( [] ) --> nProcName

Arguments

This is a numeric value >= 0 indicating the call stack position of the currently executed routine whose symbolic name should be returned. The default value is zero, which indicates the currently executed routine.

Return The function returns a character string holding the name of the routine that is currently being executed. If is larger than the number of entries in the call stack, or if the symbolic name is not included as debug information in the linked executable file, an empty string is returned ("").

Description ProcName() is a debug function used to determine the symbolic name of the routine currently being executed. It is mainly used in conjunction with error handling routines that identify the location of runtime errors. See function ErrorBlock() for a discussion of error handling.

Info See also: Category: Source: LIB: DLL:

ErrorBlock(), ProcFile(), ProcLine() Debug functions vm\proc.c xhb.lib xhbdll.dll

Example // The example implements a user defined function that collects call stack // information in an array. FUNCTION GetCallStack() LOCAL aStack := {} LOCAL nStack := 1 // Skip the GetCallStack() function in the result DO WHILE .NOT. Empty( ProcName(nStack) ) AAdd( aStack, { ProcFile(nStack), ProcName(nStack), ProcLine(nStack) } nStack ++ ENDDO RETURN aStack

Function Reference

1075

PRow()

PRow() Returns the row position of the print head.

Syntax PRow() --> nRow

Return The function returns a numeric value indicating the current row position of the print head.

Description PRow() reports the current row position of the print head when console output is directed to the printer after SET DEVICE TO PRINTER or SET PRINTER ON is issued. During printer output, PRow() maintains an internal counter which is initialized with zero. The counter is incremented by 1 when output begins in a new line, and reset to zero with the EJECT command. The function does not increment the counter for printer control characters that advance the print head to a new line, like line feed (Chr(10)) or form feed (Chr(12)). If such a control character is sent to the printer, the current print head position must be programmatically adjusted with the SetPrc() function.

Info See also: Category: Source: LIB: DLL:

?|??, @...SAY, Col(), EJECT, IsPrinter(), PadC() | PadL() | PadR(), PCol(), QOut() | QQOut(), Row(), SET DEVICE, SET PRINTER, SetPrc() Environment functions rtl\console.c xhb.lib xhbdll.dll

Example // This example prints address labels using PRow() and SetPrc() PROCEDURE Main USE Customer INDEX ON Upper(Lastname) TO Cust01 SET DEVICE TO PRINTER SetPrc( 2, 0 ) DO WHILE .NOT. Eof() @ PRow()+1 , 0 @ PRow() , PCol()+1 @ PRow()+1 , 0 @ PRow()+1 , 0 @ PRow()+1 , 0 @ PRow() , PCol()+1 @ PRow()+1 , 0

SAY SAY SAY SAY SAY SAY SAY

Trim( FIELD->Firstname ) Trim( FIELD->Lastname ) Trim( FIELD->Street ) Trim( FIELD->City ) Trim( FIELD->State ) FIELD->Zip ""

SKIP SetPrc( 2, 0 ) ENDDO SET DEVICE TO SCREEN

1076

Function Reference

PRow() CLOSE ALL RETURN

Function Reference

1077

PValue()

PValue() Retrieves the value of a parameter passed to a function, method or procedure.

Syntax PValue( ) --> xParamValue

Arguments

This is a numeric value indicating the ordinal position of the parameter to check.

Return The function returns the value of the parameter at position passed to a function, method or procedure. If is larger than PCount(), the return value is NIL.

Description PValue() is useful to retrieve the value of a parameter when a function, method or procedure is called with more arguments than are declared in the formal argument list.

Info See also: Category: Source: LIB: DLL:

PCount(), HB_AParams(), HB_ArgV(), Valtype() Debug functions, Environment functions, xHarbour extensions vm\pvalue.c xhb.lib xhbdll.dll

Example // The example declares a function with an unknown number // of parameters. The value of each parameter is retrieved // with PValue(). PROCEDURE Main ? Average( 10, 20 ) ? Average( 1,2,3,4,5,6,7,8,9,10 )

// result: 15.00 // result: 5.50

RETURN

FUNCTION Average( ... ) LOCAL nSum := 0, i, imax imax := PCount()

// number of passed arguments

FOR i:=1 TO imax nSum += PValue( i ) NEXT

// sum data

RETURN ( nSum / imax )

1078

Function Reference

QOut() | QQOut()

QOut() | QQOut() Displays values of expressions to the console window.

Syntax QOut( [] ) --> NIL QQOut( []) --> NIL

Arguments

is an optional, comma separated list of expressions whose values are output. When no expression is specified, the QOut() function outputs a new line while QQOut() outputs nothing.

Return The return value is always NIL.

Description QOut() and QQOut() are text mode functions that display the result of a comma separated list of expressions to the currently selected console output device. This can be the screen, or console window, or the printer. The difference between QOut() and QQOut() is that QOut() first outputs a carriage-return/line-feed pair so that the output of always begins at a new line, while QQOut() outputs the values of at the current cursor or printhead position. The QOut() or QQOut() function first locates the current cursor or printhead position and shifts it one to the right. Row() and Col() are updated with the new cursor position if SET PRINTER is OFF, otherwise they are updated with the new printhead position. Should the output of QOut() or QQOut() reach the right border of the screen (defined by MaxCol()), it will wrap to the next line. Should the output of QOut() or QQOut() reach the bottom border of the screen (defined by MaxRow()), the screen will scroll up one line. It is possible to output the expression(s) to the printer by using SET PRINTER ON before calling QOut() or QQOut(). It is also possible to output to a text file using the SET ALTERNATE TO command, followed by the SET ALTERNATE ON command. The SET CONSOLE OFF command will prevent display on the screen without interrupting the output to the printer or text file. When the expression(s) need formatting, use the Transform() function or any user-defined function. For padding, use any of the Pad() functions to center, left align or right align the expression(s).

Function Reference

1079

QOut() | QQOut()

Info See also: Category: Source: LIB: DLL:

?|??, @...SAY, PadC() | PadL() | PadR(), SET ALTERNATE, SET CONSOLE, SET PRINTER, TEXT, Transform() Output functions rtl\console.c xhb.lib xhbdll.dll

Example // This example displays a list of expressions: PROCEDURE Main LOCAL var1 := 1, var2 := Date(), var3 := .T. QOut( "This line will be displayed on the console." ) QOut( "This line will be displayed beneath the previous line." ) QQOut( "No carriage return / linefeed for this expression!" ) QOut( var1, var2, var3, "These were variables" ) RETURN

1080

Function Reference

QueryRegistry()

QueryRegistry() Checks if a particular registry key with specified value exists.

Syntax QueryRegistry( , , , , []

; ; ; ; ) --> lExists

Arguments

This numeric parameter specifies the root entry in the Windows registry to search for a registry key. #define constants are available in the Winreg.ch file that can be used for . They begin the the prefix HKEY_.

This is a character string holding the search path in the registry to locate . The path must include a backslash as delimiter, if required, but may neither begin or end with a backslash.

This is a character string holding the name of the registry key to check and/or assign a value to. must be located underneath .

This is a value of data type Character, Date, Logical or Numeric to compare with the value of .

This parameter defaults to .F. (false), so that is only searched and its value compared with . When is .T. (true) a non existent key is created, and the value is assigned to the registry key.

Return The function returns .T. (true), when the specified registry key exists and has the value . Otherwise .F. (false) is returned.

Description Function QueryRegistry() checks if a registry key of a particular value exists in the registry and/or creates this key/value pair. By default, the function searches the key/value pair beginning with the root , following the search path . If the key/value pair exists, the return value is .T. (true). When it does not, the return value is .F. (false), unless the optional parameter isset to .T. (true). In this case, a non existent key is created. The value is assigned to an existing key.

Function Reference

1081

QueryRegistry()

Winreg.ch Winreg.ch adds quite some overhead to an application program by adding structure definitions. If this is not required, Winreg.ch does not need to be #included. QueryRegistry() recognizes the following values for in addition to the HKEY_* #define constants:

Registry keys Registry Key

Equivalent value

HKEY_LOCAL_MACHINE HKEY_CLASSES_ROOT HKEY_CURRENT_USER HKEY_CURRENT_CONFIG HKEY_LOCAL_MACHINE HKEY_USERS

0 1 2 3 4 5

Note: on Windows NT, 2000, XP or later, the user may need certain security rights in order to be able to read and/or change the registry.

Info See also: Category: Header: Source: LIB: DLL:

SetRegistry(), GetRegistry() Registry functions, xHarbour extensions Winreg.ch rtl\winreg.prg xhb.lib xhbdll.dll

Example // The example queries the registry for entries as they exist // after the installation of xHarbour builder of October 2006. // One registry entry does not exist and is created. * #include "Winreg.ch" #define HKEY_CURRENT_USER

// not needed for this example 0

// use alternative #define constant

PROCEDURE Main LOCAL nHKey := 0 LOCAL cRegPath := "SOFTWARE\xHarbour.com\xHarbour Builder" ? QueryRegistry( nHKey, cRegPath, "Edition", "Enterprise" ) // result: .T. ? QueryRegistry( nHKey, cRegPath, "rootdir", "C:\xhb" ) // result: .T. // Query non existent registry key ... IF .NOT. QueryRegistry( nHKey, cRegPath, ; "xhb build last", "October 2006" ) // ... and create it QueryRegistry( nHKey, cRegPath, ; "xhb build last", "October 2006", .T. ) ENDIF ? GetRegistry( nHKey, cRegPath, "xhb build last" )

1082

Function Reference

QueryRegistry() // result: October 2006 RETURN

Function Reference

1083

RAscan()

RAscan() Searches a value in an array beginning with the last element.

Syntax RAscan( , , [] , [] , [] , []

; ; ; ; ; ) --> nElement

Arguments

This is the array to iterate.

is either the value to search in or a code block containing the search condition. The code block receives a single parameter which is the value stored in the current array element. The code block must return a logical value. When the return value is .T. (true), the function stops searching and returns the position of the corresponding array element.

This is a numeric expression indicating the first element in the array to begin the search with. It defaults to Len(), the last element of the array.

A numeric expression specifying the number of elements to search. It defaults to 1+Len()-.

This parameter influences the comparison for searching character strings in . If .T. (true) is passed, an exact string comparison is performed. When omitted or if .F. (false) is passed, string comparison follows the SET EXACT rules.

This parameter is only relevant for arrays that contain single characters in their elements. A single character is treated like a numeric ASCII value when is .T. (true). The default is.F. (false).

Return RAScan() returns the numeric ordinal position of the array element that contains the searched value. When no match is found, the return value is 0.

Description The array function RAscan() traverses the array for the value specified with . If is not a code block, RAscan() compares the values of each array element for being equal with the searched value. If this comparison yields .T. (true), the function stops searching and returns the numeric position of the array element containing the searched value. 1084

Function Reference

RAscan()

If a code block is passed for , it is evaluated and receives as parameter the value of the current array element. The code block must contain a comparison rule that yields a logical value. AScan() considers the value as being found when the codeblock returns .T. (true). Otherwise the function proceeds with the next array element. Note: use function AScan() to search an array beginning with the first element.

Info See also: Category: Source: LIB: DLL:

AEval(), Asc(), Ascan(), ASort(), ATail(), Eval(), IN, SET EXACT Array functions, xHarbour extensions vm\arrayshb.c xhb.lib xhbdll.dll

Example // The example demonstrates the difference between AScan() and RAscan(). PROCEDURE Main() LOCAL aArray := { "A", 1, Date(), 1, .F. } ? Ascan( aArray, 1 ) ? RAScan( aArray, 1 )

// result: 2 // result: 4

RETURN

Function Reference

1085

RAt()

RAt() Locates the position of a substring within a character string.

Syntax RAt( , , [], [] ) --> nPos

Arguments

is the substring to search for.

is the searched character string.

A numeric expression indicating the position of the first character in to begin the search with. It defaults to Len().

A numeric expression indicating the position of the last character in to include in the search. It defaults to 1.

Return The function returns a numeric value which is the position in where is found. The return value is zero when is not found.

Description This function RAt() searches the string from right to left for the character string . The search begins at position and is case-sensitive. If does not contain , the function returns 0. Note: use function At() to search from left to right.

Info See also: Category: Source: LIB: DLL:

$, At(), IN, Left(), Right(), StrTran(), SubStr() Character functions rtl\rat.c xhb.lib xhbdll.dll

Example // The example demonstrates various results of RAt(). PROCEDURE Main() LOCAL cString := "xHarbour"

1086

? RAt( "Ha", cString )

// result: 2

? RAt( "ARB" , cString )

// result: 0

Function Reference

RAt() ? RAt( "ARB" , Upper(cString) )

// result: 3

? RAt( "r" , cString )

// result: 8

? RAt( "r" , cString, 7 )

// result: 4

? RAt( "r" , cString, 5, 7 ) RETURN

// result: 0

Function Reference

1087

RddInfo()

RddInfo() Queries and/or changes configuration data of RDDs.

Syntax RddInfo( , [], [] ) --> xOldSetting

Arguments

This is a numeric parameter for which #define constants exist in the file DbInfo.ch. They identify the numerous settings that can be queried or changed for replacable database drivers (RDD9 and begin with the prefix RDDI_ (see below).

is an optional argument specifying a new value for the RDD setting identified by . The data type for depends on the RDD setting to change (see below). If the RDD setting is READONLY, the parameter is ignored.

is an optional character string with the name of the RDD to query or configure. It defaults to the return value of RddSetDefault().

Return The function returns the value of the specified RDD setting which is set before the function is called.

Description RddInfo() is a universal function managing numerous RDD settings available in xHarbour. If an RDD does not support a setting, it may create a runtime error or simply ignore the function call upon its own discretion. In the latter case, the return value of RddInfo() is NIL. The constants that can be used for are listed below: RDDI_BLOB_SUPPORT

--> lIsBlobSupported (READONLY) The return value is .T. (true) when the RDD supports binary large objects (BLOBs), otherwise .F. (false) is returned. BLOBs are supported by the DBFBLOB RDD. Refer to function BlobDirectImport() for an example of BLOB usage.

RDDI_CANPUTREC

--> lCanWriteData (READONLY) See also: function RddList(). The return value is .T. (true) when data can be written record-wise instead of field-wise to the file maintained by the RDD, otherwise .F. (false) is returned. Recordwise data storage is an internal optimization of an RDD.

RDDI_ISDBF

--> lIsDbfSupported (READONLY) The return value is .T. (true) when the RDD supports databases in DBF file format, otherwise .F. (false) is returned.

RDDI_LOCKSCHEME 1088

[] --> nOldLockScheme Function Reference

RddInfo()

See also: command SET DBFLOCKSCHEME. This setting queries or changes the locking scheme for SHARED database access in a multi user environment. Refer to the SET DBFLOCKSCHEME command for a description of locking schemes. The values that can be used for are the same #define constants as described with the command. RDDI_MEMOBLOCKSIZE

[] --> nOldBlockSize See also: command SET MEMOBLOCK. This setting queries or changes the default block size for memo fields to use by an RDD. If an RDD does not support memo fields, the return value is zero.

RDDI_MEMOEXT

[] --> nOldFileExtension See also: command SET MFILEEXT. This setting queries or changes the default extension for memo files to use by an RDD. If an RDD does not support memo fields, the return value is an empty string ("").

RDDI_MEMOTYPE

[] --> nOldMemoType This setting queries or configures the default memo file format to use by an RDD when it creates a new database containing memo fields with the DbCreate() function. To change the default memo file format, #define constants from Dbinfo.ch must be used for . They begin with the prefix DB_MEMO_. Supported memo file formats are DBT, FPT and SMT.

RDDI_MEMOVERSION

[] --> nOldMemoVersion This setting queries or configures the a subtype, or version, for FPT memo files. It can be set in addition to the memo type RddInfo(RDDI_MEMOTYPE, DB_MEMO_FPT). To change the subtype of the FPT memo file format, #define constants from Dbinfo.ch must be used for . They begin with the prefix DB_MEMOVER_. Supported memo file subtypes are FoxPro, SIX and FLEX.

RDDI_ORDBAGEXT

[] --> cOldFileExtension See also: function OrdBagExt(). This setting queries or changes the default extension for index files to use by an RDD. If an RDD does not support indexes, the return value is an empty string ("").

RDDI_TABLEEXT

[] --> cOldFileExtension See also: function DbTableExt(). This setting queries or changes the default extension for database files to use by an RDD. If an RDD does not support database files, the return value is an empty string ("").

Function Reference

1089

RddInfo()

Info See also: Category: Header: Source: LIB: DLL:

1090

DbInfo(), DbOrderInfo(), DbRecordInfo(), RddList(), RddName(), RddSetDefault() Database drivers, Info functions, xHarbour extensions Dbinfo.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

RddList()

RddList() Retrieves information about available Replaceable Database Drivers (RDDs).

Syntax RddList( [] ) --> aRDDNames

Arguments

A numeric value indicating the type of RDDs to list names for. #define constants contained in RDDSYS.CH are used for this parameter.

Types of RDDs Constant

Value

Description

RDT_FULL *) RDT_TRANSFER *) default

1 2

RDDs with full functionality RDDs having only import/export capabilities

Return The function returns a one-dimensional array whose elements contain the names of replaceable database drivers as character strings.

Description RddList() is an informational RDD function used to obtain the names of RDDs available at runtime of an xHarbour application.

Info See also: Category: Header: Source: LIB: DLL:

RddInfo(), RddName(), RddSetDefault() Database drivers rddsys.ch rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example requests various RDDs to be linked and lists // the RDD names. #include "RDDSYS.CH" REQUEST DBFCDX REQUEST SDF REQUEST DELIM PROCEDURE Main LOCAL aNames aNames := RddList( RDT_FULL )

Function Reference

1091

RddList() ? "RDT_FULL" AEval( aNames, {|c| Qout(c) } ) aNames := RddList( RDT_TRANSFER ) ? ? "RDT_TRANSFER" AEval( aNames, {|c| Qout(c) } ) RETURN

1092

Function Reference

RddName()

RddName() Retrieves the name of an RDD used to open files in a work area

Syntax RddName() --> cRDDName

Return The function returns the name of the replaceable database driver managing the files in a work area as character string. If no file is open in a work area, an empty string ("") is returned.

Description RddName() is an informational function that retrieves the name of the RDD specified with the USE command to open files in a workarea.

Info See also: Category: Source: LIB: DLL:

RddInfo(), RddList(), RddSetDefault() Database drivers rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example shows the result of RddName() calls in the current and // in aliased work areas. REQUEST DBFCDX PROCEDURE Main USE Customer ALIAS Cust USE Orders ALIAS Ord NEW VIA "DBFCDX" ? RddMame() ? Cust->( RddName() ) ? Ord-> ( RddName() )

// result: DBFCDX // result: DBFNTX // result: DBFCDX

CLOSE ALL RETURN

Function Reference

1093

RddSetDefault()

RddSetDefault() Retrieves or changes the default replaceable database driver.

Syntax RddSetDefault( [] ) --> cOldRDD

Arguments

This is a character string holding the name of the RDD to select as the new default RDD for opening files in a work area.

Return The function returns a character string holding the name of the RDD selected as default RDD before the function is called. If is specified and an RDD of this name does not exist, a runtime error is raised.

Description RddSetDefault() queries or changes the default replaceable database driver. The default RDD is used to open or create database and index files in a work area when the VIA clause of the USE command is omitted. Note: some RDDs, such as DBFCDX, for example, must be linked explicitly to an xHarbour application using the REQUEST statement.

Info See also: Category: Source: LIB: DLL:

RddInfo(), RddList(), RddName(), REQUEST Database drivers rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example REQUESTs the DBFCDX driver, opens a database // with DBFNTX and then changes the default RDD. REQUEST DBFCDX PROCEDURE Main ? RddSetDefault()

// result: DBFNTX

USE Customer ALIAS Cust

1094

? RddSetDefault( "DBFCDX" ) USE Orders ALIAS Ord NEW

// result: DBFNTX

? RddSetDefault()

// result: DBFCDX

? RddMame() ? Cust->( RddName() ) ? Ord-> ( RddName() )

// result: DBFCDX // result: DBFNTX // result: DBFCDX

Function Reference

RddSetDefault() CLOSE ALL RETURN

Function Reference

1095

ReadModal()

ReadModal() Activates editing of @...GET entry fields in text mode.

Syntax ReadModal( , [] , [], [] , [] , [] , []

; ; ; ; ; ; ) --> lUpDated

Arguments

This is the GetList array used to collet Get() objects created with the @...GET command.

This is a numeric value indicating the ordinal position of the first Get entry field held in to receive input focus. It defaults to 1.

Optionally, a TopBarMenu() object can be specified. In this case, the menu can be activated during ReadModal().

This is a numeric value specifying the screen row for displaying messages of individual Get objects or the menu . The range for is between 0 and MaxRow().

This is a numeric value specifying the left screen coordinate for displaying status messages. Usually, is set to the value 0.

This is a numeric value specifying the right screen coordinate for displaying status messages. Usually, is set to the value of MaxCol().

The parameter is an optional character string defining the color for the messages to display. It defaults to SetColor().

Return The return value is .T. (true) if any Get object in is edited and changed by the user, otherwise .F. (false) is returned.

Description ReadModal() is the functional equivalent of the READ command. The only parameter processed in addition to READ is . It specifies the first Get to begin editing with. 1096

Function Reference

ReadModal()

Refer to the READ command for more information.

Info See also: Category: Source: LIB: DLL:

Function Reference

@...GET, @...SAY, Get(), LastKey(), READ, TopBarMenu() Get system, UI functions rtl\getsys.prg, rtl\tgetlist.prg xhb.lib xhbdll.dll

1097

RecCount()

RecCount() Returns the number of records available in a work area.

Syntax RecCount() --> nRecords

Return The function returns the number of records available in a work area as a numeric value. If the work area is not used or if a database is empty, the return value is zero.

Description RecCount() is identical with LastRec(). Refer to LastRec() for a description.

Info See also: Category: Source: LIB: DLL:

1098

LastRec() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Function Reference

RecNo()

RecNo() Retrieves the number of the current record in a work area.

Syntax RecNo() --> nRecord

Return The function returns a numeric value which is the record number of the current record in a work area. If no database is open in the work area, RecNo() returns zero.

Description RecNo() retrieves the record number of the current record in a work area. The record number identifies a database record unambiguously and can be used with the DbGoto() function to navigate the record pointer of a work area to a particular record. Record numbers can be used for physical navigation in a database, they do not represent the logical order of records in an indexed database.

Info See also: Category: Source: LIB: DLL:

Bof(), DbGoto(), DbInfo(), DbSkip(), Eof(), GO, LastRec(), OrdKeyGoto(), RecSize(), SKIP Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example outlines the difference between physical and logical // records. REQUEST Dbfcdx PROCEDURE Main USE Customer VIA "DBFCDX" INDEX ON Upper(LastName) TAG NAME TO Cust01 DbGoto( 1 ) ? Lastname, Recno()

// Physical first record // result: Miller 1

DbGoto( LastRec() ) ? Lastname, Recno()

// Physical last record // result: Smith 22

OrdKeyGoto( 1 ) ? Lastname, Recno()

// Logical first record // result: Alberts 20

OrdKeyGoto( LastRec() ) ? Lastname, Recno()

// Logical last record // result: Waters 15

USE RETURN

Function Reference

1099

RecSize()

RecSize() Retrieves the number of bytes required to store a database record.

Syntax RecSize() --> nBytes

Return The function returns a numeric value indicating the record length, or number of bytes required to store a record in a database open in a work area. If no database is open in the work area, the return value is zero.

Description RecSize() is an informational database function used to determine the record length of the database open in a work area. The record length refers to the number of bytes a database file grows when a new record is added to the database with APPEND BLANK.

Info See also: Category: Source: LIB: DLL:

DbInfo(), DiskSpace(), FCount(), FieldName(), Header(), LastRec(), RecNo() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example implements a user-defined function which calculates // the file size of a DBF file. FUNCTION DbfFileSize() RETURN ( (RecSize() * LastRec()) + Header() + 1 )

1100

Function Reference

Replicate()

Replicate() Creates a character string by replicating an input string.

Syntax Replicate( , ) --> cReplicatedString

Arguments

This parameter is the input string to replicate times.

A numeric value indicating the number or times to replicate .

Return The function returns a character string holding the input string number of times.

Description Replicate() provides a convenient way for creating an output string consisting of multiple copies of an input string. A similar function is Space() which creates a character string consisting of blank space characters only.

Info See also: Category: Source: LIB: DLL:

PadC() | PadL() | PadR(), Space() Character functions rtl\replic.c xhb.lib xhbdll.dll

Example // The example shows results of Replicate() PROCEDURE Main ? Replicate( "-", 17 ) ? Replicate( "xHarbour ", 2 ) ? Replicate( "!", 17 ) RETURN

Function Reference

// result: ----------------// result: xHarbour xHarbour // result: !!!!!!!!!!!!!!!!!

1101

RestScreen()

RestScreen() Displays a SaveScreen() string.

Syntax RestScreen( [] , [] , [], [] ,

; ; ; ; ) --> NIL

Arguments

A numeric value indicating the screen coordinate for the top row of the rectangle to display the SaveScreen() string. The default value is 0.

A numeric values indicating the screen coordinate for the left column of the rectangle to display the SaveScreen() string. The default value is 0.

A numeric value indicating the screen coordinate for the bottom row of the rectangle to display the SaveScreen() string. The default value is MaxRow().

A numeric values indicating the screen coordinate for the right column of the rectangle to display the SaveScreen() string. The default value is MaxCol().

A character string previously returned from function SaveScreen().

Return The function returns NIL.

Description RestScreen() displays the contents of a console window previously saved with the SaveScreen() function. The coordinates , , and do not necessarily have to be the same coordinates used with SaveScreen(). They must, however, describe a rectangular area of the exact same size. If the rectangle defined for SaveScreen() differs from the rectangle defined for RestScreen(), the result of RestSCreen() is unpredictable.

1102

Function Reference

RestScreen()

Info See also: Category: Source: LIB: DLL:

DispBegin(), SaveScreen() Screen functions rtl\saverest.c xhb.lib xhbdll.dll

Example // The example displays a frame moving diagonal in a console window. // The SaveScreen() string is created only once, while the frame is // displayed and erased at different screen coordinates. PROCEDURE Main LOCAL nTop:=1, nLeft:=1, nBottom:=10, nRight:=40, cScreen, i CLS cScreen := SaveScreen( nTop, nLeft, nBottom, nRight ) FOR i:=1 TO 20 DispBox( nTop, nLeft, nBottom, nRight, 2, "W+/B" ) RestScreen( nTop, nLeft, nBottom, nRight, cScreen ) Inkey(0.2) nTop ++ nLeft ++ nBottom ++ nRight ++ NEXT RETURN

Function Reference

1103

Right()

Right() Extracts characters from the right side of a string

Syntax Right( , ) --> cSubString

Arguments

A character string to extract a substring from.

A numeric value specifying the number of characters to extract from the right side of .

Return The function returns a character string containing Min( , Len() ) characters.

Description The character function Right() extracts a substring from the right side of . The returned substring contains characters. If is larger than Len(), the return value is a copy of . The counterpart of Right() is Left(), which extracts a substring from the left side of a string.

Info See also: Category: Source: LIB: DLL:

At(), HB_ATokens(), Left(), LTrim(), RAt(), RTrim(), Stuff(), SubStr() Character functions rtl\right.c xhb.lib xhbdll.dll

Example // The example illustrates return values of function Right() PROCEDURE Main ? CDoW(Date()) ? Right( CDoW(Date()), 3)

1104

// result: Friday // result: day

? Time() ? Right( Time(), 5)

// result: 14:45:12 // result: 45:12

? Right("xHarbour", 7) RETURN

// result: Harbour

Function Reference

RLock()

RLock() Locks the current record for concurrent write access in a work area.

Syntax RLOCK() --> lIsLocked

Return The function returns .T. (true) if the current record is successfully locked, otherwise .F. (false) is returned.

Description The network function RLock() locks the current record in a work area for concurrent write access. If the record is successfully locked, it still can be read by other applications, but it can only be changed by the application which has obtained the record lock. RLock() releases all pending record locks prior to attempting to lock the current record. If this attempt fails, the record is currently locked by another application in a network. Record locks are required when a database is opened in SHARED mode and data must be written to the database file using the REPLACE command, or when the deleted flagof the current record is changed using DELETE or RECALL. After the record is changed, the record lock must be released using UNLOCK or DbUnlock().

Info See also: Category: Source: LIB: DLL:

APPEND BLANK, DbRLock(), DbRLockList(), DbUnlock(), DbUseArea(), FLock(), SET EXCLUSIVE, UNLOCK, USE Database functions, Network functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example demonstrates a typical coding pattern for updating a // record in a networked environment. PROCEDURE Main USE Customer ALIAS Cust SHARED INDEX ON Upper( LastName+FirstName) TO Cust01 SEEK "WALTERS" IF Found() IF RLock() REPLACE FIELD->Lastname WITH "Waters" DbUnlock() ELSE Alert( "Record is currently locked" ) ENDIF ENDIF

Function Reference

1105

RLock() USE RETURN

1106

Function Reference

Round()

Round() Rounds a numeric value to a specified number of digits

Syntax Round( , ) --> nRounded

Arguments

This is the numeric value to round.

If the parameter is a positive number, it specifies the number of decimal places to retain after the decimal point. If specified as negative value, Round() operates on the digits before the decimal point, thus rounding integer numbers.

Return The function returns the rounded numeric value.

Description Round() is a numeric function used to round numbers to a given number of decimal places. Digits 5 to 9 are rounded up, while digits 0 to 4 round down.

Info See also: Category: Source: LIB: DLL:

Abs(), Int(), SET DECIMALS, SET FIXED, Str(), Val() Numeric functions rtl\round.c xhb.lib xhbdll.dll

Example // The example demonstrates results of Round() and how SET FIXED // influences the display of rounded numbers. PROCEDURE Main SET DECIMALS TO 4 SET FIXED ON ? ? ? ?

Round( Round( Round( Round(

1234.5678, 1234.5678, 1234.5678, 1234.5678,

0) 1) 2) 3)

? Round( 1234.5678,-1) ? Round( 1234.5678,-2) ? Round( 1234.5678,-3)

// // // //

result: result: result: result:

1235.0000 1234.6000 1234.5700 1234.5680

// result: 1230.0000 // result: 1200.0000 // result: 1000.0000

SET FIXED OFF ? Round( 1234.5678, 0)

Function Reference

// result: 1235

1107

Round() ? Round( 1234.5678, 1) ? Round( 1234.5678, 2) ? Round( 1234.5678, 3)

// result: 1234.6 // result: 1234.57 // result: 1234.568

? Round( 1234.5678,-1) ? Round( 1234.5678,-2) ? Round( 1234.5678,-3)

// result: 1230 // result: 1200 // result: 1000

RETURN

1108

Function Reference

Row()

Row() Returns the current row position of the screen cursor.

Syntax Row() --> nRowPos

Return The function returns a numeric value indicating the current row position of the screen cursor. The top row has position 0 and the bottom position is identified by MaxRow().

Description The function returns the current cursor row position within a console window (text-mode). The cursor position changes with screen output using console output commands and functions. Use function SetPos() to position the screen cursor at a defined row and column coordinate.

Info See also: Category: Source: LIB: DLL:

?|??, @...GET, @...SAY, Col(), MaxRow(), PCol(), PRow(), SETPOS() Screen functions rtl\setpos.c xhb.lib xhbdll.dll

Example // The examples displays and changes the screen cursor position. PROCEDURE Main CLS ? Row(), Col()

// result: 0

0

// result: 2

8

? "xHarbour" ? Row(), Col() RETURN

Function Reference

1109

RTrim()

RTrim() Removes trailing blank spaces from a character string.

Syntax RTrim( [,] ) --> cTrimmedString Trim( [,] ) --> cTrimmedString

Arguments

A character string which is copied without trailing blank space characters.

This parameter defaults to .F. (false). If .T. (true) is passed, function RTrim() treats the whitespace characters TAB (Chr(9)) and CRLF (Chr(13)+Chr(10)) like blank spaces and removes them as well.

Return The function returns a copy of without blank spaces at the end of the string.

Description RTrim() is used for formatting character strings whose ending characters consist of blank spaces (Chr(32)). The function creates a copy of but ignores blank spaces at the end of the input string. It is frequently used to format character strings stored in database fields. Such strings are padded with blank paces up to the field length. Note() function Trim() is a synonym for RTrim().

Info See also: Category: Source: LIB: DLL:

Alltrim(), LTrim(), PadC() | PadL() | PadR(), SubStr() Character functions rtl\trim.c xhb.lib xhbdll.dll

Example // The example shows various possibilities for trimming a string. #define CRLF

Chr(13)+Chr(10)

PROCEDURE Main LOCAL cStr := " ? ? ? ?

Len( Len( Len( Len(

cStr ) LTrim( cStr ) ) RTrim( cStr ) ) AllTrim( cStr ) )

cStr := "xHarbour

1110

xHarbour

" // // // //

result: result: result: result:

14 12 10 8

" + CRLF

Function Reference

RTrim() ? Len( cStr ) ? Len( RTrim( cStr ) ) ? Len( RTrim( cStr, .T. ) )

// result: // result: // result:

12 12 8

RETURN

Function Reference

1111

SaveScreen()

SaveScreen() Saves a rectangular screen region for later display.

Syntax SaveScreen( [], [], [], [] ) --> cScreen

Arguments

A numeric value indicating the screen coordinate for the top row of the rectangular screen region to save. The default value is 0.

A numeric values indicating the screen coordinate for the left column of the rectangular screen region to save. The default value is 0.

A numeric value indicating the screen coordinate for the bottom row of the rectangular screen region to save. The default value is MaxRow().

A numeric values indicating the screen coordinate for the right column of the rectangular screen region to save. The default value is MaxCol().

Return The function returns a character string holding textual and color information of the saved screen rectangle.

Description SaveScreen() is used to save the current display in a console window. The function combines textual and color information in the returned string. This string can later be displayed using the RestScreen() function. Note: textual information on screen is placed at odd positions in the return string, while color attributes for each character are stored at even positions in the SaveScreen() string.

Info See also: Category: Source: LIB: DLL:

RestScreen() Screen functions rtl\saverest.c xhb.lib xhbdll.dll

Example // The example saves a screen region, changes the display of that // region, and restores it to its original state. PROCEDURE Main LOCAL nTop:=0, nLeft:=0, nBottom:=10, nRight:=40, cScreen

1112

Function Reference

SaveScreen() cScreen := SaveScreen( nTop, nLeft, nBottom, nRight ) SET COLOR TO "W+/B" DispBox( nTop, nLeft, nBottom, nRight ) WAIT "Press a key..." RestScreen( nTop, nLeft, nBottom, nRight, cScreen ) WAIT "Screen is restored Press a key..." RETURN

Function Reference

1113

Scroll()

Scroll() Scrolls a screen region horizontally and/or vertically.

Syntax Scroll( [] , [] , [], [] , [] , []

; ; ; ; ; ) --> NIL

Arguments

A numeric value indicating the screen coordinate for the top row of the rectangular screen region to scroll. The default value is 0.

A numeric values indicating the screen coordinate for the left column of the rectangular screen region to scroll. The default value is 0.

A numeric value indicating the screen coordinate for the bottom row of the rectangular screen region to scroll. The default value is MaxRow().

A numeric values indicating the screen coordinate for the right column of the rectangular screen region to scroll. The default value is MaxCol().

This is a numeric value indicating the number of rows to scroll the screen region in vertical direction. A positive value scrolls left, while negative values scroll right. The default value is zero, which does not scroll vertically.

This is a numeric value indicating the number of columns to scroll the screen region in horizontal direction. A positive value scrolls up, while negative values scroll down. The default value is zero, which does not scroll horizontally.

Return The return value is NIL.

Description Scroll() manipulates the screen display in a console window by moving a rectangular area in horizontal and/or vertical direction. This is accomplished by deleting a row and/or column in scroll direction, shifting the screen area and displaying a blank row and/or column at the end using the standard color. This is repeated until the number of rows and/or columns specified is reached.

1114

Function Reference

Scroll()

Note: if NIL is passed for both, and , the entire rectangle defined with , , and is blanked.

Info See also: Category: Source: LIB: DLL:

@...BOX, @...CLEAR, @...TO, CLEAR SCREEN, RestScreen() Screen functions rtl\scroll.c xhb.lib xhbdll.dll

Example // The example displays numbers 0 to 50 in a screen area that has only // ten rows. When the screen cursor hits the bottom of the area, the // display is scrolled up. PROCEDURE Main LOCAL nTop:= 10, nLeft:=10, nBottom:=20, nRight:=20, cScreen LOCAL nRow, nCol, n CLS SET COLOR TO W+/B DispBox( nTop-1, nLeft-1, nBottom+1, nRight+1 ) SET COLOR TO W+/R nRow := Row() nCol := Col() FOR n := 0 TO 50 @ nRow, nCol SAY n Inkey(0.1) nRow ++ IF nRow > nBottom Scroll( nTop, nLeft, nBottom, nRight, 1 ) nRow := nBottom ENDIF NEXT RETURN

Function Reference

1115

Seconds()

Seconds() Returns the number of seconds elapsed since midnight

Syntax Seconds() --> nSeconds

Return The function returns a numeric value indicating the seconds elapsed since midnight with a granularity of 1/100th of a second.

Description Seconds() is used to calculate time spans in seconds that have elapsed since a start time. Note that the return value is reset to zero when midnight passes.

Info See also: Category: Source: LIB: DLL:

ElapTime(), Days(), Time(), Secs() Date and time rtl\seconds.c xhb.lib xhbdll.dll

Example // The example shows a typical usage scenario for Seconds() PROCEDURE Main LOCAL nStart := Seconds() Inkey(1.5)

// some lengthy operation

? "Elapsed:", Seconds() - nStart RETURN

1116

Function Reference

SecondsSleep()

SecondsSleep() Suspends thread execution for a number of seconds.

Syntax SecondsSleep( ) --> NIL

Arguments

This is a numeric value indicating the number of seconds to pause thread execution. The granularity is three places after the decimal point (1/1000th of a second).

Return The function returns always NIL.

Description Function SecondsSleep() suspends program execution in the current thread for the period of seconds. During this period of time, no CPU resources are consumed by the current thread. The function accepts a numeric value with up to 3 decimal places (1/1000th of a second). Note: this function is also available in single threaded applications.

Info See also: Category: Source: LIB: DLL:

Function Reference

Inkey(), StartThread(), ThreadSleep(), WAIT Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

1117

Secs()

Secs() Calculates the number of seconds from a time string.

Syntax Secs( ) --> nSeconds

Arguments

This is a character string formatted as hh:mm:ss. It holds a time string based on a 24h clock.

Return The function returns a numeric value representing the number of seconds corresponding to the input string.

Description Secs() is a time conversion function that accepts a Time() compliant character string and calculates from it the corresponding number of seconds. The reverse function of Secs() is TSTring().

Info See also: Category: Source: LIB: DLL:

Seconds(), ElapTime(), Time(), TString() Date and time rtl\samples.c xhb.lib xhbdll.dll

Example // The example demonstrates return values of Secs() PROCEDURE Main ? Secs( "23:59:59" ) ? Secs( "00:00:00" ) ? Secs( "12:00:00" ) ? Time() ? Secs( Time() ) RETURN

1118

// // // // //

result: 86399 result: 0 result: 43200 result: 16:07:34 result: 58054

Function Reference

Select()

Select() Retrieves the work area number by alias name.

Syntax Select( [] ) --> nWorkArea

Arguments

A character string holding the alias name of the work area to select as current.

Return The function returns an integer numeric value representing the work area number of the work area having the alias name . If this alias does not exist, the return value is zero. When is omitted, the function returns the work area number of the current work area.

Description Select() retrieves the work area number by its alias name. This is the opposite of function Alias(), which retrieves the alias name of a work area by its number. Work areas are numbered from 1 to 65535. They hold open database and index files and make them accesible to database functions and commands.

Info See also: Category: Source: LIB: DLL:

Alias(), DbSelectArea(), FieldGet(), SELECT, USE, Used() Database functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The example opens two databases in two different work areas // shows their work area numbers. PROCEDURE Main USE Customer ALIAS Cust DbSelectArea(10) USE Invoice ALIAS Inv ? Select() ? Select( "Cust" ) ? Select( "Inv" )

// result: 10 // result: 1 // result: 10

CLOSE ALL RETURN

Function Reference

1119

Set()

Set() Retrieves or changes a system setting.

Syntax Set( , [], [] ) --> xOldSetting

Arguments

This is a numeric parameter for which #define constants exist in the file Set.ch. They identify the numerous system settings that can be queried or changed.

is an optional argument specifying a new value for the system setting identified by . The data type for depends on the system setting to change (see below).

Some system settings require a second parameter. This is what parameter is used for.

Return The function returns the value of the specified system setting which is set before the function is called.

Description Set() is a universal function managing numerous system settings available in xHarbour. Many of these settings can be changed via SET commands, which is the recommended way. To query the current value of a system setting, however, must be done by calling the Set() function. This function accepts as first parameter a #define constant, which identifies the system setting to query or change. The available constants are listed in alphabetical order below:

1120

_SET_ALTERNATE

| on | OFF See also: command SET ALTERNATE. If the setting is enabled, functions QOut() | QQout() write to the screen and to a file, provided that a file is opened or created with _SET_ALTFILE. If disabled, which is the default, Qout() and QQout() only write to the screen (and/or to the PRINTFILE).

_SET_ALTFILE

, See also: command SET ALTERNATE. When set, creates or opens file to write Qout() and QQout() output to. If .T. (true) is passed for (=third parameter of Set()) and the file already exists, the file is opened and positioned at the end of file, so that new output is appended to the existing file. Otherwise, the file is created. If a file is already opened, it is closed before the new file is opened or created (even if it is the same file). The default file extension is ".txt". There is no default file name. Call with an empty string to close the file.

_SET_AUTOPEN

| ON | off See also: command SET AUTOPEN. When set, opens a structural index file automatically with the USE command, when the index file has the same filename (without extension) as the database file. Default is enabled. Note: this setting must be supported Function Reference

Set()

by the replaceble database driver. DBFCDX supports this setting, for example. It opens the structural index file. To automatically select an index of that file, _SET_AUTORDER must be set. _SET_AUTORDER

See also: command SET AUTORDER. When set, and _SET_AUTOPEN is set to .T. (true), the RDD selects automatically the index at position as current index. The default is 0, i.e. no index is selected as current, although the index file may be open. Note: this setting must be supported by the replaceble database driver. DBFCDX supports this setting, for example.

_SET_AUTOSHARE

See also: command SET AUTOSHARE. The default value is zero, causing an application not to use automatic SHARE mode detection when databases are opened. The value 1 means, the application detects if it runs in a network. If it does not, all database access is done EXCLUSIVE. If is set to 2, databases are always opened in EXCLUSIVE mode.

_SET_BACKGROUNDTASKS | on | OFF See also: command SET BACKGROUND TASKS. When enabled, background tasks are active. When disabled, which is the default, tasks are inactive. _SET_BACKGROUNDTICK See also: command SET BACKGROUNDTICK. This setting is the number of xHarbour pCodes to execute before background tasks are checked to run. The default value for is 1000. When this value is enlarged, the system saves time for task checking. Reducing the value improves the response time for background tasks. _SET_BELL

| on | OFF See also: command SET BELL. When enabled, the bell sounds when the last position of a GET entry field is reached and/or when a GET validation fails. Disabled by default.

_SET_CANCEL

See also: function SetCancel(). When enabled, which is the default, pressing Alt+C or Ctrl+Break terminates the program. When disabled, both keystrokes can be read by Inkey(). Note: _SET_KEY has precedence over _SET_CANCEL.

_SET_COLOR

See also: function SetColor(). This setting exists for compatibility reasons. It is superseeded by function SetColor().

_SET_CONFIRM

| on | OFF See also: command SET CONFIRM. If enabled, an exit key must be pressed to leave a GET. If disabled, which is the default, typing past the end will leave a GET.

_SET_CONSOLE

| ON | off See also: command SET CONSOLE. If enabled, which is the default, all screen output goes to the console window. When disabled, screen output is suppressed.

_SET_CURSOR

See also: function SetCursor(). is a #define constant from the SetCurs.ch file. It defines the shape of the cursor in a console application. The default is SC_NORMAL.

_SET_DATEFORMAT

| AMERICAN | ansi | British | French | German | Italian | Japan | USA See also: command SET DATE. is a character string specifying the date format for displaying Date values.

_SET_DBFLOCKSCHEME

Refer to command SET DBFLOCKSCHEME for a comprehensive description of this setting.

Function Reference

1121

Set()

1122

_SET_DEBUG

When set to .T., pressing Alt+D activates the debugger. When set to .F., which is the default, Alt+D can be read by Inkey(). This setting is also affected by AltD(1) and AltD(0).

_SET_DECIMALS

See also: command SET DECIMALS. Sets the number of decimal digits to use for displaying or printing numeric values when SET FIXED is ON. Defaults to 2. If SET FIXED is OFF, then SET DECIMALS is only used to determine the number of decimal digits to use after using Exp(), Log(), SQrt(), or division. Other math operations may adjust the number of decimal digits that the result will display. Note: This never affects the precision of a number. Only the display format is affected.

_SET_DEFAULT

See also: command SET DEFAULT. Sets the default directory in which to open, create and check for database and index files. Defaults to the current directory (empty string).

_SET_DELETED

| on | OFF See also: command SET DELETED. If enabled, records marked for deletion are not visible. If disabled, which is the default, deleted records are visible.

_SET_DELIMCHARS

"::" See also: command SET DELIMITERS. Sets the GET delimiter characters. Defaults to "::".

_SET_DELIMITERS

| on | OFF See also: command SET DELIMITERS. If enabled, GETs are delimited on screen. If disabled, which is the default, no GET delimiters are used.

_SET_DEVICE

SCREEN | print See also: command SET DEVICE. Selects the output device for DEVOUT(). When set to "PRINTER", all output is sent to the printer device or file set by _SET_PRINTFILE. When set to anything else, all output is sent to the screen. Defaults to "SCREEN".

_SET_DIRCASE

See also: command SET DIRCASE. This setting controls how the directory name will be acessed on disk. If 0 is specified, which is the default, mixed case letters are allowed. If 1 is speficied, lower case letters are used, also, converts all letters to lower case. If 2 is speficied, upper case letter are used, also, converts all letters to upper case.

_SET_DIRSEPARATOR

See also: command SET DIRSEPARATOR. This setting specifies a single character to be used as path separator. Default is the backslash "\".

_SET_EOL

See also: command SET EOL. This setting specifies the end-of-line character(s) used by an xHarbour application. It defaults to Crarriage Return plus Line Feed (Chr(13)+Chr(10)).

_SET_EPOCH

(1900) See also: command SET EPOCH. Determines how to handle the conversion of 2-digit years to 4 digit years. When a 2-digit year is greater than or equal to the year part of the epoch, the century part of the epoch is added to the year. When a 2-digit year is less than the year part of the epoch, the century part of the epoch is incremented and added to the year. The default epoch is 1900, which converts all 2digit years to 19xx. Example: If the epoch is set to 1950, 2-digit years in the range from 50 to 99 get converted to 19xx and 2-digit years in the range 00 to 49 get converted to 20xx.

_SET_ERRORLOG

, See also: command SET ERRORLOG. Function Reference

Set()

_SET_ERRORLOOP

See also: command SET ERRORLOOP. This setting defines the recursion depth if recursive errors occur in the xHarbour error handling routine. is a numeric value that defines the maximume error recursion level after which an xHarbour application terminates. The default value is 8.

_SET_ESCAPE

| ON | off See also: command SET ESCAPE. When enabled, which is the default, pressing Esc will exit a READ. When disabled, pressing Esc during a READ is ignored, unless the Esc key has been assigned to a function using SetKey().

_SET_EVENTMASK

See also: command SET EVENTMASK. Determines which events function Inkey() responds to. #define constants must be used for . They are listed in the file INKEY.CH.

_SET_EXACT

| on | OFF See also: command SET EXACT. When enabled, all string comparisons other than exactly equal (==) exclude trailing spaces when checking for equality. When disabled, which is the default, all string comparisons other than exactly equal treat two strings as equal if the right hand string is "" or if the right hand string is shorter than or the same length as the left hand string and all of the characters in the right hand string match the corresponding characters in the left hand string.

_SET_EXCLUSIVE

| on | OFF See also: command SET EXCLUSIVE. When enabled, which is the default, all database files are opened in exclusive mode. When disabled, all database files are opened in shared mode. Note: The EXCLUSIVE and SHARED clauses of the USE override this setting.

_SET_EXIT

See also: function ReadExit(). Toggles the use of Up-arrow and Down-arrow as READ exit keys. Specifying true (.T.) enables them as exit keys, and false (.F.) disables them. Used internally by the ReadExit() function.

_SET_EXTRAFILE

When set, creates or opens a secondary SET ALTERNATE file that receives QOut() and QQOut() output.

_SET_FILECASE

See also: command SET FILECASE. This setting controls how the file will be acessed on disk. If 0 is specified, mixed case letters are allowed. This is the default setting. If 1 is speficied, lower case letters are used, also, convert all letters to lower case. If 2 is speficied, upper case letters are used, also, convert all letters to upper case.

_SET_FIXED

| on | OFF See also: command SET FIXED. When enabled, all numeric values will be displayed and printed with the number of decimal digits set by SET DECIMALS, unless a PICTURE clause is used. When disabled, which is the default, the number of decimal digits that are displayed depends upon a variety of factors. See _SET_DECIMALS for more.

_SET_HARDCOMMIT

| on | OFF See also: command SET HARDCOMMIT. When enabled, forces an immediate disk write operation for database and index files when a record is changed. When disabled,which is the default, changes are cached in internal database buffers which are flushed later to a file.

Function Reference

1123

Set()

1124

_SET_IDLEREPEAT

When enabled, which is the default, idle tasks are repeatedly executed in the background when the application enters an idle state. When disabled, the list of idle tasks is executed only once when the application enters an idle state.

_SET_INSERT

When enabled, characters typed in a GET or MemoEdit() are inserted. When disabled, which is the default, characters typed in a GET or MemoEdit() overwrite. Note: This setting can also be toggled between on and off by pressing the Insert key during a GET or MemoEdit().

_SET_INTENSITY

| ON | off When enabled, which is the default, GETs and PROMPTs are displayed using the enhanced color setting. When disabled, GETs and PROMPTs are displayed using the standard color setting.

_SET_LANGUAGE

See also: function HB_LangSelect(). Specifies the language to be used for xHarbour messages. The default value is "EN".

_SET_MARGIN

(0) See also: command SET MARGIN. Sets the left margin for all printed output. The default value is 0. Note: PCol() reflects the printer's column position including the margin (e.g., SET MARGIN TO 5 followed by DevPos(5, 10) makes PCol() return 15).

_SET_MBLOCKSIZE

See also: command SET MEMOBLOCK. This setting specifies the default block size for memo fields. If not set, which is the default, the default block size for memo fields is defined by the RDD.

_SET_MCENTER

| on | OFF See also: command SET MESSAGE. This setting toggles the CENTER option of the SET MESSAGE command. If enabled, display PROMPTs centered on the MESSAGE row. If disabled, which is the default, display PROMPTs at column position 0 on the MESSAGE row.

_SET_MESSAGE

See also: command SET MESSAGE. If set to 0, which is the default, PROMPTs are always suppressed. Otherwise, PROMPTs are displayed on the set row. Note: It is not possible to display prompts on the top-most screen row, because row 0 is reserved for the SCOREBOARD, if enabled.

_SET_MFILEEXT

See also: command SET MFILEEXT. This setting specifies the default file extension for memo files. If not set, which is the default, the default extension is defined by the RDD.

_SET_OPTIMIZE

| ON | off See also: command SET OPTIMIZE. This setting toggles the filter optimization for database navigation in the current work area.

_SET_PATH

("") See also: command SET PATH. Specifies a path of directories to search through to locate a file that can't be located in the DEFAULT directory. Defaults to no path (""). Directories must be separated by a semicolon (e.g., "C:\DATA;C:\MORE").

_SET_PRINTER

| on | OFF See also: command SET PRINTER. If enabled, QOut() and QQOut() write to the screen and to the printer. If disabled, which is the default, QOut() and QQOut() only write to the screen (and/or to the SET ALTERNATE file). Function Reference

Set()

_SET_PRINTFILE

, See also: command SET PRINTER. When set, creates or opens file to write QOut(), QQOut() and DevOut() output to. If is TRUE and the file already exists, the file is opened and positioned at end of file. Otherwise, the file is created. If a file is already opened, it is closed before the new file is opened or created (even if it is the same file). The default file extension is ".prn". The default file name is "PRN", which maps to the default printer device. Call with an empty string to close the file.

_SET_SCOREBOARD

| ON | off See also: command SET SCOREBOARD. When enabled, which is the default, READ and MemoEdit() display status messages on screen row 0. When disabled, READ and MemoEdit() status messages are suppressed.

_SET_SOFTSEEK

| on | OFF See also: command SET SOFTSEEK. When enabled, a SEEK that fails will position the record pointer to the first key that is higher than the sought after key or to LastRec() + 1 if there is no higher key. When disabled, which is the default, a SEEK that fails will position the record pointer to LastRec()+1.

_SET_STRICTREAD

| on | OFF See also: command SET STRICTREAD. When disabled, which is the default, internal memory buffers are used to load datbase fields into memory variables. When enabled, datbase fields are always read from disk.

_SET_TRACE

| ON | off See also: command SET TRACE. When enabled, which is the default, output of function TraceLog() is written to the trace file specified with _SET_TRACEFILE. When disabled, function TraceLog() produces no output.

_SET_TRACEFILE

The setting specifies the trace file name where function TraceLog() writes output to. The default value is "trace.log".

_SET_TRACESTACK

The setting defines the first routine in the callstack to add to the trace file with function TraceLog(). The default value is 2.

_SET_TRIMFILENAME

When disabled, which is the default, strings containing file names are treated according to SET FILECASE and SE T DIRCASE. When enabled, trailing blank spaces in file names are ignored, in addition.

_SET_TYPEAHEAD

See also: command SET TYPEAHEAD. Sets the size of the keyboard typeahead buffer. Defaults to 50. The minimum is 16 and the maximum is 4096.

_SET_UNIQUE

| on | OFF See also: command SET UNIQUE. When enabled, indexes are not allowed to have duplicate keys. When disabled, indexes are allowed duplicate keys.

_SET_VIDEOMODE

See also: command SET VIDEOMODE. Specifies the video mode.

_SET_WRAP

| on | OFF See also: command SET WRAP. When enabled, lightbar menus can be navigated from the last position to the first and from the first position to the last. When disabled, which is the default, there is a hard stop at the first and last positions.

Function Reference

1125

Set()

Info See also: Category: Header: Source: LIB: DLL:

SetCancel() Environment functions set.ch rtl\set.c xhb.lib xhbdll.dll

Example // // // //

The example implements a user defined function that saves/restores all system settings available in xHarbour. Note the constants _SET_COUNT, HB_SET_COUNT and HB_SET_BASE. They are used to distinguish Clipper compatible settings from xHarbour additions. #include "Set.ch" PROCEDURE Main LOCAL aSet := Settings() AEval( aSet, {|x| QOut( ValToPrg(x) ) } ) RETURN FUNCTION LOCAL LOCAL LOCAL

Settings( aNewSet ) nAll := _SET_COUNT + HB_SET_COUNT aOldSet[ nAll ] nSetting := 0, i, j

DO WHILE ++ nSetting lOldSetting

Arguments

This is a logical value. If .T. (true) is passed, the asterisk (*) in the background color of a SetColor() string causes the foreground color (text) to blink. If .F. (false) is passed, the background color is set to high intensity.

Return The function returns the setting which is active before SetBlink() is called.

Description SetBlink() is a compatibility function which toggles interpretation of the blink attribute (*) if it is specified for the backgroud color of a SetColor() string. The blink attribute is only relevant when an application runs in full screen text mode. In addition, its availability is operating system dependent. If the blink attribute is not supported by the operating system, the asterisk (*) is treated like the high intensity color attribute (+).

Info See also: Category: Source: LIB: DLL:

ColorSelect(), SetColor() Screen functions rtl\setcolor.c xhb.lib xhbdll.dll

Example // The example displays text with the SetBlink() setting on and off. PROCEDURE Main CLS SetColor( "N/GR*" ) @ 0, 0 CLEAR TO 2, MaxCol() ? "Blink attribute is:", SetBlink() WAIT "Press a key to toggle blink attribute" SetBlink( .NOT. SetBlink() ) @ 0, 0 CLEAR TO 2, MaxCol() ? "Blink attribute is:", SetBlink() WAIT "Press a key to end" RETURN

Function Reference

1127

SetCancel()

SetCancel() Determines if Alt+C and Ctrl+Break terminate an application

Syntax SetCancel( [] ) --> lOldSetting

Arguments

This is a logical value. If .T. (true) is passed, the keys Alt+C and Ctrl+Break terminate an application unconditionally. .F. (false) disables automatic program termination when a user presses these keys.

Return The function returns the setting which is active before SetCancel() is called.

Description SetCancel() is used to disable the automatic program termination routine which can be activated by pressing the keys Alt+C or Ctrl+Break. The setting is .T. (true) by default. When a user presses either key combination, an xHarbour application is terminated unconditionally. If automatic program termination is not desired, SetCancel() should be set to .F. (false) and a program termination routine should be implemented.

Info See also: Category: Source: LIB: DLL:

SET ESCAPE, SET KEY, Set(), SetKey() Environment functions rtl\set.c xhb.lib xhbdll.dll

Example // The example demonstrates howto override the default program termination // for Alt+C or Ctrl+Break with a user defined one. #include "Inkey.ch"

PROCEDURE Main WAIT "Alt+C terminates unconditionally" SetCancel( .F. ) SetKey( K_ALT_C, {|| MyExitProc() } ) WAIT "Alt+C calls user defined exit routine" ? "Normal program termination" RETURN

1128

Function Reference

SetCancel() PROCEDURE MyExitProc LOCAL n := Alert( "Exit program?", { "Yes", "No" } ) IF n == 1 ? "User terminated program" QUIT ENDIF RETURN

Function Reference

1129

SetColor()

SetColor() Retrieves and/or changes the current color setting for text mode.

Syntax SetColor( [] ) --> cOldColorString

Arguments

The parameter is a character string holding color settings. The first five colors are used for different pre-defined scopes. A color setting consists of a color pair that defines the foreground and background color in text mode applications. Single colors are specified with a letter (see description), foreground and background colors must be separated with a slash, and color pairs for different scopes must be comma separated.

Color settings in a color string Setting

Position

Scope

Standard Enhanced Border Background Unselected

1 2 3 4 5

All screen output commands and functions GETs and selection highlights Border around screen, not supported on most monitors Not supported Unselected GETs

Return The function returns a color string holding the previous color settings.

Description SetColor() is used to query or change the current color settings for screen output in text mode applications. A single color value consists of two letters separated by a backslash. They define the foreground and background color. A color value can be modified with a color attribute. The plus sign (+) raises the intensity, or brightness, of a color, while the asterisk can be interpreted either a as intensity or as blink attribute (see function SetBlink()) The letters listed in the following table are recognized as color values:

Letters for colors in text mode

1130

Letter

Color monitor

Monochrome

B B+ BG BG+ G G+ GR GR+ I N+

Blue Bright Blue Cyan Bright Cyan Green Bright Green Brown Yellow Inverse Video Gray

Underline Bright Underline White Bright White White Bright White White Bright White Inverse Video Black Function Reference

SetColor() N, Space R R+ RB RB+ U W W+ X

Black Red Bright Red Magenta Bright Magenta Black White Bright White Blank

Black White Bright White White Bright White Underline White Bright White Blank

Info See also: Category: Source: LIB: DLL:

ColorSelect(), SET COLOR, SET INTENSITY, SetBlink() Screen functions rtl\setcolor.c xhb.lib xhbdll.dll

Example // This example demonstrates how to save, change and restore // color settings. PROCEDURE Main LOCAL cOldColor := SetColor() LOCAL cNewColor := PadR( "W+/N,W+/B", 40 ) CLS ? "Current color :", cOldColor ? SetColor( cNewColor ) @ Row(), Col() SAY "Enter new color:" GET cNewColor READ cNewColor := Trim( cNewColor ) SetColor( cNewColor ) ? "New color is :", cNewColor SetColor( cOldColor ) ? "Back to original" RETURN

Function Reference

1131

SetCursor()

SetCursor() Queries or changes the shape of the cursor on the screen.

Syntax SetCursor( [] ) --> nOldCursorShape

Arguments

This is a numeric value for wich #define constants listed in SETCURS.CH are used. They specify a particular cursor shape.

Constants for cursor shapes Constant

Value

Description

SC_NONE SC_NORMAL SC_INSERT SC_SPECIAL1 SC_SPECIAL2

0 1 2 3 4

No cursor Underline Lower half block Full block Upper half block

Return The function returns a numeric value representing the cursor shape.

Description SetCursor() specifies the shape of the screen cursor for text mode applications. Passing the va lue zero hides the cursor. A value greater than zero displays the cursor in the corresponding shape. If no parameter is passed, the function returns the current setting.

Info See also: Category: Header: Source: LIB: DLL:

SET CONSOLE, SET CURSOR, SET(), SETCOLOR(), SetPos() Screen functions Setcurs.ch rtl\setcurs.c xhb.lib xhbdll.dll

Example // The example displays all possible cursor shapes by iterating // an array. #include "Inkey.ch" #include "Setcurs.ch" PROCEDURE Main LOCAL nCurrent := 0 LOCAL nOldCursor := SetCursor() LOCAL aNewCursor := { ; { "SC_NONE ", SC_NONE

1132

}, ;

Function Reference

SetCursor() { { { {

"SC_NORMAL ", "SC_INSERT ", "SC_SPECIAL1", "SC_SPECIAL2",

SC_NORMAL SC_INSERT SC_SPECIAL1 SC_SPECIAL2

}, }, }, }

; ; ; }

DO WHILE Lastkey() K_ESC @ 0, 0 IF ++ nCurrent > 5 nCurrent := 1 ENDIF SetCursor( aNewCursor[nCurrent,2] ) ? "Cursor: ", aNewCursor[nCurrent,1] ENDDO RETURN

Function Reference

1133

SetErrorMode()

SetErrorMode() Queries or changes the behavior with operating system errors.

Syntax SetErrorMode( [] ) --> nOldErrorMode

Arguments

This parameter is a numeric value of 0 or 1. Other values are ignored.

Return The function returns a numeric value indicating the previous error mode.

Description Function SetErrorMode() instructs the operating system how an xHarbour application handles errors that occur on the operating system level. For example, when function DiskChange() is called and the specified disk drive has no disk inserted, the operating system would display a message box prompting the user for inserting a disk. To suppress message boxes displayed by the operating system, SetErrorMode(1) must be called. SetErrorMode(0) enables the display of message boxes created by the operating system.

Info See also: Category: Source: LIB: DLL:

1134

DiskChange(), ErrorBlock(), IsDisk() Error functions, xHarbour extensions rtl\errorsys.prg xhb.lib xhbdll.dll

Function Reference

SetKey()

SetKey() Associates a code block with a key

Syntax SetKey( , [] ) --> bOldCodeblock

Arguments

This is a numeric value representing the key code of the key to associate with. The key code is returned by the Inkey() function. To specify values for this parameter use #define constants from the file INKEY.CH.

This parameter optionally specifies a code block to be executed when the key is pressed. Passing NIL explicitely for releases a previously assigned code block.

Return The function returns the code block associated with before SetKey() is called. If no code block is associated with the key, the return value is NIL.

Description SetKey() queries or changes associations between key codes and code blocks. When a code block is associated with a key and the user presses this key, the code block is automatically executed during a wait state. An application enters a wait state when user input is requested. This includes functions like AChoice(), Browse(), DbEdit(), MemeoEdit() and commands like ACCEPT, INPUT, READ and WAIT, but it does not include the Inkey() function. Inkey() does not monitor key/code block associations. The associated code block receives three parameters: the return values of functions ProcName(), ProcLine() and ReadVar(). When an application starts, the F1 key is automatically associated with a code block calling the userdefined function or procedure named Help, if it exists.

Info See also: Category: Header: Source: LIB: DLL:

Eval(), Inkey(), SET KEY Environment functions inkey.ch rtl\setcurs.c xhb.lib xhbdll.dll

Example // // // //

The example implements function SetKeys() which accepts a two column array holding data for key/code block associations. Passing the array for the first time, activates the associations. Passing it a second time, releases them.

Function Reference

1135

SetKey() #include "Inkey.ch" PROCEDURE Main LOCAL cString := "Testing SetKey()" LOCAL aKey := { ; { K_F2, {|c1,n,c2| F2_Key(c1,n,c2) } }, ; { K_F3, {|c1,n,c2| F3_Key(c1,n,c2) } } ; } CLS // associate keys with code blocks SetKeys( aKey ) @ 10,10 SAY "Press F1, F2 or F3" GET cString READ // release code block associations SetKeys( aKey ) RETURN

PROCEDURE Help( cProcName, nProcLine, cReadVar ) LOCAL cScreen := SaveScreen() LOCAL bBlock := SetKey( K_F1, NIL ) // no recursive calls CLS ? "Help routine" ? "Called from:", cProcName, nProcLine, cReadVar WAIT SetKey( K_F1, bBlock ) Restscreen(,,,, cScreen ) RETURN

PROCEDURE F2_Key( cProcName, nProcLine, cReadVar ) LOCAL cScreen := SaveScreen() LOCAL bBlock := SetKey( K_F2, NIL ) // no recursive calls CLS ? "F2 key pressed" ? "Called from:", cProcName, nProcLine, cReadVar WAIT SetKey( K_F2, bBlock ) Restscreen(,,,, cScreen ) RETURN

PROCEDURE F3_Key( cProcName, nProcLine, cReadVar ) LOCAL cScreen := SaveScreen() LOCAL bBlock := SetKey( K_F3, NIL ) // no recursive calls CLS ? "F3 key pressed" ? "Called from:", cProcName, nProcLine, cReadVar WAIT SetKey( K_F3, bBlock ) Restscreen(,,,, cScreen ) RETURN

PROCEDURE SetKeys( aKeys ) LOCAL i, imax := Len( aKeys ) FOR i:=1 TO imax

1136

Function Reference

SetKey() aKeys[i,2] := SetKey( aKeys[i,1], aKeys[i,2] ) NEXT RETURN

Function Reference

1137

SetLastError()

SetLastError() Sets a numeric value as last error code.

Syntax SetLastError( ) --> nOldErrorCode

Arguments

This is the numeric value specifying the new return value of function GetLastError().

Return The function returns the current error code of GetLastError().

Description SetLastError() is used to void any previous error code returned by GetLastError() before a DLL function is executed. Normally, the function is called with the parameter 0, which means "no error". If GetLastError() returns a value 0 when the DLL function has returned, a programmer can be sure that the error occured within this DLL function.

Info See also: Category: Source: LIB: DLL:

1138

DllCall(), GetLastError() DLL functions, xHarbour extensions rtl\dllcall.c xhb.lib xhbdll.dll

Function Reference

SetMode()

SetMode() Changes the size of a console window.

Syntax SetMode( , ) --> lSuccess

Arguments

This is a numeric value specifying the height of a console window. It is the number of rows available for display.

This is a numeric value specifying the width of a console window. It is the number of columns available for display.

Return The function returns .T. (true) if the size of a console window is changed, otherwise .F. (false).

Description SetMode() changes the size of a console window to the specified number of rows and columns. The changed size is reflected by functions MaxRow() and MaxCol(). If the values for or are too large to fit on the screen, they are adjusted. Note: if a console application runs in full screen text mode, there are only a limited number of row/column combinations that can be displayed. This is hardware dependent. Common combinations for the number of rows and columns are: 25,80 | 43,80 | 50,80 | 60,80 | 25,132 | 43,132 | 50,132 | 60,132.

Info See also: Category: Source: LIB: DLL:

MaxCol(), MaxRow() Screen functions rtl\gx.c xhb.lib xhbdll.dll

Example // The example allows for interactively changing the size of a // console window. #include "Inkey.ch" PROCEDURE Main LOCAL nMaxRow := MaxRow() LOCAL nMaxCol := MaxCol() CLS DO WHILE LastKey() K_ESC @ 1,1 SAY "Enter MaxRow:" GET nMaxRow PICTURE "999"

Function Reference

1139

SetMode() @ 2,1 SAY "Enter MaxCol:" GET nMaxCol PICTURE "999" READ CLS IF SetMode( nMaxRow+1, nMaxCol+1 ) ? "New MaxRow()", MaxRow() ? "New MaxCol()", MaxCol() ELSE ? "Unable to set new screen mode" ENDIF WAIT CLS ENDDO RETURN

1140

Function Reference

SetMouse()

SetMouse() Determines the visibility of the mouse cursor.

Syntax SetMouse( [], [], [] ) --> lIsMouseVisible

Arguments

A logical value can be passed. .T. (true) makes the mouse cursor visible and .F. (false) hides it.

A numeric value between 0 and MaxRow() specifying the new row position of the mouse cursor.

A numeric value between 0 and MaxCol() specifying the new columnn position of the mouse cursor.

Return The function returns .T. (true) when the mouse cursor is visible, otherwise .F. (false)

Description SetMouse() is used in full screen or console window applications to show or hide the mouse cursor and optionally move it to a new position on the screen. It combines the functions MSetPos(), MShow() and MHide().

Info See also: Category: Source: LIB: DLL:

Function Reference

NumButtons(), MSetCursor(), MSetPos() Mouse functions rtl\mousex.c xhb.lib xhbdll.dll

1141

SetPos()

SetPos() Changes the position of the screen cursor in text mode.

Syntax SetPos( , ) --> NIL

Arguments

This is a numeric value in the range of 0 to MaxRow(). It specifies the new row position to move the screen cursor to.

This is a numeric value in the range of 0 to MaxCol(). It specifies the new column position to move the screen cursor to.

Return The return value is always NIL.

Description The function SetPos() moves the screen cursor in text mode applications to the specified row and column coordinates. The new position is reflected by the functions Row() and Col(). Use function SetCursor() to change visibility and shape of the cursor. The current screen cursor position is used by console commands and functions which do not recognize screen coordinates as starting point for display.

Info See also: Category: Source: LIB: DLL:

Col(), Row(), SET CURSOR, SetCursor() Screen functions rtl\setpos.c xhb.lib xhbdll.dll

Example // The displays the current positionof the screen cursor, changes it // and displays a string at the new position. PROCEDURE Main CLS ? Row(), Col() SetPos( 13, 30 ) ?? "New output goes here" ? Row(), Col() RETURN

1142

Function Reference

SetPrc()

SetPrc() Changes the PRow() and PCol() values.

Syntax SetPrc( , ) --> NIL

Arguments

This is a numeric value specifying the new return value of function PRow().

A numeric value specifying the new return value of function PCol().

Return The return value is always NIL.

Description SetPrc() is used to programmatically set the return values of functions PRow() and PCol(). Both functions maintain internal counters for monitoring the print head position in console applications when output is directed to the printer, either with SET PRINTER or SET DEVICE. The PCol() value is incremented with every character sent to the printer. If a character string contains non printable characters or printer control codes, the physical print head does not change its position on paper while the internal counter is incremented. In this situation, the internal counter gets out of sync with the actual print head position. The internal counter must then be manually adjusted using SetPrc(). When print output is accomplished using @...SAY, SetPrc() is required to reset PRow() if the new row position is smaller than PRow(). Otherwise, an automatic page eject occurs.

Info See also: Category: Source: LIB: DLL:

PCol(), PRow(), SET DEVICE, Set() Environment functions rtl\console.c xhb.lib xhbdll.dll

Example // // // //

The example implements a user-defined function that sends non-printable characters, or printer control characters, to the printer. The current PRow() and PCol() values are saved before characters are sent, and then restored using SetPrc(). FUNCTION LOCAL LOCAL LOCAL

PrintCtrlCode( cCtrlCode ) lPrint := Set( _SET_PRINTER, .T. ) nRow := PRow() nCol := PCol()

?? cCtrlCode

Function Reference

1143

SetPrc() Set( _SET_PRINTER, lPrint ) RETURN SetPrc( nRow, nCol )

1144

Function Reference

SetRegistry()

SetRegistry() Creates a key/value pair in the registry.

Syntax SetRegistry( , , ,

; ; ; ) --> lSuccess

Arguments

This numeric parameter specifies the root entry in the Windows registry to create a new registry key in. #define constants are available in the Winreg.ch file that can be used for . They begin the the prefix HKEY_.

This is a character string holding the registry path to create in. The path must include a backslash as delimiter, if required, but may neither begin or end with a backslash.

This is a character string holding the name of the registry key to create. It is created directly underneath .

This is a value of data type Character, Date, Logical or Numeric to assign to .

Return The function returns .T. (true), when the specified key/value pair is created in the registry. Otherwise .F. (false) is returned.

Description Function SetRegistry() creates a key/value pair in the Windows registry. If the key exists already, the value is assigned. The value may only be of Valtype() "C", "D", "L" or "N". Other data types are not supported. A Date value is converted with function StoD() an stored as a REG_SZ value in the registry A logical value will be converted to 1 or 0 and set as REG_DWORD.

Winreg.ch Winreg.ch adds quite some overhead to an application program by adding structure definitions. If this is not required, Winreg.ch does not need to be #included. SetRegistry() recognizes the following values for in addition to the HKEY_* #define constants:

Function Reference

1145

SetRegistry()

Registry keys Registry Key

Equivalent value

HKEY_LOCAL_MACHINE HKEY_CLASSES_ROOT HKEY_CURRENT_USER HKEY_CURRENT_CONFIG HKEY_LOCAL_MACHINE HKEY_USERS

0 1 2 3 4 5

Note: on Windows NT, 2000, XP or later, the user may need certain security rights in order to be able to change the registry.

Info See also: Category: Header: Source: LIB: DLL:

QueryRegistry(), GetRegistry() Registry functions, xHarbour extensions Winreg.ch rtl\winreg.prg xhb.lib xhbdll.dll

Example // The example creates a new registry path and fills it with // five new key/value pairs. The new created keys are read from // the registry and displayed. * #include "Winreg.ch" #define HKEY_CURRENT_USER

// not needed for this example 0

// use alternative #define constant

PROCEDURE Main LOCAL nHKey := HKEY_CURRENT_USER LOCAL cRegPath := "SOFTWARE\MyApplication" LOCAL hRegKey := Hash() LOCAL cRegKey hRegKey["Version"] hRegKey["Creationdate"] hRegKey["Demo"] hRegKey["Trialdays"] hRegKey["rootpath"]

:= := := := :=

"1.0" Date() .T. 30 "C:\programs\myapp\"

HEval( hRegKey, ; {|cKey, xVal| SetRegistry( nHKey, cRegPath, cKey, xVal ) ; } ) FOR EACH cRegKey IN hRegKey:keys ? cRegKey, "=", GetRegistry( nHKey, cRegPath, cRegKey ) NEXT RETURN

1146

Function Reference

SoundEx()

SoundEx() Converts a character string using the Soundex algorithm.

Syntax SoundEx( ) --> cSoundex

Arguments

This is a character string to convert.

Return The functions returns a soundex string. It begins with a letter, followed by three digits.

Description SoundEx() converts a character string applying the Soundex algorithm. This algorithm compares letters according to their phonetic similarity, so that words with similar phonetics, but different spelling, may yield the same soundex string. This is used to detect misspelled words, or to index database fields by phonetic similarity. Note that the Soundex algorithm works only with 7bit letters and is case insensitive. It is developed for the English language and may not work with other languages that use special characters in their alphabet.

Info See also: Category: Source: LIB: DLL:

Function Reference

DbSeek(), INDEX, OrdWildSeek(), SET SOFTSEEK Character functions, Conversion functions rtl\soundex.c xhb.lib xhbdll.dll

1147

Space()

Space() Returns a string consisting of blank spaces.

Syntax Space( ) --> cSpaces

Arguments

This is a numeric value specifying the number of blank spaces to return.

Return The function returns a character string consisting of blank spaces (Chr(32)). If is smaller than 1, the return value is an empty string ("").

Description Space() is a specialized form of Replicate() that replicates the blank space (chr(32)) times and returns the result string. Space() is commonly used to initialize variables with a character string buffer that has no content but blank spaces.

Info See also: Category: Source: LIB: DLL:

1148

PadC() | PadL() | PadR(), Replicate() Character functions rtl\space.c xhb.lib xhbdll.dll

Function Reference

Sqrt()

Sqrt() Calculates the square root of a positive number

Syntax SQrt( ) --> nSquareRoot

Arguments

This is a positive numeric value to compute the square root for.

Return The function returns the square root of as a numeric value.

Description The function calculates the square root of a positive number to double precision. When the result is output, the number of decimal places displayed depends on SET DECIMALS and SET FIXED. Note that the displayed decimals may be rounded for display which does not affect numeric precision in calculations.

Info See also: Category: Source: LIB: DLL:

Exp(), Log(), SET DECIMALS, SET FIXED Mathematical functions, Numeric functions rtl\math.c xhb.lib xhbdll.dll

Example // The example displays various results of SQrt() PROCEDURE Main SET DECIMALS TO 6 ? SQrt(0.2) ? SQrt(2.0) ? SQrt(200) ? SQrt(9) ? SQrt(9) ^ 2 RETURN

Function Reference

// Result: 0.447214 // Result: 1.414214 // Result: 14.142136 // Result: // Result:

3.000000 9.000000

1149

StartThread()

StartThread() Starts a new thread.

Syntax StartThread( || ; [,] ) --> pThreadHandle or StartThread( , | ; [,] ) --> pThreadHandle

Arguments

This is a code block to be executed in the new thread.

This is a character string holding the symbolic name of a function or procedure to be executed in the new thread.

Instead o a function orprocedure name, the pointer to a function or procedure can be specified. It can be obtained using function HB_FuncPtr().

If the first parameter is an object (Valtype()=="O"), the second parameter specifies the method to execute in the new thread.

This is a character string holding the symbolic name of the method of to be executed.

This is a pointer to the method to be executed. It can be obtained using function HB_ObjMsgPtr().

An optional, comma separated list of values to be passed as parameters to a code block, function, procedure or method can be specified with .

Return The function returns a handle to the started thread.

Description StartThread() is the only function in xHarbour that creates a new thread, and assigns to it the program code to be executed in the new thread. An application begins execution always with one thread, the Main thread, from where new threads can be spawned. When an application uses multiple threads, the program code specified for a particular thread runs parallel with program code assigned to other 1150

Function Reference

StartThread()

threads. The simultaneous execution of program code in multiple threads is the task of the operating system which grants CPU access for different threads on its own behalf. Function StartThread() assigns the program code to execute in a new thread to the operating system. This can be a function, procedure, code block or the method of an object. These possibilities are covered by the parameters accepted by StartThread(). In addition, all values specified with are passed on to the routine defined for the new thread when the operating system starts with thread execution. When StartThread() returns, the new thread may or may not have started to execute the assigned routine. StartThread() merely guarantees that all memory resources are set up for the operating system to run the new thread. Unless an error occurs, the function returns a handle to the new thread. This Thread handle must be preserved for use with other multi-threading functions. The Thread handle is valid as long as the operating systeme executes the thread, i.e. as long as the thread is running. The Thread handle becomes invalid when the operating system terminates the thread. Function IsValidThread() is available to test if a thread is still running.

Notes on Multi-threaded programming A detailed description of "Threads" and "Multi-threaded programming" goes way beyond the scope of this documentation. There are many books available on this topic and many free online resources inform about them (see www.wikipedia.org for a start) A programmer has absolutely no control about WHEN the operating system starts or ends a thread, or WHEN it grants a thread access to the CPU. This fact of parallel program execution rises concurrency issues when two threads access the same memory resources, like a STATIC variable, for example. The value of a STATIC variable is not guaranteed when two threads change its value simultaneously. The thread that had last access to a STATIC variable, determines its value. Concurrency issues for memory resources that may arise in multi-threaded programming can be resolved be means of Mutexes. A Mutex can be locked and freed by one thread. A thread that holds a lock on a Mutex blocks execution of other threads, thus preventing them from accessing the memory recources protected by the Mutex while it is locked. See function HB_MutexCreate() for more information on Mutexes.

Info See also: Category: Source: LIB: DLL:

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), IsValidThread(), JoinThread(), StopThread(), ThreadSleep() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Example // // // //

The example uses a thread to display the time in the upper right corner of the screen while function Browse() is active. The thread is suspended for one second with ThreadSleep(). PROCEDURE Main LOCAL pThread CLS USE Customer pThread := StartThread( "ShowTime", 0, MaxCol()-7 ) Browse()

Function Reference

1151

StartThread() StopThread( pThread ) WaitForThreads() RETURN

PROCEDURE ShowTime( nRow, nCol ) DO WHILE .T. DispOutAt( nRow, nCol, Time() ) ThreadSleep( 1000 ) ENDDO RETURN

1152

Function Reference

StoD()

StoD() Converts a "yyyymmdd" formatted string to a Date value

Syntax StoD( [] ) --> dDate

Arguments

This is an optional character string holding 8 digits to convert to a Date value. The digits are interpreted as year, month and day ( "yyyymmdd" ).

Return The function returns the converted character string as a Date value. If no parameter is passed, or if is an empty string (""), an empty Date value is returned.

Description StoD() converts a DtoS() string back to a Date value. This string contains date information which is independent from country specific Date format settings.

Info See also: Category: Source: LIB: DLL:

CtoD(), Date(), DtoC(), DtoS() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example displays various results of StoD() PROCEDURE Main SET CENTURY ON ? StoD( "20060501" ) ? StoD( "19060521" ) ? StoD() ? StoD("") ? StoD( "ABCDEFG" ) RETURN

Function Reference

// // // // //

result: 05/01/2006 result: 05/21/1906 result: / / result: / / result: / /

1153

StopThread()

StopThread() Stops a thread from outside.

Syntax StopThread( , [] ) --> NIL

Arguments

This is the handle of the thread to stop running. A thread handle is returned from function StartThread().

Optionally, the handle of a Mutex owned by can be passed. This causes NotifyAll() being called when the thread is stopped. All other threads blocked by resume operation when the thread is terminated by the operating system.

Return The return value is always NIL.

Description Function StopThread() sends a thread termination request for to the operating system, and halts the current thread until the requested second thread has finally terminated. If the second thread owns the Mutex , all threads blocked by are notified and resume operation when the thread represented by has ended. Be very cautiuos with StopThread(). This function instructs the operating system to terminate a running second thread defined with . That means, the current thread executing StopThread() can stop a second thread from outside. The result of the second thread is undetermined, since it may be interrupted by the operating system at any programming instruction (the second thread could be terminated by the operating system within a FOR or DO WHILE loop, before a RETURN statement is executed). It is highly recommended to use Mutexes to control the begin and end of a thread when the current thread requires the result of another thread. Important: StopThread() is different from KillThread(). When a thread calls StopThread(), it is suspended until the requested (second) thread has actually ended. KillThread(), in contrast, does not halt the current thread. KillThread() works asynchronously while Stopthread() works synchronously.

Info See also: Category: Source: LIB: DLL:

1154

HB_MutexCreate(), HB_MutexLock(), HB_MutexUnlock(), KillThread(), Notify(), StartThread(), StopThread() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Function Reference

Str()

Str() Converts a numeric value to a character string.

Syntax Str( , [] , [], []

; ; ; ) --> cString

Arguments

A numeric value to convert to a character string.

An optional numeric value specifying the length of the return string, including sign and decimal places.

This is an optional numeric value indicating the number of decimal places to return.

This parameter defaults to .F. (false). When .T. (true) is passed, the returned string has no leading spaces.

Return The function returns formatted as a character string.

Description Str() converts a numeric value to a character string. This is required when numeric values must be concatenated with character strings for formatted display, or when index keys containing Numeric and Character fields must be created. If the length of the return string is specified too small, so that Int() does not fit into the result, Str() returns a string filled with asterisks (*). If only decimal places do not fit entirely, Str() rounds to the requested decimal places. If both, and , are not specified, Str() obtains default values for both optional parameters as follows:

Formatting rules of Str() Numeric value

Length of return string

Field variable Expressions/constants Val() Day() and Month() Year() Recno()

Field length plus decimals Minimum of 10 digits plus decimals Minimum of 3 digits 3 digits 5 digits 7 digits

Function Reference

1155

Str()

Note: the number string is formatted without leading spaces when .T. (true) is specified for the fourth parameter.

Info See also: Category: Source: LIB: DLL:

CStr(), NumToHex(), StrZero(), Transform(), Val() Character functions, Conversion functions rtl\str.c xhb.lib xhbdll.dll

Example // The example demonstrates formatting rules applied by Str() PROCEDURE Main LOCAL nValue := 123.456 ? Str( nValue )

1156

// result:

123.456

? Str( nValue, ? Str( nValue,

1 ) 2 )

// result: * // result: **

? Str( nValue, ? Str( nValue, ? Str( nValue,

3 ) 4 ) 5 )

// result: 123 // result: 123 // result: 123

? ? ? ?

Str( Str( Str( Str(

nValue, nValue, nValue, nValue,

5, 6, 7, 8,

1 2 3 4

) ) ) )

// // // //

result: result: result: result:

? Str( ? Str( ? Str( ? Str( ? Str( RETURN

nValue, nValue, nValue, nValue, nValue,

10, 10, 10, 10, 10,

0 1 2 3 4

) ) ) ) )

// // // // //

result: result: result: result: result:

123.5 123.46 123.456 123.4560 123 123.5 123.46 123.456 123.4560

Function Reference

StrToHex()

StrToHex() Converts a character string to a Hex string.

Syntax StrToHex( , [] ) --> cHexString

Arguments

This is a character string to convert to hexadecimal notation.

Optionally, a character string can be specified that is inserted between the hexadecimal ASCII codes of each character in .

Return The function returns a character string holding the passed value in hexadecimal notation.

Description StrToHex() converts a character string to a Hex formatted character string by converting the ASCII codes of each charater in and collecting them in the return string. The reverse function is HexToStr() which accepts a Hex encoded character string. Note: is provided for formatting purposes of the returned string and to enhance readability. If it is used, the returned string cannot be decoded with HexToStr().

Info See also: Category: Source: LIB: DLL:

CStr(), HexToNum(), HexToStr(), NumToHex(), Transform() Character functions, Conversion functions, xHarbour extensions rtl\hbhex2n.c xhb.lib xhbdll.dll

Example // The example demonstrates return values of StrToHex() without // and with separating character PROCEDURE Main LOCAL cString := "xHarbour" ? StrToHex( cString ) ? StrToHex( cString, "|" ) RETURN

Function Reference

// result: 78486172626F7572 // result: 78|48|61|72|62|6F|75|72

1157

StrTran()

StrTran() Searches and replaces characters within a character string or memo field.

Syntax StrTran( , , [] , [] , []

; ; ; ; ) --> cNewString

Arguments

This parameter is the input string or memo field to search in.

This is the character string to search for in .

A character string is replaced with in . It defaults to an empty string (""), i.e. if is not specified, is removed from .

This is a numeric value indicating the first occurrence of to replace. The default value is 1.

This is a numeric value indicating the number of occurrences of to replace. If not specified, all occurrences of are replaced.

Return The function returns a copy of where is replaced with .

Description StrTran() is a powerful search and replace function used to modify character strings. The function searches in the input string and replaces it with the replacement string. If and are not specified, all occurrances of are replaced. The search and replacement strings do not need to have the same length.

1158

Function Reference

StrTran()

Info See also: Category: Source: LIB: DLL:

At(), HardCR(), MemoTran(), RAt(), Stuff(), SubStr() Character functions rtl\strtran.c xhb.lib xhbdll.dll

Example // // // //

The example shows various possibilities for StrTran() usage. It begins with simple character search and replacements. At the end, StrTran() is used to create a macro expression that creates an array from a character string. PROCEDURE Main LOCAL cString := "a,BBB,cccc" LOCAL aArray ? StrTran( cString, "B" )

// result: a,,cccc

? StrTran( cString, "B", "b", 2 )

// result: a,Bbb,cccc

? StrTran( cString, "c", "C", 2 , 2 )

// result: a,BBB,cCCc

aArray := &( '{"' + StrTran( cString, ',', '","' ) + '"}' ) ? aArray[1] ? aArray[2] ? aArray[3] RETURN

Function Reference

// result: a // result: BBB // result: cccc

1159

StrZero()

StrZero() Converts a numeric value to a character string, padded with zeros.

Syntax StrZero( , [], [] ) --> cString

Arguments

A numeric value to convert to a character string.

An optional numeric value specifying the length of the return string, including sign and decimal places.

This is an optional numeric value indicating the number of decimal places to return.

Return The function returns formatted as a character string, padded with zeros.

Description StrZero() converts a numeric value to a character string. This is required when numeric values must be concatenated with character strings for formatted display, or when index keys containing Numeric and Character fields must be created. If the length of the return string is specified too small, so that Int() does not fit into the result, StrZero() returns a string filled with asterisks (*). If only decimal places do not fit entirely, StrZero() rounds to the requested decimal places. If both, and , are not specified, StrZero() obtains default values for both optional parameters as follows:

Formatting rules of StrZero()

1160

Numeric value

Length of return string

Field variable Expressions/constants Val() Day() and Month() Year() Recno()

Field length plus decimals Minimum of 10 digits plus decimals Minimum of 3 digits 3 digits 5 digits 7 digits

Function Reference

StrZero()

Info See also: Category: Source: LIB: DLL:

Str(), Transform(), Val() Conversion functions, Character functions rtl\strzero.c xhb.lib xhbdll.dll

Example // The example demonstrates formatting rules applied by StrZero() PROCEDURE Main LOCAL nValue := 123.456 ? StrZero( nValue )

// result: 0000000123.456

? ? ? ? ?

StrZero( StrZero( StrZero( StrZero( StrZero(

nValue, nValue, nValue, nValue, nValue,

1 2 3 4 5

) ) ) ) )

? ? ? ?

StrZero( StrZero( StrZero( StrZero(

nValue, nValue, nValue, nValue,

5, 6, 7, 8,

1 2 3 4

nValue := - 123.456 ? StrZero( nValue, 10, ? StrZero( nValue, 10, ? StrZero( nValue, 10, ? StrZero( nValue, 10, ? StrZero( nValue, 10, RETURN

Function Reference

) ) ) )

0 1 2 3 4

) ) ) ) )

// // // // //

result: result: result: result: result:

* ** 123 0123 00123

// // // //

result: result: result: result:

123.5 123.46 123.456 123.4560

// // // // //

result: result: result: result: result:

-000000123 -0000123.5 -000123.46 -00123.456 -0123.4560

1161

Stuff()

Stuff() Deletes and/or inserts characters in a string.

Syntax Stuff( , , , ) --> cNewString

Arguments

This parameter is the input string to modify.

This is a numeric value specifying the position of the first character in to begin the operation with.

This is a numeric value specifying the number of characters to delete, beginning at position , before is inserted into .

This is a character string to insert into at position . Its length can be smaller or larger than .

Return The function returns a modified copy of .

Description Stuff() modifies an input string by first deleting characters and then inserting the replacement string . Since can be in the range of 0 to Len() and can be any character string, including an empty string (""), the function can perform the operations Delete, Insert, Replace or a combination of them. Unlike function StrTran(), which searches a substring, Stuff() uses a numeric start position to perform the character string operation.

Info See also: Category: Source: LIB: DLL:

At(), Left(), RAt(), Right(), StrTran(), SubStr() Character functions rtl\stuff.c xhb.lib xhbdll.dll

Example // The example demonstrates the different character string operations // that can be performed with Stuff() PROCEDURE Main LOCAL cString := "1234567"

1162

Function Reference

Stuff() // Delete ? Stuff( cString, 3, 2, "" )

// result: 12567

// Insert ? Stuff( cString, 3, 0, "abc" )

// result: 12abc34567

// Replace ? Stuff( cString, 3, 2, "ab" )

// result: 12ab567

// Replace and delete ? Stuff( cString, 3, 4, "ab" )

// result: 12ab7

// Replace and insert ? Stuff( cString, 3, 2, "abcde" ) // result: 12abcde567 // Replace and delete rest ? Stuff( cString, 3, 6, "abc" )

// result: 12abc

RETURN

Function Reference

1163

Subscribe()

Subscribe() Subscribes for notifications on a Mutex.

Syntax Subscribe( , ; , ; [@] ) --> xReturn

Arguments

This is the handle of the Mutex to subscribe, or listen, to. A mutex handle is returned by HB_MutexCreate().

A numeric value specifying the maximum period of time to wait before the function returns when there is no notification on the Mutex. The unit for this value is 1/1000th of a second. If is omitted, the current thread waits infinitely for a notification, i.e. the function does not return until a notification is received. @

When this parameter is passed by reference, it is assigned .T. (true) or .F. (false). True is assigned, when the thread executing Subscribe() is notified within the timeout period of from the thread that has locked the Mutex .

Return The function returns NIL, unless the thread which calls Notify() on the Mutex passes a second parameter to Notify(). This second parameter is returned by Subscribe().

Description Function Subscribe() is the counterpart of Notify(), or NotifyAll(), respectively. The functions are used to control concurrent program execution between two ore more threads. The functions Notify() and Subscribe() can only be called in two different threads and require a common Mutex to operate on. When a thread "A" calls SubScribe() with the Mutex , this thread "A" is suspended for a time period of . Specifying nothing for the timeout period suspends thread "A" until another thread "B" calls Notify(). When thread "B" calls Notify() or NotifyAll() during the time period of on the same Mutex , thread "A" resumes program execution. As a result, function Subscribe() puts the current thread on hold until a second thread notifies the Mutex , or the timeout period has expired. The timeout never expires when is omitted, i.e. the current thread resumes only if the Mutex is notified by a second thread. The parameter must be passed by reference to detect if the current thread resumes as a result of a notification by a second thread (==.T.) or due to the expiration of the timeout period of (==.F.).

1164

Function Reference

Subscribe()

When thread "A" calls Subscribe() and thread "B" calls Notify(), the second parameter passed to Notify() in thread "B" defines the return value of Subscribe() in thread "A". That is, thread "B" can pass a value to thread "A" via the Subscribe()/Notify() protocol. All that is required is a Mutex which is subscribed to in thread "A", and notified in thread "B".

Info See also: Category: Source: LIB: DLL:

Function Reference

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), Notify(), NotifyAll(), StartThread(), SubscribeNow() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

1165

SubscribeNow()

SubscribeNow() Subscribes for notifications on a Mutex and discards pending notifications.

Syntax SubscribeNow( , ; , ; [@] ) --> xReturn

Arguments

This is the handle of the Mutex to subscribe, or listen, to. A mutex handle is returned by HB_MutexCreate().

A numeric value specifying the maximum period of time to wait before the function returns when there is no notification on the Mutex. The unit for this value is 1/1000th of a second. If is omitted, the current thread waits infinitely for a notification, i.e. the function does not return until a notification is received. @

When this parameter is passed by reference, it is assigned .T. (true) or .F. (false). True is assigned, when the thread executing SubscribeNow() is notified within the timeout period of from the thread that has locked the Mutex .

Return The function returns NIL, unless the thread which calls Notify() on the Mutex passes a second parameter to Notify(). This second parameter of Notify() is returned by SubscribeNow().

Description Function SubscribeNow() is used in the same way as Subscribe(). The only difference is that SubscribeNow() voids all possibly pending notifications that may have been issued on while SubscribeNow() is being executed. This guarantees that the current thread is put on hold until another thread notifies the Mutex after SubscribeNow() has returned. Refer to Subscribe() for detailed information on the SubScribe()/Notify() protocol.

Info See also: Category: Source: LIB: DLL:

1166

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), HB_MutexLock(), Notify(), StartThread(), Subscribe() Multi-threading functions, Mutex functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

Function Reference

SubStr()

SubStr() Extracts a substring from a character string.

Syntax SubStr( , , [] ) --> cSubstring

Arguments

This parameter is the input string to extract a substring from.

This is a numeric value specifying the first character of to include in the extracted string. If is a positive number, the function extracts from the beginning, or the left side, of . If is a negative number, the function extracts from the end, or the right side, of .

This is a numeric value specifying the number of characters to extract, beginning at position . If omitted, all characters from to the end of are extracted.

Return The function returns the extracted character string.

Description SubStr() is a versatile function for extracting parts of a character string beginning at the position . It is similar to functions Left() and Right(), but can extract a substring from the middle of the input string. SubStr() is often used in conjunction with At() and RAt() to find the starting position of the substring to extract.

Info See also: Category: Source: LIB: DLL:

At(), HB_ATokens(), HB_RegEx(), Left(), RAt(), Right(), Str(), StrTran(), Stuff() Character functions rtl\substr.c xhb.lib xhbdll.dll

Example // The example demonstrates extraction of substrings and how // SubStr() relates to Left() and Right(). PROCEDURE Main LOCAL cString := "www.xHarbour.com" ? SubStr( cString, 5 ) ? SubStr( cString, 5, 8 )

// result: xHarbour.com // result: xHarbour

? SubStr( cString, 1, 3 ) ? Left( cString, 3 )

// result: www // result: www

Function Reference

1167

SubStr() ? SubStr( cString, -3, 3 ) ? Right( cString, 3 ) RETURN

1168

// result: com // result: com

Function Reference

TBMouse()

TBMouse() Moves the browse cursor to the mouse pointer.

Syntax TBMouse( , , ) --> nHandled

Arguments

This parameter must be a TBrowse() object.

A numeric value between 0 and MaxRow() specifying the row position of the mouse cursor. It can be queried using MRow().

A numeric value between 0 and MaxCol() specifying the columnn position of the mouse cursor. It can be queried using MCol().

Return The function returns 0 when the browse cursor was successfully moved to the screen coordinates passed for the mouse pointer. Otherwise, the return value is 1.

Description TBMouse() is a utiliy function for implementing "mouse awareness" for TBrowse objects. When the mouse pointer is located within the data area of a TBrowse object, the function calls navigation methods of the object until the browse cursor is located underneath the screen coordinates specified with and . A call to TBMouse() is standard behavior for TBrowse():applyKey().

Info See also: Category: Source: LIB: DLL:

Function Reference

MCol(), MRow(), TBrowse() Mouse functions, xHarbour extensions rtl\tbrowse.prg xhb.lib xhbdll.dll

1169

TBrowseDB()

TBrowseDB() Creates a new TBrowse object to be used with a database.

Syntax TBrowseDB( [] , [] , [], []

; ; ; ) --> oTBrowse

Arguments and

Numeric values indicating the screen coordinates for the upper left corner of the TBrowse() window. The default value for both parameters is zero.

Numeric value indicating the bottom row screen coordinate. It defaults to MaxRow().

Numeric value indicating the right column screen coordinate. It defaults to MaxCol().

Return TBrowseDB() returns new TBrowse object with the specified coordinate and a default :skipBlock, :goTopBlock and :goBottomBlock to browse a database.

Description TBrowseDB() is a quick way to create a TBrowse object along with the minimal support needed to browse a database. Note that the returned TBrowse object contains no TBColumn objects. They must be added for each field to display in the browse window.

Info See also: Category: Source: LIB: DLL:

Browse(), DbEdit(), TBColumn(), TBrowse(), TBrowseNew() Object functions rtl\tbrowse.prg xhb.lib xhbdll.dll

Example // The example builds a simple TBrowse object for a database #include "TBrowse.ch" PROCEDURE Main LOCAL oTBrowse, aFields, cField, nKey USE Customer aFields := Array( FCount() ) AEval( aFields, {|x,i| aFields[i] := FieldName(i) } )

1170

Function Reference

TBrowseDB() oTBrowse := TBrowseDB() WITH OBJECT oTBrowse FOR EACH cField IN aFields :addColumn( TBColumnNew( cField, FieldBlock( cField ) ) ) NEXT END DO WHILE .T. oTBrowse:forceStable() nKey := Inkey(0) IF oTBrowse:applyKey( nKey ) == TBR_EXIT EXIT ENDIF ENDDO CLOSE Customer RETURN

Function Reference

1171

TBrowseNew()

TBrowseNew() Creates a new TBrowse object.

Syntax TBrowseNew( [] , [] , [], []

; ; ; ) --> oTBrowse

Arguments

This is the numeric screen coordinate for the top row of the browse display. It defaults to zero and is assigned to the instance variable :nTop.

This is the numeric screen coordinate for the left column of the browse display. It defaults to zero and is assigned to the instance variable :nLeft.

This is the numeric screen coordinate for the bottom row of the browse display. It defaults to MaxRow() and is assigned to the instance variable :nBottom.

This is the numeric screen coordinate for the right column of the browse display. It defaults to MaxCol() and is assigned to the instance variable :nRight.

Return Function TBrowseNew() returns a new, initialized TBrowse object.

Description Function TBrowseNew() is the functional equivalent of TBrowse():new(). Refer to the description of the Tbrowse object.

Info See also: Category: Source: LIB: DLL:

1172

TBrowse() Object functions rtl\tbrowse.prg xhb.lib xhbdll.dll

Function Reference

ThreadSleep()

ThreadSleep() Puts a thread to sleep.

Syntax ThreadSleep( , [] ) --> NIL

Arguments

This is a numeric value indicating the period of time to suspend the current thread. The unit is 1/1000th of a second.

The parameter defaults to .F. (false) so that the thread resumes after have elapsed. When set to .T. (true), the thread resumes when a new event is placed into the thread's message queue on the operating system level. During this stage, the thread consumes no CPU resources.

Return The function returns always NIL.

Description Function ThreadSleep() is used to suspend the current thread for a defined period of time. This is useful, for example, when a thread should check some status variables periodically and process data only if the status has changed. If the second parameter is set to .T. (true), the thread ignores an resumes only after a message is put into the thread's message queue by the operating system. Note: this function is also available in single threaded applications.

Info See also: Category: Source: LIB: DLL:

Function Reference

Inkey(), SecondsSleep(), StartThread(), WAIT Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

1173

Throw()

Throw() Throws an exception.

Syntax Throw( ) --> NIL

Arguments

This parameter must be an Error() object.

Return The return value is NIL.

Description Function Throw() is part of xHarbour's error handling system and is used in conjunction with a TRY...CATCH statement. The error object passed to Throw() is forwarded to the CATCH option, if present. There, the information stored in the error object can be evaluated for error handling.

Info See also: Category: Source: LIB: DLL:

1174

BEGIN SEQUENCE, Error(), ErrorBlock(), ErrorNew(), TRY...CATCH Error functions, Debug functions, xHarbour extensions vm\throw.c xhb.lib xhbdll.dll

Function Reference

Time()

Time() Retrieves the system time as a formatted character string.

Syntax Time() --> cHHMMSS

Return The function returns a character string containing the system time formatted as hh:mm:ss.

Description Time() is used to obtain a time formatted character string containing hours, minutes and seconds of a 24h clock.

Info See also: Category: Source: LIB: DLL:

AmPm(), Date(), Seconds(), SubStr() Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example shows the results of Time() and how to extract // hour, minutes, and seconds PROCEDURE Main LOCAL cTime := Time() LOCAL cHour, cMin, cSec ? cTime // Result: 13:27:47 cSec := Right ( cTime, 2 ) cMin := SubStr( cTime, 3, 2 ) cHour := Left ( cTime, 2 ) ? Val( cHour ) * 3600 + Val( cMin ) * 60 + Val( cSec ) // result: 48467.00 RETURN

Function Reference

1175

Tone()

Tone() Sounds a speaker tone with specific tone frequency and duration.

Syntax Tone( , [] ) --> NIL

Arguments

This is a positive numeric value specifying the frequency of the tone.

This is a positive numeric value specifying the duration of the tone in units of 1/18th of a second.

Return The function returns always NIL.

Description Tone() is a compatibility function used to produce a speaker tone of defined frequency and duration.

Info See also: Category: Source: LIB: DLL:

Chr(), SET BELL Environment functions rtl\tone.c xhb.lib xhbdll.dll

Example // The example shows a user-defined function that alerts a user // when an error condition occurs. FUNCTION ErrorBeep() Tone( 1000, 1 ) Tone( 1000, 2 ) RETURN NIL

1176

Function Reference

TraceLog()

TraceLog() Traces and logs the contents of one or more variables.

Syntax TraceLog( ) --> lTrue

Arguments

This is a comma separated list of variables to trace during program execution.

Return The function returns .T. (true).

Description The TraceLog() function traces and logs the contents of one or more variables in the trace log file. Each time TraceLog() is called, a new entry is added to the log file. To suppress output of the function SET TRACE must be set to OFF.

Info See also: Category: Source: LIB: DLL:

AltD(), SET ERRORLOG, SET TRACE Debug functions, xHarbour extensions rtl\traceprg.prg xhb.lib xhbdll.dll

Example // This example logs the contents of three variables in the trace.log file. The // log contains type and value of the variables as well as the line number, // procedure and source file where the trace was executed. PROCEDURE Main() LOCAL xValue1 := 1 LOCAL xValue2 := 1 LOCAL xValue3 := 1 TraceLog( xValue1, xValue2, xValue3 ) xValue1 := 2 xValue2 := 33 xValue3 := xValue1 + xValue2 TraceLog( xValue1, xValue2, xValue3 ) xValue1 := Str(++xValue1) xValue2 := 33 xValue3 := xValue2++ TraceLog( xValue1, xValue2, xValue3 ) MemoEdit( Memoread( "Trace.log" ) ) RETURN

Function Reference

1177

Transform()

Transform() Converts values to a PICTURE formatted character string.

Syntax Transform( , ) --> cFormattedString

Arguments

This is a value of data type Character, Date, Logic, Memo or Numeric to be formatted.

This is a PICTURE formatting string defining the formatting rules (see below).

Return The function returns a character string holding the formatted value of .

Description Transform() is used to convert values of simple data types (C,D,L,M,N) to formatted character strings. Formatting rules are defined with the second parameter . This picture string may consist of characters defining a picture function, or characters defining a picture mask, or both. If picture function and mask are present in the picture string, the picture function must be first and the mask characters must be separated from the picture function by a single blank space.

Picture function A picture function specifies formatting rules for the entire output string. It must begin with the @ sign followed by one or more letters listed in the table below:

Picture function characters Function

Formatting rule

B C D E L R X Z ( !

Formats numbers left-justified Adds CR (credit) after positive numbers Formats dates in SET DATE format Formats dates and numbers in British format Pads numbers with zeros instead of blank spaces Nontemplate characters are inserted Adds DB (debit) after negative numbers Formats zeros as blanks Encloses negative numbers in parentheses Converts alphabetic characters to uppercase

Picture mask The picture mask must be separated by a single space from the picture function. When no picture function is used, the picture string is identical with the picture mask. The mask defines formatting rules for individual characters in the output string. Characters from the following table can be used. The position of a character of a picture mask specifies formatting for the character of the output string at the 1178

Function Reference

Transform()

same position. An exception is the @R function which causes non-mask characters being inserted into the output string.

Picture mask characters Charactere

Formatting rule

A,N,X,9,# L Y ! $ * . ,

Formats digits for any data type Formats logicals as "T" or "F" Formats logicals as "Y" or "N" Converts alphabetic characters to uppercase Adds a dollar sign in place of a leading space in a number Adds an asterisk in place of a leading space in a number Specifies a decimal point position Specifies a comma position

Info See also: Category: Source: LIB: DLL:

@...SAY, DtoC(), Lower(), PadC() | PadL() | PadR(), Str(), Upper(), Val() Conversion functions rtl\transfrm.c xhb.lib xhbdll.dll

Example // The example demonstrates different formatting results of Transform() PROCEDURE Main LOCAL nGain LOCAL nLoss LOCAL cPhone LOCAL cName

:= := := :=

8596.58 -256.50 "5558978532" "Jon Doe"

? Transform( 8596.58, "@E 9,999.99" )

// result: 8.596,58

? Transform( 8596.58, "999,999.99" ) // result: 8,596.58 ? Transform( 8596.58, "@L 999,999.99" ) // result: 008,596.58 ? Transform( -256.50, "@)" )

// Result: (256.50)

? Transform( "5558978532", "@R (999)999-9999" ) // Result: (555)897-8532 ? Transform( "xharbour", "@!" ) ? Transform( "xharbour", "A!AAAAAA" ) RETURN

Function Reference

// Result: XHARBOUR // Result: xHarbour

1179

Trim()

Trim() Removes trailing blank spaces from a character string.

Syntax Trim( [,] ) --> cTrimmedString RTrim( [,] ) --> cTrimmedString

Arguments

A character string which is copied without trailing blank space characters.

This parameter defaults to .F. (false). If .T. (true) is passed, function Trim() treats the whitespace characters TAB (Chr(9)) and CRLF (Chr(13)+Chr(10)) like blank spaces and removes them as well.

Return The function returns a copy of without blank spaces at the end of the string.

Description Trim() is used for formatting character strings whose ending characters consist of blank spaces (Chr(32)). The function creates a copy of but ignores blank spaces at the end of the input string. It is frequently used to format character strings stored in database fields. Such strings are padded with blank paces up to the field length. Note() function RTrim() is a synonym for Trim().

Info See also: Category: Source: LIB: DLL:

Alltrim(), LTrim(), PadC() | PadL() | PadR(), SubStr() Character functions rtl\trim.c xhb.lib xhbdll.dll

Example // The example shows various possibilities for trimming a string. #define CRLF

Chr(13)+Chr(10)

PROCEDURE Main LOCAL cStr := " ? ? ? ?

Len( Len( Len( Len(

cStr ) LTrim( cStr ) ) Trim ( cStr ) ) AllTrim( cStr ) )

cStr := "xHarbour

1180

xHarbour

" // // // //

result: result: result: result:

14 12 10 8

" + CRLF

Function Reference

Trim() ? Len( cStr ) ? Len( Trim( cStr ) ) ? Len( Trim( cStr, .T. ) )

// result: // result: // result:

12 12 8

RETURN

Function Reference

1181

TString()

TString() Converts numeric seconds into a time formatted character string.

Syntax TString( ) --> cTimeString

Arguments

This is a numeric value specifying the number of seconds elapsed since midnight. If is larger than 86400, it is set back to 0.

Return The function returns a character string containing the number of seconds formatted as hh:mm:ss.

Description TString() is used to convert numeric seconds into a time formatted character string containing hours, minutes and seconds of a 24h clock. It is the reverse function of Secs().

Info See also: Category: Source: LIB: DLL:

Days(), ElapTime(), Time(), Seconds(), Secs() Date and time rtl\samples.c xhb.lib xhbdll.dll

Example // The example shows various possibilities of converting seconds // and time strings. PROCEDURE Main LOCAL nSeconds := Seconds() LOCAL cTime := Time() ? nSeconds ? TString( nSeconds ) ? Secs( cTime )

// result: 57816.61 // result: 16:03:36 // result: 57816

? TString( 0 ) ? TString( 60 ) ? TString( 3600 )

// result: 00:00:00 // result: 00:01:00 // result: 01:00:00

? TString( 86399 ) ? TString( 86400 ) ? TString( 86460 ) RETURN

1182

// result: 23:59:59 // result: 00:00:00 // result: 00:01:00

Function Reference

Type()

Type() Determines the data type of a macro expression.

Syntax Type( ) --> cDataType

Arguments

This is a character string holding the name of a dynamic memory variable (PRIVATE or PUBLIC), field variable or an expression.

Return The function returns a character string identifying the data type of when it is evaluated using the macro operator (&) (see description).

Description Type() is used to determine the data type of a macro expression by evaluating or executing it with the macro operator. The expression is most often the name of a dynamic memory variable, or a field variable. Type() can also determine the data type of a macro expression containing function calls. This is restricted, however, to basic functions built into xHarbour which operate on simple data types. If the macro expression contains calls to complex functions or user-defined functions, Type() does not evaluate the macro expression and, thus, cannot determine the data type. The function returns one of the following characters or character strings

Return values of Type() Return value

Data type

A B C D H L M N O P U UE UI

Array Code block Character string Date value Hash Logical value Memo field Numeric value Object Pointer to function or method Undefined symbol or NIL Syntax error in macro expression Data type is indeterminable (macro expression too complex)

Note Type() cannot determine the data type of lexically scoped variables (GLOBAL, LOCAL and STATIC). Use Valtype() for such variables.

Function Reference

1183

Type()

Info See also: Category: Source: LIB: DLL:

Valtype() Debug functions rtl\type.c xhb.lib xhbdll.dll

Example // This example shows all possible return values of Type() PROCEDURE Main PRIVATE aArray PRIVATE bBlock PRIVATE cChar PRIVATE dDate PRIVATE hHash PRIVATE lLogic PRIVATE nNumber PRIVATE oObject PRIVATE pPtr PRIVATE uNIL

:= := := := := := := := := :=

{ 1, 2, 3 } {|x| 1+x } "xHarbour" Date() Hash() .F. 123.45 GetNew() ( @Test() ) NIL

USE Customer ALIAS Cust ? ? ? ? ? ? ? ? ? ? ?

Type( Type( Type( Type( Type( Type( Type( Type( Type( Type( Type(

"aArray" ) "bBlock" ) "cChar" ) "dDate" ) "hHash" ) "lLogic" ) "Cust->notes" ) "nNumber" ) "oObject" ) "pPtr" ) "uNIL" )

// // // // // // // // // // //

result: result: result: result: result: result: result: result: result: result: result:

A B C D H L M N O P U

? ? ? ? ?

Type( Type( Type( Type( Type(

"Val(" ) "Test()" ) "TestFunc()" ) "Date()" ) "oObject:hasFocus()" )

// // // // //

result: result: result: result: result:

UE UI U D L

Test( pPtr, hHash ) ? Type( ? Type( ? Type( ? Type( ? Type( ? Type( ? Type( RETURN

"'A'" ) "A" ) "{1}" ) "{=>}" ) "9" ) ".F." ) "IIf(.T.,'A',1)" )

// result: P H // // // // // // //

result: result: result: result: result: result: result:

C U A H N L C

PROCEDURE Test PARAMETERS p1, p2 ? Type( "p1" ), Type( "p2" ) RETURN

1184

Function Reference

U2bin()

U2bin() Converts a numeric value to an unsigned long binary integer (4 bytes).

Syntax U2bin( ) --> cInteger

Arguments

A numeric value in the range of 0 to +(2^32)-1.

Return The function returns a four-byte character string representing a 32-bit unsigned long binary integer.

Description U2bin() is a binary conversion function that converts a numeric value (Valtype()=="N") to a four-byte binary number (Valtype()=="C"). The range for the numeric return value is determined by an unsigned long integer. If is outside this range, a runtime error is raised. U2bin() is the inverse function of Bin2U().

Info See also: Category: Source: LIB: DLL:

Asc(), Bin2i(), Bin2l(), Bin2u(), Bin2w(), Chr(), I2bin(), L2bin(), W2bin(), Word() Binary functions, Conversion functions rtl\binnumx.c xhb.lib xhbdll.dll

Example // The example demonstrates return values of U2bin(). PROCEDURE Main LOCAL c c := U2bin(0) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 0 0 0 c := U2bin(1) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 1 0 0 0 c := U2bin(256) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 1 0 0 c := U2bin(65536) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 1 0 0

Function Reference

1185

U2bin() c := U2bin(2147483648) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 0 0 0 128 c := U2bin(4294967295) ? Asc(c[1]), Asc(c[2]), Asc(c[3]), Asc(c[4]) // 255 255 255 255 RETURN

1186

Function Reference

Upper()

Upper() Converts a character string to uppercase.

Syntax Upper( ) --> cUpperCaseString

Arguments

A character string to convert to uppercase letters.

Return The return value is a character string containing only uppercase letters.

Description The character function Upper() copies the passed string, replaces all lowercase letters with uppercase letters and returns the result. It is related to function Lower() wich converts a string to lowercase letters. Both functions are used for case-insensitive string routines.

Info See also: Category: Source: LIB: DLL:

IsLower(), IsUpper(), Lower() Character functions rtl\strcase.c xhb.lib xhbdll.dll

Example // The example demonstrates various results of Upper() PROCEDURE Main ? Upper( "xHARbOUR" ) ? Upper( "123 ABC - def" )

// result: XHARBOUR // result: 123 ABC - DEF

RETURN

Function Reference

1187

Used()

Used() Determines if a database file is open in a work area.

Syntax Used() --> lIsUsed

Return The function returns .T. (true) if a database file is open in a specified work area, otherwise .F. (false) is returned.

Description Used() determines if a database file is open in a work area, i.e. if a work area is "used". If the function is called without the alias operator, it operates in the current work area. The current work area is selected with function DbSelectArea().

Info See also: Category: Source: LIB: DLL:

Alias(), DbSelectArea(), DbUseArea(), SELECT, Select(), USE Database functions, Environment functions rdd\dbcmd.c xhb.lib xhbdll.dll

Example // The shows how to query the Used status of work areas PROCEDURE Main ? Select() ? Used()

// result: 1 // result: .F.

USE Customer ALIAS Cust NEW ? Select() ? Used()

// result: 1 // result: .T.

DbSelectArea( 2 ) ? Select() ? Used()

// result: 2 // result: .F.

? (1)->(Used()) ? (2)->(Used()) ? Cust->(Used())

// result: .T. // result: .F. // result: .T.

CLOSE Cust RETURN

1188

Function Reference

Val()

Val() Convert a character string containing digits to numeric data type

Syntax Val( ) --> nNumber

Arguments

This is a character string containing digits. In addition, it may contain a decimal point and/or sign.

Return The function returns a numeric value as the result of the conversion operation. If does not represent a number, the return value is zero.

Description Val() analyses the parameter which may contain only "+-.0123456789". If contains any other character, a letter, for example, or if a second decimal point is detected, the conversion is terminated and the digits analysed so far are returned as numeric value. Leading blank space characters, however, are ignored. The function recognizes the SET FIXED and SET DECIMALS settings and rounds the number if contains more decimal places than set with SET DECIMAL.

Info See also: Category: Source: LIB: DLL:

Round(), SET DECIMALS, SET FIXED, Str(), Transform() Character functions, Conversion functions rtl\val.c xhb.lib xhbdll.dll

Example // The example shows return values of Val() depending on SET FIXED // and SET DECIMALS PROCEDURE Main SET DECIMALS TO 2 SET FIXED ON ? ? ? ?

Val( "123.456" ) Val(" 123.456") Val( "123*456" ) Val("x123*456" )

? Val( "-123.456" ) ? Val( " -123.456" ) ? Val( "123.456" )

// // // //

result: 123.46 result: 123.46 result: 123.00 result: 0.00

// result: -123.46 // result: -123.46 // result: 0.00

SET DECIMALS TO 3

Function Reference

1189

Val() SET FIXED OFF ? ? ? ?

Val( "123.456" ) Val(" 123.456") Val( "123*456" ) Val("x123*456" )

? Val( "-123.456" ) ? Val( " -123.456" ) ? Val( "123.456" )

// // // //

result: 123.456 result: 123.456 result: 123 result: 0

// result: -123.456 // result: -123.456 // result: 0.000

RETURN

1190

Function Reference

ValToPrg()

ValToPrg() Converts a value to PRG code.

Syntax ValToPrg( ) --> cPRGcode

Arguments

This is a value of any data type.

Return The function returns a character string that can be compiled as PRG code.

Description Function ValToPrg() accepts a value of any data type and returns a character string holding PRG code. The PRG code can be compiled and produces the passed value. This is guaranteed for all data types except Object and Code block, since certain restrictions exist for these data types when they are serialized into a character string. Refer to function HB_Serialize() for more information on these restrictions. Note: if a pointer is passed, the produced PRG code is a Hex number which does not compile to a pointer but to a Numeric value. Pointers are only determined at runtime of an application and cannot be hard coded.

Info See also: Category: Source: LIB: DLL:

CStr(), HB_Serialize(), Valtype(), ValToPrgExp() Conversion functions, xHarbour extensions rtl\cstr.prg xhb.lib xhbdll.dll

Example // The example demonstrates return values of function ValToPrg() // with data types where the function is guaranteed to work. PROCEDURE Main LOCAL aArray LOCAL cString LOCAL dDate LOCAL hHash LOCAL lLogic LOCAL nNumber LOCAL pPointer LOCAL undef ? ? ? ? ?

ValToPrg( ValToPrg( ValToPrg( ValToPrg( ValToPrg(

Function Reference

:= := := := := := := :=

{ 1, 2, 3 } "xHarbour" Date() { "A" => 1, "B" => 2 } .T. 1.2345 ( @Main() ) NIL

aArray cString dDate hHash lLogic

) ) ) ) )

// // // // //

result: result: result: result: result:

{ 1, 2, 3 } "xHarbour" sToD( '20061011' ) { "A" => 1, "B" => .T.

2 }

1191

ValToPrg() ? ValToPrg( nNumber ) ? ValToPrg( pPointer ) ? ValToPrg( undef ) RETURN

1192

// result: 1.2345 // result: 0x4C5000 // result: NIL

Function Reference

ValToPrgExp()

ValToPrgExp() Converts a value to charecter string holding a macro-expression.

Syntax ValToPrgExp( ) --> cMacroExpression

Arguments

This is a value of any data type.

Return The function returns a character string that can be compiled with the macro operator.

Description Function ValToPrgExp() accepts a value of any data type and returns a character string holding a macro-expression. This expression produces the vale when it is compiled with the Macro-operator. This is guaranteed for all data types except Object and Code block, since certain restrictions exist for these data types when they are serialized into a character string. Refer to function HB_Serialize() for more information on these restrictions. Note: if a pointer is passed, the produced PRG code is a Hex number which does not macro-compile to a pointer but to a Numeric value.

Info See also: Category: Source: LIB: DLL:

&, CStr(), HB_Serialize(), Valtype(), ValToPrg() Conversion functions, xHarbour extensions rtl\cstr.prg xhb.lib xhbdll.dll

Example // The example demonstrates return values of function ValToPrgExp() // with data types where the function is guaranteed to work. PROCEDURE Main LOCAL aArray := { 1, 2, 3 } LOCAL cString := "xHb" LOCAL dDate := Date() LOCAL hHash := { "A" => 1, "B" => 2 } LOCAL lLogic := .T. LOCAL nNumber := 1.2345 LOCAL pPointer := ( @Main() ) LOCAL undef := NIL ? ? ? ? ? ?

ValToPrgExp( ValToPrgExp( ValToPrgExp( ValToPrgExp( ValToPrgExp( ValToPrgExp(

Function Reference

aArray cString dDate hHash lLogic pPointer

) ) ) ) ) )

// // // // // //

result: result: result: result: result: result:

{ 1, 2, 3 } Chr(120) + Chr(72) + Chr(98) sToD( '20061011' ) { Chr( 65) => 1, Chr( 66) => 2 } .T. HexToNum('4C5000')

1193

ValToPrgExp() ? ValToPrgExp( undef RETURN

1194

)

// result: NIL

Function Reference

Valtype()

Valtype() Determines the data type of the value returned by an expression.

Syntax Valtype( ) --> cDataType

Arguments

This is an expression of any data type.

Return The function returns a character string identifying the data type of (see description).

Description Valtype() is used to determine the data type of an arbitrary expression, including lexically scoped variables (GLOBAL, LOCAL, STATIC), and (user-defined) functions and methods. Valtype() is more powerful than Type() which determines the data type of macro expressions only. The function returns one of the following characters:

Return values of Valtype() Return value

Data type

A B C D H L M N O P U

Array Code block Character string Date value Hash Logical value Memo field Numeric value Object Pointer to function, procedure or method Undefined symbol or NIL

Note: if any part of does not exist, Valtype() generates a runtime error.

Function Reference

1195

Valtype()

Info See also: Category: Source: LIB: DLL:

Type(), HB_IsArray(), HB_IsBlock(), HB_IsByRef(), HB_IsDate(), HB_IsHash(), HB_IsLogical(), HB_IsMemo(), HB_IsNIL(), HB_IsNull(), HB_IsNumeric(), HB_IsObject(), HB_IsPointer(), HB_IsString() Debug functions, Pointer functions rtl\valtype.c xhb.lib xhbdll.dll

Example // The example shows all possible return values of Valtype() PROCEDURE Main LOCAL aArray LOCAL bBlock LOCAL cChar LOCAL dDate LOCAL hHash LOCAL lLogic LOCAL nNumber LOCAL oObject LOCAL pPtr LOCAL uNIL

:= := := := := := := := := :=

{ 1, 2, 3 } {|x| 1+x } "xHarbour" Date() Hash() .F. 123.45 GetNew() ( @Test() ) NIL

USE Customer ALIAS Cust ? ? ? ? ? ? ? ? ? ? ?

Valtype( Valtype( Valtype( Valtype( Valtype( Valtype( Valtype( Valtype( Valtype( Valtype( Valtype(

aArray ) bBlock ) cChar ) dDate ) hHash ) lLogic ) Cust->notes ) nNumber ) oObject ) pPtr ) uNIL )

// // // // // // // // // // //

result: result: result: result: result: result: result: result: result: result: result:

A B C D H L M N O P U

? Valtype( Date() ) // result: D ? Valtype( oObject:hasFocus() ) // result: L Test( pPtr, hHash )

// result: P H

? Valtype( IIf( .T., "A", 1 ) ) // result: C ? Valtype( "A" ) ? Valtype( A ) RETURN

// result: C // result: runtime error

PROCEDURE Test( p1, p2 ) ? Valtype( p1 ), Valtype( p2 ) RETURN

1196

Function Reference

Version()

Version() Retrieves xHarbour version information.

Syntax Version() --> cVersion

Return The function returns a charcter string holding version information of xHarbour.

Description Version() is an informational function that returns the version of the xHarbour runtime library.

Info See also: Category: Source: LIB: DLL:

HB_BuildInfo(), HB_Compiler(), Os() Environment functions rtl\version.c xhb.lib xhbdll.dll

Example PROCEDURE Main ? Version() RETURN

Function Reference

// result: xHarbour build 0.99.61 Intl. (SimpLex)

1197

W2bin()

W2bin() Converts a numeric value to an unsigned short binary integer (2 bytes).

Syntax W2Bin( ) --> cInteger

Arguments

A numeric value in the range of 0 to +(2^15) - 1.

Return The function returns a two-byte character string representing a 16-bit unsigned short binary integer .

Description W2Bin() is a binary conversion function that converts a numeric value (Valtype()=="N") to a two byte binary number (Valtype()=="C"). The range for the numeric return value is determined by an unsigned short integer. If is outside this range, a runtime error is raised.

Info See also: Category: Source: LIB: DLL:

Asc(), Bin2i(), Bin2l(), Bin2u(), Bin2w(), Chr(), I2bin(), L2bin(), U2bin() Binary functions, Conversion functions rtl\binnumx.c xhb.lib xhbdll.dll

Example // The example demonstrates return values of W2Bin(). PROCEDURE Main LOCAL cInt cInt := W2bin(0) ? Asc( cInt[1] ), Asc( cInt[2] )

// result:

0

0

cInt := W2bin(1) ? Asc( cInt[1] ), Asc( cInt[2] )

// result:

1

0

cInt := W2bin(256) ? Asc( cInt[1] ), Asc( cInt[2] )

// result:

0

1

cInt := W2bin(32768) ? Asc( cInt[1] ), Asc( cInt[2] )

// result:

0

128

cInt := W2bin(65535) ? Asc( cInt[1] ), Asc( cInt[2] )

// result: 255

255

RETURN

1198

Function Reference

WaitForThreads()

WaitForThreads() Suspends the current thread until all other threads have terminated.

Syntax WaitForThreads() --> NIL

Return The return value is always NIL.

Description Function WaitForThreads() is only effective when it is called in the Main thread of an xHarbour application. This is the thread executing the first function, or start routine, of the application. WaitForThreads() suspends the Main thread until all other threads have terminated. This makes sure that only the Main thread is active when the function returns. If WaitForThreads() is called in a different thread than the Main thread, it returns immediately and does not suspend thread execution. Note: when a thread, other than the Main thread, should wait for the termination of a second thread, function JoinThread() can be used.

Info See also: Category: Source: LIB: DLL:

Function Reference

GetCurrentThread(), GetThreadID(), HB_MutexCreate(), JoinThread(), StartThread(), StopThread(), ThreadSleep() Multi-threading functions, xHarbour extensions vm\thread.c xhbmt.lib xhbmtdll.dll

1199

WildMatch()

WildMatch() Tests if a string begins with a search pattern.

Syntax WildMatch( , , [] ) --> lFound

Arguments

This is a character string defining the search pattern. It may include as wild card characters the question mark (?, matches one character) or the asterisk (*, matches any number of characters).

This parameter is a character string to match against .

The parameter defaults to .F. (false), causing the function to return when a matching pattern is found at the beginning of . When .T. (true) is passed, is matched entirely against .

Return The function returns .T. (true) when contains the search pattern.

Description WildMatch() is a pattern matching function that searches a string for a search pattern. If the search pattern is found, the function returns .T. (true). WildMatch() operates similarly to OrdWildSeek() but can be used as part of a SET FILTER condition on an unindexed database.

Info See also: Category: Source: LIB: DLL:

$, At(), IN, OrdWildSeek(), SET FILTER Character functions, xHarbour extensions rtl\strmatch.c xhb.lib xhbdll.dll

Example // The example demonstrates the pattern matching algorithm employed // by WildMatch() and how the function can be used as filter condition // for a database PROCEDURE Main LOCAL cStr := "The xHarbour compiler"

1200

? WildMatch( "bo?" ? WildMatch( "bo?"

, cStr, .F. ) , cStr, .T. )

// result: .F. // result: .F.

? WildMatch( "*bo" ? WildMatch( "*bo"

, cStr, .F. ) , cStr, .T. )

// result: .T. // result: .F.

Function Reference

WildMatch() ? WildMatch( "The" ? WildMatch( "The"

, cStr, .F. ) , cStr, .T. )

// result: .T. // result: .F.

? WildMatch( "The*r", cStr, .F. ) ? WildMatch( "The*r", cStr, .T. )

// result: .T. // result: .T.

? WildMatch( "The?x", cStr, .F. ) ? WildMatch( "The?x", cStr, .T. )

// result: .T. // result: .F.

USE Customer SET FILTER TO WildMatch( "W*s", FIELD->LastName ) GO TOP DbEval( {|| QOut( FIELD->LastName ) } ) // Output: Names starting with "W" and ending with "s" // Walters // Waters CLOSE Customer RETURN

Function Reference

1201

Word()

Word() Converts a floating point number to a 32-it integer value.

Syntax Word( ) --> nInteger

Arguments

A numeric floating point value in the range of -1*(2^31) to (2^31)-1.

Return The function returns an integer value.

Description Word() is a compatibility function and not recommended to use. Use function Int() to create integer numbers.

Info See also: Category: Source: LIB: DLL:

1202

Bin2L(), Int(), L2Bin() Conversion functions rtl\word.c xhb.lib xhbdll.dll

Function Reference

Year()

Year() Extracts the numeric year from a Date value

Syntax Year( ) --> nYear

Arguments

This is a Date value to extract the year from.

Return The function returns a four digit year as a numeric value, or zero when is an empty date.

Description Year() extracts the year from a date value as a four digit number, without recognizing the settings SET DATE or SET CENTURY. Other parts of a date value can be extracted using function Day() or Month().

Info See also: Category: Source: LIB: DLL:

CDoW(), CMonth(), CtoD(), Day(), DtoC(), Month() Conversion functions, Date and time rtl\dateshb.c xhb.lib xhbdll.dll

Example // The example shows results of the function Year() PROCEDURE Main ? Date() ? Year( Date() ) ? Year( Date() ) - 19

// result: 05/10/06 // result: 2006 // result: 1987

RETURN

Function Reference

1203

Class Reference (textmode)

1204

Class Reference (textmode)

C Structure class

C Structure class Abstract class for C structure support.

Description xHarbour supports C structures as they are required by many external API functions, such as the Windows API, or Third Party libraries. The C Structure class is an abstract class serving as super class for all structures declared with the typedef struct declaration. Instance variables and methods of this class are available in all declared structures. On the PRG level, a structure is represented by an object whose instance variables hold the values of structure members. On the C level it is a contiguous binary character string holding the structure members. This character string is maintained by a structure object in an internal buffer which can be retrieved with the :value() method, or changed with the :buffer() method. In contrast to other classes, C structures are not instantiated with a :new() or :init() method, but with the structure creation statement (struct).

Predefined structures in xHarbour The #include file Winapi.ch contains a large number of predefined structures that are required by Windows API functions. If a Windows API function is called on the PRG level via DllCall() that requires a structure as parameter, the corresponding structure declaration can be done by simply including the Winapi.ch file. The following table lists the structures that are available when WinApi.ch is included:

Structures for Windows API functions Declared

Structure

Names

CHOOSEFONT CLIENTCREATESTRUCT COLORSCHEME CREATESTRUCT DLGITEMTEMPLATE DLGTEMPLATEEX DLGTEMPLATE DRAWITEMSTRUCT HDITEM ICONINFO LITEM LOGFONT LVCOLUMNA LVITEMA MDINEXTMENU MEASUREITEMSTRUCT MENUINFO MENUITEMINFO MSG NCCALCSIZE_PARAMS NMCUSTOMDRAW NMHDR

NMHEADER NMPGCALCSIZE NMPGSCROLL NMREBARCHEVRON NMREBAR NMTBCUSTOMDRAW NMTBHOTITEM NMTOOLBARA NMTREEVIEWA NMTVCUSTOMDRAW NMTVGETINFOTIP NMTVKEYDOWN NONCLIENTMETRICS OPENFILENAME OSVERSIONINFO OSVERSIONINFOEX PAINTSTRUCT POINTS POINT RBHITTESTINFO REBARBANDINFOA REBARINFO

RECT SCROLLBARINFO SCROLLINFO SIZE TBADDBITMAP TBBUTTON TBBUTTONINFOA TCITEMA TEXTMETRIC TOOLINFOA TOOLTIPTEXT TRACKMOUSEEVENT TVHITTESTINFO TVINSERTSTRUCT TVITEMEX TVITEM WINDOWPLACEMENT WINDOWPOS WNDCLASSEX WNDCLASS

Class Reference (textmode)

1205

C Structure class class - Instance variables

Instance variables

:aCMembers Array holding the structure member names. Data type: Default:

A (READONLY) NIL

Description The instance variable :aCMembers contains a one dimensional array. Its elements contain character strings with the names of structure members.

:aCTypes Array holding the data types of structure members. Data type: Default:

A (READONLY) NIL

Description The instance variable :aCTypes contains a one dimensional array. Its elements contain numeric values encoding the C data types of the structure members. Constants listed in CStruct.ch are used for data type encoding:

C data types for structure members

1206

Constant

Value

CTYPE_CHAR CTYPE_UNSIGNED_CHAR CTYPE_CHAR_PTR CTYPE_UNSIGNED_CHAR_PTR CTYPE_SHORT CTYPE_UNSIGNED_SHORT CTYPE_SHORT_PTR CTYPE_UNSIGNED_SHORT_PTR CTYPE_INT CTYPE_UNSIGNED_INT CTYPE_INT_PTR CTYPE_UNSIGNED_INT_PTR CTYPE_LONG CTYPE_UNSIGNED_LONG CTYPE_LONG_PTR CTYPE_UNSIGNED_LONG_PTR CTYPE_FLOAT CTYPE_FLOAT_PTR CTYPE_DOUBLE CTYPE_DOUBLE_PTR CTYPE_VOID_PTR CTYPE_STRUCTURE CTYPE_STRUCTURE_PTR

1 -1 10 -10 2 -2 20 -20 3 -3 30 -30 4 -4 40 -40 5 50 6 60 7 1000 10000 Class Reference (textmode)

C Structure class class - Instance variables

:nAlign Byte alignment of structure members Data type: N (READONLY) Default: NIL

Description The instance variable :nAlign contains a numeric value used for the byte alignment of the internal binary buffer of a structure object. This value is identical with the value set with pragma pack() before typedef struct is declared.

Methods

:array() Fills an array with all structure member values.

Syntax :array() --> aMemberValues

Description Method :array() returns an array filled with the values of all structure members.

:buffer() Assigns a binary character string to the internal buffer.

Syntax :buffer( , [] ) --> self

Arguments

This is a character string with replaces the internal binary buffer of a structure object.

This parameter defaults to .F. (false). It should be set to .T. (true) when the structure object maintains a nested structure. That is, it contains other structure objects in its instance variables.

Description Method :buffer() is used to change the internal binary buffer of a structure object. must be a binary character string with :sizeOf() bytes. If the string contains less characters, Chr(0) is added up to the correct length. The method extracts the values for each structure member from and assigns them to the corresponding instance variables of the structure object.

Class Reference (textmode)

1207

C Structure class class - Methods

:deValue() Re-loads binary structure data from memory.

Syntax :deValue( [] ) --> self

Arguments

This parameter defaults to .F. (false). It should be set to .T. (true) when the structure object maintains a nested structure. That is, it contains other structure objects in its instance variables.

Description Method :deValue() reads structure data from memory and assigns values to all instance variables representing structure members. This is required when the structure data is passed to an API function which changes values of structure members. The changed values are then copied into the instance variables of the structure object with method :deValue().

:getPointer() Retrieves the pointer to the internal binary buffer.

Syntax :getPointer() --> pStructure

Description Method :getPointer() returns a pointer to the internal binary buffer of a structure object. This pointer can then be passed via DllCall() to an external API function requiring a structure as parameter. Note that method :deValue() must be called when the API function changes members of the structure. Otherwise the changes do not become visible in the structure object.

:pointer() Changes the pointer to the internal binary buffer.

Syntax :pointer( , [] ) --> self

Arguments

This is a pointer to structure data in memory.

This parameter defaults to .F. (false). It should be set to .T. (true) when the structure object maintains a nested structure. That is, it contains other structure objects in its instance variables.

1208

Class Reference (textmode)

C Structure class class - Methods

Description Method :pointer() is used to change the internal binary buffer of a structure object via a pointer. must be the memory address of :sizeOf() bytes. The method reads this number of bytes from memory and extracts from it the values for structure members. These values are assigned to the corresponding instance variables of the structure object.

:reset() Voids the values of all structure members.

Syntax :reset() --> self

Description Method :reset() clears the internal binary buffer of a struture object and assignes NIL to all instance variables holding the values of structure members.

:sizeOf() Determines the size of a structure in bytes.

Syntax :sizeOf() --> nStructureSize

Description Method :sizeOf() returns a numeric value representing the number of bytes a structure occupies in memory. This value is quite often required in structures used by the Windows API. If one structure member exist that indicates the structure size, it must be assigned the return value of method :sizeOf().

:value() Retrieves the internal binary buffer of a structure object

Syntax :value() --> cBinaryStructure

Description Method :value() retrieves the binary representation of a structure and all its members and returns it as a character string.

Class Reference (textmode)

1209

C Structure class class - Methods

Info See also: Category: Header: Source: LIB: DLL:

DllCall(), pragma pack(), (struct), typedef struct C Structure support, xHarbour extensions cstruct.ch, winapi.ch, wintypes.ch rtl\cstruct.prg xhb.lib xhbdll.dll

Example // The example outlines the steps necessary for calling a // Windows API function which requires a structure as parameter. #include "CStruct.ch" #include "Wintypes.ch"

// required for "typedef struct" // required Windows C data types

pragma pack(4)

// all Windows API structures // are 4 byte aligned

// structure declaration taken via // copy&paste from Windows SDK typedef struct _OSVERSIONINFOEX { ; DWORD dwOSVersionInfoSize; // ^ this ";" must be added DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformId; TCHAR szCSDVersion[128]; WORD wServicePackMajor; WORD wServicePackMinor; WORD wSuiteMask; BYTE wProductType; BYTE wReserved; } OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX; #define DC_CALL_STD

0x0020

PROCEDURE Main LOCAL oVerInfo // Create OSVERSIONINFOEX structure object oVerInfo := (struct OSVERSIONINFOEX) // assign structure size to structure member oVerInfo:dwOSVersionInfoSize := oVerInfo:sizeOf() // pass structure object by reference to DllCall() // (it is an OUT parameter) DllCall( "Kernel32.dll", DC_CALL_STD , ; "GetVersionEx", @oVerInfo ) // display result of API ? oVerInfo:dwMajorVersion ? oVerInfo:dwMinorVersion ? oVerInfo:dwBuildNumber

// result: 5 // result: 1 // result: 2006

// this member contains a byte array // retrieve it as character string ? oVerInfo:szCSDVersion:asString() // result: Service Pack 2 RETURN

1210

Class Reference (textmode)

Error()

Error() Creates a new Error object.

Syntax Error( [] , [] , [] , [] , [], [] , [] , [] , [ ]

; ; ; ; ; ; ; ; ) --> oError

Arguments

This is a character string holding the name of the subsystem where the error occurred. It is assigned to oError:subSystem.

This is a numeric value indicating a generic error code. It is assigned to oError:genCode. The file Error.ch contains #define constants used for this parameter. They begin with the prefix EG_.

This is a numeric value indicating an error code specific for the subsystem where the error occurred. It is assigned to oError:subCode.

This is a character string holding the name of the failed operation. It is assigned to oError:operation.

This is a character string holding a description of the failed operation. It is assigned to oError:description.

This is an array whose elements hold the arguments of the failed operation. It is assigned to oError:args.

This is a character string holding the file name of the module where the error occurred. It is assigned to oError:moduleName.The parameter defaults to the return value of function ProcFile().

This is a character string holding the name of the function, method or procedure where the error occurred. It is assigned to oError:procName. The parameter defaults to the return value of function ProcName(). Class Reference (textmode)

1211

Error()

This is a numeric value indicating the line number of the source code file where the error occurred. It is assigned to oError:procLine. The parameter defaults to the return value of function ProcLine().

Return The function returns a new Error object, optionally filled with information about a runtime error.

Description Objects of the Error class are used for error handling and error recovery by the xHarbour runtime system. An Error object is created when a runtime error occurs. Information about a runtime error is assigned to instance variables of the object before an exception is triggered by the runtime system. The Error object is then passed to the error handling routine programmed in the xHarbour application. There are two statements available for user-defined error handling routines: BEGIN SEQUENCE and TRY...CATCH. See these statements for examples of local error handling. Note: the default error handling routine is function DefError() implemented in the file source\rtl\ErrorSys.prg

Instance variables

:args Array holding the arguments of a failed operation. Data type: Default:

A NIL

Description This instance variable receives a one-dimensional array whose elements contain the arguments of a failed operation. When no argument error is detected, the instance variable contains NIL.

:canDefault Indicates if a default recovery is available. Data type: Default:

L .F.

Description If :canDefault contains .T. (true), a default error recovery routine is available. This routine is requested at runtime by returning .F. (false) from the current error code block set with ErrorBlock(). The minimum error recovery is to ignore the error. When the error code block returns .T. (true), the error handling routine is called again. Note: the value of :canDefault is never .T. (true) when :canSubstitute is .T. (true), i.e. if :canSubstitute contains .T. (true), :canDefault contains .F. (false).

1212

Class Reference (textmode)

Error class - Instance variables

:canRetry Indicates if a retry operation is possible. Data type: L Default: .F.

Description If :canDefault contains .T. (true), a retry operation is possible. The failed operation is retried, when the current error code block set with ErrorBlock() returns .T. (true). Each time the failed operation is retried and fails again, the value of :tries is incremented by one. Note: the value of :canRetry is never .T. (true) when :canSubstitute is .T. (true), i.e. if :canSubstitute contains .T. (true), :canRetry contains .F. (false).

:canSubstitute Indicates if an erroneous result can be substituted. Data type: L Default: .F.

Description If :canSubstitute contains .T. (true), the result of an erroneous operation can be substituted. The result of the failed operation is replaced with the return value of the current error code block set with ErrorBlock() Note: the value of :canSubstitute is never .T. (true) if either :canDefault or :canRetry is .T. (true).

:cargo Instance variable for user-defined purposes. Data type: ANY Default: NIL

Description This instance variable is not used by an Error object. It is available for user-defined purposes when an arbitrary value should be attached to an Error object.

:description Character string holding a description of the error. Data type: C Default: ""

Description The instance variable contains a character string describing the error condition. If the subsystem provides no error description, :description contains an empty string ("").

Class Reference (textmode)

1213

Error class - Instance variables

:fileName Name of the disk file associated with the operation Data type: Default:

C ""

Description The instance variable contains a character string holding the name of a disk file participating in the failed operation. If there is no file operation, :fileName contains an empty string ("").

:genCode Generic numeric error code. Data type: Default:

N NIL

Description The instance variable contains a numeric value representing a generic error code. If :genCode contains zero, an unknown error has occurred. #define constants are listed in Error.ch for other generic error conditions.

Generic error codes

1214

Constant

Value

Description

EG_ARG EG_BOUND EG_STROVERFLOW EG_NUMOVERFLOW EG_ZERODIV EG_NUMERR EG_SYNTAX EG_COMPLEXITY EG_MEM EG_NOFUNC EG_NOMETHOD EG_NOVAR EG_NOALIAS EG_NOVARMETHOD EG_BADALIAS EG_DUPALIAS EG_NOOBJECT EG_CREATE EG_OPEN EG_CLOSE EG_READ EG_WRITE EG_PRINT EG_UNSUPPORTED EG_LIMIT EG_CORRUPTION EG_DATATYPE EG_DATAWIDTH

1 2 3 4 5 6 7 8 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 30 31 32 33 34

Argument error Bound error Bound error, Numeric overflow Zero divisor Zero divisor Syntax error Operation too complex Memory low Undefined function No exported method Variable does not exist Alias does not exist No exported variable Illegal characters in alias Alias already in use Not an object Create error Open error Close error Read error Write error Print error Operation not supported Limit exceeded Corruption detected Data type error Data width error Class Reference (textmode)

Error class - Instance variables EG_NOTABLE EG_NOORDER EG_SHARED EG_UNLOCKED EG_READONLY EG_APPENDLOCK EG_LOCK EG_ARRACCESS EG_ARRASSIGN EG_ARRDIMENSION EG_NOTARRAY EG_CONDITION EG_BADSELF EG_ARRREF EG_OLEEXECPTION

35 36 37 38 39 40 41 46 47 48 49 50 51 52 1001

Workarea not in use Workarea not indexed Exclusive required Lock required Write not allowed Append lock failed Lock Failure array access array assign array dimension not an array conditional Invalid self reserved (OLE exception occurred)

:moduleName Character string holding the name of the PRG source file where the error occurred. Data type: C Default: ""

Description The instance variable contains a character string holding the name of the PRG source code file where the failed operation is implemented. If this information is not available, :moduleName contains an empty string ("").

:operation Character string holding a description of the failed operation. Data type: C Default: ""

Description The instance variable contains a character string holding the name of the failed operation. If this information is not available, :operation contains an empty string ("").

:osCode Numeric operating system error code. Data type: N Default: 0

Description When an operation fails due to an Operating system error, its numeric error code is assigned to :osCode. It can also be retrieved using function DosError() or FError(). If the failed operation is not an operating system error, :osCode contains zero.

Class Reference (textmode)

1215

Error class - Instance variables

:procName Character string holding the name of the function where the error occurred. Data type: Default:

C ""

Description The instance variable contains a character string holding the name of the function method or procedure where the failed operation occurred. If this information is not available, :procName contains an empty string ("").

:procLine Numeric value indicating the line number of the source code file where the error occurred. Data type: Default:

N 0

Description The instance variable contains the line number of the PRG source code file where the failed operation occurred. If this information is not available, :procLine contains zero.

:severity Numeric value indicating error severity. Data type: Default:

N 0

Description The instance variable contains a numeric value representing the severity of the error. #define constants are available in Error.ch to classify the severity of a runtime error:

Severity levels of runtime errors

1216

Constant

Value

Description

ES_WHOCARES ES_WARNING ES_ERROR

0 1 2

ES_CATASTROPHIC

3

Just informational, not really an error This error is not a real error yet, but may lead to one later This error must be corrected immediately in an error handling routine This error requires immediate termination of the application

Class Reference (textmode)

Error class - Instance variables

:subCode Numeric subsystem-specific error code. Data type: N Default: 0

Description The instance variable contains a numeric value representing a subsystem-specific error code. If :subCode contains zero, the subsystem provides no further error information.

:subSystem Character string holding the name of the subsystem where the error occurred. Data type: C Default: ""

Description The instance variable contains a character string describing the subsystem that has raised the runtime error. If the subsystem is unknown, :subSystem contains an empty string ("").

:tries Number of times the failed operation was attempted to be executed. Data type: N Default: 0

Description The instance variable contains a numeric value which is initially zero. When :canRetry is .T. (true) and a failed operation is retried, the value of :tries is incremented by one. Thus, :tries is a counter for how often a failed operation is retried.

Info See also: Category: Header: Source: LIB: DLL:

BEGIN SEQUENCE, DosError(), ErrorBlock(), FError(), Neterr(), TRY...CATCH, Throw() Object functions Error.ch rtl\terror.prg, rtl\error.c xhb.lib xhbdll.dll

Example // // // //

The example is a code snippet from the file WIN32OLE.PRG. It demonstrates how a runtime error can be handled using the TRY...CATCH statements and how to fill an Error object with information about a runtime error. METHOD OleValuePlus( xArg ) CLASS TOleAuto LOCAL xRet, oErr

Class Reference (textmode)

1217

Error class - Instance variables TRY xRet := ::OleValue CATCH oErr := ErrorNew() oErr:Args oErr:CanDefault oErr:CanRetry oErr:CanSubstitute oErr:Description oErr:GenCode oErr:Operation oErr:Severity oErr:SubCode oErr:SubSystem

+ xArg

:= := := := := := := := := :=

{ Self, xArg } .F. .F. .T. "argument error" EG_ARG '+' ES_ERROR 1081 "BASE"

RETURN Throw( oErr ) END RETURN xRet

1218

Class Reference (textmode)

Get()

Get() Creates a new Get object.

Syntax Get():new( [] , [] , , [] , [] , []

; ; ; ; ; ) --> oGet

Arguments

This is the numeric row coordinate on the screen where the Get object is displayed. It defaults to the return value of function Row(). is assigned to oGet:row.

This is the numeric column coordinate on the screen where the Get object is displayed. It defaults to the return value of function Col(). is assigned to oGet:col.

This is the data code block connecting a Get object with a variable holding the edited value (see description below). is assigned to oGet:block.

This is a character string holding the symbolic name of a memory variable of PRIVATE or PUBLIC scope. If the Get object should edit such a variable, is optional. defaults to an empty string ("") and is assigned to oGet:name.

This is a character string holding a PICTURE format. defaults to an empty string ("") and is assigned to oGet:picture.

This is a character string holding a color string of up to four color values. (refer to function SetColor() for color values). is assigned to oGet:colorSpec.

Return Function Get() returns a new Get object and method :new() initializes the object.

Description Get objects provide the means for data entry in text mode applications. They are generally created with the @...GET command and collected in a PUBLIC array named GetList. All Get objects stored in the GetList array are processed with the READ command, or the ReadModal() function, respectively. A Get object displays data to be edited and provides methods for keyboard input and cursor movement when it receives input focus. The data to be edited can be stored a memory or field variable, it is not stored in the Get object itself. Instead, a Get object must receive a data code block with the Class Reference (textmode)

1219

Get()

parameter, which can be created using functions MemVarBlock(), FieldBlock() or FieldWBlock(). The data code block can also be coded in a general form like this: LOCAL variable bVarBlock := {|xValue| IIf( xValue==NIL, variable, variable := xValue ) }

This code block has one parameter and refers to the variable whose value is edited. A Get object retrieves the variable's value by evaluating the data code block with no parameter, and it assigns the edited value to the variable by passing the edited value to the data code block when it looses input focus.

Instance variables

:badDate Indicates if the editing buffer contains an invalid date value. Data type: Default:

L .F.

Description The instance variable :badDate contains .T. (true) when a Date value is being edited and the current value in the edit buffer of a Get object represents an invalid date. In all other cases, :badD ate contains .F. (false).

:block Data code block of the Get object. Data type: Default:

B NIL

Description The instance variable :block contains the data code block of a Get object. It is the most important instance variable and must be provided upon object creation. The data code block is the connection between the Get object and the edited variable. Note: a Get object evaluates the data code block during different stages of an editing cycle and it is not recommended to evaluate :block directly. Instead, use methods :varGet() and :varPut() when the data code block must be evaluated explicitely. This way, a Get object receives knowledge when the edited variable is changed outside the Get object.

1220

Class Reference (textmode)

Get class - Instance variables

:buffer Character string held in the editing buffer. Data type: C Default: NIL

Description The instance variable :buffer contains the editing buffer while a Get object has input focus. This buffer is the edited value in form of a character string.

:capRow Numeric row position of a caption. Data type: N Default: 0

Description The instance variable :capRow contains the numeric row position of the caption of a Get object. It is only meaningful when instance variable :caption contains a character string to display as a caption.

:capCol Numeric column position of a caption. Data type: N Default: 0

Description The instance variable :capCol contains the numeric column position of the caption of a Get object. It is only meaningful when instance variable :caption contains a character string to display as a caption.

:caption Character string defining the caption. Data type: C Default: ""

Description The instance variable :caption can be assigned a character string to be displayed at position :capRow and :capCol whithin the Get object's :display() method. If the :caption string contains an ampersand (&), the ampersand is removed from the :caption string and the next character to the right of the ampersand is displayed using the fourth color value of :colorSpec.

Class Reference (textmode)

1221

Get class - Instance variables

:cargo Instance variable for user-defined purposes. Data type: Default:

ANY NIL

Description This instance variable is not used by a Get object. It is available for user-defined purposes when an arbitrary value should be attached to a Get object.

:changed Indicates if the editing buffer was changed. Data type: Default:

L .F.

Description The instance variable :changed contains .T. (true) when the edit buffer of the Get object is changed while the object has input focus. In all other cases, :changed contains .F. (false).

:clear Indicates if the editing buffer should be cleared Data type: Default:

L .F.

Description The instance variable :clear contains .T. (true) when the Get object has input focus and the edit buffer of the object should be cleared with the next key stroke. This is the case when the first key press is numeric and the edited value is numeric, or when the picture function "@K" is used in the :picture string. In all other cases, :clear contains .F. (false).

:col Numeric column position of the Get object. Data type: Default:

N Col()

Description The instance variable :col contains the numeric column position where a Get object displays the value of the edited variable on the screen.

1222

Class Reference (textmode)

Get class - Instance variables

:colorSpec Color string for display and editing. Data type: C Default: SetColor()

Description The instance variable :colorSpec contains a color string holding up to four color values. They are used for the following purposes:

Color usage of Get objects Color value

Description

#1 #2 #3 #4

Displays edited value when Get does not have input focus Displays edited value when Get has input focus Displays caption string of Get object Displays character marked with an ampersan (&) in the caption string

Note: if :colorSpec contains less than four color values, the last color value is used for the missing colors.

:control Optional object for mouse control. Data type: O Default: NIL

Description The instance variable :control can be assigned an object that must have the method :hitTest(). The method is used in the same way as Get:hitTest(). The :control object, such as TBColumn() or TBrowse(), is associated with the Get object.

:decPos Numeric position of the decimal point during editing. Data type: N Default: NIL

Description The instance variable :decPos contains a numeric value greater than zero when a Get object has input focus and the edited value is numeric and has a decimal fraction. In this case, :decPos is the position of the decimal point in the edit buffer. In all other cases, :decPos contains zero.

Class Reference (textmode)

1223

Get class - Instance variables

:exitState Numeric code indicating how editing was terminated. Data type: Default:

N GE_NOEXIT

Description The instance variable :exitState contains a numeric value indicating how the editing process wa s terminated. #define constants are available in the file GETEXIT.CH that identify exit states.

Exit states of Get objects Constant

Value

Description

GE_NOEXIT GE_UP GE_DOWN GE_TOP GE_BOTTOM GE_ENTER GE_WRITE

0 1 2 3 4 5 6

GE_ESCAPE GE_WHEN GE_SHORTCUT GE_MOUSEHIT

7 8 9 10

No exit attempted Go to previous Get Go to next Get Go to first Get Go to last Get Terminate editing of current Get and proceed with next Terminate editing of all Gets in GetList array (terminate READ command) Terminate editing of all Gets without saving data Pre-validation failed, don't give input focus Accelerator key is pressed (see :caption) Another Get is clicked with the mouse

:hasFocus Indicates if the Get object has input focus. Data type: Default:

L .F.

Description The instance variable :hasFocus contains .T. (true) when Get object has input focus, otherwise .F. (false).

:minus Indicates if a minus sign is entered for numbers. Data type: Default:

L .F.

Description The instance variable :minus contains .T. (true) when Get object has input focus, the edited value is a number and the minus sign is entered inti the edit buffer. In all other cases, :minus contains .F. (false).

1224

Class Reference (textmode)

Get class - Instance variables

:message Character string to be displayed as message when Get receives input focus.

Description The instance variable :message can be assigned a character string which is displayed in the message area defined with the ReadModal() function when the Get object receives input focus.

:name Character string holding the symbolic name of the edited variable. Data type: C Default: ""

Description The instance variable :name contains the character string passed with parameter to the :new method. It is the symbolic name of the edited variable. Note that this is only relevant when the edited variable is of PRIVATE or PUBLIC scope. Symbolic names of such variables are available at runtime and can be used to generate a data code block for the Get object.

:original Character string holding the original value before editing started. Data type: C Default: ""

Description Before a Get object starts editing a value, it creates a copy of the edited value and stores it in the instance variable :original in form of a character string. When the user has changed the edit buffer, the original value can be recalled with method :undo(). :original holds the original value only while the Get object has input focus.

:picture Character string holding a PICTURE format. Data type: C Default: ""

Description The instance variable :picture holds a PICTURE formatting string used for displaying and editing the variable. Refer to command @...GET for a comprehensive description of PICTURE formatting strings.

Class Reference (textmode)

1225

Get class - Instance variables

:pos Current cursor position within the editing buffer. Data type: Default:

N 0

Description The instance variable :pos contains a numeric value greater than zero while a Get object has input focus. It is the current cursor position within the edit buffer. In all other cases, :pos contains zero.

:postBlock Code block to validate a new value before Get looses input focus. Data type: Default:

B NIL

Description Optionally, a code block can be assigned to :postValidate that is used to validate edited data. The code block receives as parameter the Get object and must return a logical value. When the code block returns .T. (true) the Get object looses input focus. When it returns .F. (false), the current data available in the edit buffer is assumed invalid and the Get object retains input focus.

:preBlock Code block to validate a va lue before Get receives input focus. Data type: Default:

B NIL

Description Optionally, a code block can be assigned to :preValidate that is used to test if a Get object may receive input focus. The code block receives as parameter the Get object and mus t return a logical value. When the code block returns .T. (true), the Get object receives input focus. When it returns .F. (false), the next Get object is searched that may receive input focus.

:reader Code block calling an alternative Get reader procedure. Data type: Default:

B NIL

Description The instance variable :reader is reserved for a user-defined Get reader procedure. :reader can be assigned a code block which receives the Get object and must call a procedure that processes user input for the Get object. Refer to METHOD Reader in source \rtl\Getlist.prg for an example of a Get reader implementation.

1226

Class Reference (textmode)

Get class - Instance variables

:rejected Indicates if the last key stroke was rejected during editing. Data type: L Default: .F.

Description The instance variable :rejected contains .T. (true) when the last key stroke is rejected during editing. For example, when a number is edited and the user typed an alphabetic character. When the Get object has no input focus or when a valid key is pressed, :rejected contains .F. (false).

:row Numeric row position of the Get object. Data type: N Default: Row()

Description The instance variable :row contains the numeric row position where a Get object displays the value of the edited variable on the screen.

:subscript Array element subscript when array is edited. Data type: A Default: NIL

Description When the data code block references a variable holding an array, the instance variable :subscript must be assigned an array whose element(s) contain the numeric subscript(s) pointing to the array element that is to be edited by the Get object. For example: LOCAL aArray := { "One", "Two" } LOCAL bData := {|| aArray } LOCAL oGet := Get():new( ,, bData ) oGet:subscript := {2} ? oGet:varGet()

// result: Two

:type Data type of edited value. Data type: C Default: ""

Description The instance variable :type contains a single letter indicating the data type of the edited value while the Get object has input focus. This letter is equivalent with the return value of function Valtype(). Class Reference (textmode)

1227

Get class - Instance variables

:typeOut Indicates attempt to move the cursor out of editing buffer. Data type: Default:

L .F.

Description The instance variable :typeOut contains .T. (true) when the user attempts to move the cursor outside the edit buffer, or when the edit buffer is full and a new key is pressed in insert mode. In all other cases, :typeOut contains .F. (false).

State changing methods

:assign() Assigns the contents of the edit buffer to the edited variable

Syntax :assign() --> self

Description The :assign() method evaluates the data code block and passes the current value in the edit buffer on to it, thus assigning the edited value to the edited variable. The method is only meaningful when the Get object has input focus.

:colorDisp() Changes the color and redisplays the Get.

Syntax :colorDisp( ) --> self

Arguments

This is a character string holding a color string of up to four color values. is assigned to :colorSpec.

Description The method :colorDisp() assigns a new color string to :colorSpec and redisplays the Get object.

1228

Class Reference (textmode)

Get class - State changing methods

:display() Displays the Get on the screen.

Syntax :display() --> self

Description When the Get object has input focus, method :display() displays the edited value using the second color value of :colorSpec and positions the cursor on the first editable character in the edit buffer. If the Get object does not have input focus, the edited value is displayed using the first color value of :colorSpec and the cursor remains unchanged.

:hitTest() Tests if a Get is hit by the mouse cursor.

Syntax :hitTest( , ) --> nHitCode

Arguments

This is the numeric row position of the mouse cursor. It can be queried using function MRow().

This is the numeric column position of the mouse cursor. It can be queried using function MCol().

Description Method :hitTest() accepts the numeric row and column position of the mouse cursor and returns a numeric value indicating whether or not the mouse cursor is located within the Get object. #define constants are available in the BUTTON.CH file identifying the return value of :hitTest().

Return values of oGet:hitTest() Constant

Value

Description

HTNOWHERE HTCLIENT

0 -2049

Mouse cursor is outside Get object Mouse cursor is inside Get object

:killFocus() Removes input focus from the Get object.

Syntax :killFocus() --> self

Class Reference (textmode)

1229

Get class - State changing methods

Description Method :killFocus() removes the input focus from a Get object and releases all internal variables required during editing, such as :buffer or :original.

:reset() Resets internal state information of a Get object.

Syntax :reset() --> self

Description Method :reset() rebuilds the character string held in the edit buffer of a Get object from the current value of the edited variable, and moves the cursor to the first editable character. The method is only meaningful while the Get object has input focus.

:setFocus() Gives input focus to the Get object.

Syntax :setFocus() --> self

Description Method :setFocus() gives input focus to a Get object and assigns values to instance variables required for editing. This includes :buffer, :original, :pos and :decPos.

:undo() Assigns the original value back to the edited variable.

Syntax :undo() --> self

Description Method :undo() discards all changes applied to the edit buffer during editing and assigns the contents of :original back to the edited variable.

:unTransform() Converts the editing buffer to its original data type.

Syntax :unTransform() --> xValue

1230

Class Reference (textmode)

Get class - State changing methods

Description Method :unTransform() converts the character string held in :buffer to the original data type of the edited value and returns the converted value. This method is only meaningful while the Get object has input focus.

:updateBuffer() Updates the editing buffer and redisplays the Get.

Syntax :updateBuffer() --> self

Description Method :updateBuffer() rebuilds the editing buffer from the current value of the edited variable and displays the buffer. This method is only meaningful while the Get object has input focus.

:varGet() Returns the current value of the edited variable.

Syntax :varGet() --> xValue

Description Method :varGet() evaluates the data code block stored in :block without passing a value to it, and returns the value of the edited variable. If the variable holds an array, :varGet() returns the contents of the array element specified with :subscript.

:varPut() Assigns a new value to the edited variable.

Syntax :varPut( ) --> xValue

Description Method :varPut() evaluates the data code block stored in :block passing to it, and returns this value. If the edited variable holds an array, :varPut() assigns to the array element specified with :subscript.

Class Reference (textmode)

1231

Get class - Cursor movement methods

Cursor movement methods

:end() Moves the cursor to the last position in the edit buffer.

Syntax :end() --> self

Description When a Get object has input focus, method :end() moves the cursor to the rightmost editable character in the edit buffer.

:home() Moves the cursor to the first position in the edit buffer.

Syntax :home() --> self

Description When a Get object has input focus, method :home() moves the cursor to the leftmost editable character in the edit buffer.

:left() Moves the cursor one character to the left.

Syntax :left() --> self

Description When a Get object has input focus, method :left() moves the cursor one character to the left in the edit buffer, unless the cursor is positioned on the first editable character.

:right() Moves the cursor one character to the right.

Syntax :right() --> self

Description When a Get object has input focus, method :right() moves the cursor one character to the right in the edit buffer, unless the cursor is positioned on the last editable character. 1232

Class Reference (textmode)

Get class - Cursor movement methods

:toDecPos() Moves the cursor to the immediate right of Get:decPos.

Syntax :toDecPos() --> self

Description When a Get object has input focus and the edited value is a number with a decimal fraction, method :toDecPos() moves the cursor to the immediate right of the decimal point.

:wordLeft() Moves the cursor to the beginning of the next left word.

Syntax :wordLeft() --> self

Description When a Get object has input focus, method :wordLeft() moves the cursor to the first character of the next word left of the current cursor position.

:wordRight() Moves the cursor to the beginning of the next right word.

Syntax :wordRight() --> self

Description When a Get object has input focus, method :wordRight() moves the cursor to the first character of the next word right of the current cursor position.

Editing methods

:backspace() Moves the cursor to the left and deletes a character.

Syntax :backspace() --> self

Description When a Get object has input focus, method :backSpace() moves the cursor one character to the left and deletes this character. Class Reference (textmode)

1233

Get class - Editing methods

:delete() Deletes the character at the current cursor position.

Syntax :delete() --> self

Description When a Get object has input focus, method :delete() deletes the character at the current cursor position.

:delEnd() Deletes all characters from the current cursor position to the end of the edit buffer.

Syntax :delEnd() --> self

Description When a Get object has input focus, method :delEnd() deletes the characters in the edit buffer beginning at the current cursor position up to the last character in the buffer.

:delLeft() Deletes the character to the left of the cursor.

Syntax :delLeft() --> self

Description When a Get object has input focus, method :delLeft() deletes the character to the left of the cursor position without moving the cursor.

:delRight() Deletes the character to the right of the cursor.

Syntax :delRight() --> self

Description When a Get object has input focus, method :delRight() deletes the character to the right of the cursor position without moving the cursor.

1234

Class Reference (textmode)

Get class - Editing methods

:delWordLeft() Deletes the word to the left of the cursor.

Syntax :delWordLeft() --> self

Description When a Get object has input focus, method :delWordLeft() moves the cursor to the first character of the next word left of the current cursor position and deletes the entire word.

:delWordRight() Deletes the word to the right of the cursor

Syntax :delWordRight() --> self

Description When a Get object has input focus, method :delWordRight() moves the cursor to the first character of the next word right of the current cursor position and deletes the entire word.

:insert() Inserts a single character into the edit buffer.

Syntax :insert( ) --> self

Description When a Get object has input focus, method :insert() inserts the character into the edit buffer at the current cursor posiion. If is not valid, or if the edit buffer is full, :rejected is set to .T. (true) and the edit buffer remains unchanged.

:overStrike() Overwrites a single character in the editing buffer.

Syntax :overStrike( ) --> self

Description When a Get object has input focus, method :overstrike() replaces the character at the current cursor posiion in the edit buffer with . If is not valid, :rejected is set to .T. (true) and the edit buffer remains unchanged.

Class Reference (textmode)

1235

Get class - Editing methods

Info See also: Category: Header: Source: LIB: DLL:

@...GET, READ, ReadModal(), ReadVar(), Valtype(), SetColor() Get system, Object functions Button.ch, Getexit.ch rtl\getsys.prg, rtl\tget.prg, rtl\tgetlist.prg, rtl\mssgline.prg xhb.lib xhbdll.dll

Example // The example compares the creation of a single Get // using command oriented and object oriented syntax PROCEDURE Main LOCAL cString:= "Testing Gets LOCAL bBlock @ 2, 2 SAY GET COLOR VALID PICTURE

"String 1" cString "N/BG,W+/B" !Empty( cString ) "@K"

"

; ; ; ;

READ bBlock := {|x| IIf( x==NIL, cString, cString := x ) } @ 4, 2 SAY "String 2" oGet oGet:row oGet:col oGet:block oGet:name oGet:picture oGet:colorSpec oGet:postBlock oGet:display()

:= := := := := := := :=

Get():new() Row() Col() + 1 bBlock "cString" "@K" "N/BG,W+/B" {|o| ! Empty(o:varGet()) }

ReadModal( {oGet} ) RETURN

1236

Class Reference (textmode)

HBObject()

HBObject() Abstract base class for user-defined classes.

Description The HBObject() class serves as base class for all other built-in and user-defined classes declared with the CLASS statement. This class has no member variables but only methods required for creating instances, or objects, of a class (note: an instance is an object of a class). All methods of HBObject() can be called in user-defined classes. They define a standard behaviour required in all classes. This standard behaviour can be changed in user-defined classes when methods of HBObject() are re-declared in a new class and re-implemented. Note: the most commonly re-defined method in user-defined classes is the :init() method.

Methods for object creation and initialization

:new() Creates a new instance of a class.

Syntax :new( [] ) --> oInstance

Arguments

Optionally, a comma separated list of parameters can be passed to :new(). They are forwarded in the same sequence to the :init() method of the class. The :init() method must be declared in a user-defined class for accessing the passed parameters when an object is initialized in the :init() method.

Return The method returns a new instance of the class.

Description Method :new() is the only method that creates instances of a class. The method is special since it can only be used with the class function of a class, not with an object. This is the basic syntax pattern for creating a new object: oNewObject := ClassFunction():new()

Note: it is not recommended to re-define the :new() method in a user-defined class.

Class Reference (textmode)

1237

HBObject class - Methods for object creation and initialization

:init() Initializes a new instance (object) of a class.

Syntax :init( [] ) --> self

Arguments

All parameters passed to the :new() method are forwarded to :init().

Return The method returns the object self.

Description Method :init() is called from method :new() and serves the purpose of initializing a newly created object. The parameters passed to :new() are forwarded to :init() where the received values are usually stored in instance variables of the new object. An alternative initilization of instance variables is provided with the INIT clause of the DATA declaration of a class.

:initClass() Initializes class variables of a class.

Syntax :initClass( [] ) --> self

Arguments

All parameters passed to the Class function are forwarded to :initClass().

Return The method returns the object self.

Description Method :initClass() is implicitly called from the Class function declared with the CLASS declaration. It serves the purpose of initializing class members which exist only once in a class and have the same values for all instances of a class. An alternative initialization of class variables is provided with the INIT clause of the CLASSDATA declaration of a class. This is the recommended way for initializing class variables.

1238

Class Reference (textmode)

HBObject class - Methods for object inspection

Methods for object inspection

:className() Retrieves the name of the class an object belongs to.

Syntax :className() --> cClassName

Return The method returns a character string holding the name of the class.

Description It is often required in object oriented programming to identify the exact class an object belongs to. This is accomplished by retrieving the object's class name with :className().

:classSel() Retrieves the messages understood by an object.

Syntax :classSel() --> aMessages

Return The method returns a one-dimensional array. Its elements contain character strings holding the symbolic names of the messages declared in the object's class. !DESRCIPTION Method :classSel() is used to query the symbolic member names of an object's class and super class(es). Member names are declared in the CLASS declaration. They form the messages understood by an object and are declared with DATA or METHOD within the class declaration.

:isDerivedFrom() Checks if an object belongs to or is derived from a class.

Syntax :isDerivedFrom( | ) --> lIsDerived

Return The method returns .T. (true) if the object executing the method belongs to or is derived from the specified class, otherwise .F. (false) is returned.

Description Method :isDerivedFrom() is a synonym for method :isKindOf(). Refer to this method.

Class Reference (textmode)

1239

HBObject class - Methods for object inspection

:isKindOf() Checks if an object is kind of a class.

Syntax :isKindOf( | ) --> lIsKindOf

Arguments

This is a second object which is compared with self

Alternatively, the class to compare self with can be specified as a character string holding the class name.

Return The method returns .T. (true) if the object executing the method is kind of the specified class, otherwise .F. (false) is returned.

Description Method :isKindOf() is used to check if an object is either an instance of the specified class, or if it knows the same member variables and methods. The latter is the case when the class of is a super class of self. A sub-class is always "kind of" a super class.

Methods for error ha ndling

:error() Creates a runtime error.

Syntax oHBObject:error(

, , , ,

; ; ; ; ) --> xReturn

Arguments

This is a character string describing the error (see oError:description).

This is the class name of the object (self:className()).

This is a character string holding the name of the method currently being executed. 1240

Class Reference (textmode)

HBObject class - Methods for error handling

This is a numeric error code (see oError:genCode).

This is an array holding the values involved with the runtime error (see oError:genCode).

Return The method returns the value of the current error handling code block.

Description Method :error() provides a convenient way for raising a runtime error within methods. The parameters passed to the method are filled ino an Error() object which is passed to the current ErrorBlock(). A simple usage scenario for the :error() method is shown below. It reduces the amount of code for creating an Error() object by a great extent: #include "hbclass.ch" #include "Error.ch" PROCEDURE Main LOCAL obj := Test():new() ? obj:calc( 2, 9 ) ? obj:calc( "ABCD", 0x77 ) RETURN

CLASS Test EXPORTED: METHOD Calc ENDCLASS METHOD calc( n1, n2 ) CLASS Test IF Valtype( n1 ) + Valtype( n2) "NN" RETURN ::error( "Type mismatch", ::className(), "calc", EG_ARG, {n1,n2} ) ENDIF RETURN n1 * n2

:msgNotFound() Handles unknown messages sent to an object.

Syntax :msgNotFound( ) --> xReturn

Arguments

This is a character string holding the symbolic name sent to the object self.

Return If not overloaded, the method returns the result of the :error() method. Class Reference (textmode)

1241

HBObject class - Methods for error handling

Description Method :msgNotFound() is called when the symbolic name of a message sent to an object does not exist in the class or its super class(es). It receives as parameter a character string holding the message name that does not exist. Note: This method cannot be overloaded in a user-defined class with a regular METHOD declaration. :msgNotFound() is only replaced with the ERROR HANDLER declaration.

Info See also: Category: Source: LIB: DLL:

1242

CLASS, DATA, ERROR HANDLER, METHOD (declaration) Object functions, xHarbour extensions rtl\tobject.prg xhb.lib xhbdll.dll

Class Reference (textmode)

HBPersistent()

HBPersistent() Abstract base class for user-defined persistent object.

Description The HBPersistent() class is an abstract class for the creation of persistent objects. When user-defined classes should become persistent, they must inherit from HBPersistent() which provides methods for converting an object to/from a binary string and/or file on disk. All instance variables declared with the PERSISTENT attribute are preserved and re-assigned when a persistent object is converted to a binary string and back to the Object data type. Note: if code blocks are stored in instance variables of a persistent object, the same restrictions apply as outlined with function HB_Serialize().

Methods for saving an object

:saveToFile() Writes the persistent object data to a file.

Syntax :saveToFile( ) --> lSuccess

Arguments

This is a character string holding the name of the file to create. It must include path and file extension. If the path is omitted from , the file is created in the current directory.

Description Method :saveToFile() creates the file and writes into it the binary data of the object executing the method. If the file exists already, it is overwritten. The save data can be copied back to an object using method :loadFromFile()

:saveToText() Creates a binary string from the data held in an object.

Syntax :saveToText() --> cBinaryString

Description Method :saveToText() copies the data held in instance variables of the object into a binary string, which is returned. The object can copy the data back to its instance variables using method :loadFromText(). Class Reference (textmode)

1243

HBPersistent class - Methods for restoring an object

Methods fo r restoring an object

:loadFromFile() Loads persistent object from a file.

Syntax :loadFromFile( ) --> lSuccess

Arguments

This is a character string holding the name of the file to read. It must include path and file extension. If the path is omitted from , the file is searched in the current directory.

Description Method :loadFromFile() reads binary data from the file and copies it to the object executing the method. The file must be created by the method :saveToFile() If the file does not exists, a runtime error is raised.

:loadFromText() Copies data held in a binary string to an object.

Syntax :loadFromText( ) --> lSuccess

Description Method :loadFromText() copies the data held in to the instance variables of the object. Only instance variables declares as PERSISTENT receive values from the binary string. The latter must be created with method :saveToText().

Info See also: Category: Source: LIB: DLL:

CLASS, DATA, HB_Serialize() Object functions, xHarbour extensions rtl\persist.prg xhb.lib xhbdll.dll

Example // The example demonstrates the steps required to make objects // persistent. Only the instance variables with the PERSISTENT // attribute are written to and restored from the file. #include "HbClass.ch" PROCEDURE Main LOCAL obj, cPersistent

1244

Class Reference (textmode)

HBPersistent class - Methods for restoring an object obj := test():new() obj:volatile := "Volatile" obj:show() obj:value := "Data from file"

obj:saveToFile( "Persist.txt" ) obj := NIL WAIT "obj is gone, press a key..." obj := Test():new() obj:loadFromFile( "Persist.txt" ) obj:show() ? "Elapsed:", RETURN

Seconds()-obj:secs

CLASS Test FROM HBPersistent DATA value INIT "Test persistent Object" DATA date INIT Date() DATA time INIT Time() DATA secs INIT Seconds() DATA volatile METHOD show ENDCLASS METHOD Show ? ::value ? "Creation Date:", ? "Creation Time:", ? " Timestamp:", ? "Volatile data:", RETURN

Class Reference (textmode)

PERSISTENT PERSISTENT PERSISTENT PERSISTENT

::date ::time ::secs ::volatile

1245

MenuItem()

MenuItem() Creates a new MenuItem object.

Syntax MenuItem():new( , |, [] , [] , []

; ; ; ; ) --> oMenuItem

Arguments

This is a character string displayed as the caption of a menu item. An accelerator key can be marked in the caption string by prefixing it with an ampersand (&). A menu item is then selected when a user presses the prefixed character. It is assigned to the instance variable :caption. Instead of a character string, the #define constant MENU_SEPARATOR from Button.ch can be passed for . This creates a horizonal separator line to distinguish logical groups of menu items within a Popup menu.

This is the menu activation code block which calls the subroutine after a user has selected the menu item. It is assigned to the instance variable :data.

Instead of a code block, a Popup() menu object can be specified as second parameter. In this case, a sub-menu is opened when the menu item is selected. This allows for programming menu systems with nested sub-menus.

Optionally, a numeric Inkey() code can be passed that serves as shortcut key for evaluating . It is assigned to the instance variable :shortCut.

A character string holding a status message associated with a menu item can optionally be specified. It is displayed in the message row when a TopBarMenu() is activated. is assigned to the instance variable :message.

An optional numeric value can be passed which is stored in the instance variable :ID. If this parameter is used, it should be a unique value for each MenuItem object created.

Return Function MenuItem() creates a new MenuItem object, and method :new() initializes the object.

Description The MenuItem() class is a utility class whose objects are only used in conjunction with TopBarMenu() and/or Popup() objects. A MenuItem() object holds in its instance variables all information required to 1246

Class Reference (textmode)

MenuItem()

display a single menu item within a top bar menu or a pop-up menu, and to branch program control after a user has selected a menu item. Note: refer to the example of the TopBarMenu() class for using MenuItem() objects.

Instance variables

:caption Caption string of the menu item. Data type: C Default: ""

Description The instance variable :caption holds the character string that is actually displayed on screen within a TopBarMenu() or a Popup() menu. The caption may also define the accelerator key for a menu item by prefixing a single character in the caption string with an ampersand (&). If present, the corresponding character is displayed in a different color than the rest of the caption. When a MenuItem object is contained in a TopBarMenu() object, a user can select a menu item by pressing the accelerator key together with the Alt key. If the MenuItem object is maintained by a Popup() menu, the menu item is selected when a user presses only the accelerator key. Note: if :caption contains the #define constant MENU_SEPARATOR from Button.ch, the menu item is displayed as a horizontal separator line and becomes not accessible.

:cargo Instance variable for user-defined purposes. Data type: ANY Default: NIL

Description This instance variable is not used by a MenuItem object. It is available for user-defined purposes when an arbitrary value should be attached to a MenuItem object.

:checked Logical value indicating a check mark. Data type: L Default: .F.

Description When .T. (true) is assigned to :checked, a check mark is displayed to the left of the caption string within a Popup() menu. Otherwise, no check mark is displayed. The character used for the check mark is the first character of the string assigned to the :style instance variable. Class Reference (textmode)

1247

MenuItem class - Instance variables

:data Menu selection code block or Popu menu object. Data type: Default:

B,O NIL

Description The instance variable :data contains either a code block or a Popup() menu object, unless a menu item's caption is the #define constant MENU_SEPARATOR. If :data is a code block, it is eveluated when a menu item is selected. The code block receives as parameter the MenuItem object containing the code block. If :data contains a Popup() menu object, this pop-up menu is opened upon menu selection.

:enabled Logical value indicating if a menu item can be selected. Data type: Default:

L .T.

Description When .T. (true) is assigned to :enabled, the menu item is accessible when a menu is activated. Assigning .F. (false) makes the menu item unaccessible for the user.

:id Numeric identifier for a menu item. Data type: Default:

N NIL

Description The instance variable :ID is assigned the fifth parameter passed to the :new() method. It can be used to uniquely identify a menu item when a user makes a menu selection. Refer to the example of the TopBarMenu() class to see how :ID can be used for branching program cotrol within a SWITCH statement.

:message Character string describing a menu item. Data type: Default:

C NIL

Description The instance variable :message contains the fourth parameter passed to the :new() method. It is a character string displayed in the message row of a TopBatMenu() object when the menu is activated.

1248

Class Reference (textmode)

MenuItem class - Instance variables

:shortCut Numeric shortcut key. Data type: N Default: NIL

Description The instance variable :shortCut contains the third parameter passed to the :new(). It specifies the Inkey() code that evaluates the :data code block when a MenuItem object is contained in a Popup() menu object, and this menu is not open. If a MenuItem object is contained in a TopBarMenu() object, the :shortCut key has no effect.

:style Character string for check mark and sub-menus Data type: ANY Default: HB_TMENUITEM_STYLE

Description The instance variable :style contains a string of two characters. The first character is displayed to the left of the caption string, when :checked contains .T. (true). The second character is displayed to the right of the caption string, when :isPopup() returns .T. (true). The default characters are given by the #define constant HB_TMENUITEM_STYLE of Button.ch.

Methods

:isPopUp() Checks if the menu item opens a sub-menu.

Syntax :isPopUp() --> lIsPopup

Description Method :isPopup() returns .T. (true) when a Popup() menu object is stored in :data, otherwise .F. (false) is returned.

Info See also: Category: Header: Source: LIB: DLL:

@...GET, MenuModal(), Popup(), READ, SetColor(), TopBarMenu() Get system, Object functions Box.ch, Button.ch rtl\tmenuitm.prg xhb.lib xhbdll.dll

Class Reference (textmode)

1249

Popup()

Popup() Creates a new Popup menu object.

Syntax PopUp():new( [] , [] , [], []

; ; ; ) --> oPopUpMenu

Arguments and

Numeric values indicating the screen coordinates for the upper left corner of the Popup menu. The default value for and is -1. These values are assigned to the instance variables :top and :left. and

Numeric values indicating the screen coordinates for the lower right corner of the Popup menu. The default value for and is -1. These values are assigned to the instance variables :bottom and :right.

Return Function Popup() creates a new Popup menu object, and method :new() initializes the object.

Description The Popup class provides objects maintaining po-pup or pull-down menus. After creation of a Popup object, one or more MenuItem() objects must be added with method :addItem(). They contain information on the menu items to display in a pop-up menu. A Popup menu object is made visible with its :open() method, which maintains a rectangular area on the screen where the menu items are displayed. The :close() method hides the menu. Popup menu objects are designed to be integrated into a TopBarMenu() object for creating a complete menu system consisting of a horizontal top bar menu that includes a series of (nested) pull-down menus. If a Popup menu object is added to TopBarMenu object, the screen coordinates for the Popup menu are calculated automatically for proper display. In this case, no screen coordinates are required for method :new(). Note: refer to the example of the TopBarMenu() class for using Popup menu objects.

1250

Class Reference (textmode)

Popup class - Instance variables

Instance variables

:border Character string for thesurrounding border. Data type: C Default: B_SINGLE

Description The instance variable :border holds a character string used to display a border around the Popup menu. It is the same string used for function DispBox(). The default is a single line border. To change the default, #define constants listed in Box.ch can be used. They begin with the prefix B_*.

:bottom Numeric bottom screen row for display. Data type: N Default: 0

Description The instance variable :bottom contains a numeric value. It is the bottom screen row of the Popup menu.

:cargo Instance variable for user-defined purposes. Data type: ANY Default: NIL

Description This instance variable is not used by a Popup menu object. It is available for user-defined purposes when an arbitrary value should be attached to a Popup menu object.

:colorSpec Color string for the Popup menu display. Data type: C Default: "N/W,W/N,W+/W,W+/N,N+/W,W/N"

Description The instance variable :colorSpec holds a color string with six color values. It is initialized with the string "N/W,W/N,W+/W,W+/N,N+/W,W/N". The individual color values are used for the following purposes:

Class Reference (textmode)

1251

Popup class - Instance variables

Colors for Popup menus Color value

Used for display of

1 2 3 4 5 6

unselected menu items selected menu item accelerator key of unselected menu items accelerator key of selected menu item disabled menu items menu border

:current Currently selected menu item. Data type: Default:

N 0

Description The instance variable :current contains a numeric value indicating the ordinal position of the currently selected menu item. Items are numbered from 1 to :itemCount. If no menu item is selected, :current contains zero.

:itemCount Number of menu items. Data type: Default:

N 0

Description The instance variable :itemCount contains a numeric value indicating the number of menu items, or MenuItem() objects, maintained by a Popup menu object.

:left Numeric left screen column for display. Data type: N Default: -1

Description The instance variable :left contains a numeric value. It is the screen coordinate of the left column of the Popup menu.

1252

Class Reference (textmode)

Popup class - Instance variables

:right Numeric right screen column for display. Data type: N Default: 0

Description The instance variable :right contains a numeric value. It is the screen coordinate of the right column of the Popup menu.

:top Numeric top screen row for display. Data type: N Default: -1

Description The instance variable :bottom contains a numeric value. It is the top screen row of the Popup menu.

:width Numeric width for display. Data type: N Default: 0

Description The instance variable :width contains a numeric value. It is the total width of the Popup menu.

Menu item methods

:addItem() Adds a MenuItem object to a Popup menu object.

Syntax :addItem( ) --> self

Arguments

This is the MenuItem() object to add to the Popu object.

Description Method :addItem() accepts a MenuItem() object and adds it to the internal list of menu items. The return value is the self object. The instance variable :itemCount reflects the new number of MenuItem() objects maintained by a Popup object. Class Reference (textmode)

1253

Popup class - Menu item methods

:delItem() Deletes a MenuItem object from a Popup object.

Syntax :delItem( ) --> self

Arguments

This is a numeric value specifying the ordinal position of the menu item to delete from the Popup object. Menu items are numbered from 1 to :itemCount.

Description Method :delItem() can be used to remove a single menu item from a Popup object. This can be useful when the number of selectable menu items changes dynamically at runtime, depending on a condition. Alternatively, single menu items can be disabled or enabled.

:getFirst() Retrieves the ordinal position of the first selectable menu item.

Syntax :getFirst() --> nFirstMenuItemPos

Description Method :getFirst() returns a numeric value indicating the ordinal position of the first, or toptmost, selectable menu item. When a menu item is disabled, it cannot be accessed by the user. When no menu item can be selected, the return value is zero.

:getItem() Retrieves a MenuItem object from a Popup object.

Syntax :getItem( ) --> oMenuItem

Arguments

This is a numeric value specifying the ordinal position of the menu item to retrieve from the Popup object. Menu items are numbered from 1 to :itemCount.

Description Method :getItem() is used to retrieve the MenuItem() object at position from a Popup object.

1254

Class Reference (textmode)

Popup class - Menu item methods

:getLast() Retrieves the ordinal position of the last selectable menu item.

Syntax :getLast() --> nLastMenuItemPos

Description Method :getLast() returns a numeric value indicating the ordinal position of the last selectable menu item at the bottomof aPupup menu. When a menu item is disabled, it cannot be accessed by the user. When no menu item can be selected, the return value is zero.

:getNext() Retrieves the ordinal position of the next selectable menu item.

Syntax :getNext() --> nNextMenuItemPos

Description Method :getNext() returns a numeric value indicating the ordinal position of the selectable menu item below the currently selected menu item. When a menu item is disabled, it cannot be accessed by the user. If the current menu item is the last one, or when no menu item can be selected, the return value is zero.

:getPrev() Retrieves the ordinal position of the previous selectable menu item.

Syntax :getPrev() --> nPrevMenuItemPos

Description Method :getPrev() returns a numeric value indicating the ordinal position of the selectable menu item above the currently selected menu item. When a menu item is disabled, it cannot be accessed by the user. If the current menu item is the first one, or when no menu item can be selected, the return value is zero.

:insItem() Inserts a MenuItem object into a Popup object.

Syntax :insItem( , ) --> self

Class Reference (textmode)

1255

Popup class - Menu item methods

Arguments

This is a numeric value specifying the ordinal position where to insert the menu item. The value for must be in the range from 1 to :itemCount. Otherwise, it is ignored.

This is the MenuItem() object to insert into the Popup object.

Description Method :insItem() accepts a MenuItem() object and inserts it into the internal list of menu items at position . The return value is the self object. The instance variable :itemCount reflects the new number of MenuItem() objects maintained by a Popup object. If is outside the valid range, the number of menu items remains unchanged.

:setItem() Replaces a MenuItem object in a Popup object.

Syntax :setItem( , ) --> self

Arguments

This is a numeric value specifying the ordinal position of the menu item to replace. The value for must be in the range from 1 to :itemCount. Otherwise, it is ignored.

This is the MenuItem() object that replaces an existing one in the Popup object.

Description Method :setItem() accepts a MenuItem() object and replaces the existing MenuItem object at position . The return value is the self object. If is outside the valid range, no menu item is replaced.

Menu display and selection

:close() Hides a visible Popup menu.

Syntax :close() --> self

1256

Class Reference (textmode)

Popup class - Menu display and selection

Description Method :close() hides a visible Popup menu and displays the screen contents covered by the menu. If the menu is not visible, the method has no effect. The return value is the self object.

:display() Displays a Popup menu.

Syntax :display() --> self

Description Method :display() draws the border of a Popup menu and then iterates through the internal list of MenuItem() objects to display their captions within the rectangular area of the menu.

:getAccel() Determines if a key code identifies an accelerator key.

Syntax :getAccel( ) --> nMenuItemPos

Arguments

This is a numeric Inkey() code to check.

Description Method :getAccel() is used to check if a numeric inkey code is an accelerator key that should trigger a menu action. Accelerator keys are key combinations of the Alt key an a letter of a menu item caption prefixed with an ampersand (&). If the key code is an accelerator key, the method returns the ordinal position of the corresponding menu item as a numeric value. If it is not an accelerator, the return value is zero.

:getShortct() Determines if a key code identifies a shortcut key.

Syntax :getShortct( ) --> mMenuItemPos

Arguments

This is a numeric Inkey() code to check.

Class Reference (textmode)

1257

Popup class - Menu display and selection

Description Method :getShortct() is used to check if a numeric inkey code is a shortcut key that should trigger a menu action. Shortcut keys are defined when MenuItem() objects are created. They are stored in the instance variable :shortCut of MenuItem objects. If the key code is a shortcut key, the method returns the ordinal position of the corresponding menu item as a numeric value. If it is not a shortcut, the return value is zero.

:hitTest() Checks if a menu item is clicked with the mouse.

Syntax :hitTest( , ) --> nMenuItemPos

Arguments

This is the numeric row position of the mouse cursor. It can be queried using function MRow().

This is the numeric column position of the mouse cursor. It can be queried using function MCol().

Description Method :hitTest() accepts the numeric row and column position of the mouse cursor and returns a numeric value > 1 indicating the ordinal position of the menu item that is underneath the mouse cursor. If the mouse hit a non-selectable or disabled menu item inside the border of a popup menu, the return value is zero. When the border of the menu is clicked, the return value is negative and can be tested with #define constants available in Button.ch.

Constants for :hitTest() results Constant

Value

Description

HTTOPLEFT HTTOP HTTOPRIGHT HTRIGHT HTBOTTOMRIGHT HTBOTTOM HTBOTTOMLEFT HTLEFT

-1 -2 -3 -4 -5 -6 -7 -8

Mouse is on the upper left corner Mouse is on the top border Mouse is on the upper right corner Mouse is on the right border Mouse is on the lower right corner Mouse is on the bottom border Mouse is on the lower left corner Mouse is on the left border

:isOpen() Checks if a Popup menu is visible.

Syntax :isOpen() --> lIsOpen 1258

Class Reference (textmode)

Popup class - Menu display and selection

Description Method :isOpen() returns .T. (true) when a Popup menu is visible, otherwise .F: (false) is returned.

:open() Opens a Popup menu.

Syntax :open() --> self

Description Method :open() first saves the screen contents that will be covered by a Popup menu and then calls the :display(). If the menu is already visible, the method has no effect. The return value is the self object.

:select() Changes the currently selected menu item.

Syntax :select( ) --> nMenuItemPos

Arguments

This is a numeric value specifying the ordinal position of the menu item to select as current. The value for must be in the range from 1 to :itemCount. Otherwise, it is ignored.

Description Method :select() defines the menu item at position as currently selected item. The selected menu item is displayed highlighted when method :display() is executed.

Info See also: Category: Header: Source: LIB: DLL:

@...GET, MenuItem(), MenuModal(), TopBarMenu(), SetColor() Get system, Object functions Box.ch, Button.ch rtl\tpopup.prg xhb.lib xhbdll.dll

Class Reference (textmode)

1259

TBColumn()

TBColumn() Creates a new TBColumn object.

Syntax TBColumn():new( , ) --> oTBColumn

Arguments

This is a character string which is displayed in the column heading of a TBrowse() display.

This is a code block which returns the data to be displayed within the data area of one column of a TBrowse() display.

Return Function TBColumn() returns a new TBColumn object and method :new() initializes the object.

Description TBColumn objects are required for creating a browser in text mode applications. They are always used in conjunction with a TBrowse() object which is a container for TBColumn objects. A TBColumn object contains all information required for displaying a single column of data in a browse view. As a consequence, TBColumn objects are useless on their own and must be added to a TBrowse object with its :addColumn() method.

Instance variables

:block Code block to retrieve data for the column. Data type: Default:

B NIL

Description The instance variable :block must be assigned a code block which returns the data to be displayed in a single column of a browse view. When the data source is a database file, the return value of function FieldBlock() or FieldWBlock() can be assigned to :block.

1260

Class Reference (textmode)

TBColumn class - Instance variables

:cargo Instance variable for user-defined purposes. Data type: ANY Default: NIL

Description This instance variable is not used by a TBColumn object. It is available for user-defined purposes when an arbitrary value should be attached to a TBColumn object.

:colorBlock Code block selecting the color of data cells depending on their values Data type: B Default: NIL

Description The instance variable :colorBlock can be assigned a code block which selects the color for a single data cell within a column of data. If it is present, :colorBlock is passed the return value of :block, which is the data to be displayed. :colorBlock must return an array with two numeric elements. Each element points to a color value of the color string stored in the instance variable :colorSpec of the TBrowse object containing the TBColumn object. The first element selects the color for normal display of the data cell, and the second points to the color to use for highlighting the data cell.

:colSep Characters used as vertical column separator. Data type: C Default: NIL

Description The instance variable :colSep holds a character string of one of more characters which are displayed as a separator between data columns in the browse view. The initial value for :colSep is NIL, which causes the column separator defined for the TBrowse object being displayed. If a TBColumn object has its own :colSep assigned, it overrides the column separator specified for the TBrowse object.

:defColor Array holding numeric indexes into the color table of TBrowse Data type: A Default: {1,2,1,1}

Description The instance variable :defColor contains an array of four numeric values. They are used as indexes into the color string stored in the instance variable :colorSpec of the TBrowse object containing a TBColumn object. The first element selects the color for normal data display, the second highlights a data cell (the browse cursor), the third selects the color for the column heading and the fourth is used for the column footing. Note that :colorBlock overrides :defColor. Class Reference (textmode)

1261

TBColumn class - Instance variables

:footing Character string displayed as column footing. Data type: Default:

C ""

Description A character string can be assigned to :footing which is displayed as column footing. The semicolon serves as line-break character when a column footing should be displayed in multiple lines. To change a column footing after a browse view is displayed, method :configure() of the TBrowse object containing the column must be called.

:footSep Characters used as horizontal separator for column footings. Data type: Default:

C ""

Description The instance variable :footSep holds a character string of one of more characters which are displayed as a separator between the data area and the column footing. The initial value for :footSep is an empty string ("") which suppresses the display of a footing separator. If :footSep contains more than one character, the last character is displayed across the width of a column, while the first character is displayed at the position of :colSep.

:heading Character string displayed as column heading. Data type: Default:

C ""

Description A character string can be assigned to :heading which is displayed as column heading. The semicolon serves as line-break character when a column heading should be displayed in multiple lines. To change a column heading after a browse view is displayed, method :configure() of the TBrowse object containing the column must be called.

:headSep Characters used as horizontal separator for column headings. Data type: Default:

C NIL

Description The instance variable :headSep holds a character string of one of more characters which are displayed as a separator between the data area and the column heading. The initial value for :headSep is an empty string ("") which suppresses the display of a heading separator. If :headSep contains more than one 1262

Class Reference (textmode)

TBColumn class - Instance variables

character, the last character is displayed across the width of a column, while the first character is displayed at the position of :colSep.

:picture Character string holding a PICTURE format. Data type: C Default: NIL

Description The instance variable :picture holds a PICTURE formatting string used for displaying values in a column. Refer to function Transform() for a comprehensive description of PICTURE formatting strings.

:postBlock Code block for data validation. Data type: B Default: NIL

Description Optionally, a code block can be assigned to :postValidate that is used to validate edited data. This code block is not used by a TBColumn object but provides a convenient way for implementing editable browsers. :postBlock can be used by a Get() object when the current cell in a column should be edited.

:preBlock Code block for edit validation. Data type: B Default: NIL

Description Optionally, a code block can be assigned to :preValidate that is used to test if editing is allowed. This code block is not used by a TBColumn object but provides a convenient way for implementing editable browsers. :preBlock can be used by a Get() object when the current cell in a column should be edited.

:width Numeric width of column. Data type: N Default: 0

Description The instance variable :width contains a numeric value representing the width of a column on the screen. If no value is assigned, :width it is initialized upon initial display of the column. The width is calculated as the maximum length of :heading, :footing and data area of a column when :block is evaluated for the first time. Class Reference (textmode)

1263

TBColumn class - Instance variables

Assigning 0 to :width makes the column unvisible although it is still present in a TBrowse object.

Methods

:setStyle() Retrieves or changes a column style.

Syntax :setStyle( , [] ) --> lOldOnOff

Arguments

This is a numeric value indicating the style to query or change. #define constants are listed in the file TBrowse.ch which can be used for .

Constants for TBColumn styles Constant

Value

Description

TBC_READWRITE TBC_MOVE TBC_SIZE TBC_CUSTOM

1 2 3 4

Is the user allowed to edit cells in the column? Is the user allowed to move this column in the browser? Is the user allowed to resize this column in the browser? Minimum value for use-defined custom styles.



This is an optional logical value. When .T. (true) is passed, the style is switched on, .F. (false) switches it off.

Description A TBColumn object maintains a set of styles that can be switched on and off. The styles can be used as a convenient way of implementing specific behaviour for a TBColumn object. A TBColumn object itself does not use this information.

Info See also: Category: Header: Source: LIB: DLL:

TBrowse() Object functions tbrowse.ch rtl\tbcolumn.prg xhb.lib xhbdll.dll

Example // Refer to function TBrowse() for an example of TBColumn usage.

1264

Class Reference (textmode)

TBrowse()

TBrowse() Creates a new TBrowse object.

Syntax TBrowse():new( [] , [] , [], []

; ; ; ) --> oTBrowse

Arguments

This is the numeric screen coordinate for the top row of the browse display. It defaults to zero and is assigned to the instance variable :nTop.

This is the numeric screen coordinate for the left column of the browse display. It defaults to zero and is assigned to the instance variable :nLeft.

This is the numeric screen coordinate for the bottom row of the browse display. It defaults to MaxRow() and is assigned to the instance variable :nBottom.

This is the numeric screen coordinate for the right column of the browse display. It defaults to MaxCol() and is assigned to the instance variable :nRight.

Return Function TBrowse() returns a new TBrowse object and method :new() initializes the object.

Description TBrowse objects are used in text mode applications to display tabular data organized in rows and columns in a rectangular area on the screen. Common data sources for TBrowse objects are database files or arrays. In order to display such data, a TBrowse object must receive objects of the TBColumn() class which contain all information required for displaying a single column in a browse view. In addition, a TBrowse object must be assigned code blocks required for navigating the row pointer of the data source as a response to user input. The example below demonstrates all steps required to create a fully functional browse view with TBrowse and TBColumn objects.

Class Reference (textmode)

1265

TBrowse class - Instance variables

Instance variables

:autoLite Logical value for automatic highlighting of the browse cursor. Data type: Default:

L .T.

Description When :autoLite is set to .T. (true), which is the default, a TBrowse object automatically highlights the browse cursor when the browse display is stable. Setting :autoLite to .F. (false) requires the browse cursor be highlighted programmatically using method :hilite().

:border Character string defining a border to display around the browse display. Data type: Default:

C ""

Description The instance variable :border can be assigned a character string of eight characters which are used to display a border around the browse area. #define constants specifying standard borders are listed in the file BOX.CH. They can be used as values for :border. The border is drawn with function DispBox().

:cargo Instance variable for user-defined purposes. Data type: Default:

ANY NIL

Description This instance variable is not used by a TBrowse object. It is available for user-defined purposes when an arbitrary value should be attached to a TBrowse object.

:colCount Number of columns maintained by the TBrowse object Data type: Default:

N 0

(READONLY)

Description The instance variable :colCount contains a numeric value representing the number of columns, or TBColumn objects, maintained by a TBrowse object.

1266

Class Reference (textmode)

TBrowse class - Instance variables

:colorSpec Color string for the TBrowse display. Data type: C Default: SetColor()

Description The instance variable :colorSpec holds a color string with two or more color values. It is initialized with the return value of SetColor(). By default, a TBrowse object uses the first color value for displaying the column headings and data rows, and the second color for highlighting the browse cursor. This default behavior can be overriden for individual columns by using :defColor or :colorBlock of a single TBColumn() object.

:colPos Numeric column position of the browse cursor. Data type: N Default: 0

Description The instance variable :colPos contains a numeric value indicating the current column position of the browse cursor. Columns are numbered beginning with one, which is the leftmost column. The column position of the browse cursor can be changed by assigning a value between 1 and :colCount to :colPos. This causes the TBrowse object to perform a complete stabilization cycle.

:colSep Characters used as vertical column separator. Data type: C Default: ""

Description The instance variable :colSep holds a character string of one of more characters which are displayed as a separator between data columns during a stabilization cycle. The initial value for :colSep is a blank space. If a TBColumn object has its own :colSep assigned, it overrides the column separator specified for the TBrowse object.

:footSep Characters used as horizontal separator for column footings. Data type: C Default: ""

Description The instance variable :footSep holds a character string of one of more characters which are displayed as a separator between the data area and the column footings. The initial value for :footSep is an empty string ("") which suppresses the display of a footing separator. If :footSep contains more than one character, the last character is displayed across the width of a column, while the first character is Class Reference (textmode)

1267

TBrowse class - Instance variables

display at the position of :colSep. If a TBColumn object has its own :footSep assigned, it overrides the footing separator specified for the TBrowse object.

:freeze Number of columns to freeze in the browse display. Data type: Default:

N 0

Description The instance variable :freeze can be assigned a numeric value which indicates the number of columns to remain fixed and visible on the left side of the browse display. Frozen columns are not moved by horizontal scrolling.

:goBottomBlock Code block that navigates the data source to the last row. Data type: Default:

B NIL

Description The instance variable :goBottomBlock must be assigned a code block which navigates the row pointer of the data source to the last row. This code block is evaluated in method :goBottom(). When the data source is a database file, a typical code block for :goBottomBlock is {|| DbGoBottom() }.

:goTopBlock Code block that navigates the data source to the first row. Data type: Default:

B NIL

Description The instance variable :goTopBlock must be assigned a code block which navigates the row pointer of the data source to the first row. This code block is evaluated in method :goTop(). When the data source is a database file, a typical code block for :goTopBlock is {|| DbGoTop() }.

:headSep Character used as horizontal separator for column headings. Data type: Default:

C ""

Description The instance variable :headSep holds a character string of one of more characters which are displayed as a separator between the data area and the column headings. The initial value for :headSep is an empty string ("") which suppresses the display of a heading separator. If :headSep contains more than one character, the last character is displayed across the width of a column, while the first character is 1268

Class Reference (textmode)

TBrowse class - Instance variables

display at the position of :colSep. If a TBColumn object has its own :headSep assigned, it overrides the heading separator specified for the TBrowse object.

:hitBottom Indicates that the browser reached the end of the data source. Data type: L Default: .F.

Description The instance variable :hitBottom contains .T. (true) when a user attempts to navigate the row pointer of the data source past the last row. In all other cases it contains .F. (false). :hitBottom is set during a stabilization cycle.

:hitTop Indicates that the browser reached the beginning of the data source. Data type: L Default: .F.

Description The instance variable :hitTop contains .T. (true) when a user attempts to navigate the row pointer of the data source before the first row. In all other cases it contains .F. (false). :hitTop is set during a stabilization cycle.

:leftVisible Numeric position of the leftmost unfrozen column in the browse display. Data type: N Default: 1

Description The instance variable :leftVisible contains a numeric value indicating the ordinal position of the leftmost unfrozen column. Unfrozen columns can be scrolled horizontally. If all columns are frozen, :leftVisible contains zero.

:mColPos Numeric column position of the mouse cursor within the browse display. Data type: N Default: 0

Description The instance variable :mColPos contains a numeric value indicating the ordinal position of the column where the mouse cursor is currently located. Columns are numbered beginning with one, which is the leftmost column.

Class Reference (textmode)

1269

TBrowse class - Instance variables

:message Character string to display in the Get system's status line Data type: Default:

C ""

Description The instance variable :message can be assigned a character string when a TBrowse object is used with the Get system. The message string is displayed in the status line of the Get system when the READ command or function ReadModal() is executed.

:mRowPos Numeric row position of the mouse cursor within the browse display. Data type: Default:

N 0

Description The instance variable :mRowPos contains a numeric value indicating the ordinal position of the data row where the mouse cursor is currently located. Data rows are numbered from 1 to :rowCount.

:nBottom Numeric bottom row coordinate of the browse display. Data type: Default:

N MaxRow()

Description The instance variable :nBottom contains a numeric value. It is the screen coordinate of the bottom row of the browse window. Assigning a new value to :nBottom invalidates the entire browse display. To stabilize the TBrowse object after changing :nBottom requires a complete stabilization cycle.

:nLeft Numeric left column coordinate of the browse display Data type: Default:

N 0

Description The instance variable :nLeft contains a numeric value. It is the screen coordinate of the left column of the browse window. Assigning a new value to :nLeft invalidates the entire browse display. To stabilize the TBrowse object after changing :nLeft requires a complete stabilization cycle.

1270

Class Reference (textmode)

TBrowse class - Instance variables

:nRight Numeric right column coordinate of the browse display Data type: N Default: MaxCol()

Description The instance variable :nRight contains a numeric value. It is the screen coordinate of the right column of the browse window. Assigning a new value to :nRight invalidates the entire browse display. To stabilize the TBrowse object after changing :nRight requires a complete stabilization cycle.

:nTop Numeric top row coordinate of the browse display Data type: N Default: 0

Description The instance variable :nTop contains a numeric value. It is the screen coordinate of the top row of the browse window. Assigning a new value to :nTop invalidates the entire browse display. To stabilize the TBrowse object after changing :nTop requires a complete stabilization cycle.

:rightVisible Numeric position of the rightmost unfrozen column in the browse display. Data type: N Default: 1

Description The instance variable :rightVisible contains a numeric value indicating the ordinal position of the rightmost unfrozen column that is visible. Unfrozen columns can be scrolled horizontally. If all columns are frozen, :rightVisible contains zero.

:rowCount Number of data rows in the browse display. Data type: N Default: 0

Description The instance variable :rowCount contains a numeric value representing the number of rows in the data area displayed by a TBrowse object.

Class Reference (textmode)

1271

TBrowse class - Instance variables

:rowPos Numeric row position of the browse cursor. Data type: Default:

N 1

Description The instance variable :rowPos contains a numeric value indicating the current row position of the browse cursor within the browse display. The row position of the browse cursor can be changed by assigning a value between 1 and :rowCount to :rowPos. This causes the TBrowse object to perform a complete stabilization cycle.

:skipBlock Code block that navigates the row pointer of the data source. Data type: Default:

B NIL

Description The instance variable :skipBlock must be assigned a code block which navigates the row pointer of the data source. This code block is evaluated in method :stabilize() or :forceStable(). The code block must accept one numeric parameter which is the number of rows the row pointer must be changed during a single stabilization cycle. The return value of :skipBlock must be numeric as well. It tells the Tbrowse object how far the row pointer of the data source was actually skipped. When the data source is a database file, a typical code block for :skipBlock is: oTBrowse:skipBlock := {|nSkip| DbSkipper(nSkip) }

This code block calls the utility function DbSkipper() which navigates the browse cursor upon request of a TBrowse object.

:stable Indicates that the browse display is stable. Data type: Default:

L .F.

Description The instance variable :stable contains .T. (true) when a TBrowse object has completed a stabilization cycle. Method :stabilize() must be called as long as :stable contains .F. (false) in order to display data for all rows and columns of the browser.

1272

Class Reference (textmode)

TBrowse class - Methods for columns

Methods for columns

:addColumn() Adds a TBColumn object to a TBrowse object.

Syntax :addColumn( ) --> oTBColumn

Arguments

This is the TBColumn object to add to the TBrowse object.

Description Method :addColumn() accepts a TBColumn() object and adds it to the internal list of column objects. The return value is the added object. The instance variable :colCount reflects the new number of column objects maintained by a TBrowse object. When the TBColumn object is added, the entire TBrowse display is invalidated and all data from the data source is re-read during the next stabilization cycle.

:colWidth() Returns the width of a column in the browse display.

Syntax :colWidth( ) --> nColumnWidth

Arguments

This is a numeric value specifying the ordinal position of the column whose width should be returned. Columns are numbered from 1 to :colCount.

Description Method :colWidth() is used to determine the width of a single column in the TBrowse display. If no column exists at position , the return value is zero.

:delColumn() Removes a TBColumn object from a TBrowse object.

Syntax :delColumn( ) --> oTBColumn

Class Reference (textmode)

1273

TBrowse class - Methods for columns

Arguments

This is a numeric value specifying the ordinal position of the column to remove from the browser. Columns are numbered from 1 to :colCount.

Description Method :delColumn() is used to remove a single column from a TBrowse object. The method returns the removed object so that it can be preserved and inserted at another position. When the TBColumn object is removed, the entire TBrowse display is invalidated and all data from the data source is re-read during the next stabilization cycle.

:getColumn() Retrieves a TBColumn object from a TBrowse object.

Syntax :getColumn( ) --> oTBColumn

Arguments

This is a numeric value specifying the ordinal position of the column to retrieve from the browser. Columns are numbered from 1 to :colCount.

Description Method :getColumn() retrieves the TBColumn object at position from a TBrowse object. If the TBColumn object is changed, the TBrowse object must be notified about such changes by calling one of the methods :configure(), :invalidate() or :refreshAll(). Changes made to the TBColumn object become then visible during the next stabilization cycle.

:insColumn() Inserts a TBColumn object into a TBrowse object.

Syntax :insColumn( , ) --> oTBColumn

Arguments

This is a numeric value specifying the ordinal position where to insert a TBColumn object in the browser.

This is the TBColumn object to insert into the TBrowse object.

1274

Class Reference (textmode)

TBrowse class - Methods for columns

Description Method :insColumn() accepts a TBColumn() object and inserts it into the internal list of column objects. The return value is the inserted object. The instance variable :colCount reflects the new number of column objects maintained by a TBrowse object. When the TBColumn object is inserted, the entire TBrowse display is invalidated and all data from the data source is re-read during the next stabilization cycle.

:setColumn() Replaces a TBColumn object within a TBrowse object

Syntax :setColumn( , ) --> oTBColumnOld

Arguments

This is a numeric value specifying the ordinal position of the TBColumn object to replace in the browser.

This is the TBColumn object that replaces an existing one in the TBrowse object.

Description Method :setColumn() accepts a TBColumn() object and replaces the existing column object at position . The return value is the replaced TBColumn object. When the TBColumn object is replaced, the entire TBrowse display is invalidated and all data from the data source is re-read during the next stabilization cycle.

Display methods

:colorRect() Changes the color of a group of cells in the browse display.

Syntax :colorRect( , ) --> self

Arguments := { , , , }

This is an array holding four numeric values. They specify the ordinal positions of the data rows and columns of a rectangular area in the browse display whose color should be changed. := { , }

This is an array holding two numeric values. They specify the color values of the color string held in :colorSpec to use for display. The first element points to the color value for normal Class Reference (textmode)

1275

TBrowse class - Display methods

display and the second element indicates the color for highlighting a cell, or the browse cursor, respectively.

Description Method :colorRect() can be used to change the color of a rectangular area within the data rows of the browse display. This area is defined using ordinal positions of data rows and columns, not screen coordinates. The top and bottom borders of the rectangle must be specified as ordinal row positions in the range from 1 to :rowCount, and the left and right borders are ordinal column positions ranging from 1 to :colCount. The two array elements of point to color values of the color string held in :colorSpec. The first element selects the color for normal display while the second determines the color for the browse cursor when it is moved into the rectangular area . When the colored area is scrolled vertically outside the browse display, the cells in this area do not retain the changed color.

:configure() Reconfigures the internal data of a TBrowse object.

Syntax :configure() --> self

Description Method :configure() instructs a TBrowse object to recalculate the entire browse display and inspect all TBColumn objects stored in the internal list of columns. All data is re-read from the data source and the browse display is refreshed during the next stabilization cycle. :configure() needs to be called when certain instance variables of TBColumn objects are changed while the browser is visible. For example, when oTBColumn:width or oTBColumn:heading is changed, :configure() must be called to make these changes visible.

:deHilite() Dehighlights the browse cursor.

Syntax :deHilite() --> self

Description Method :deHilite() changes the color of the browse cursor to the normal color. It is used in conjunction with method :hilite() to control the color of the browse cursor programmatically when instance variable :autoLite is set to .F. (false).

:forceStable() Performs a complete stabilization of the browse display.

Syntax :forceStable() --> self 1276

Class Reference (textmode)

TBrowse class - Display methods

Description Method :forceStable() stabilizes the entire browse display. No user input is possible until the method returns.

:hilite() Highlights the browse cursor.

Syntax :hilite() --> self

Description Method :hilite() changes the color of the browse cursor to the hilighted color. It is used in conjunction with method :deHilite() to control the color of the browse cursor programmatically when instance variable :autoLite is set to .F. (false).

:invalidate() Invalidates the entire browse display.

Syntax :invalidate() --> self

Description Method :invalidate() instructs a TBrowse object to redraw the entire browse display during the next stabilization cycle. This includes column headings and footings and all data rows. Note, however, that the data is not re-read from the data source. Call :refreshAll() to update the data rows from the data source.

:refreshAll() Invalidates all data rows of the browse display.

Syntax :refreshAll() --> self

Description Method :refreshAll() causes a TBrowse object to update the display of all data rows by re-reading :rowCount rows of the data source in the next stabilization cycle.

:refreshCurrent() Invalidates the current data row of the browse display.

Syntax :refreshCurrent() --> self Class Reference (textmode)

1277

TBrowse class - Display methods

Description Method :refreshCurrent() causes a TBrowse object to update the display of the current data row by rereading the current row of the data source in the next stabilization cycle.

:setStyle() Retrieves or changes a browse style.

Syntax :setStyle( , [] ) --> lOldOnOff

Arguments

This is a numeric value indicating the style to query or change. #define constants are listed in the file TBrowse.ch which can be used for .

Constants for TBrowse styles Constant

Value

Description

TBR_APPEND TBR_APPENDING TBR_MODIFY TBR_MOVE TBR_SIZE TBR_CUSTOM

1 2 3 4 5 6

Is the user allowed to add data to the data source? Is the user adding data to the data source? Is the user allowed to edit cells in the browser? Is the user allowed to move columns in the browser? Is the user allowed to resize columns in the browser? Minimum value for use-defined custom styles.



This is an optional logical value. When .T. (true) is passed, the style is switched on, .F. (false) switches it off.

Description A TBrowse object maintains a set of styles that can be switched on and off. The styles can be used as a convenient way of implementing specific behaviour for a TBrowse object. A TBrowse object itself does not use this information.

:stabilize() Performs one incremental stabilization cycle.

Syntax :stabilize() --> lIsStable

Description Method :stabilize() performs one incremental stabilization cycle and returns .T. (true) when the browse display is stable. In a stable display, all heading, footing and data rows are displayed, the browse cursor corresponds with the current row in the data source and is highlighted, and no keystrokes are pending for processing. As long as the method returns .F. (false), :stabilize() must be called repeatedly to complete the stabilization cycle. 1278

Class Reference (textmode)

TBrowse class - Display methods

It is possible to interrupt the incremental stabilization cycle and call cursor navigation methods as a response to user input. This can speed up the entire browse display when a user holds a navigation key pressed for a longer period of time, for example.

Cursor navigation

:down() Navigates the cursor to the next row.

Syntax :down() --> self

Description Method :down() instructs the TBrowse object to move the browse cursor to the next data row. If the browse cursor is already located in the last data row, which is at position :rowCount, the data area of the browse display is scrolled up one line and a new data row is read from the data source. If the current row of the data source is the last row already, :down() does not move the browse cursor but sets the instance variable :hitBottom to .T. (true).

:end() Navigates the cursor to the rightmost visible data column.

Syntax :end() --> self

Description Method :end() moves the browse cursor to the rightmost visible data column. It does not scroll the browse display.

:goBottom() Navigates the cursor to the last row in the data source.

Syntax :goBottom() --> self

Description Method :goBottom() evaluates the code block stored in the instance variable :goBottomBlock. The code block receives no argument and must navigate the row pointer of the data source to the last row. A TBrowse object then rebuilds the data area of the browse display in the next stabilization cycle and positions the browse cursor on the last visible data row.

Class Reference (textmode)

1279

TBrowse class - Cursor navigation

:goTop() Navigates the cursor to the first row in the data source.

Syntax :goTop() --> self

Description Method :goTop() evaluates the code block stored in the instance variable :goTopBlock. The code block receives no argument and must navigate the row pointer of the data source to the first row. A TBrowse object then rebuilds the data area of the browse display in the next stabilization cycle and positions the browse cursor on the first data row.

:home() Navigates the cursor to the leftmost visible data column.

Syntax :home() --> self

Description Method :home() moves the browse cursor to the leftmost visible data column. It does not scroll the browse display.

:left() Navigates the cursor left one column.

Syntax :left() --> self

Description Method :left() moves the browse cursor one column to the left. If the next left column is currently not visible, the browse display is scrolled to the right.

:pageDown() Navigates the cursor to the next page in the data source.

Syntax :pageDown() --> self

Description Method :pageDown() instructs the TBrowse object to display the next :rowCount rows of the data source. This invalidates the entire browse display and :rowCount rows are re-read from the data source in the next stabilization cycle. If the last row of the data source is already visible, the browse cursor is positioned on the last visible data row. When :pageDown() is called and the current row of the data 1280

Class Reference (textmode)

TBrowse class - Cursor navigation

source is the last row already, :pageDown() does not move the browse cursor but sets the instance variable :hitBottom to .T. (true).

:pageUp() Navigates the cursor to the previous page in the data source.

Syntax :pageUp() --> self

Description Method :pageUp() instructs the TBrowse object to display the previous :rowCount rows of the data source. This invalidates the entire browse display and :rowCount rows are re-read from the data source in the next stabilization cycle. If the first row of the data source is already visible, the browse cursor is positioned on the first visible data row. When :pageUp() is called and the current row of the data source is the first row already, :pageUp() does not move the browse cursor but sets the instance variable :hitTop to .T. (true).

:panEnd() Navigates the cursor to the rightmost data column.

Syntax :panEnd() --> self

Description Method :panEnd() moves the browse cursor to the last data column. The browse display is scrolled to the left until the rightmost column becomes visible.

:panHome() Navigates the cursor to the leftmost visible data column.

Syntax :panHome() --> self

Description Method :panHome() moves the browse cursor to the first data column. The browse display is scrolled to the right until the leftmost column becomes visible.

:panLeft() Pans the browse display left without changing the cursor position.

Syntax :panLeft() --> self

Class Reference (textmode)

1281

TBrowse class - Cursor navigation

Description Method :panLeft() scrolls the browse display one column to the right so that the next unvisible column becomes visible on the left. The browse cursor remains in its current column, if possible.

:panRight() Pans the browse display right without changing the cursor position.

Syntax :panRight() --> self

Description Method :panRight() scrolls the browse display one column to the left so that the next unvisible column becomes visible on the right. The browse cursor remains in its current column, if possible.

:right() Navigates the cursor right one column.

Syntax :right() --> self

Description Method :right() moves the browse cursor one column to the right. If the next right column is currently not visible, the browse display is scrolled to the left.

:up() Navigates the cursor to the previous row.

Syntax :up() --> self

Description Method :up() instructs the TBrowse object to move the browse cursor to the previous data row. If the browse cursor is already located in the first data row, the data area of the browse display is scrolled down one line and a new data row is read from the data source. If the current row of the data source is the first row already, :up() does not move the browse cursor but sets the instance variable :hitTop to .T. (true).

1282

Class Reference (textmode)

TBrowse class - Event handling

Event handling

:applyKey() Evaluates a code block associated with a navigation key.

Syntax :applyKey( ) --> nReturnCode

Arguments

This is a numeric Inkey() code to be processed by a TBrowse object.

Description Method :applyKey() instructs a TBrowse object to process user input obtained from function Inkey(). The return value is a numeric code that indicates whether or not the stabilization loop must be terminated. #define constants are listed in the file TBrowse.ch that can be used to test possible return values of :applyKey().

Return values of :applyKey() Constant

Value

Description

TBR_EXIT TBR_CONTINUE TBR_EXCEPTION

-1 0 1

User request for the browse to lose input focus Code block associated with was evaluated is unknown, key was not processed

A TBrowse object maintains a :setKey() dictionary of Inkey() codes and associated code blocks that perform default navigation. The default key processing is as follows:

Default key processing Inkey code

Method or function

K_DOWN K_UP K_RIGHT K_LEFT K_CTRL_LEFT K_CTRL_RIGHT K_END K_HOME K_CTRL_END K_CTRL_HOME K_PGDN K_PGUP K_CTRL_PGDN K_CTRL_PGUP K_ESC K_LBUTTONDOWN other codes

:down() :up() :right() :left() :panLeft() :panRight() :end() :home() :panEnd() :panHome() :pageDown() :pageUp() :goBottom() :goTop() None TBMouse()

Class Reference (textmode)

Return code

TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_CONTINUE TBR_EXIT see below TBR_EXCEPTION 1283

TBrowse class - Event handling

When the browse display is clicked with the mouse and a data cell is hit, :applyKey() returns TBR_CONTINUE. If no data is hit, the return code is TBR_EXCEPTION.

:hitTest() Tests if a TBrowse is hit by the mouse cursor.

Syntax :hitTest( , ) --> nHitCode

Arguments

This is the numeric row position of the mouse cursor. It can be queried using function MRow().

This is the numeric column position of the mouse cursor. It can be queried using function MCol().

Description Method :hitTest() accepts the numeric row and column position of the mouse cursor and returns a numeric value indicating whether or not the mouse cursor is located within the TBrowse object. #define constants are available in the BUTTON.CH file identifying the return value of :hitTest().

Return values of oTBrowse:hitTest() Constant

Value

Description

HTNOWHERE HTCELL HTHEADING

0 -5121 -5122

Mouse cursor is outside the browse display Mouse cursor is inside a data cell Mouse cursor is inside a column heading

:setKey() Sets or retrieves a code block associated with a navigation key.

Syntax :setKey( , [] ) --> bOldBlock

Arguments

This is the numeric Inkey() code of the key to be associated with a code block.

This is an optional code block to be associated with the inkey code .

Description Method :setKey() maintains a dictionary of inkey codes and associated code blocks that are processed in method :applyKey(). If is omitted, the method returns the current code block 1284

Class Reference (textmode)

TBrowse class - Event handling

associated with . If is a code block, the return value is the replaced code block if an association exists for . An existing inkey/code block association is removed from the :setKey() dictionary when NIL is explicitly passed for . When a new code block is added to the :setKey() dictionary, it should accept two parameters since the TBrowse object and the inkey code are passed to it in method :applyKey(). Also, the return value of the code block should be one of the #define constants TBR_EXIT, TBR_CONTINUE or TBR_EXCEPTION. Refer to method :applyKey() for a discussion of these constants.

Info See also: Category: Header: Source: LIB: DLL:

DbSkipper(), SetColor(), TBColumn(), TBrowseDb(), TBrowseNew(), TBMouse() Object functions tbrowse.ch rtl\tbrowse.prg xhb.lib xhbdll.dll

Examples // The example demonstrates the steps required for creating a // browse view for a database file. #include "TBrowse.ch" PROCEDURE Main LOCAL oTBrowse, oTBColumn LOCAL bFieldBlock, cFieldName, i, nKey USE Customer ALIAS Cust // create TBrowse object oTBrowse := TBrowse():new( 2,2, MaxRow()-2, MaxCol()-2 ) oTBrowse:headSep := "-" oTBrowse:colorSpec := "N/BG,W+/R" // add code blocks for oTBrowse:goTopBlock oTBrowse:goBottomBlock oTBrowse:skipBlock

navigating the record pointer := {|| DbGoTop() } := {|| DbGoBottom() } := {|nSkip| DbSkipper(nSkip) }

// create TBColumn objects and add them to TBrowse object FOR i:=1 TO FCount() cFieldName := FieldName( i ) bFieldBlock := FieldBlock( cFieldName ) oTBColumn := TBColumn():new( cFieldName, bFieldBlock ) oTBrowse:addColumn( oTBColumn ) NEXT // display browser and process user input DO WHILE .T. oTBrowse:forceStable() nKey := Inkey(0) IF oTBrowse:applyKey( nKey ) == TBR_EXIT EXIT ENDIF ENDDO USE RETURN

Class Reference (textmode)

1285

TBrowse class - Event handling // // // // //

The example demonstrates the steps required for creating a browse view for a two dimensional array. Note that the data source and row pointer of the data source are stored in oTBrowse:cargo. The pseudo instance variables :data and :recno are translated by the preprocessor. #include "TBrowse.ch" #xtrans #xtrans

:data :recno

=> =>

:cargo\[1] :cargo\[2]

PROCEDURE Main LOCAL i, nKey, bBlock, oTBrowse, oTBColumn LOCAL aHeading := { "File Name", ; "File Size", ; "File Date", ; "File Time", ; "File Attr" } LOCAL aWidth := { 20, 10, 9, 9, 9 } // Create TBrowse object // data source is the Directory() array oTBrowse := TBrowse():new( 2, 2, MaxRow()-2, MaxCol()-2 ) oTBrowse:cargo := { Directory( "*.*" ), 1 } oTBrowse:headSep oTBrowse:colorSpec

:= "-" := "N/BG,W+/R"

// Navigation code blocks oTBrowse:goTopBlock := oTBrowse:goBottomBlock := oTBrowse:skipBlock :=

for array {|| oTBrowse:recno := 1 } {|| oTBrowse:recno := Len( oTBrowse:data ) } {|nSkip| ArraySkipper( nSkip, oTBrowse ) }

// create TBColumn objects and add them to TBrowse object FOR i:=1 TO Len( aHeading ) // code block for individual columns of the array bBlock := ArrayBlock( oTBrowse, i ) oTBColumn := TBColumn():new( aHeading[i], bBlock ) oTBColumn:width := aWidth[i] oTBrowse:addColumn( oTBColumn ) NEXT // display browser and process user input DO WHILE .T. oTBrowse:forceStable() nKey := Inkey(0) IF oTBrowse:applyKey( nKey ) == TBR_EXIT EXIT ENDIF ENDDO RETURN // This code block uses detached LOCAL variables to // access single elements of a two-dimensional array. FUNCTION ArrayBlock( oTBrowse, nSubScript ) RETURN {|| oTBrowse:data[ oTBrowse:recno, nSubScript ] }

1286

Class Reference (textmode)

TBrowse class - Event handling // This function navigates the row pointer of the // the data source (array) FUNCTION ArraySkipper( nSkipRequest, oTBrowse ) LOCAL nSkipped LOCAL nLastRec := Len( oTBrowse:data ) // Length of array IF oTBrowse:recno + nSkipRequest < 1 // skip requested that navigates past first array element nSkipped := 1 - oTBrowse:recno ELSEIF oTBrowse:recno + nSkipRequest > nLastRec // skip requested that navigates past last array element nSkipped := nLastRec - oTBrowse:recno ELSE // skip requested that navigates within array nSkipped := nSkipRequest ENDIF // adjust row pointer oTBrowse:recno += nSkipped // tell TBrowse how many rows are actually skipped. RETURN nSkipped

Class Reference (textmode)

1287

TopBarMenu()

TopBarMenu() Creates a new TopBarMenu object.

Syntax TopBarMenu():new( , , ) --> oTopBarMenu

Arguments

This is a numeric value specifying the screen row for displaying the menu bar. It is assigned to the instance variable :row. The range for is between 0 and MaxRow().

This is a numeric value specifying the left screen coordinate of the menu bar. It is assigned to the instance variable :left. Usually, is set to the value 0.

This is a numeric value specifying the right screen coordinate of the menu bar. It is assigned to the instance variable :right. Usually, is set to the value of MaxCol().

Return Function TopBarMenu() returns a TobParMenu object and method :new() initializes it.

Description Objects of the TopBarMenu class are used to build a text-mode menu system. A TopBarMenu object generally serves as the main menu and displays its menu items horizontally in one row on the screen. Each menu item is provided as a MenuItem() object and added using method :addItem(). The creation of submenus is accomplished with the aid of Popup() menu objects. When the menu is completely build, it is activated using method :modal() or by passing the TopBarMenu object to function MenuModal().

Instance variables

:cargo Instance variable for user-defined purposes. Data type: Default:

ANY NIL

Description This instance variable is not used by a TopBarMenu object. It is available for user-defined purposes when an arbitrary value should be attached to a TopBarMenu object.

1288

Class Reference (textmode)

TopBarMenu class - Instance variables

:colorSpec Color string for the TopBarMenu display. Data type: C Default: "N/W,W/N,W+/W,W+/N,N+/W,W/N"

Description The instance variable :colorSpec holds a color string with six color values. It is initialized with the string "N/W,W/N,W+/W,W+/N,N+/W,W/N". The individual color values are used for the following purposes:

Colors for TopBarMenu Color value

Used for display of

1 2 3 4 5 6

unselected menu items selected menu item accelerator key of unselected menu items accelerator key of selected menu item disabled menu items menu border

Note: the sixth color value is actually not used by a TobParMenu object but by Popup() menu objects for displaying the menu border.

:current Currently selected menu item. Data type: N Default: 0

Description The instance variable :current contains a numeric value indicating the ordinal position of the currently selected menu item. Items are numbered from 1 to :itemCount. If no menu item is selected, :current contains zero.

:itemCount Number of menu items. Data type: N Default: 0

Description The instance variable :itemCount contains a numeric value indicating the number of menu items, or MenuItem() objects, maintained by a TopBarMenu object.

Class Reference (textmode)

1289

TopBarMenu class - Instance variables

:left Numeric left screen column for display. Data type: Default:

N NIL

Description The instance variable :left contains a numeric value. It is the screen coordinate of the left column of the menu bar.

:right Numeric right screen column for display. Data type: Default:

N NIL

Description The instance variable :right contains a numeric value. It is the screen coordinate of the right column of the menu bar.

:row Numeric screen row for display. Data type: Default:

N NIL

Description The instance variable :row contains a numeric value. It is the screen row of the menu bar.

Menu item methods

:addItem() Adds a MenuItem object to a TopBarMenu object.

Syntax :addItem( ) --> self

Arguments

This is the MenuItem() object to add to the TopBarMenu object.

1290

Class Reference (textmode)

TopBarMenu class - Menu item methods

Description Method :addItem() accepts a MenuItem() object and adds it to the internal list of menu items. The return value is the self object. The instance variable :itemCount reflects the new number of MenuItem() objects maintained by a TopBarMenu object.

:delItem() Deletes a MenuItem object from a TopBarMenu object.

Syntax :delItem( ) --> self

Arguments

This is a numeric value specifying the ordinal position of the menu item to delete from the TopBarMenu object. Menu items are numbered from 1 to :itemCount.

Description Method :delItem() can be used to remove a single menu item from a TopBarMenu object. This can be useful when the number of selectable menu items changes dynamically at runtime, depending on a condition. Alternatively, single menu items can be disabled or enabled.

:getFirst() Retrieves the ordinal position of the first selectable menu item.

Syntax :getFirst() --> nFirstMenuItemPos

Description Method :getFirst() returns a numeric value indicating the ordinal position of the first, or leftmost, selectable menu item. When a menu item is disabled, it cannot be accessed by the user. When no menu item can be selected, the return value is zero.

:getItem() Retrieves a MenuItem object from a TopBarMenu object.

Syntax :getItem( ) --> oMenuItem

Arguments

This is a numeric value specifying the ordinal position of the menu item to retrieve from the TopBarMenu object. Menu items are numbered from 1 to :itemCount. Class Reference (textmode)

1291

TopBarMenu class - Menu item methods

Description Method :getItem() is used to retrieve the MenuItem() object at position from a TopBarMenu object.

:getLast() Retrieves the ordinal position of the last selectable menu item.

Syntax :getLast() --> nLastMenuItemPos

Description Method :getLast() returns a numeric value indicating the ordinal position of the last, or rightmost, selectable menu item. When a menu item is disabled, it cannot be accessed by the user. When no menu item can be selected, the return value is zero.

:getNext() Retrieves the ordinal position of the next selectable menu item.

Syntax :getNext() --> nNextMenuItemPos

Description Method :getNext() returns a numeric value indicating the ordinal position of the selectable menu item to the right of the currently selected menu item. When a menu item is disabled, it cannot be accessed by the user. If the current menu item is the last one, or when no menu item can be selected, the return value is zero.

:getPrev() Retrieves the ordinal position of the previous selectable menu item.

Syntax :getPrev() --> nPrevMenuItemPos

Description Method :getPrev() returns a numeric value indicating the ordinal position of the selectable menu item to the left of the currently selected menu item. When a menu item is disabled, it cannot be accessed by the user. If the current menu item is the first one, or when no menu item can be selected, the return value is zero.

1292

Class Reference (textmode)

TopBarMenu class - Menu item methods

:insItem() Inserts a MenuItem object into a TopBarMenu object.

Syntax :insItem( , ) --> self

Arguments

This is a numeric value specifying the ordinal position where to insert the menu item. The value for must be in the range from 1 to :itemCount. Otherwise, it is ignored.

This is the MenuItem() object to insert into the TopBarMenu object.

Description Method :insItem() accepts a MenuItem() object and inserts it into the internal list of menu items at position . The return value is the self object. The instance variable :itemCount reflects the new number of MenuItem() objects maintained by a TopBarMenu object. If is outside the valid range, the number of menu items remains unchanged.

:setItem() Replaces a MenuItem object in a TopBarMenu object.

Syntax :setItem( , ) --> self

Arguments

This is a numeric value specifying the ordinal position of the menu item to replace. The value for must be in the range from 1 to :itemCount. Otherwise, it is ignored.

This is the MenuItem() object that replaces an existing one in the TopBarMenu object.

Description Method :setItem() accepts a MenuItem() object and replaces the existing MenuItem object at position . The return value is the self object. If is outside the valid range, no menu item is replaced.

Class Reference (textmode)

1293

TopBarMenu class - Menu display and selection

Menu display and selection

:display() Displays the entire TopBarMenu.

Syntax :display() --> self

Description Method :display() iterates through the list of MenuItem() objects and displays their captions on the screen.

:getAccel() Determines if a key code identifies an accelerator key.

Syntax :getAccel( ) --> nMenuItemPos

Arguments

This is a numeric Inkey() code to check.

Description Method :getAccel() is used to check if a numeric inkey code is an accelerator key that should trigger a menu action. Accelerator keys are key combinations of the Alt key an a letter of a menu item caption prefixed with an ampersand (&). If the key code is an accelerator key, the method returns the ordinal position of the corresponding menu item as a numeric value. If it is not an accelerator, the return value is zero.

:hitTest() Checks if a menu item is clicked with the mouse.

Syntax :hitTest( , ) --> nMenuItemPos

Arguments

This is the numeric row position of the mouse cursor. It can be queried using function MRow().

1294

Class Reference (textmode)

TopBarMenu class - Menu display and selection

This is the numeric column position of the mouse cursor. It can be queried using function MCol().

Description Method :hitTest() accepts the numeric row and column position of the mouse cursor and returns a numeric value indicating the ordinal position of the menu item that is underneath the mouse cursor. If the mouse is outside the menu bar, the return value is zero.

:modal() Activates the menu.

Syntax :modal(

, [] , [] , [], [], []

; ; ; ; ; ) --> nMenuItemID

Arguments

This is a numeric value indicating the ordinal position of the first menu item to be selected when the menu is activated.

This is a numeric value specifying the screen row for displaying messages assigned to the instance variable :message of menu items. The range for is between 0 and MaxRow().

This is a numeric value specifying the left screen coordinate for displaying menu messages. Usually, is set to the value 0.

This is a numeric value specifying the right screen coordinate for displaying menu messages. Usually, is set to the value of MaxCol().

The parameter is an optional character string defining the color for the message to display. It defaults to SetColor().

Optionally, a GetList array can be passed when the menu is activated during READ.

Description Method :modal() activates the top bar menu and processes user input with the cursor keys. To react to mouse events, SET EVENTMASK must be set accordingly. When the user selects a menu item, the Class Reference (textmode)

1295

TopBarMenu class - Menu display and selection

corresponding :data code block is evaluated, if present. The method returns the ordinal position of the selected menu item. If the user cancels menu selection with the Esc key, the return value is zero.

:select() Changes the currently selected menu item.

Syntax :select( ) --> nMenuItemPos

Arguments

This is a numeric value specifying the ordinal position of the menu item to select as current. The value for must be in the range from 1 to :itemCount. Otherwise, it is ignored.

Description Method :select() defines the menu item at position as currently selected item. The selected menu item is displayed highlighted when method :display() is executed.

Info See also: Category: Header: Source: LIB: DLL:

@...GET, MenuItem(), MenuModal(), Popup(), READ, SetColor() Get system, Object functions Button.ch rtl\ttopbar.prg xhb.lib xhbdll.dll

Example // // // // // //

The example outlines the construction of a text-mode menu system with user defined routines. CreateMainMenu() returns a TopBarMenu object, CreateSubMenu() builds pull-down menus, and MenuSelect() branches to subroutines of the program. The menu is activated in a DO WHILE .T. loop. This requires a separate Exit routine for program termination. #include "Button.ch" #include "Inkey.ch" PROCEDURE Main LOCAL oTopBar := CreateMainMenu() CLS DO WHILE .T. MenuModal( oTopBar , 1, ; MaxRow(), 0, MaxCol(), ; oTopBar:colorSpec ) ENDDO RETURN

FUNCTION CreateMainMenu() LOCAL oMainMenu := TopBarMenu():new( 0, 0, MaxCol() )

1296

Class Reference (textmode)

TopBarMenu class - Menu display and selection LOCAL bMenuBlock := {|o| MenuSelect(o) } LOCAL cMenuColor := "N/BG,W+/R,GR+/BG,GR+/R,N+/BG,N/BG" LOCAL aItems oMainMenu:colorSpec := cMenuColor aItems := { ; { " &Open " , K_ALT_O { " &Save " , K_ALT_S { MENU_SEPARATOR, { " E&xit " , K_ALT_X }

, "Open routine" , "Save routine" , , "Exit program"

, , , ,

11 12 13 14

}, }, }, }

; ; ; ;

CreateSubMenu( oMainMenu, " &File ", bMenuBlock, aItems ) aItems := { ; { " Cop&y " , { " &Paste " , { MENU_SEPARATOR, { " C&ut " , { " &Delete " , }

K_CTRL_INS, K_SH_INS , , K_SH_DEL , K_DEL ,

"Copy routine" , 21 "Paste routine" , 22 , 23 "Cut routine" , 24 "Delete routine", 25

}, }, }, }, }

; ; ; ; ;

CreateSubMenu( oMainMenu, " &Edit ", bMenuBlock, aItems ) aItems := { ; { " &Info { " &About }

" "

, K_F1 ,

, "Help routine" , 31 }, ; , "About program" , 32 } ;

CreateSubMenu( oMainMenu, " &Help ", bMenuBlock, aItems ) RETURN oMainMenu

FUNCTION CreateSubMenu( oMenu, cMenuItem, bBlock, aItems ) LOCAL aItem, oItem, oSubMenu oSubMenu := PopUp():new() oSubMenu:colorSpec := oMenu:colorSpec FOR EACH aItem IN aItems oItem := MenuItem():new( aItem[1], bBlock , aItem[2], aItem[3], aitem[4] oSubMenu:addItem ( oItem ) NEXT

; ; ; ; )

oItem := MenuItem():new( cMenuItem, oSubMenu ) oMenu:addItem( oItem ) RETURN

PROCEDURE MenuSelect( oMenuItem ) @ 1, 0 CLEAR TO MaxRow(), MaxCol() SWITCH oMenuItem:ID CASE 14 ExitRoutine() ; EXIT DEFAULT

Class Reference (textmode)

1297

TopBarMenu class - Menu display and selection Alert( oMenuItem:message ) END RETURN

PROCEDURE ExitRoutine IF Alert( "Exit program?", { "Yes", "No" } ) == 1 QUIT ENDIF RETURN

1298

Class Reference (textmode)

TXmlDocument()

TXmlDocument() Creates a new TXmlDocument object.

Syntax TXmlDocument():new( [|], [] )

Arguments

This is a file handle of an XML file to read. It is returned from function FOpen().

Instead of a file handle, an XML formatted character string can be passed. If the first parameter is omitted, the object has no XML data, but can be used to add XML nodes and create a new XML file (see example).

This parameter instructs the TXMlDocument object how to read an XML file and/or how to write XML nodes into a file. #define constants listed in Hbxml.ch are used to specify :

Constants for XML object creation Constant

Value

Description

HBXML_STYLE_INDENT HBXML_STYLE_TAB HBXML_STYLE_THREESPACES HBXML_STYLE_NOESCAPE

1 2 4 8

Indents XML nodes with one space Indents XML nodes with tabs Indents XML nodes with three spaces Reads and creates unescaped characters in data sections

Note: when the style HBXML_STYLE_NOESCAPE is set, the textual content enclosed in an opening and closing XML tag is scanned for characters that normally must be escaped in XML. This can lead to a considerable longer time for reading the XML data. The characters to be escaped are single and double quotes ('"), ampersnad (&), and angled brackets (). If such characters exist in textual content and are not escaped, a parsing error is generated, unless HBXML_STYLE_NOESCAPE is used.

Return Function TXmlDocument() creates the object and method :new() initializes it.

Description The TXmlDocument() class provides objects for reading and creating XML files. XML stands for eXtensible Markup Language which is similar to HTML, but designed to describe data rather to display it. To learn more about XML itself, the internet provides very good free online tutorials. The website www.w3schools.com is is a good place to quickly learn the basics on XML. A TXmlDocument object maintains an entire XML document and builds from it a tree of TXmlNode() objects which contain the actual XML data. The first XML node is stored in the :oRoot instance variable, which is the root node of the XML tree. Beginning with the root node, an XML document can Class Reference (textmode)

1299

TXmlDocument()

be traversed or searched for particular data. The classes TXmlIteratorScan() and TXmlIteratorRegEx() are available to find a particular XML node, based on its tag name, attribute or data it contains.

Instance variables

:oRoot Root node of the XML tree. Data type: Default:

O NIL

Description The instance variable :oRoot contains a TXmlNode() object representing the root node of the XML tree. It can be used as starting point for searching the tree with iterator objects like TXmlIteratorScan().

:nStatus Status information on XML parsing. Data type: Default:

N HBXML_STATUS_OK

Description The instance variable :nStatus contains a numeric value indicating the current status while a TXmlObject is reading a file or XML string and builds the tree of TXmlNode() objects. #define constants are listed in Hbxml.ch that can be used to check the status. They begin with the prefix HBXML_STATUS_.

:nError Error code for XML parsing. Data type: Default:

N HBXML_ERROR_NONE

Description When the XML file or string cannot be parsed, the instance variable :nError contains a numeric value 0, indicating the reason for failure. #define constants are listed in Hbxml.ch that can be used to check the error. They begin with the prefix HBXML_ERROR_. A textual description of the error can be obtained by passing :nError to function HB_XmlErrorDesc().

1300

Class Reference (textmode)

TXmlDocument class - Instance variables

:nLine Current line number being parsed. Data type: N Default: 1

Description The instance variable :nLine contains the line number currently being parsed. Line numbering begins with 1. If an error occurs during parsing, :nLine contains the line number of the offending line.

:oErrorNode TXmlNode object containing illegal XML code. Data type: O Default: NIL

Description The instance variable :oErrorNode is assigned a TXmlNode() object when the XML parser detects illegal XML code. The object in :oErrorNode contains the illegal XML data and is available for inspection. If no error is detected, :oErrorNode contains NIL.

:nNodeCount Number of nodes in the XML tree. Data type: N Default: 0

Description The instance variable :nNodeCount contains a numeric value indicating the total number of nodes in the XML tree.

Methods for XML data manipulation

:read() Reads an XML file or string.

Syntax :read( [|], [] ) --> self

Arguments

This is a file handle of an XML file to read. It is returned from function FOpen().

Class Reference (textmode)

1301

TXmlDocument class - Methods for XML data manipulation

Instead of a file handle, an XML formatted character string can be passed. If the first parameter is omitted, the object has no XML data, but can be used to add XML nodes and create a new XML file.

This parameter instructs the TXMlDocument object how to read an XML file and/or how to write XML nodes into a file. #define constants listed in Hbxml.ch are used to specify :

Constants for XML object creation Constant

Value

Description

HBXML_STYLE_INDENT HBXML_STYLE_TAB HBXML_STYLE_THREESPACES HBXML_STYLE_NOESCAPE

1 2 4 8

Indents XML nodes with one space Indents XML nodes with tabs Indents XML nodes with three spaces Reads and creates unescaped characters in data sections

Description Method :read() receives the same parameters as the :new() method and instructs an existing TXmlDocument object to discard the previously created XML tree and build a new one from the file handle or XML string. When the XML data is sucessfully parsed, instance variable :nError is set to zero. Note: when the style HBXML_STYLE_NOESCAPE is set, the textual content enclosed in an opening and closing XML tag is scanned for characters that normally must be escaped in XML. This can lead to a considerable longer time for reading the XML data. The characters to be escaped are single and double quotes ('"), ampersnad (&), and angled brackets (). If such characters exist in textual content and are not escaped, a parsing error is generated, unless HBXML_STYLE_NOESCAPE is used.

:toString() Creates an XML formatted character string.

Syntax :toString( ) --> cXmlString

Arguments

This parameter instructs the TXMlDocument object how to create the XML code. #define constants listed in Hbxml.ch are used to specify :

Constants for XML code creation

1302

Constant

Value

Description

HBXML_STYLE_INDENT HBXML_STYLE_TAB HBXML_STYLE_THREESPACES

1 2 4

Indents XML nodes with one space Indents XML nodes with tabs Indents XML nodes with three spaces Class Reference (textmode)

TXmlDocument class - Methods for XML data manipulation HBXML_STYLE_NOESCAPE

8

Creates unescaped characters in data sections

Description Method :toString() creates an XML formatted character string containing all nodes and data currently held in the XML tree. The parameter can be used to indent the nodes for readability, or to leave characters in data sections unescaped.

:write() Creates an XML formatted character string.

Syntax :write( , [] ) --> self

Arguments

This is the handle of a file to write XML data to. It is returned from function FCreate().

This parameter instructs the TXMlDocument object how to create the XML code. #define constants listed in Hbxml.ch are used to specify :

Constants for XML code creation Constant

Value

Description

HBXML_STYLE_INDENT HBXML_STYLE_TAB HBXML_STYLE_THREESPACES HBXML_STYLE_NOESCAPE

1 2 4 8

Indents XML nodes with one space Indents XML nodes with tabs Indents XML nodes with three spaces Creates unescaped characters in data sections

Description Method :write() writes all XML nodes and data currently held in the XML tree to the open file . The parameter can be used to indent the nodes for readability, or to leave characters in data sections unescaped.

Methods for searching and navigating

:findFirst() Locates the first XML node containing particular data.

Syntax :findFirst( [] []

Class Reference (textmode)

, ; , ;

1303

TXmlDocument class - Methods for searching and navigating [] , ; [] ) --> oTXmlNode | NIL

Arguments

This is a character string holding the name of the XML node to find.

This is a character string holding the name of an attribute of the XML node to find.

This is a character string holding the value of the attribute of the XML node to find.

This is a character string holding the textual content of the XML node to find.

Description Method :findFirst() locates the first XML node in the XML tree that matches the search criteria. If no parameter is passed, the first XML node in the tree is returned. Search criteria can be any combination of name, attribute and textual content. If no matching node is found, the return value is NIL. If a matching node is found, the next node matching the same search criteria is returned from method :findNext().

:findFirstRegEx() Locates the first XML node containing particular data using regular expressions.

Syntax :findFirstRegEx( [] , ; [] , ; [] , ; [] ) --> oTXmlNode | NIL

Arguments

This is a character string holding the regular expression to match with name of the XML node to find.

This is a character string holding the regular expression to match with the name of an attribute of the XML node to find.

This is a character string holding the regular expression to match with the value of the attribute of the XML node to find.

1304

Class Reference (textmode)

TXmlDocument class - Methods for searching and navigating

This is a character string holding the regular expression to match with the textual content of the XML node to find.

Description Method :findFirstRegEx() locates the first XML node in the XML tree that matches the regular expressions passed. If no parameter is passed, the first XML node in the tree is returned. Search criteria can be any combination of name, attribute and textual content. If no matching node is found, the return value is NIL. If a matching node is found, the next node matching the same search criteria is returned from method :findNext().

:findNext() Finds the next XML node matching a search criteria.

Syntax :findNext() --> oTXmlNode | NIL

Description Method :findNext() continues the search for a matching XML node and returns the corresponding TXmlNode object. The search criteria defined with a previous call to :findFirst() or :findFirstRegEx() is used. If no further XML node is found, the return value is NIL.

Info See also: Category: Header: Source: LIB: DLL:

TXmlIterator(), TXmlIteratorRegEx(), TXmlIteratorScan(), TXmlNode() Object functions, xHarbour extensions hbxml.ch rtl\txml.prg xhb.lib xhbdll.dll

Examples Creating an XML file // // // // // // // // // // // // // //

The example uses the Customer database and creates an XML file from it. The database structure and its records are written to different nodes in the XML file. The basic XML tree is this: data #include "hbXml.ch"

Class Reference (textmode)

1305

TXmlDocument class - Methods for searching and navigating PROCEDURE Main LOCAL aStruct, aField, nFileHandle LOCAL oXmlDoc, oXmlNode, hAttr, cData LOCAL OXmlDatabase, oXmlStruct, oXmlRecord, oXmlField USE Customer aStruct

:= DbStruct()

// Create empty XML document with header oXmlDoc := TXmlDocument():new( '' ) // Create main XML node oXmlDatabase := TXmlNode():new( , "database", { "name" => "CUSTOMER" } ) oXmlDoc:oRoot:addBelow( oXmlDatabase ) // copy structure information to XML oXmlStruct := TXmlNode():new( , "structure" ) oXmlDataBase:addBelow( oXmlStruct ) FOR EACH aField IN aStruct // store field information in XML attributes hAttr := { "name" => Lower( aField[1] ), ; "type" => aField[2], ; "len" => LTrim( Str(aField[3]) ), ; "dec" => LTrim( Str(aField[4]) ) } oXmlField := TXmlNode():new(, "field", hAttr ) oXmlStruct:addBelow( oXmlField ) NEXT // copy all records to XML oXmlNode := TXmlNode():new( , "records" ) oXmlDataBase:addBelow( oXmlNode ) DO WHILE .NOT. Eof() hAttr := { "id" => LTrim( Str( Recno() ) ) } oXmlRecord := TXmlNode():new( , "record", hAttr ) FOR EACH aField IN aStruct IF aField[2] == "M" // Memo fields are written as CDATA cData := FieldGet( Hb_EnumIndex() ) oXmlField := TXmlNode():new( HBXML_TYPE_CDATA , ; Lower( aField[1] ), ; NIL , ; cData ) ELSE // other fields are written as normal tags cData := FieldGet( Hb_EnumIndex() ) cData := Alltrim( CStr( cData ) ) oXmlField := TXmlNode():new( HBXML_TYPE_TAG , ; Lower( aField[1] ), ; NIL , ; cData ) ENDIF // add field node to record oXmlRecord:addBelow( oXmlField ) NEXT // add record node to records oXmlNode:addBelow( oXmlRecord )

1306

Class Reference (textmode)

TXmlDocument class - Methods for searching and navigating SKIP ENDDO // create XML file nFileHandle := FCreate( "Customer.xml" ) // write the XML tree oXmlDoc:write( nFileHandle, HBXML_STYLE_INDENT ) // close files FClose( nFileHandle ) USE RETURN

Reading an XML file // This example uses the Customer.xml file created in the // prevous example and extracts from it the structure definition // for the Customer.dbf file. PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new() LOCAL oXmlNode, aStruct := {} oXMlDoc:read( Memoread( "customer.xml" ) ) oXmlNode := oXmlDoc:findFirst() ? oXmlNode:cName oXmlNode := oXmlDoc:findFirst( "structure" ) ? oXmlNode:cName oXmlNode := oXmlDoc:findFirst( "field" ) DO WHILE oXmlNode NIL // attributes are stored in a hash AAdd( aStruct, { oXmlNode:aAttributes[ "name" ] , oXmlNode:aAttributes[ "type" ] , Val( oXmlNode:aAttributes[ "len" ] ), Val( oXmlNode:aAttributes[ "dec" ] )

; ; ; } )

oXmlNode := oXmlDoc:findNext() ENDDO AEval( aStruct, {|a| Qout( ValToPrg(a) ) } ) RETURN

Escape characters in XML // The example demonstrates the effect of HBXML_STYLE_NOESCAPE // when XML code is created. #include "hbXml.ch" PROCEDURE Main LOCAL oXmlDoc, oXmlNode oXmlDoc := TXmlDocument():new( '' ) oXmlNode:= TXmlNode():new( , "text", , [this must be escaped: "'&] ) oXmlDoc:oRoot:addBelow( oXmlNode )

Class Reference (textmode)

1307

TXmlDocument class - Methods for searching and navigating ? oXmlDoc:toString() ** output: // // this must be escaped: "'&<> ? oXmlDoc:toString( HBXML_STYLE_NOESCAPE ) ** output: // // this must be escaped: "'& RETURN

1308

Class Reference (textmode)

TXmlIterator()

TXmlIterator() Creates a new TXmlIterator object.

Syntax TXmlIterator():new( ) --> oTXmlIterator

Arguments

This is a TXmlNode() object to create the iterator object for.

Return The function returns a TXmlIterator object and method :new() initializes it.

Description The TXmlIterator class provides objects for iterating nodes in an XML document and its sub-nodes (in the XML tree). An XML document is managed by an object of the TXmlDocument() class. The creation of a TXmlIterator object requires a TXmlNode() object wich serves as starting point for the iterator. The iterator is restricted to the branch in the XML tree represented by the initial XML node.

Methods

:clone() Clones the TXmlIterator object.

Syntax :clone() --> oClone

Description Method :clone() creates a duplicate of the self object. The returned TXmlIterator object uses the same search criteria and the same TXmlNode object for a search.

:getNode() Retrieves the current XML node matching the search criteria.

Syntax :getNode() --> oTXmlNode | NIL

Description Method :getNode() returns the current TXmlNode() object as it is determined by a previous call to :next(). If no further XML node exists, the return value is NIL. Class Reference (textmode)

1309

TXmlIterator class - Methods

:next() Retrieves the next XML node in the tree.

Syntax :next() --> oTXmlNode | NIL

Description Method :next() returns the next TXmlNode() object. If no further XML node is found, the return value is NIL.

:rewind() Goes back to the first XML node matching the search criteria.

Syntax :rewind() --> oTXmlNode | NIL

Description Method :rewind() sets the XML node passed to the :new() method as the current node, thus rewinding the entire iteration.

:setContext() Defines the currently found XML node as first node.

Syntax :setContext() --> self

Description Method :setContext() defines the currently found XML node as the first node. An iteration can then be restarted with this node when method :rewind() is called.

Info See also: Category: Source: LIB: DLL:

TXmlDocument(), TXmlNode(), TXmlIteratorScan(), TXmlIteratorRegEx() Object functions, xHarbour extensions rtl\txml.prg xhb.lib xhbdll.dll

Example // // // //

The example use the Customer.xml file as created with the TXmlDocument() example, and extracts from it the field names of the database structure. Note that the iterator is restricted to the subnodes of the "structure" node. PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new() LOCAL oXmlNode, oXmlIter

1310

Class Reference (textmode)

TXmlIterator class - Methods oXMlDoc:read( Memoread( "customer.xml" ) ) oXmlNode := oXmlDoc:findFirst( "structure" ) oXmlIter := TXmlIterator():new( oXmlNode ) DO WHILE .T. oXmlNode := oXmlIter:next() IF oXmlNode == NIL EXIT ENDIF ? oXmlNode:getAttribute( "name" ) ENDDO RETURN

Class Reference (textmode)

1311

TXmlIteratorRegEx()

TXmlIteratorRegEx() Creates a new TXmlIteratorRegEx object.

Syntax TXmlIteratorRegEx():new( ) --> oTXmlIteratorRegEx

Arguments

This is a TXmlNode() object to create the iterator object for. It serves as starting node for iterating.

Return The function returns a TXmlIteratorRegEx object and method :new() initializes it.

Description The TXmlIteratorRegEx class is derived from the TXmlIterator() class and has the same methods. The only difference is that regular expressions are used to define search criteria for finding a particular XML node in an XML tree. The regular expressions are defined once with the :find() method, which searches for the first matching XML node. Subsequent XML nodes matching the regular expressions then searched with the :next() method. The end of a search is indicated when either :find() or :next() return NIL instead of a TXmlNode object matching the regular expressions.

Search methods

:find() Searches the first XML node matching the regular expressions.

Syntax :find( [] , [], [] , []

; ; ; ) --> oTXmlNode | NIL

Arguments

This is a character string holding the regular expression for matching the tag name of XML nodes.

This is a character string holding the regular expression for matching the name of an XML attribute. 1312

Class Reference (textmode)

TXmlIteratorRegEx class - Search methods

The a regular expression to match an attribute value optionally defined with the character string .

This is an optional character string holding the regular expression for matching the textual data of XML nodes.

Description Method :find() defines the regular expressions for a TXmlIteratorRegEx object and performs the initial search. Four different regular expressions can be defined to match tag name, attribute name, attribute value or textual data. If a matching XML node exists, the corresponding TXmlNode() object is returned, otherwise the return value is NIL. The search can be continued using the same regular expressions with method :next().

:next() Searches the next XML node matching the regular expressions.

Syntax :next() --> oTXmlNode | NIL

Description Method :next() returns the next TXmlNode() object matching the regular expressions defined with the :find() method. If no further XML node is found, the return value is NIL.

Info See also: Category: Source: LIB: DLL:

TXmlDocument(), TXmlNode(), TXmlIterator(), TXmlIteratorScan() Object functions, xHarbour extensions rtl\txml.prg xhb.lib xhbdll.dll

Example // // // // //

The example use the Customer.xml file as created with the TXmlDocument() example. Two XmlIteratorScan objects are used to scan the nodes and field nodes below record nodes. The example displays the contents of the nodes whose textual content begin with "R" or "S". PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new() LOCAL oXmlRecord, oXmlField, oXmlRecScan, oXmlFieldScan LOCAL cRegEx := "^[R?]|^[S?]" oXMlDoc:read( Memoread( "customer.xml" ) ) oXmlNode := oXmlDoc:findFirst( "records" ) // iterator for nodes oXmlRecScan := TXmlIteratorScan():new( oXmlNode ) oXmlRecord := oXmlRecScan:find( "record" )

Class Reference (textmode)

1313

TXmlIteratorRegEx class - Search methods DO WHILE oXmlRecord NIL // iterator for nodes oXmlFieldScan := TXmlIteratorRegEx():new( oXmlRecord ) oXmlField := oXmlFieldScan:find( "lastname" ,,, cRegEx ) IF oXmlField NIL ? oXmlField:cData ENDIF oXmlRecord := oXmlRecScan:next() ENDDO RETURN

1314

Class Reference (textmode)

TXmlIteratorScan()

TXmlIteratorScan() Creates a new TXmlIteratorScan object.

Syntax TXmlIteratorScan():new( ) --> oTXmlIteratorScan

Arguments

This is a TXmlNode() object to create the iterator object for. It is the starting point for searching nodes in the XML tree.

Return The function returns a TXmlIteratorScan object and method :new() initializes it.

Description The TXmlIteratorScan class is derived from the TXmlIterator() class and has the same methods. The only difference is that search criteria can be defined to find a particular XML node in an XML tree. The search criteria is defined once with the :find() method, which searches for the first matching XML node. Subsequent XML nodes matching the search criteria are then searched with the :next() method. The end of a search is indicated when either :find() or :next() return NIL instead of a TXmlNode object matching the search criteria.

Search methods

:find() Searches the first XML node matching the search criteria.

Syntax :find( [] , [], [] , []

; ; ; ) --> oTXmlNode | NIL

Arguments

This is a character string holding the tag name of the XML node to search for.

This is a character string holding the name of an XML attribute to search for.

The attribute value to search is optionally defined with the character string . Class Reference (textmode)

1315

TXmlIteratorScan class - Search methods

This is an optional character string holding the textual data of an XML node to search.

Description Method :find() defines the search criteria for a TXmlIteratorScan object and performs the initial search. The search criteria can be defined as any combination of tag name, attribute name, attribute value or textual data. If a matching XML node exists, the corresponding TXmlNode() object is returned, otherwise the return value is NIL. The search can be continued using the same search criteria with method :next().

:next() Searches the next XML node matching the search criteria.

Syntax :next() --> oTXmlNode | NIL

Description Method :next() returns the next TXmlNode() object matching the search criteria defined with the :find() method. If no further XML node is found, the return value is NIL.

Info See also: Category: Source: LIB: DLL:

TXmlDocument(), TXmlNode(), TXmlIterator(), TXmlIteratorRegEx() Object functions, xHarbour extensions rtl\txml.prg xhb.lib xhbdll.dll

Example // // // // //

The example use the Customer.xml file as created with the TXmlDocument() example. Two XmlIteratorScan objects are used to scan the nodes and field nodes below record nodes. The example displays the reecord IDs and the data from the nodes. PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new() LOCAL oXmlNode, oXmlRecScan, oXmlFieldScan oXMlDoc:read( Memoread( "customer.xml" ) ) oXmlNode := oXmlDoc:findFirst( "records" ) // iterator for nodes oXmlRecScan := TXmlIteratorScan():new( oXmlNode ) oXmlNode := oXmlRecScan:find( "record" ) DO WHILE oXmlNode NIL ? oXmlNode:getAttribute( "id" ) // iterator for nodes oXmlFieldScan := TXmlIteratorScan():new( oXmlNode ) oXmlNode := oXmlFieldScan:find( "lastname" )

1316

Class Reference (textmode)

TXmlIteratorScan class - Search methods ?? " ", oXmlNode:cData oXmlNode := oXmlRecScan:next() ENDDO RETURN

Class Reference (textmode)

1317

TXmlNode()

TXmlNode() Creates a new TXmlNode object.

Syntax TXmlNode():new( [] , , [], []

; ; ; ) --> oTXmlNode

Arguments

This is an optional numeric value indicating the type of the XML node. XML node types are distinguished by the folloing #define constants listed in Hbxml.ch:

Types of XML nodes Constant

Value

Description

HBXML_TYPE_TAG *) HBXML_TYPE_COMMENT HBXML_TYPE_PI HBXML_TYPE_DIRECTIVE HBXML_TYPE_DATA HBXML_TYPE_CDATA HBXML_TYPE_DOCUMENT *) default type

0 1 2 3 4 5 6

Regular XML node XML comment XML processing instruction XML directive Parsed XML data section (PCDATA) Unparsed XML data section (CDATA) XML document



This is a character string holding the tag name of the XML node to create.

Optionally, the attributes of of the XML node to create can be passed as a Hash. The Hash key is the attribute name and the Hash value is the attribute value. Note that both, Hash values and keys, must be of data type Character.

This is an optional character string holding the textual data of the TXmlNode object. If this parameter is used, the TXmlNode object represents a leaf, not a node. is the text apperaing between the opening and closing XML .

Return The function returns a TXmlNode object and method :new() initializes the object.

Description Objects of the TXmlNode class represent a single node, or a leaf, in an XML document. XML documents are maintained by the TXmlDocument() class which build a tree of XML nodes when reading an XML document. A TXmlDocument object creates this tree and fills it with TXmlNode objects. 1318

Class Reference (textmode)

TXmlNode()

One TXmlNode object contains in its instance variables the XML tag name, an optional list of XML atttributes, and the textual content of an XML node, when it is a leaf node. The XML node hierarchy of an XML document is reflected in instance variables of an TXmlNode object. These are :oParent and :oChild holding TXmlNode objects of the next higher or lower level in the XML tree, plus :oNext and :oPrev holding the next or previous TXmlNode object of the same level in the XML tree. The nesting level of a TXmlNode object can be queried with method :depth(). Note: the beforementioned instance variables allow for traversing an XML tree programmatically. Before doing so, the search and scan capabilities of the classes TXmlIterator(), TXmlIteratorRegEx() and TXmlIteratorScan() should be investigated. They are designed to aid in traversing an XML document and extracting information from it.

Instance variables

:aAttributes Contains attributes of an XML node. Data type: H Default: {=>}

Description The instance variable :aAttributes contains a Hash. The hash keys are the names of the attributes while the Hash values are the attribute values. Attribute values are of data type Character.

:cData Contains textual data of an XML node. Data type: C Default: NIL

Description The instance variable :cData contains a character string representing the texual content of an XML leaf node. This is the text eclosed in an openening and closing XML tag.

:cName Contains the tag name of an XML node. Data type: C Default: NIL

Description The instance variable :cName holds the tag name of an XML node as a character string.

Class Reference (textmode)

1319

TXmlNode class - Instance variables

:nBeginLine Contains the line number of an XML node. Data type: Default:

N 0

Description The instance variable :nBeginLine is assigned a numeric value when a TXmlDocument() object reads and parses an XML document. :nBeginLine is the line number of the XML node in the XML document.

:nType Contains the type number of an XML node. Data type: Default:

N HBXML_TYPE_TAG

Description The type of an XML node is encoded as a numeric value and stored in :nType. #define constants listed in Hbxml.ch are used for this instance variable

XML node types Constant

Value

Description

HBXML_TYPE_TAG HBXML_TYPE_COMMENT HBXML_TYPE_PI HBXML_TYPE_DIRECTIVE HBXML_TYPE_DATA HBXML_TYPE_CDATA HBXML_TYPE_DOCUMENT

0 1 2 3 4 5 6

Regular XML node XML comment Processing instruction XML directive Parsed data section Unparsed data section Document node

:oChild Contains the child node of an XML node. Data type: Default:

O NIL

Description The instance variable :oChild contains a TXmlNode object representing the first XML node of the next lower level in an XML tree. If there is no lower level, or if the XML node is a leaf, :oChild contains NIL.

1320

Class Reference (textmode)

TXmlNode class - Instance variables

:oNext Contains the next XML node in the XML document. Data type: O Default: NIL

Description The instance variable :oNext contains a TXmlNode object representing the next XML node of the same nesting level in an XML tree. If there is no further XML tag, this TXMlNode object is the last node of this nesting level in the XML tree, and :oNext contains NIL.

:oParent Contains the parent XML node. Data type: O Default: NIL

Description The instance variable :oParent contains a TXmlNode object representing the XML node of the next higher level in an XML tree. If there is no higher level, :oParent contains NIL.

:oPrev Contains the previous XML node in the XML document. Data type: O Default: NIL

Description The instance variable :oPrev contains a TXmlNode object representing the previous XML node of the same nesting level in an XML tree. If there is no further XML tag, this TXMlNode object is the first node of this nesting level in the XML tree, and :oPrev contains NIL.

Methods for attributes

:getAttribute() Retrieves an attribute from an XML tag by name.

Syntax :getAttribute( ) --> cValue | NIL

Arguments

This is a character string holding the name of the XML attribute to retrieve the value for.

Class Reference (textmode)

1321

TXmlNode class - Methods for attributes

Description Method :getAttribute() retrieves the value of an XML attribute as a character string. If no attribute exists having as name, the return value is NIL.

:setAttribute() Sets a named attribute and its value for an XML tag.

Syntax :setAttribute( , ) --> cValue

Arguments

This is a character string holding the name of the XML attribute to create or assign a value to.

The attribute value is set with the character string .

Description Method :setAttribute() assigns the value to the XML attribute . If the attribute does no exist, it is created.

Methods for nodes

:addBelow() Adds a new XML node below the current XML node.

Syntax :addBelow( ) --> oChildNode

Arguments

This ia a TXmlNode object to add to the XML tree below the current XML node.

Description Method :addBelow() adds a new XML node to the XML tree, one level below the current node. The return value is the child node of the self object.

1322

Class Reference (textmode)

TXmlNode class - Methods for nodes

:clone() Clones an XML node.

Syntax :clone() --> oXmlClone

Description Method :clone() creates a duplicate of the self object, including all XML attributes and possible data. Child nodes are not duplicated. Method :cloneTree() is available to clone an XML node including all child nodes.

:cloneTree() Clones an XML node with all sub-nodes.

Syntax :cloneTree() --> oXmlCloneWithSubNodes

Description Method :cloneTree() creates a duplicate of the self object, including all child nodes.

:insertAfter() Inserts an XML node after the current node.

Syntax :insertAfter( ) --> oParentNode

Arguments

This ia a TXmlNode object to insert into the XML tree after the current XML node.

Description Method :insertAfter() inserts a TXMlNode object at the same nesting level into the XML tree. The inserted XML node appears immediately after the self object.

:insertBefore() Inserts an XML node before the current node.

Syntax :insertBefore( ) --> oPreviousNode

Class Reference (textmode)

1323

TXmlNode class - Methods for nodes

Arguments

This ia a TXmlNode object to insert into the XML tree before the current XML node.

Description Method :insertBefore() inserts a TXMlNode object at the same nesting level into the XML tree. The inserted XML node appears immediately before the self object. The return value is the previous XML node.

:insertBelow() Inserts a new XML node below the current XML node.

Syntax :insertBelow( ) --> self

Arguments

This ia a TXmlNode object to insert into the XML tree below the current XML node.

Description Method :insertBelow() adds a new XML node to the XML tree, one level below the current node.

:nextInTree() Retrieves the next XML node in the XML tree.

Syntax :nextInTree() --> oNextNode | NIL

Description Method :nextInTree() returns the next TXmlNode object in the XML tree, regardless of its nesting level or :depth(). If the method returns NIL, the TXmlNode object executing the method is the last object in the XML tree and no further TXmlNode objects exist below the current one. If the return value is a TXmlNode object, it can have a higher, lower or the same nesting level.

:unlink() Removes an XML node from the XML tree.

Syntax :unlink() --> self

1324

Class Reference (textmode)

TXmlNode class - Methods for nodes

Description Method :unlink() removes the XmlNode object executing the method from the XML tree. The method removes this object and its sub-nodes from the tree. As a result, this TXmlNode object, and its subnodes, is deleted from the TXmlDocument() object maintaining the tree of TXmlNode objects.

Methods for XML code

:toString() Creates an XML formatted character string.

Syntax :toString( ) --> cXmlString

Description

:write() Writes an XML formatted character string to a file.

Syntax :write( , ) --> lSuccess

Arguments

This is the handle of a file to write XML data to. It is returned from function FCreate().

This parameter instructs the TXmlNode object how to create the XML code. #define constants listed in Hbxml.ch are used to specify :

Constants for XML code creation Constant

Value

Description

HBXML_STYLE_INDENT HBXML_STYLE_TAB HBXML_STYLE_THREESPACES HBXML_STYLE_NOESCAPE

1 2 4 8

Indents XML nodes with one space Indents XML nodes with tabs Indents XML nodes with three spaces Creates unescaped characters in data sections

Description Method :write() writes all XML nodes and data currently held by the TXmlNode object and all subnodes to the open file . The parameter can be used to indent the nodes for readability, or to leave characters in data sections unescaped.

Class Reference (textmode)

1325

TXmlNode class - Informational methods

Informational methods

:depth() Determines the depth of an XML node.

Syntax :depth() --> nDepth

Description Method :depth() returns a numeric value indicating the nesting level, or depth, of the XML node represented by a TXmlNode object within an XML document.

:path() Determines the complete path of an XML node.

Syntax :path() --> cXmlPath

Description Method :path() returns a character string holding the names of all XML nodes existing before this node plus the name of this node. The names of XML nodes are separated by a slash (/).

:toArray() Creates an array holding all XML information of a TXmlNode object.

Syntax :toArray() --> aXmlNodeInfo

Description Method :toArray() is provided for informational or debugging purposes. The return value is an array with four elements. They contain all data of an XML node as stored in four instance variables: { ::nType, ::cName, ::aAttributes, ::cData }

1326

Class Reference (textmode)

TXmlNode class - Informational methods

Info See also: Category: Header: Source: LIB: DLL:

TXmlDocument(), TXmlIterator() Object functions, xHarbour extensions hbxml.ch rtl\txml.prg xhb.lib xhbdll.dll

Examples Creating XML nodes // // // //

The example creates an XML document with two nodes of different nesting level, or depth. The inner XML node is a leaf node. Both XML nodes have the same attribute. Note that the starting point of the node creation is the root node of the XML document. #include "HbXml.ch" PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new( '' ) LOCAL oXmlNode := oXmlDoc:oRoot LOCAL oXmlSubNode oXmlSubNode := TXmlNode():new( , "AAA", ; { "id" => "1" }, "NOT A LEAF NODE" ) oXmlNode:addBelow( oXmlSubNode ) oXmlNode := oXmlSubNode oXmlSubNode := TXmlNode():new(, "BBB", {"id" => "1"}, "Leaf node" ) oXmlNode:addBelow( oXmlsubNode ) ? oXmlDoc:toString( HBXML_STYLE_INDENT ) ** Output // // // Leaf node // NOT A LEAF NODE RETURN

Inserting XML nodes // The example creates an XML document and inserts XML nodes // before and after the current node. #include "HbXml.ch" PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new( '' LOCAL oXmlNode := oXmlDoc:oRoot LOCAL oXmlSubNode1, oXmlSubNode2

)

oXmlSubNode1 := TXmlNode():new(, "AAA" ) oXmlNode:addBelow( oXmlsubNode1 ) oXmlNode := oXmlSubNode1 oXmlSubNode1 := TXmlNode():new(, "BBB", {"id" => "1"}, "Leaf node" ) oXmlNode:addBelow( oXmlsubNode1 )

Class Reference (textmode)

1327

TXmlNode class - Informational methods oXmlSubNode2 := TXmlNode():new(, "BBB", {"id" => "2"} , ; ":insertBefore()" ) oXmlSubnode1:insertBefore( oXmlSubNode2 ) oXmlSubNode2 := TXmlNode():new(, "BBB", {"id" => "3"} , ; ":insertAfter()" ) oXmlSubnode1:insertAfter( oXmlSubNode2 ) ? oXmlDoc:toString( HBXML_STYLE_INDENT ) ** // // // // // //

Output :insertBefore() Leaf node :insertAfter()

RETURN

Deleting XML nodes // The example creates an XML document with a nesting level, or depth, // of 3. The XML node at nesting level 2 is removed from the XML document. #include "HbXml.ch" PROCEDURE Main LOCAL oXmlDoc := TXmlDocument():new( '' LOCAL oXmlNode := oXmlDoc:oRoot LOCAL oXmlSubNode1, oXmlSubNode2

)

oXmlSubNode1 := TXmlNode():new(, "AAA", { "id" => "1" }, "1st level" ) oXmlNode:addBelow( oXmlsubNode1 ) oXmlNode := oXmlSubNode1 oXmlSubNode1 := TXmlNode():new(, "BBB", { "id" => "1" }, "2nd level" ) oXmlNode:addBelow( oXmlsubNode1 )

oXmlSubNode2 := TXmlNode():new(, "CCC", { "id" => "1" }, "3rd level" ) oXmlSubnode1:addBelow( oXmlSubNode2 ) ? oXmlDoc:toString( HBXML_STYLE_INDENT ) ** Output // // // // 3rd level // 2nd level // 1st level // delete this node from the XML document oXmlSubNode1:unlink() ? oXmlDoc:toString( HBXML_STYLE_INDENT ) ** Output (only one node is left) // // 1st level

1328

Class Reference (textmode)

TXmlNode class - Informational methods ? oXmlSubNode1:toString( HBXML_STYLE_INDENT ) ** Output (deleted node has a sub-node) // // 3rd level // 2nd level RETURN

Class Reference (textmode)

1329

Preprocessor Reference

1330

Preprocessor Reference

#command | #translate

#command | #translate User defined command or translation rule for the preprocessor.

Syntax #command #translate



=> =>



Arguments

This is the definition of a pattern to search for in the PRG source code. The => characters are part of the preprocessor directive and must be used as separator between and .

This is the definition of a pattern to replace with in the PRG source code.

Description The directives #command and #translate specify translation rules for the preprocessor. Source code is modified in a compilation cycle according to these rules by the preprocessor. The modified source code is then processed by the compiler. To obtain the result of the preprocessor, the compiler switch /p or /pt must be used. This causes the translation result of the preprocessor be output to a file with the PPO extension (PPO stands for PreProcessed Output). Both directives provide a powerful automated transformation tool, that allow for extending the xHarbour language with user-defined commands, pseudo functions, and for source code patterns to be simplified by the programmer and later expanded to verbose expressions with the aid of the preprocessor. While #command is used to define a complete statement, #translate instructs the preprocessor to find even portions of statements. Both directives identify keywords only up to the first four characters and are not case-sensitive. To match keywords to their entire length, the directives #xcommand or #xtranslate must be used (note the 'x' prefix). Directives are usually programmed in #include files having the CH extension. The rules they define for translating source code are applied according to their preference and sequence in which they appear in an include file. The directive with highest preference is #define, followed by #translate/#xtranslate and #command/#xcommand. That means, #define directives are processed first until no more #define matches are found. In a next step, #translate/#xtranslate rules are applied and finally #command/#xcommand is processed. This process is recurring, so that each transformation forces a rescan of the whole new line, starting again with #define directives. The sequence for processing directives is determined by their order of definition in the program code. The most recently specified directive overrides/hides any prior directive that would have otherwise matched the same input. Because directives defined at the end of a file are processed prior to those at the beginning of a file, when a set of rules depend one on the output of the other, the first rule to expand, should be listed last. This is important to note when having to use multiple rules in order to implement user-defined commands that have various syntactical forms or use mutual exclusive options, thus requiring multiple rules. The most general form of a user-defined command must appear towards the top of an #include file, while specialized forms must be placed below (towards the end of a file). This makes sure that Preprocessor Reference

1331

#command | #translate

spezialized forms of a user-defined command are given the opportunity to match first, before the more general rules are evaluated. When a directive results in a pattern of program code for which another directive is defined, the translation procedure is repeated until all translation directives are resolved by the preprocessor. This allows for defining complex translation rules where a particualer sequence of program code is translated in multiple intermediate steps using different directives. Directives may be defined directly within a given source files, or within any of the files included into the compiled source file, by means of the #include directive. The xHarbour compiler includes a set of pre-loaded standard rules, compatible with the CA-Clipper 'std.ch' file. You may choose to exclude these default rules, by using the compiler -u command line switch. You may also "inject" a set of rules from any command header file, into the compliation of any source, by means of the -u+ command line switch. This will load such command header file as if it was directly included in the compiled source, by means of the #include directive. When the compilation of one PRG file is complete, all translation rules valid for this file are discarded and the preprocessor operates with a new set of translation rules for the next PRG file.

Translation rules The and portions of a translation rule are syntactically programmed using literal tokens, words and markers. A directive must begin with a word or a literal token, it cannot begin with a marker. Markers are a place holders in a translation rule for variable portions of patterns in the program code to translate. They can be compared to memory variables that hold character strings during the translation process. Markers have symbolic names and are always enclosed in angled brackets. +------ marker --------+--------+ | | | #command SET FILTER TO => DbSetFilter( , ) | | | | | | +----+----+---- words -----+ +- literal token --+

This translation rule instructs the preprocessor to search for the words SET FILTER TO and match the following expression with the marker . This marker has the symbolic name xpr and is included in the resulting code in two syntactically different ways. The words SET FILTER TO are completely removed and replaced with DbSetFilter(). The symbolic name for markers must follow the same rules as for memory variables, i.e. it must begin with an alphabetic character or an underscore, followed by alphabetic characters, digits or underscores. Unlike symbolic variable names, symbolic names for markers are case sensitive. Markers on the left side of the => characters are referred to as Match markers, while those on the right side are called Result markers. There is a set of Match markers to distinguish syntactically different patterns of program code to search for, and a set of Result markers that define syntactically different forms of how the matched input string should appear in the output. The large number of possible combinations of different Match and Result markers makes the preprocesser a very flexible tool for translating almost any kind of PRG source code.

Match marker Match markers are used in the part of a directive and instruct the preprocessor about the pattern to match in the PRG code. The following table lists the available Match markers:

1332

Preprocessor Reference

#command | #translate

Match Markers Syntax

Name



Regular match marker List match marker Restricted match marker Wild match marker Extended Expression match marker Single token match marker

Regular match marker: This marker is the most commonly used one. It matches any valid expression in the program code. List match marker: Expressions in program code that are comma separated lists are matched with the List match marker. It is used when a command has a variable number of arguments separated with commas. Restricted match marker: This marker limits the number of words or literals valid for a command option. One or more words valid for an option are included following a colon after the symbolic name of the marker. Multiple words must be separated with commas. The words are matched caseinsensitive. Wild match marker: The Wild match marker matches everything from the current position to the end of a statement. This includes input text that may not be a valid expression. Extended expression match marker: This marker is used for command arguments that may or may not be enclosed in parentheses. Single token match marker: This marker identifies single tokens appearing adjacent in an expression. It is required to match words and literal tokens when they are not separated with blank spaces. Optional clauses: It is possible to define optional clauses for to match program code with optional arguments or keywords that may be absent. Optional clauses for must be enclosed in square brackets [] and can be nested. They are matched in program code irrespective of the order they appear in a search rule and a user defined command. That means, if the search rule defines optional clauses in the order A,B,C and they are used in PRG code in C,A,B order, there will still be a match for all three optional clauses. Adjacent optional clauses in a search rule must consist either of a keyword or a keyword/literal token plus Match marker. They cannot contain only Match markers without keyword or literal token. Escape character: When the characters [ and < are part of the PRG code to match, they must be escaped in the search rule by prepending a backslash \. Line continuation: When the definition of a search pattern spans across multiple lines, each line must end with a semicolon. The ; serves as line continuation character.

Result marker A result marker receives the input text matched by the Match marker having the same symbolic name. The input text is written to the output text at the place where the Result marker appears in the portion of a translation directive. Different Result markers allow for modifying the syntactical notation written to the output. The following table lists the available Result markers:

Preprocessor Reference

1333

#command | #translate

Result Markers Syntax

Name

#

Regular result marker Dumb stringify result marker Normal stringify result marker Smart stringify result marker Blockify result marker Logify result marker

Regular result marker: This marker is the most general one. It receives matched input and writes it unmodified to the output. If there is no match in the search, nothing is written to the output. Dumb stringify result marker: This marker encloses matched input in quotes and writes a literal character string to the output. If there is no match in the search, a null string ("") is written to the output. If the input is matched with the List match marker, the entire list is enclosed in quotes, not individual list elements. Normal stringify result marker: This marker encloses matched input in quotes and writes a literal character string to the output. If there is no match in the search, nothing is written to the output. If the input is matched with the List match marker, each individual list element is written as a quoted character string to the output. Smart stringify result marker: This marker encloses matched input only in quotes when it is not enclosd in parentheses. If the input is enclosed in parentheses, it is written unmodified to the output. When the matched input is a macro expression, it is optimized by the Smart stringify result marker. Blockify result marker: This marker embeds matched input in code block literals {|| }. The resulting code block has no parameters but contains only the matched expression. If the input is matched with the List match marker, each element of the list is output as an individual code block. Logify result marker: The marker writes literal logical values to the output. If there is a match, the output is .T. (true), otherwise .F. (false). Optional clauses: Optional clauses for must be enclosed in square brackets []. Unlike optional clauses for the ones for cannot be nested. If an optional clause is matched multiple times in it is output as many times in . Escape character: When the characters [ and < are part of the PRG code to output, they must be escaped in the result rule by prepending a backslash \. Line continuation: When the definition of a result pattern spans across multiple lines, each line must end with a semicolon. The ; serves as line continuation character. If the output should be created as multiple statements, use two ;; semicolons to separate each statement.

Examples for preprocessor directives The examples below demonstrate various combinations of Match and Result markers as they are used in the definition of preprocessor directives. Note that each example has three sections: the directive (CH file), the match pattern (PRG file) and the resulting output (PPO file).

1334

Preprocessor Reference

#command | #translate

Info See also: Category:

#define, #include, #uncommand | #untranslate, #xcommand | #xtranslate Preprocessor directives

Examples Regular match marker => Regular result marker // CH file #translate IsNegative()

=>

( \< 0)

// PRG file IF IsNegative( nValue ) ENDIF // PPO file IF (nValue < 0) ENDIF

List match marker => Regular result marker // CH file #command ? []

=>

QOut( )

// PRG file ? "Today is", Date(), "!" // PPO file QOut("Today is",Date(),"!" )

Restricted match marker => Smart stringify result marker // CH file #command SET DELETED

=>

Set( _SET_DELETED, )

// PRG file cVar := "ON" SET DELETED OFF SET DELETED &cVar // PPO file cVar := "ON" Set(11,"OFF" ) Set(11,cVar )

Restricted match marker => Logify result marker // CH file #command SET ALTERNATE TO [] => ; Set( _SET_ALTFILE, , ) // PRG file SET ALTERNATE TO test.log SET ALTERNATE TO test.log ADDITIVE // PPO file

Preprocessor Reference

1335

#command | #translate Set(19,"test.log",.F. ) Set(19,"test.log",.T. )

List match marker => Smart stringify result marker // CH file #command COPY STRUCTURE [TO ] [FIELDS ] => ; __dbCopyStruct( , { } ) // PRG file COPY STRUCTURE TO Temp.dbf FIELDS Lastname, Firstname cDbFile cFName1 cFName2

:= "Customer.dbf" := "Firstname" := "Lastname"

COPY STRUCTURE TO (cDbFile) FIELDS (cFname1), (cFname2) // PPO file __dbCopyStruct("Temp.dbf",{ "Lastname","Firstname" } ) cDbFile := "Customer.dbf" cFName1 := "Firstname" cFName2 := "Lastname" __dbCopyStruct((cDbFile),{ (cFname1),(cFname2) } )

Regular match marker => Blockify result marker // CH file #command SET FILTER TO => DbSetFilter( , ) // PRG file SET FILTER TO FIELD->City = "New York" // PPO file DbSetFilter({||FIELD->City = "New York"},'FIELD->City = "New York"' )

Wild match marker => Smart stringify result marker // CH file #command SET PATH TO

=> Set( _SET_PATH, )

// PRG file cTemp := "C:\temp" SET PATH TO c:\xhb\source\samples SET PATH TO (cTemp) // PPO file cTemp := "C:\temp" Set(6,"c:\xhb\source\samples" ) Set(6,(cTemp) )

Single token match marker => Regular result marker // CH file #translate := , => ; := IIF( .NOT. Empty(), , ) // PRG file

1336

Preprocessor Reference

#command | #translate lLogic := (Val(Time()) < 12) ? c := lLogic?"am", "pm" // PPO file lLogic := (Val(Time()) < 12) QOut(c := IIF(.NOT. Empty(lLogic),"am","pm") )

Optional match clauses => Multiple statements // CH file #command REPLACE WITH ; [, WITH ] := ; [; := ] // PRG file REPLACE FIELD->LastName

=> ;

WITH "Miller"

REPLACE FIELD->LastName WITH "Miller", ; FIELD->FirstName WITH "John" // PPO file FIELD->LastName := "Miller" FIELD->LastName := "Miller" ; FIELD->FirstName := "John"

Preprocessor Reference

1337

#define

#define Defines a symbolic constant or pseudo-function.

Syntax #define [] #define ([]) []

Arguments

This is the symbolic name of the constant to define. #define constants are case sensitive.

This is the value all occurances of are replaced with in the PRG source code by the preprocessor. If is omitted, is removed from the PRG source code.

This is the symbolic name of the pseudo function to define. It is case sensitive and must be followed by parentheses.

A comma separated list of parameters can optionally be specified for the pseudo-function.

This is the expression the pseudo-function is translated to by the preprocessor. All occurrances of ( ) are substituted with .

Description One of the most important directives is the #define directive. It is used to define a symbolic name and optionally associate it with a constant value, or to define a pseudo-function. Both, #define constants and pseudo-functions, help a programmer to maintain PRG source code better, and enhance its readability. In addition, #define constants are used for the purpose of conditional compilation in conjunction with the #if, #ifdef and #ifndef directives. The #define directive is processed by the preprocessor, similar as #command and #translate. The major difference, however, is that #define directives are case sensitive and are coded without the => characters as separators.

Symbolic constants A common usage for the #define directive is the definition of symbolic constants that are optionally associated with a constant value. By convention, the names of symbolic constants are coded in upper case so they are easily recognized in the PRG source code. When a symbolic constant is associated with a value, the symbolic name of the constant value can be used similar as the usage of a named memory variable. The difference is, that the value of a symbolic constant cannot change at runtime of a program. This is because symbolic constants are resolved by the preprocessor, while memory variables are run-time entities. The following code example explains the difference between a symbolic constant and a memory variable: 1338

Preprocessor Reference

#define // PRG code #define #define

K_INS _SET_INSERT

22 29

nKey := Inkey(0) IF nKey == K_INS Set( _SET_INSERT, .NOT. Set( _SET_INSERT ) ) ENDIF

This code queries a key press using the Inkey() function. When the user presses the Ins key, the setting for insert/overwrite mode is toggled. The code relies on two symbolic constants, K_ESC and _SET_INSERT, and both have a numeric value associated. This allows a programmer to use a symbolic name for the IF condition and the Set() function call. The code is processed by the preprocessor. As a result, the compiler processes the following: // PPO code nKey := Inkey(0) IF nKey == 22 Set(29, .NOT. Set(29 ) ) ENDIF

A programmer could have coded the preprocessor result in the first place. It is, however, more intuitive for a programmer to use symbolic names in PRG code than to memorize numeric constants for a variety of reasons. It becomes also clear that while nKey, as a memory variable, can change its value later in the program, symbolic #define constants cannot: they are replaced with their associated constant value at compile time.

Pseudo-functions A #define directive can be coded in functional syntax. Function calls that match with such an directive are translated by the preprocessor and replaced with the result pattern of the directive. The following example illustrates this: // PRG code #define InRange( val, low, high )

(val >= low .AND. high >= val)

n := 10 nLow := 5 nHigh := 11 IF InRange( n, nLow, nHigh ) ? "value fits in range" ENDIF

The IF condition looks syntactically like a function call accepting three memory variables as arguments. However, there is no function call due to the #define directive. The compiler processes an .AND. expression instead: // PPO code n := 10 nLow := 5 nHigh := 11 IF (n >= nLow .AND. nHigh

Preprocessor Reference

>= n)

1339

#define QOut("value fits in range" ) ENDIF

The usage of pseudo-functions is advantageous when a function call can be coded as a complex oneline expression. This can relieve a programmer from much typing and reduces the size of the resulting executable file since the overhead of a function call can be avoided. Note, however, that the name of the pseudo-function is case-sensitive, and that the function must be coded with the exact number of arguments specified in the #define directive.

Conditional compilation A third area where #define directives play an important role is conditional compilation. Program code can be compiled in different ways depending on the presence or absence of #define constants and/or their values. This is accomplished in conjunction with the directives #if, #ifdef and #ifndef. Please refer to these topics for examples of Conditional compilation.

Info See also: Category:

1340

#command | #translate, #if, #ifdef, #ifndef, #undef, #xcommand | #xtranslate Preprocessor directives

Preprocessor Reference

#error

#error Raises an explicit compiler error along with a message.

Syntax #error []

Arguments

If specified, this is a text to display when the #error directive is processed.

Description The #error directive instructs the preprocessor to raise an error and display the message text specified with . The message text is output on Stdout so that it can be collected in a file. This directive is only used in conjunction with conditional compilation.

Info See also: Category:

#command | #translate, #define, #if, #ifdef, #ifndef, #stdout Preprocessor directives

Example // The example demonstrates a scenario where the #error directive // is useful. An error message is output when a particular #define // constant exists. #define

DEMO_VERSION

PROCEDURE Main #ifdef DEMO_VERSION #error Do not include DEMO code in production version #endif ? "Normal statements" ENDIF

Preprocessor Reference

1341

#if

#if Compile a section of code based on a condition.

Syntax #if [ #elif ] [ #else ] #endif

Arguments ..

is one or more logical conditions that are resolved by the preprocessor. Conditions are formulated using #define constants, numeric or logical literal values. A condition expression may include comparison operators. ..

is the program code to include in the preprocessor output when a condition is true.

Description The #if..#elif..#else..#endif directives are used for conditional compilation. They work analogous to the IF..ELSEIF..ELSE..ENDIF statements, but are resolved by the preprocessor, rather than the compiler. In contrast to the #ifdef and #ifndef directives, which test only the presence or absence of #define constants, #if allows for testing the values of such constants and comparing them with other values. In addition, multiple conditions can be formulated using #if..#elif. When the #else directive is used, it must be the last one, followed by #endif. The statements following the first condition that resolves to True is included in the preprocessor output. All other statements are discarded. That means, even if multiple conditions are True, only one of the code statements appears in the preprocessor output. When all conditions are False, the statements following the #else directive, if present, are used. The following rules are applied by the preprocessor to evaluate a condition:

1342

1.

A numeric literal 0 yields True, while exact zero yields False.

2.

The logical literal .T. is True, .F. is False.

3.

#define constants with no associated value yield False.

4.

The literal value NIL yields False.

5.

Other literal values cannot be used and result in a compile error.

6.

Numeric values can be compared using the comparison operators !=, #, >, >=, =, ==, =< and RESTRICTED_VERSION InitFullPackage() #elif MAKE_VERSION > DEMO_VERSION InitRestrictedPackage() #else InitDemoPackage() #endif ? "Common code for all packages" RETURN

Preprocessor Reference

1343

#ifdef

#ifdef Compiles a section of code depending on the presence of a #define constant.

Syntax #ifdef [ #else ] #endif

Arguments

This is the symbolic name of a #define constant. ..

These are program statements to include or exclude in the preprocessor output. is included when is defined. Otherwise, the statements following #else, if present, are included.

Description The #ifdef..#else..#endif directives are used for conditional compilation. They work similar to the IF..ELSE..ENDIF statements, but are resolved by the preprocessor, rather than the compiler. #ifdef tests if a #define constant exists. When the constant is defined, the statements following #ifdef are included in the preprocessor output. When the constant does not exist, the statements folowing #else, if present, are used. #endif closes the conditional compilation block.

Info See also: Category:

#define, #if, #ifndef, #undef Preprocessor directives

Example // // // //

The example demonstrates how to implement an extended error checking in the DEBUG version of a program. When DEBUG is not defined, all ErrCheck() pseudo-functions are removed from the PRG code by the preprocessor. #define DEBUG #ifdef DEBUG #xtranslate ErrCheck(,) => ; IF () ;; IF Alert( "Error:;"+,{"Continue","Ouit"}) 1 ;; QUIT ;; ENDIF ;; ENDIF #else #xtranslate ErrCheck(,) => #endif PROCEDURE Main( cParams ) ErrCheck( Empty(cParams), "Command line params missing" )

1344

Preprocessor Reference

#ifdef ? "Error check OK" RETURN

Preprocessor Reference

1345

#ifndef

#ifndef Compiles a section of code depending on the absence of a #define constant.

Syntax #ifndef [ #else ] #endif

Arguments

This is the symbolic name of a #define constant. ..

These are program statements to include or exclude in the preprocessor output. is included when is not #define'd. Otherwise, the statements following #else, if present, are included.

Description The #ifdef..#else..#endif directives are used for conditional compilation. They work similar to the IF..ELSE..ENDIF statements, but are resolved by the preprocessor, rather than the compiler. #ifndef tests if a #define constant does not exist. When the constant is undefined, the statements following #ifndef are included in the preprocessor output. When the constant does exist, the statements folowing #else, if present, are used. #endif closes the conditional compilation block.

Info See also: Category:

#define, #if, #ifdef Preprocessor directives

Example // // // //

The example demonstrates a common technique used to avoid multiple inclusion of an #include file. If, by accident, an include file is included more than once, the directives are skipped by the preprocesor since the #define constant MY_CH_FILE is created on first inclusion. #ifndef MY_CH_FILE #define MY_CH_FILE #endif

1346

Preprocessor Reference

#include

#include Inserts the contents of a file into the current source code file.

Syntax #include ""

Arguments

This is the name of the file to insert into the file which contains the #include directive. The file name must be enclosed in double quotes.

Description The #include directive instructs the preprocessor to insert the contents of the file into the currently processed source file, passing the merged result to the compiler. is the name of the include file, and can contain full path information. If no path is specified with , the preprocessor searches for this file in the following locations and order: 1.

the current directory.

2.

the directory specified with the /i compiler switch.

3.

the list of directories specified with the SET INCLUDE= environment variable.

Include files, often also referred to as Header files, have the CH extension in xHarbour. They are generally used to collect preprocessor directives. This way, directives can be maintained in one central place only. The #include directive is then used to make directives available for many PRG source code files. Header files are only included to source code files that contain the #include directive. An exeption is the STD.CH file or the file specified with the /u compiler switch, which are included in all PRG files. An include file may contain the #include directive so that one header file can include the next. This chained inclusion, however, is limited to a series of 15 files, each of which includes a new one. By using the -u+ compiler switch you may "force" a header file to be included, as if the source to be compiled has #include "" as it's first line. Unless you use the -u (by itself) compiler switch, all source files are compiled with the set of default rules (comparable to CA-Clipper's std.ch file) loaded.

Info See also: Category:

#command | #translate, #define Preprocessor directives

Example // The example illustrates inclusion of a file required for // declaring classes with xHarbour. #include "hbclass.ch" PROCEDURE Main LOCAL obj := MyClass():new( "Hello World" )

Preprocessor Reference

1347

#include obj:display() obj:value := "Hi there" obj:display() RETURN CLASS MyClass EXPORTED: DATA value METHOD new( cString ) CONSTRUCTOR METHOD display ENDCLASS METHOD new( cString ) CLASS MyClass ::value := cString RETURN self METHOD display CLASS MyClass ? ::value RETURN self

1348

Preprocessor Reference

#pragma

#pragma Controls compiler switches at compile time.

Syntax #pragma = ON|OFF #pragma / +|-

Arguments

This is the keyword identifying the compiler option to switch ON or OFF.

As an alternative, the compiler switch can be specified in abbreviated notation followed by a plus sign (ON) or minus sign (OFF).

Description The #pragma directive is the only one processed by the compiler instead of the preprocessor. #pragma allows for changing compiler options while a PRG file is being compiled. It becomes possible to change a compiler switch for a single line of source code and set it back to its original value when that line is processed. The directive supports the following pragmas:

xHarbour pragmas Keywords

Switches

Description

AUTOMEMVARS = On|Off DEBUGINFO = On|Off ENABLEWARNINGS = On|Off EXITSEVERITY = nLevel FORCEMEMVARS = On|Off LINEINFO = On|Off NOSTARTPROC = On|Off PREPROCESSING = On|Off WARNINGLEVEL = nLevel SHORTCUTTING = On|Off TRACEPRAGMAS = On|Off

/A +|/B +|/W +|/E /V +|/L +|/N +|/P +|/W /Z +|-

automatic memvar declaration include debug info enable warnings set exit severity variables are assumed M-> suppress line number information no implicit starting procedure generate pre-processed output (.ppo) file sets warning level supress shortcutting trace pragma settings

Note: there is no switch notation for the TRACEPRAGMAS pragma.

Info See also: Category:

#error, #stdout Preprocessor directives, xHarbour extensions

Example // // // // // //

The example demonstrates the result of pragmas using two identical IF statements. The first IF statement generates a warning and leaves the variable c2 unassigned due to shortcut optimization. The second IF statement generates no warning and assigns a value to c2 since warning and shortcut optimization are both switched off.

Preprocessor Reference

1349

#pragma #pragma TRACEPRAGMAS = ON #pragma ENABLEWARNINGS = ON PROCEDURE Main LOCAL c1 := "A" IF IsAlpha( c1 ) .OR. ; IsDigit( c2 := "2" ) ? c1, Type( "c2" ) ENDIF

// Warning: Ambiguous referece C2 // result: A U

#pragma /Z#pragma /WIF IsAlpha( c1 ) .OR. ; IsDigit( c2 := "2" ) ? c1, Type( "c2" ) ENDIF RETURN

1350

// No Warning // result: A C

Preprocessor Reference

#stdout

#stdout Sends a compiler message to StdOut.

Syntax #stdout []

Arguments

This is a literal text string to send to the standard output device. If no text is specified, an empty line is output.

Description The #stdout directive instructs the preprocessor to display the message text specified with . The message text is output on Stdout so that it can be collected in a file.

Info See also: Category:

#error Preprocessor directives

Example // The example demonstrates the use of #stdout #define DEMO_VERSION PROCEDURE Main #ifdef DEMO_VERSION // output at compile time #stdout Creating the Demo version of the program #else #stdout This is the FULL version of the program #endif ? "Hi there!"

// output at run time

RETURN

Preprocessor Reference

1351

#uncommand | #untranslate

#uncommand | #untranslate Voids a previously defined #command or #translate directive.

Syntax #uncommand #untranslate



Arguments

This is the definition of the search pattern of a previously defined #command or #translate directive. The search pattern must be specified in the same manner as used in the definition of the #command or #translate directive to remove.

Description The directives #uncommand and #untranslate remove a previously defined #command or #translate directive. The removed translation rule becomes unavailable and can be redefined. #uncommand/#untranslate work similar to #xuncommand/#xuntranslate but match only the first keyword in the previously defined #command or #translate directive. Note: #command directives built into the xHarbour compiler cannot be removed using #uncommand.

Info See also: Category:

#command | #translate, #undef, #xuncommand | #xuntranslate Preprocessor directives, xHarbour extensions

Example // see the example for #xuncommand | #xuntranslate

1352

Preprocessor Reference

#undef

#undef Voids a #define constant or pseudo-function.

Syntax #undef

Arguments

This is the symbolic name of the constant or pseudo-function to undefine. It is case sensitive.

Description The #undef directive removes a symbolic name from the list of previously defined constants. The symbolic name becomes unavailable and can be redefined.

Info See also: Category:

#define, #if, #ifdef, #ifndef Preprocessor directives

Example // The example demonstrates a typical pattern for #ifdef, #undef and // #define directives. #ifdef DEBUG_LEVEL #undef DEBUG_LEVEL #define DEBUG_LEVEL #endif

Preprocessor Reference

3

1353

#xcommand | #xtranslate

#xcommand | #xtranslate User defined command or translation rule for the preprocessor.

Syntax #xcommand #xtranslate



=> =>



Arguments

This is the definition of a pattern to search for in the PRG source code. The => characters are part of the preprocessor directive and must be used as separator between and .

This is the definition of a pattern to replace with in the PRG source code.

Description The #xcommand and #xtranslate directives work exactly like #command and #translate with the exception, that they match all characters of keywords. #command and #translate match keywords only up to the first four characters.

Info See also: Category:

#command | #translate, #xuncommand | #xuntranslate Preprocessor directives

Example //

1354

See the example for #command | #translate

Preprocessor Reference

#xuncommand | #xuntranslate

#xuncommand | #xuntranslate Voids a previously defined #xcommand or #xtranslate directive.

Syntax #xuncommand #xuntranslate



Arguments

This is the definition of the search pattern of a previously defined #xcommand or #xtranslate directive. The search pattern must be specified in the same manner as used in the definition of the #xcommand or #xtranslate directive to remove.

Description The directives #xuncommand and #xuntranslate remove a previously defined #xcommand or #xtranslate directive. The removed translation rule becomes unavailable and can be redefined. #xuncommand/#xuntranslate match the entire translation rule previously defined with #xcommand or #xtranslate. The similar to #uncommand/#untranslate directives, in contrast, match only the first keyword in the corresponding #command or #translate directive.

Info See also: Category:

#command | #translate, #uncommand | #untranslate Preprocessor directives, xHarbour extensions

Example // The example demonstrates the effect of removing a translation rule. #xcommand COMMAND => A_Command( ) #xcommand COMMAND WITH => B_Command( , ) PROCEDURE Main COMMAND x COMMAND x WITH y

** // //

PPO file: A_Command(x ) B_Command(x,y )

// //

COMMAND x B_Command(x,y )

#xuncommand COMMAND COMMAND x COMMAND x WITH y RETURN

Preprocessor Reference

1355

Not included in this edition

1356

Not included in this edition

Undocumented functions

Undocumented functions The following sections list functions undocumented in this edition of the xHarbour Language Reference Guide. The documentation for these functions will be ready with the release of the next edition of the xHarbour Language Reference Guide. We are commited to supply you with this free update promptly. Undocumented CGI Functions Undocumented CT Functions Undocumented Misc Functions Undocumented RDD Functions Undocumented RTL Functions Undocumented TIP Functions Undocumented VM Functions

Not included in this edition

1357

Undocumented CGI Functions

Undocumented CGI Functions Module: CGI Functions CgiParseVar() Greek2Html() HtmlAny2Str() HtmlDecodeUrl() HtmlFormName() HtmlFormObject() HtmlLinkStyle() HtmlPadL()

1358

HtmlPadR() HtmlPageHandle() HtmlPageObject() InitGreek() ParseString() PutCounter() SetCorruptFunc() SetErrorFooter()

TCgi() TCgiFile() THtml() THtmlControl() THtmlForm() THtmlFrameSet() TJsList() TJsWindow()

Not included in this edition

Undocumented CT Functions

Undocumented CT Functions Module: CT Functions ACos() AddAscii() AddMonth() AfterAtNum() AsciiSum() AscPos() ASin() AtAdjust() ATan() AtN2() AtNum() AtRepl() AtToken() BeforAtNum() BitToC() Blank() Bom() Boq() Boy() Ceiling() Celsius() Center() CharAdd() CharAnd() CharEven() CharHist() CharList() CharMirr() CharMix() CharNoList() CharNot() CharOdd() CharOne() CharOnly() CharOr() CharPack() CharPix() CharRela() CharRelRep() CharRem() CharRepl() CharRll() CharRlr() CharShl() CharShr() CharsList() CharSort() CharSub() CharSwap() Not included in this edition

Exponent() Fact() Fahrenheit() FieldDeci() FieldNum() FieldSize() FileAttr() FileDate() FileDelete() FileMove() FileScreen() FileSeek() FileSize() FilesMax() FileStr() FileTime() FileValid() Floor() FloppyType() FToC() Fv() GetClearA() GetClearB() GetFldCol() GetFldRow() GetFldVar() Getprec() Getsecret() Getvolinfo() Infinity() InvertAttr() IsBit() IsDir() IsLeap() JustLeft() JustRight() KbdStat() KSetCaps() KSetIns() KSetNum() KSetScroll() LastDayoM() Log10() LtoC() LtoN() Mantissa() MaxLine() MDY() NetCancel()

RemAll() RemLeft() RemRight() RenemeFile() ReplAll() ReplLeft() ReplRight() RestCursor() RestGets() RestGets() RestSetKey() RestToken() RToD() SaveCursor() SaveGets() SaveGets() SaveSetKey() SaveToken() SayScreen() ScreenAttr() ScreenFile() ScreenMix() SetAtlike() SetBit() SetCleara() SetClearb() SetDate() SetFAttr() SetFcreate() SetFdati() SetFont() SetLastkey() SetNewDate() SetNewTime() SetPrec() SetTime() ShowTime() Sign() Sin() Sinh() Standard() StrDiff() StrFile() StrSwap() TabExpand() TabPack() Tan() Tanh() TimeValid() 1359

Undocumented CT Functions CharUnpack() CharXor() Checksum() ClearBit() ClearEol() ClearWin() ClEol() ClWin() ColorTon() Complement() Cos() CosH() Cot() CountGets() CountLeft() CountRight() Crypt() CSetArgErr() CSetAtMupa() CSetCent() CSetCurs() CSetKey() CSetRef() CSetSafety() CtcExit() CtcInit() CtoBit() CtoDoW() CtoF() CtoMonth() CtoN() CurrentGet() DaysInMonth() DaysToMonth() DbfSize() Default() DeleteFile() DirMake() DirName() DiskFormat() DiskFree() DiskReady() DiskReadyW() DiskTotal() DiskUsed() DMY() DoY() DriveType() DtoR() Enhanced() EoM() EoQ() EoY() ExeName()

1360

NetDisk() NetPrinter() NetRedir() NetRmtName() Network() Nnetwork() NtoC() NtoCDow() NtoCMonth() NtoColor() Nul() NumAnd() NumAndx() NumAt() NumCount() NumDiskl() NumHigh() NumLine() NumLow() NumMirr() NumMirrx() NumNot() NumNotx() NumOr() NumOrx() NumRol() NumRolx() NumToken() NumXor() NumXorx() Occurs() PadLeft() PadRight() Payment() Periods() Pi() PosAlpha() PosChar() PosDel() PosDiff() PosEqual() PosIns() PosLower() PosRange() PosRepl() PosUpper() PrintReady() PrintSend() PrintStat() Pv() Quarter() RangeRem() RangeRepl() Rate()

Token() TokenAt() TokenEnd() TokenExit() TokenInit() TokenLower() TokenNext() TokenNum() TokenSep() TokenUpper() Unselected() ValPos() VgaPalette() VideoType() VolSerial() Volume() WaClose() WaitPeriod() WBoard() WBox() WCenter() WClose() WCol() Week() WFCol() WFLastCol() WFLastRow() WFormat() WFRow() WInfo() WLastCol() WLastRow() WMode() WMove() WMSetPos() WNum() WoM() WOpen() WordOne() WordOnly() WordRem() WordRepl() Wordswap() WordToChar() WRow() WSelect() WSetMouse() WSetMove() WSetShadow() WStack() WStep() XToC()

Not included in this edition

Undocumented Misc Functions

Undocumented Misc Functions Module: Misc Functions HB_FEof() HB_FGoBottom() HB_FGoTo() HB_FGoTop()

Not included in this edition

HB_FInfo() HB_FLastRec() HB_FReadAndSkip() HB_FReadLn()

HB_FRecno() HB_FSelect() HB_FSkip() HB_FUse()

1361

Undocumented RDD Functions

Undocumented RDD Functions Module: RDD Functions CftsAdd() CftsClose() CftsCrea() CftsDelete() CftsIfDel() CftsNext() CftsOpen() CftsRecn() CftsReplac() CftsSet() CftsUndel() CftsVeri() CftsVers() DBDrop() DBExists() DBJoin() DBList() DBSort() DBTotal() DBUnlockAl()

1362

DBUpdate() HS_Add() HS_Close() HS_Create() HS_Delete() HS_Filter() HS_IfDel() HS_Index() HS_KeyCount() HS_Next() HS_Open() HS_Replace() HS_Set() HS_Undelete() HS_Verify() HS_Version() HSX_Close() HSX_Create() HSX_File() HSX_Get()

HSX_Handle() HSX_Open() Lock() OrdbagClear() RddRegister() SX_Decrypt() SX_DToP() SX_Encrypt() SX_FCompress() SX_FDecompress() SX_PToD() Usrrdd_AreaData() Usrrdd_AreaResult() Usrrdd_Id() Usrrdd_rdddata() Usrrdd_SetBof() Usrrdd_SetBottom() Usrrdd_SetEof() Usrrdd_SetFound() Usrrdd_SetTop()

Not included in this edition

Undocumented RTL Functions

Undocumented RTL Functions Module: RTL Functions Accelerator() AtSkipStrings() CgiRead() CgiWrite() CreateObject() CstrToVal() CurDirx() Dbf2Text() DisableWaitLocks() FileReader() FileWriter() FSetDevMod() GetActive() GetActiveObject() GetE() GetGtCloseHandler() GetMssgLine() GetPostValidate() GetPrevalidate() GetTable() GfxPrimitive() GfxText() GtCircle() GtDisk() GtGetClipboard() GtGetClipboardSize() GtInfo() GtLine() GtPasteClipboard() GtPoint() GtProcessMessages() GtRectangle() GtRgb() GtSetClipboard() GtSquare() GtSys() GtText() GuiGetPostValidate() GuiGetPrevalidate() HB_ArrayBlock() HB_BldLogMsg() HB_Clocks2Secs() HB_CloseProcess() HB_Clrarea() HB_ColorIndex() HB_ColorTon() HB_Compress() HB_CompressBufLen() HB_CompressError() Not included in this edition

HB_IdleWaitNoCpu() HB_IsService() HB_LangErrMsg() HB_LangMessage() HB_LangName() HB_LogChannel() HB_LogConsole() HB_LogDatestamp() HB_LogDebug() HB_LogEmail() HB_LogFile() HB_Logger() HB_LogInetport() HB_LogSyslog() HB_OpenProcess() HB_OsDriveSeparator() HB_OsError() HB_OsPathDelimiters() HB_OsPathListSeparator() HB_OsPathSeparator() HB_OutDebug() HB_OutDebugname() HB_PCodeVer() HB_Pointer2String() HB_PopSignalHandler() HB_ProcessValue() HB_PushSignalHandler() HB_ReadLine() HB_RegExAtx() HB_RegExReplace() HB_SerializeSimple() HB_SerialNext() HB_ServiceGenerateFault() HB_ServiceGenerateFPE() HB_ServiceLoop() HB_SetDispCp() HB_SetKeyArray() HB_SetKeyCheck() HB_SetKeyCp() HB_SetKeyGet() HB_SetKeySave() HB_SetTermcp() HB_Shadow() HB_SignalDesc() HB_Startservice() HB_String2Pointer() HB_SysLogClose() HB_SysLogMessage() HB_SysLogOpen()

IsLocked() IsNegative() MathErrMode() MathErrorBlock() NationMSG() NetAppend() NetCommitAll() NetDBuse() NetDelete() NetError() NetFilelock() NetFunc() NetLock() NetOpenFiles() NetRecall() NetRecLock() OS_NetRegOk() OS_NetVredirOk() OS_NetWorkOk() OS_Vredirok() PrgExpToVal() ReadFormat() ReadInsert() ReadKey() ReadKill() ReadUpdated() ScalarObject() ScrollBar() ScrollFixed() SecondsCPU() SetCloseEvent() SetGTCloseHandler() SetGTResizeEvent() SetInkeyAfterBlock() SetInkeyBeforeBlock() SetLastKey() SetNetDelay() SetNetMsgColor() SetPosBS() SetShutdownEvent() StrDel() StringToLiteral() StrPeek() StrPoke() TableNew() TOleAuto() TrpcClient() TrpcFunction() TrpcServeCon() 1363

Undocumented RTL Functions HB_CompressErrorDesc() HB_CreateLen8() HB_Decode() HB_DecodeorEmpty() HB_DeserialBegin() HB_DeserializeSimple() HB_DeserialNext() HB_DiskSpace() HB_DumpVar() HB_F_Eof() HB_FCommit() HB_FCreate() HB_GetLen8() HB_GT_Version()

1364

HB_TraceLevel() HB_TraceState() HB_TraceString() HB_Translate() HB_Uncompress() HB_ValToStr() HBConsoleLock() HBConsoleUnlock() HBField() HBOrder() HBRecord() HBTable() IsAffirm() IsDefColor()

TrpcService() TStream() TStreamFileReader() TStreamFileWriter() Updated() VTArrayWrapper() VTWrapper() Wild2regex() Win32bmp() Win32prn() xbpBitmap() xIsPrinter()

Not included in this edition

Undocumented TIP Functions

Undocumented TIP Functions Module: TIP Functions BuildUserPassString() HB_Base64() HB_Base64Decode() HB_Base64DecodeFile() HB_Base64Encode() HB_Base64EncodeFile() HB_UUDecode() HB_UUDecodeFile() HB_UUEncode()

Not included in this edition

HB_UUEncodeFile() Tip_FileMimeType() Tip_MimeType() Tip_TimeStamp() TipCgi() TipClient() TipClientFtp() TipClientHttp() TipClientPop()

TipClientSmtp() TipCredentials() TipEncoder() TipEncoderBase64() TipEncoderQp() TipEncoderUrl() TipMail() TUrl()

1365

Undocumented VM Functions

Undocumented VM Functions Module: VM Functions HB_HFind() HB_i18nGetBaseLanguage() HB_i18nGetBaseLanguageName() HB_i18nGetLanguage() HB_i18nGetLanguagename() HB_i18nGetPath() HB_i18nInitialized() HB_i18nLoadTable() HB_i18nSaveTable() HB_i18nSetBaseLanguage() HB_i18nSetLanguage() HB_i18nSetPath() HB_i18nSortTable() i18n() INetAddress() INetCleanup() INetClearError() INetClearPeriodCallBack()

1366

INetClearTimeLimit() INetClearTimeout() INetClose() INetConnect() INetConnecTip() INetCount() INetCreate() INetCrlf() INetDataready() INetDestroy() INetDgram() INetDgramBind() INetDgramRecv() INetDgramSend() INetErrorCode() INetErrorDesc() INetGetAlias() INetGetHosts()

INetGetPeriodCallBack() INetGetTimeLimit() INetGetTimeout() INetInit() INetPort() INetRecv() INetRecvAll() INetRecvEndBlock() INetRecvLine() INetSend() INetSendAll() INetServer() INetSetPeriodCallBack() INetSetTimeLimit() INetSetTimeout() INetStatus() INetStatusDesc()

Not included in this edition

Categories

Categories

Array functions AAdd() AChoice() AClone() ACopy() ADel() ADir() AEval() AFields() AFill() AIns() ALenAlloc() Array() AScan() ASize() ASizeAlloc() ASort() ATail() HB_ArrayId() HB_ATokens() HB_ThisArray() Len() RAscan()

Adds one element to the end of an array. Displays a list of items to select one from. Creates a deep copy of an array. Copy elements from a source array into a target array. Deletes an element from an array. Fills pre-allocated arrays with file and/or directory information. Evaluates a code block for each array element. Fills pre-allocated arrays with structure information of the current work area. Fills an array with a constant value. Inserts an element into an array. Determines for how much array elements memory is pre-allocated. Creates an uninitialized array of specified length. Searches a value in an array beginning with the first element. Changes the number of elements in an array. Pre-allocates memory for an array. Sorts an array. Returns the last element of an array. Returns a unique identifier for an array or an object variable. Splits a string into tokens based on a delimiter. Retrieves an array or object from its pointer. Returns the number of items contained in an array, hash or string Searches a value in an array beginning with the last element.

Assignment operators := = (assignment) = (compound assignment)

Inline assignment to a variable. Simple assignment operator (binary): assigns a value to a variable. Compound assignment (binary): inline operation with assignment.

Associative arrays HaaDelAt() HaaGetKeyAt() HaaGetPos() HaaGetRealPos() HaaGetValueAt() HaaSetValueAt() HGetAACompatibility() HGetVaaPos() HSetAACompatibility()

Removes a key/value pair from an associative array. Retrieves the key from an associative array by its ordinal position. Retrieves the ordinal position of a key in an associative array. Retrieves the sort order of a key in an associative array. Retrieves the value from an associative array by its ordinal position. Changes the value in an associative array by its ordinal position. Checks if a hash is compatible with an associative array. Retrieves the sort order of all keys in an associative array. Enables or disables associative array compatibility for an empty hash.

Background processing HB_BackGroundActive() HB_BackGroundAdd() HB_BackGroundDel() xHarbour Language Reference Guide

Queries and/or changes the activity of a single background task. Adds a new background task. Removes a background task from the internal task list. 1367

Background processing HB_BackGroundReset() HB_BackGroundRun() HB_BackGroundTime() HB_IdleAdd() HB_IdleDel() HB_IdleReset() HB_IdleSleep() HB_IdleSleepMSec() HB_IdleState() SET BACKGROUND TASKS SET BACKGROUNDTICK

Resets the internal counter of background tasks. Enforces execution of one or all background tasks. Queries or changes the wait interval in milliseconds after which the task is executed. Adds a background task for being executed during idle states. Removes a task from the list of idle tasks. Resets the internal counter of idle tasks. Halts idle task processing for a number of seconds. Queries or changes the default time interval for idle task processing. Signals an idle state. Enables or disables the activity of background tasks. Defines the processing interval for background tasks.

Binary functions Bin2I() Bin2L() Bin2U() Bin2W() I2Bin() L2bin() U2bin() W2bin()

Converts a signed short binary integer (2 bytes) into a numeric value. Converts a signed long binary integer (4 bytes) into a numeric value. Converts an unsigned long binary integer (4 bytes) into a numeric value. Converts an unsigned short binary integer (2 bytes) into a numeric value. Converts a numeric value to a signed short binary integer (2 bytes). Converts a numeric value to a signed long binary integer (4 bytes). Converts a numeric value to an unsigned long binary integer (4 bytes). Converts a numeric value to an unsigned short binary integer (2 bytes).

Bitwise functions HB_BitAnd() HB_BitIsSet() HB_BitNot() HB_BitOr() HB_BitReset() HB_BitSet() HB_BitShift() HB_BitXOr()

Performs a bitwise AND operation with numeric integer values. Checks if a bit is set in a numeric integer value. Performs a bitwise OR operation with a numeric integer value. Performs a bitwise OR operation with numeric integer values. Sets a bit in a numeric integer value to 0. Sets a bit in a numeric integer value to 1. Shifts bits in a numeric integer value. Performs a bitwise XOR operation with numeric integer values.

Bitwise operators & (bitwise AND) > ^^ | (bitwise OR)

Bitwise AND operator (binary): performs a logical AND operation. Left-shift operator (binary): shifts bits to the left. Right-shift operator (binary): shifts bits to the right. Bitwise XOR operator (binary): performs a logical XOR operation. Bitwise OR operator (binary): performs a logical OR operation.

Blob functions BlobDirectExport() BlobDirectGet() BlobDirectImport() BlobDirectPut() BlobExport() BlobGet() BlobImport() BlobRootDelete() BlobRootGet() 1368

Exports the contents of a binary large object (BLOB) to a file. Loads data of a binary large object (BLOB) into memory. Imports a file into a binary large object (BLOB). Assigns data to a binary large object (BLOB). Exports the contents of a memo field holding a binary large object (BLOB) to a file. Reads the contents of a memo field holding a binary large object (BLOB). Imports a file into a memo field. Deleted the root area of a BLOB file. Retrieves data from the root area of a BLOB file. xHarbour Language Reference Guide

Blob functions BlobRootLock() BlobRootPut() BlobRootUnlock()

Places a lock on the root area of a BLOB file. Stores data in the root area of a BLOB file. Releases the lock on the root area of a BLOB file.

C Structure support (struct) C Structure class HB_ArrayToStructure() HB_SizeofCStructure() HB_StructureToArray() pragma pack() typedef struct

Creates a new structure object Abstract class for C structure support. Converts an array to a binary C structure. Calculates the amount of memory required to store a C structure. Converts values contained in a binary C structure string to an array. Defines the byte alignment for the next structure declaration. Declares a new structure in C syntax.

Character functions AllTrim() At() HardCR() HB_ATokens() HB_AtX() HB_Crypt() HB_Decrypt() HB_FNameMerge() HB_FNameSplit() HB_RegEx() HB_RegExAll() HB_RegExComp() HB_RegExMatch() HB_RegExSplit() HexToStr() IsAlNum() IsAlpha() IsAscii() IsCntrl() IsDigit() IsGraph() IsLower() IsPrint() IsPunct() IsSpace() IsUpper() IsXDigit() Left() Len() Lower() LTrim() MemoEdit() MemoLine() MemoRead() MemoTran() MemoWrit() MLCount() MLCToPos()

xHarbour Language Reference Guide

Removes leading and trailing blank spaces from a string. Locates the position of a substring within a character string. Replaces soft carriage returns with hard CRs in a character string. Splits a string into tokens based on a delimiter. Locates a substring within a character string based on a regular expression. Encrypts a character string. Decrypts an encrypted character string. Composes a file name from individual components. Splits a file name into individual components. Searches a string using a regular expression Parses a string and fills an array with parsing information. Compiles a regular expression into a binary search pattern. Tests if a string contains a substring using a regular expression Parses a string using a regular expression and fills an array. Converts a Hex encoded character string to an ASCII string. Checks if the first character of a string is alpha-numeric. Checks if the first character of a string is a letter. Checks if the first character of a string is a 7-bit ASCII character. Checks if the first character of a string is a control character. Checks if the first character of a string is a digit. Checks if the first character of a string is a 7-bit graphical ASCII character. Checks if the first character of a string is a lowercase letter. Checks if the first character of a string is a printable 7-bit ASCII character. Checks if the first character of a string is a punctuation character. Checks if the first character of a string is a white-space character. Checks if the first character of a string is an uppercase letter. Checks if the first character of a string is a hexadecimal digit. Extracts characters from the left side of a string Returns the number of items contained in an array, hash or string Converts a character string to lowercase. Removes leading white-space characters from a character string. Displays and/or edits character strings and memo fields in text mode. Extracts a line of text from a formatted character string or memo field. Reads an entire file from disk into memory. Replaces "carriage return/line feed" pairs in a character string. Writes a character string or a memo field to a file. Counts the number of lines in a character string or memo field Determines the position of a single character in a formatted text string or memo field. 1369

Character functions MlPos() MPosToLC() PadC() | PadL() | PadR() RAt() Replicate() Right() RTrim() SoundEx() Space() Str() StrToHex() StrTran() StrZero() Stuff() SubStr() Trim() Upper() Val() WildMatch()

Determines the starting position of a line in a formatted character string or memo field. Calculates row and column position of a character in a formatted string or memo field. Pads values of data type Character, Date and Numeric with a fill character. Locates the position of a substring within a character string. Creates a character string by replicating an input string. Extracts characters from the right side of a string Removes trailing blank spaces from a character string. Converts a character string using the Soundex algorithm. Returns a string consisting of blank spaces. Converts a numeric value to a character string. Converts a character string to a Hex string. Searches and replaces characters within a character string or memo field. Converts a numeric value to a character string, padded with zeros. Deletes and/or inserts characters in a string. Extracts a substring from a character string. Removes trailing blank spaces from a character string. Converts a character string to uppercase. Convert a character string containing digits to numeric data type Tests if a string begins with a search pattern.

Character operators $ + HAS IN LIKE [ ] (string)

Substring operator (binary): search substring in string. Plus operator: add values, concatenate values and unary positive. Minus operator: add values, concatenate values and unary negative. Searches a character string for a matching regular expression. Searches a value in another value. Compares a character string with a regular expression. Character operator (unary): retrieves a character from a string.

Checksum functions HB_CheckSum() Hb_CRC32() HB_MD5() HB_MD5File()

Calculates the checksum for a stream of data using the Adler32 algorithm. Calculates the checksum for a stream of data using the CRC 32 algorithm. Calculates a message digest for a stream of data using the MD5 algorithm. Calculates a message digest for a file using the MD5 algorithm.

Class declaration ACCESS ASSIGN ASSOCIATE CLASS CLASS CLASSDATA CLASSMETHOD DATA DELEGATE DESTRUCTOR ENABLE TYPE CLASS ERROR HANDLER EXPORTED:

Declares an ACCESS method of a class. Declares an ASSIGN method of a class. Defines a scalar class for a native data type. Declares the class function of a user-defined class. Declares a class variable of a class. Declares the symbolic name of a class method. Declares an instance variable of a class. Declares a message to be directed to a contained object. Declares a method to be called by the garbage collector. Activates scalar classes for native data tyes. Declares the method for error handling within a class. Declares the EXPORTED attribute for a group of member variables and/or methods. EXTEND CLASS...WITH DATA Adds a new member variable to an existing class. EXTEND CLASS...WITH METHOD Adds a new method to an existing class. 1370

xHarbour Language Reference Guide

Class declaration HIDDEN: INLINE METHOD MESSAGE METHOD (declaration) METHOD (implementation) METHOD...OPERATOR METHOD...VIRTUAL OPERATOR OVERRIDE METHOD PROTECTED:

Declares the HIDDEN attribute for a group of member variables and/or methods. Declares and implements an inline method that spans across multiple lines. Declares a message name for a method. Declares the symbolic name of a method. Declares the implementation code of a method. Declares a method to be executed with an operator. Declares a method as virtual. Overloads an operator and declares a method to be invoked for it. Replaces a method in an existing class. Declares the PROTECTED attribute for a group of member variables and methods.

Code block functions AEval() DbEval() Eval() FieldBlock() FieldWBlock() HB_RestoreBlock() HB_SaveBlock() HEval() MemVarBlock()

Evaluates a code block for each array element. Evaluates a code block in a work area. Evaluates a code block. Creates a set/get code block for a field variable Creates a set/get code block for a field variable in a particular work area. Converts binary information back to a code block. Utility function for code block serialization. Evaluates a code block with each hash element. Creates a set/get code block for a dynamic memory variable.

Comparison operators $ < >= HAS IN LIKE

Substring operator (binary): search substring in string. Less than operator (binary): compares the size of two values. Less than or equal operator (binary): compares the size of two values. Not equal operator (binary): compares two values for inequality. Equal operator (binary): compares two values for equality. Exact equal operator (binary): compares two values for identity. Greater than operator (binary): compares the size of two values. Greater than or equal operator (binary): compares the size of two values. Searches a character string for a matching regular expression. Searches a value in another value. Compares a character string with a regular expression.

Console commands ? | ?? EJECT SET ALTERNATE SET CONSOLE SET PRINTER TEXT

Displays values of expressions to the console window. Ejects the current page from the printer. Records the console output in a text file. Sets if console display is shown on the screen. Enables or disables output to the printer or redirects printer output. Displays a block of literal text.

Control structures BEGIN SEQUENCE DO CASE DO WHILE FOR xHarbour Language Reference Guide

Declares a control structure for error handling. Executes a block of statements based on one or more conditions. Executes a block of statements while a condition is true. Executes a block of statements a specific number of times. 1371

Control structures FOR EACH HB_EnumIndex() IF RETURN SWITCH TRY...CATCH WITH OBJECT

Iterates elements of data types that can be seen as a collection. Returns the current ordinal position of a FOR EACH iteration. Executes a block of statements based on one or more conditions. Branches program control to the calling routine. Executes one or more blocks of statements. Declares a control structure for error handling. Identifies an object to receive multiple messages.

Conversion functions AmPm() Asc() Bin2I() Bin2L() Bin2U() Bin2W() CDoW() Chr() CMonth() ConvToAnsiCP() ConvToOemCP() CStr() CtoD() Day() Descend() DoW() DtoC() DtoS() HB_AnsiToOem() HB_Crypt() HB_Decrypt() HB_DeSerialize() HB_OemToAnsi() HB_RestoreBlock() HB_SaveBlock() HB_Serialize() HexToNum() HexToStr() I2Bin() If() | IIf() L2bin() Month() NumToHex() PadC() | PadL() | PadR() SoundEx() StoD() Str() StrToHex() StrZero() Transform() U2bin() Val() ValToPrg() ValToPrgExp() W2bin() Word() Year() 1372

Converts a time string into am/pm format. Returns the ASCII code for characters. Converts a signed short binary integer (2 bytes) into a numeric value. Converts a signed long binary integer (4 bytes) into a numeric value. Converts an unsigned long binary integer (4 bytes) into a numeric value. Converts an unsigned short binary integer (2 bytes) into a numeric value. Returns the name of a week day from a date. Converts a numeric ASCII code to a character. Returns the name of a month from a date. Converts an OEM string to the ANSI character set. Converts an ANSI string to the OEM character set. Converts a value to a character string. Converts a character string into a Date value Extracts the numeric day number from a Date value. Converts a value for a descending index. Determines the numeric day of the week from a date. Converts a Date value to a character string in SET DATE format. Converts a Date value to a character string in YYYYMMDD format. Converts a character string from the ANSI to the OEM character set. Encrypts a character string. Decrypts an encrypted character string. Converts a binary string back to its original data type. Converts a character string from the OEM to the ANSI character set. Converts binary information back to a code block. Utility function for code block serialization. Converts an arbitrary value to a binary string. Converts a Hex string to a numeric value. Converts a Hex encoded character string to an ASCII string. Converts a numeric value to a signed short binary integer (2 bytes). Returns the result of an expression based on a logical expression Converts a numeric value to a signed long binary integer (4 bytes). Extracts the numeric month number from a Date value. Converts a numeric value or a pointer to a Hex string. Pads values of data type Character, Date and Numeric with a fill character. Converts a character string using the Soundex algorithm. Converts a "yyyymmdd" formatted string to a Date value Converts a numeric value to a character string. Converts a character string to a Hex string. Converts a numeric value to a character string, padded with zeros. Converts values to a PICTURE formatted character string. Converts a numeric value to an unsigned long binary integer (4 bytes). Convert a character string containing digits to numeric data type Converts a value to PRG code. Converts a value to charecter string holding a macro-expression. Converts a numeric value to an unsigned short binary integer (2 bytes). Converts a floating point number to a 32-it integer value. Extracts the numeric year from a Date value xHarbour Language Reference Guide

Database commands

Database commands APPEND BLANK APPEND FROM AVERAGE CLOSE COMMIT CONTINUE COPY STRUCTURE COPY STRUCTURE EXTENDED COPY TO COUNT CREATE CREATE FROM DELETE DELETE TAG FIND GO INDEX JOIN LOCATE PACK RECALL REINDEX REPLACE SEEK SELECT SET AUTOPEN SET AUTORDER SET AUTOSHARE SET DBFLOCKSCHEME SET DELETED SET EXCLUSIVE SET FILTER SET INDEX SET MEMOBLOCK SET OPTIMIZE SET ORDER SET RELATION SET SCOPE SET SCOPEBOTTOM SET SCOPETOP SET STRICTREAD SKIP SORT SUM TOTAL UNLOCK UPDATE USE ZAP

xHarbour Language Reference Guide

Creates a new record in the current work area. Imports records from a database file or an ASCII text file. Calculates the average of numeric expressions in the current work area. Closes one or more specified files. Writes memory buffers of all used work areas to disk. Resumes a pending LOCATE command. Copies the current database structure to a new database file. Copies field information to a new database file. Exports records from the current work area to a database or an ASCII text file. Counts records in the current work area. Creates and opens an empty structure extended database file. Creates a new database file from a structure extended file. Marks one or more records for deletion. Deletes a tag from an index. Searches an index for a specified key value. Moves the record pointer to a specified position. Creates an index and/or index file. Merges records of two work areas into a new database. Scans the current work area for a record matching a condition. Removes records marked for deletion physically from a database file. Removes a deletion mark from one or more records. Rebuilds all open indexes in the current work area. Assigns values to field variables. Searches a value in an index. Changes the current work area. Toggles automatic opening of a structural index file. Defines the default controlling index for automatically opened index files. Defines network detection for shared file access. Selects the locking scheme for shared database access. Specifies visibility of records marked for deletion. Sets the global EXCLUSIVE open mode for databases. Defines a condition for filtering records in the current work area. Opens one or more index files in the current work area. Defines the default block size for memo files. Toggles filter optimization with indexed databases. Selects the controlling index. Synchronizes the record pointers in one or more work areas. Changes the top and/or bottom scope for navigating in the controlling index. Changes the bottom scope for navigating in the controlling index. Changes the top scope for navigating in the controlling index. Toggles read optimization for database access. Moves the record pointer to a new position. Creates a new, physically sorted database. Calculates the sum of numeric expressions in the current work area. Creates a new database summarizing numeric fields by an expression. Releases file and/or record locks in the current or all work areas Updates records in the current work area from a second work area. Opens a database and its associated files in a work area. Delete all records from the current database file

1373

Database drivers

Database drivers DbSetDriver() RddInfo() RddList() RddName() RddSetDefault()

Retrieves and/or selects the default replaceable database driver. Queries and/or changes configuration data of RDDs. Retrieves information about available Replaceable Database Drivers (RDDs). Retrieves the name of an RDD used to open files in a work area Retrieves or changes the default replaceable database driver.

Database functions Alias() BlobDirectExport() BlobDirectGet() BlobDirectImport() BlobDirectPut() BlobExport() BlobGet() BlobImport() BlobRootDelete() BlobRootGet() BlobRootLock() BlobRootPut() BlobRootUnlock() BoF() Browse() DbAppend() DbClearFilter() DbClearIndex() DbClearRelation() DbCloseAll() DbCloseArea() DbCommit() DbCommitAll() DbCopyExtStruct() DbCopyStruct() DbCreate() DbCreateIndex() DbDelete() DbEdit() DbEval() Dbf() DbFieldInfo() DbFileGet() DbFilePut() DbFilter() DbGoBottom() DbGoto() DbGoTop() DbInfo() DbOrderInfo() DbRecall() DbRecordInfo() 1374

Returns the alias name of a work area. Exports the contents of a binary large object (BLOB) to a file. Loads data of a binary large object (BLOB) into memory. Imports a file into a binary large object (BLOB). Assigns data to a binary large object (BLOB). Exports the contents of a memo field holding a binary large object (BLOB) to a file. Reads the contents of a memo field holding a binary large object (BLOB). Imports a file into a memo field. Deleted the root area of a BLOB file. Retrieves data from the root area of a BLOB file. Places a lock on the root area of a BLOB file. Stores data in the root area of a BLOB file. Releases the lock on the root area of a BLOB file. Determines if the record pointer reached the begin-of-file boundary. Browse a database file Appends a new record to a database open in a work area. Clears the current filter condition in a work area. Closes all indexes open in the current work area. Clears all active relations in a work area. Close all open files in all work areas. Closes a database file in a work area. Writes database and index buffers to disk. Writes database and index buffers of all used work areas to disk. Creates a structure extended database file. Creates a new database based on the current database structure. Creates an empty database from a structure definition array. Creates a new index and/or index file. Marks records for deletion. Browse records in a table. Evaluates a code block in a work area. Retrieves the alias name of the current work area. Retrieves information about a database field Copies data from a field into an external file. Copies the contents of an external file into a field. Returns the filter expression of a work areaMoves the record pointer to last record. Positions the record pointer on a particular record. Moves the record pointer to first record. Queries and/or changes information about a database file open in a work area. Queries and/or changes information about indexes open in a work area. Recalls a record previousy marked for deletion. Queries and/or changes information about a record of an open database file. xHarbour Language Reference Guide

Database functions DbReindex() DbRelation() DbRLock() DbRLockList() DbRSelect() DbRUnlock() DbSeek() DbSelectArea() DbSetDriver() DbSetFilter() DbSetIndex() DbSetOrder() DbSetRelation() DbSkip() DbSkipper() DbStruct() DbTableExt() DbUnlock() DbUnlockAll() DbUseArea() Deleted() Eof() FieldBlock() FieldGet() FieldName() FieldPos() FieldPut() FieldWBlock() FLock() Found() Header() IndexExt() IndexKey() IndexOrd() LastRec() LUpdate() NetErr() OrdBagExt() OrdBagName() OrdCondSet() OrdCount() OrdCreate() OrdCustom() OrdDescend() OrdDestroy() OrdFindRec() OrdFor() OrdIsUnique() OrdKey() OrdKeyAdd() OrdKeyCount() OrdKeyDel() OrdKeyGoTo() OrdKeyNo() OrdKeyRelPos() OrdKeyVal() OrdListAdd() OrdListClear() OrdListRebuild() xHarbour Language Reference Guide

Rebuilds indexes open in a work area. Returns the linking expression of a specified relation. Locks a record for write access. Returns a list of locked records. Returns the child work area number of a relation. Unlocks a record based on its indentifier. Searches a value in the controlling index. Selects the current work area. Retrieves and/or selects the default replaceable database driver. Defines a filter condition for a work area. Opens an index file. Selects the controlling index. Relates a child work area with a parent work area. Moves the record pointer in a work area. Helper function for browse objects to skip a database Loads structural information of a database into an array. Retrieves the default database file extension of the current RDD. Releases file and all record locks in a work area. Unlocks all records and releases all file locks in all work areas. Opens a database file in a work area. Queries the Deleted flag of the current record Determines when the end-of-file is reached. Creates a set/get code block for a field variable Retrieves the value of a field variable by its ordinal position. Retrieves the name of a field variable by its ordinal position. Retrieves the ordinal position of a field variable by its name. Assigns a value to a field variable by its ordinal position. Creates a set/get code block for a field variable in a particular work area. Applies a file lock to an open, shared database. Checks if the last database search operation was successful Returns the size of the database file header. Retrieves the default index file extension in a work area. Returns the index expression of an open index. Returns the ordinal position of the controlling index in a work area. Returns the number of records available in a work area. Returns the last modification date of a database open in a work area. Determines if a database command has failed in network operation. Retrieves the default extension for index files. Retrieves the file name of an open index. Sets the conditions for index creation. Determines the number of indexes open in a work area. Creates a new index. Determines if an index is a custom index. Determines the navigational order of a work area. Deletes an index from an index file. Searches a record number in the controlling index. Retrieves the FOR expression of an index. Retrieves the UNIQUE flag of an index. Returns the key expression of an index. Adds an index key to a custom built index. Retrieves the total number of keys included in an index. Removes an index key from a custom built index. Moves the record pointer to a logical record number. Returns the logical record number of the current record. Returns or sets the relative position of the current record. Retrieves the index value of the current record from the controlling index. Opens and optionally activates a new index in a work area. Closes all indexes open in a work area. Rebuilds all indexes open in the current work area 1375

Database functions OrdName() OrdNumber() OrdScope() OrdSetFocus() OrdSetRelation() OrdSkipRaw() OrdSkipUnique() OrdWildSeek() RecCount() RecNo() RecSize() RLock() Select() Used()

Returns the symbolic name of an open index by its ordinal position. Returns the ordinal position of an open index by its symbolic name. Defines the top and/or bottom scope for navigating in the controlling index. Sets focus to the controlling index in a work area Defines a scoped relation between child work area and parent work area. Moves the record pointer via the controlling index. Navigates to the next or previous record that has another index value. Searches a value in the controlling index using wild card characters. Returns the number of records available in a work area. Retrieves the number of the current record in a work area. Retrieves the number of bytes required to store a database record. Locks the current record for concurrent write access in a work area. Retrieves the work area number by alias name. Determines if a database file is open in a work area.

Date and time CDoW() CMonth() CtoD() Date() Day() Days() DoW() DtoC() DtoS() ElapTime() Max() Min() Month() Seconds() Secs() StoD() Time() TString() Year()

Returns the name of a week day from a date. Returns the name of a month from a date. Converts a character string into a Date value Returns the current date from the operating system. Extracts the numeric day number from a Date value. Calculates the number of days from elapsed seconds. Determines the numeric day of the week from a date. Converts a Date value to a character string in SET DATE format. Converts a Date value to a character string in YYYYMMDD format. Calculates the time elapsed between a start and an end time. Returns the larger value of two Numerics or Dates. Returns the smallerr value of two Numerics or Dates. Extracts the numeric month number from a Date value. Returns the number of seconds elapsed since midnight Calculates the number of seconds from a time string. Converts a "yyyymmdd" formatted string to a Date value Retrieves the system time as a formatted character string. Converts numeric seconds into a time formatted character string. Extracts the numeric year from a Date value

Debug functions AltD() CStr() ErrorBlock() ErrorLevel() HB_AParams() HB_ArgC() HB_ArgCheck() HB_ArgString() HB_ArgV() HB_ArrayId() HB_CmdArgArgV() HB_GCAll() HB_GCStep() HB_IsArray() HB_IsBlock() HB_IsByRef 1376

Activates and/or invokes the "classic" debugger. Converts a value to a character string. Sets or retrieves the error handling code block. Sets the exit code of the xHarbour application. Collects values of all parameters passed to a function, method or procedure. Returns the number of command line arguments. Checks if an internal switch is set on the command line. Retrieves the vale of an internal switch set on the command line. Retrieves the value of a command line argument. Returns a unique identifier for an array or an object variable. Returns the first command line argument (EXE file name). Scans the memory and releases all garbage memory blocks. Invokes the garbage collector for one collection cycle. Tests if the value returned by an expression is an array. Tests if the value returned by an expression is a Code block. Tests if a parameter is passed by reference. xHarbour Language Reference Guide

Debug functions HB_IsDate() HB_IsHash() HB_IsLogical() HB_IsMemo() HB_IsNIL() HB_IsNull() HB_IsNumeric() HB_IsObject() HB_IsPointer() HB_IsString() HB_ThisArray() HB_XmlErrorDesc() Memory() PCount() ProcFile() ProcLine() ProcName() PValue() Throw() TraceLog() Type() Valtype()

Tests if the value returned by an expression is a Date. Tests if the value returned by an expression is a Hash. Tests if the value returned by an expression is a logical value. Tests if the value returned by an expression is a Memo value. Tests if the value returned by an expression is NIL. Tests if the value returned by an expression is empty. Tests if the value returned by an expression is a numeric value. Tests if the value returned by an expression is an object. Tests if the value returned by an expression is a pointer. Tests if the value returned by an expression is a character string. Retrieves an array or object from its pointer. Retrieves a textual error description for XML file parsing errors. Returns memory statistics. Returns the number of passed parameters. Determines the current PRG source code file. Determines the current line number executed in a PRG source code file. Determines the symbolic name of the currently executed function, method or procedure. Retrieves the value of a parameter passed to a function, method or procedure. Throws an exception. Traces and logs the contents of one or more variables. Determines the data type of a macro expression. Determines the data type of the value returned by an expression.

Declaration ACCESS ANNOUNCE ASSIGN ASSOCIATE CLASS CLASS CLASSDATA CLASSMETHOD DATA DELEGATE DESTRUCTOR ENABLE TYPE CLASS ERROR HANDLER EXIT PROCEDURE EXPORTED:

Declares an ACCESS method of a class. Declaration of a module identifier name. Declares an ASSIGN method of a class. Defines a scalar class for a native data type. Declares the class function of a user-defined class. Declares a class variable of a class. Declares the symbolic name of a class method. Declares an instance variable of a class. Declares a message to be directed to a contained object. Declares a method to be called by the garbage collector. Activates scalar classes for native data tyes. Declares the method for error handling within a class. Declares a procedure to execeute when a program terminates. Declares the EXPORTED attribute for a group of member variables and/or methods. EXTEND CLASS...WITH DATA Adds a new member variable to an existing class. EXTEND CLASS...WITH METHOD Adds a new method to an existing class. EXTERNAL Declares the symbolic name of an external function or procedure for the linker. FIELD Declares a field variable FUNCTION Declares a function along with its formal parameters. GLOBAL Declares and optionally initializes a GLOBAL memory variable. HIDDEN: Declares the HIDDEN attribute for a group of member variables and/or methods. INIT PROCEDURE Declares a procedure to execeute when a program starts. INLINE METHOD Declares and implements an inline method that spans across multiple lines. LOCAL Declares and optionally initializes a local memory variable. MEMVAR Declares PRIVATE or PUBLIC variables. MESSAGE Declares a message name for a method. METHOD (declaration) Declares the symbolic name of a method. xHarbour Language Reference Guide

1377

Declaration METHOD (implementation) METHOD...OPERATOR METHOD...VIRTUAL OPERATOR OVERRIDE METHOD PARAMETERS PRIVATE PROCEDURE PROTECTED: PUBLIC REQUEST STATIC

Declares the implementation code of a method. Declares a method to be executed with an operator. Declares a method as virtual. Overloads an operator and declares a method to be invoked for it. Replaces a method in an existing class. Declares PRIVATE function parameters. Creates and optionally initializes a PRIVATE memory variable. Declares a procedure along with its formal parameters. Declares the PROTECTED attribute for a group of member variables and methods. Creates and optionally initializes a PUBLIC memory variable. Declares the symbolic name of an external function or procedure for the linker. Declares and optionally initializes a STATIC memory variable.

Directory functions CurDir() DefPath() DirChange() Directory() DirectoryRecurse() DirRemove() DiskChange() DiskName() DiskSpace() IsDirectory() IsDisk() MakeDir()

Returns the current directory of a drive Returns the SET DEFAULT directory. Changes the current directory. Loads file and directory information into a two-dimensional array. Loads file information recursively into a two-dimensional array. Removes a directory. Changes the current disk drive. Returns the current disk drive. Returns the free storage space for a disk drive. Checks if a character string contains the name of an existing directory. Verify if a drive is ready Creates a new directory.

DLL functions DllCall() DllExecuteCall() DllLoad() DllPrepareCall() DllUnload() FreeLibrary() GetLastError() GetProcAddress() HB_LibDo() LibFree() LibLoad() LoadLibrary() SetLastError()

Executes a function located in a dynamically loaded external library. Executes a DLL function via call template. Loads a DLL file into memory. Creates a call template for an external DLL function. Releases a dynamically loaded external DLL from memory. Releases a dynamically loaded external DLL from memory. Retrieves the error code of the last dynamically called DLL function. Retrieves the memory address of a function in a dynamically loaded DLL. Executes a function located in a dynamically loaded xHarbour DLL. Releases a dynamically loaded xHarbour DLL from memory. Loads an xHarbour DLL file into memory. Loads an external DLL file into memory. Sets a numeric value as last error code.

Environment commands CANCEL CLOSE SET BELL SET DIRCASE SET DIRSEPARATOR SET EOL SET ERRORLOG SET ERRORLOOP 1378

Terminates program execution unconditionally. Closes one or more specified files. Toggles automatic sounding of the bell in the GET system. Specifies how directories are accessed on disk. Specifies the default separator for directories. Defines the end-of-line character(s) for ASCII text files. Defines the default error log file. Defines the maximum recursion depth for error handling. xHarbour Language Reference Guide

Environment commands SET FILECASE SET FIXED SET TRACE

Specifies how files are accessed on disk. Toggles fixed formatting for displaying numbers in text-mode. Toggles output of function TraceLog().

Environment functions GetEnv() HB_AParams() HB_ArgC() HB_ArgCheck() HB_ArgString() HB_ArgV() HB_BuildDate() HB_BuildInfo() HB_CmdArgArgV() HB_Compiler() HB_EnumIndex() HB_GCAll() HB_GCStep() HB_OsNewLine() HB_VMMode() Memory() NetName() Os() Os_IsWin2000() Os_IsWin2000_Or_Later() Os_IsWin2003() Os_IsWin95() Os_IsWin98() Os_IsWin9X() Os_IsWinME() Os_IsWinNT() Os_IsWinNT351() Os_IsWinNT4() Os_IsWinVista() Os_IsWinXP() Os_IsWtsClient() Os_VersionInfo() PCol() PCount() PRow() PValue() Set() SetCancel() SetKey() SetPrc() Tone() Used() Version()

Retrieves an operating system environment variable. Collects values of all parameters passed to a function, method or procedure. Returns the number of command line arguments. Checks if an internal switch is set on the command line. Retrieves the vale of an internal switch set on the command line. Retrieves the value of a command line argument. Retrieves the formatted build date of the xHarbour compiler Retrieves build information of the xHarbour compiler. Returns the first command line argument (EXE file name). Retrieves the version of the C compiler shipped with xHarbour. Returns the current ordinal position of a FOR EACH iteration. Scans the memory and releases all garbage memory blocks. Invokes the garbage collector for one collection cycle. Returns the end-of-line character(s) to use with the current operating system. Indicates the creation mode of the xHarbour virtual machine. Returns memory statistics. Retrieves the current user name or the computer name. Returns the name of the operating system. Checks if the application is running on Windows 2000. Checks if the application is running on Windows version 2000 or later Checks if the application is running on Windows 2003. Checks if the application is running on Windows 95. Checks if the application is running on Windows 98. Checks if the application is running on a Windows 9x platform. Checks if the application is running on Windows ME. Checks if the application is running on a Windows NT platform. Checks if the application is running on Windows NT 3.51. Checks if the application is running on Windows NT 4.0. Checks if the application is running on Windows Vista. Checks if the application is running on Windows XP. Checks if the application is running on a Windows Terminal Server client. Retrieves specific version information about the operating system. Returns the column position of the print head. Returns the number of passed parameters. Returns the row position of the print head. Retrieves the value of a parameter passed to a function, method or procedure. Retrieves or changes a system setting. Determines if Alt+C and Ctrl+Break terminate an application Associates a code block with a key Changes the PRow() and PCol() values. Sounds a speaker tone with specific tone frequency and duration. Determines if a database file is open in a work area. Retrieves xHarbour version information.

Error functions Break() DosError() xHarbour Language Reference Guide

Exits from a BEGIN SEQUENCE block. Sets or retrieves the last DOS error code. 1379

Error functions ErrorBlock() ErrorLevel() ErrorNew() ErrorSys() SetErrorMode() Throw()

Sets or retrieves the error handling code block. Sets the exit code of the xHarbour application. Creates a new Error object and optionally fills it with data. Installs the default error code block. Queries or changes the behavior with operating system errors. Throws an exception.

Field functions AFields() DbFieldInfo() DbFileGet() DbFilePut() FCount() FieldDec() FieldGet() FieldLen() FieldName() FieldPos() FieldPut() FieldType()

Fills pre-allocated arrays with structure information of the current work area. Retrieves information about a database field Copies data from a field into an external file. Copies the contents of an external file into a field. Returns the number of fields in the current work area. Retrieves the number of decimal places of a field variable. Retrieves the value of a field variable by its ordinal position. Retrieves the number of bytes occupied by a field variable. Retrieves the name of a field variable by its ordinal position. Retrieves the ordinal position of a field variable by its name. Assigns a value to a field variable by its ordinal position. Retrieves the data type of a field variable.

File commands COPY FILE DELETE FILE ERASE RENAME

Copies a file to a new file or to an output device. Deletes a file from disk. Deletes a file from disk. Changes the name of a file.

File functions ADir() CurDir() CurDrive() DefPath() DirChange() Directory() DirectoryRecurse() DirRemove() DiskChange() DiskName() DiskSpace() FCharCount() FClose() FCount() FCreate() FErase() FError() File() FileStats() FLineCount() FOpen() FParse() FParseEx() 1380

Fills pre-allocated arrays with file and/or directory information. Returns the current directory of a drive Determines or changes the current disk drive Returns the SET DEFAULT directory. Changes the current directory. Loads file and directory information into a two-dimensional array. Loads file information recursively into a two-dimensional array. Removes a directory. Changes the current disk drive. Returns the current disk drive. Returns the free storage space for a disk drive. Counts the number of characters in a text file ignoring white space characters. Closes a binary file. Returns the number of fields in the current work area. Creates an empty binary file. Deletes a file from disk. Retrieves the error code of the last low-level file operation. Checks for the existence of a file in the default directory or path Retrieves file information for a single file. Counts the lines in an ASCII text file. Opens a file on the operating system level. Parses a delimited text file and loads it into an array. Parses a delimited text file and loads it into an array (optimized). xHarbour Language Reference Guide

File functions FParseLine() FRead() FReadStr() FRename() FSeek() FWordCount() FWrite() HB_FNameMerge() HB_FNameSplit() HB_FTempCreate() HB_ReadIni() HB_SetIniComment() HB_WriteIni() IsDirectory() IsDisk() MakeDir()

Parses one line of a delimited text and loads it into an array. Reads characters from a binary file into a memory variable. Reads characters up to Chr(0) from a binary file. Renames a file. Changes the position of the file pointer. Counts the words in a text file. Writes data to an open binary file. Composes a file name from individual components. Splits a file name into individual components. Creates and opens a temporary file. Reads an INI file from disk. Defines the delimiting characters for comments and inline comments. Creates an INI file and writes hash data to it. Checks if a character string contains the name of an existing directory. Verify if a drive is ready Creates a new directory.

Get system @...GET Get() MenuItem() MenuModal() Popup() READ ReadModal() TopBarMenu()

Creates a Get object (entry field) and displays it to the screen Creates a new Get object. Creates a new MenuItem object. Activates the menu system represented by a TopBarMenu object. Creates a new Popup menu object. Activates editing of @...GET entry fields in text mode. Activates editing of @...GET entry fields in text mode. Creates a new TopBarMenu object.

Hash functions HaaDelAt() HaaGetKeyAt() HaaGetPos() HaaGetRealPos() HaaGetValueAt() HaaSetValueAt() HAllocate() Hash() HClone() HCopy() HDel() HDelAt() HEval() HFill() HGet() HGetAACompatibility() HGetAutoAdd() HGetCaseMatch() HGetKeyAt() HGetKeys() HGetPairAt() HGetPartition() HGetPos() HGetVaaPos() HGetValueAt() HGetValues() HHasKey() xHarbour Language Reference Guide

Removes a key/value pair from an associative array. Retrieves the key from an associative array by its ordinal position. Retrieves the ordinal position of a key in an associative array. Retrieves the sort order of a key in an associative array. Retrieves the value from an associative array by its ordinal position. Changes the value in an associative array by its ordinal position. Pre-allocates memory for a large hash. Creates a new hash. Creates an entire copy of a hash. Copies key/value pairs from a hash into another hash. Removes a key/value pair from the hash by its key. Removes a key/value pair from the hash by its key. Evaluates a code block with each hash element. Copies the same value into all key/value pairs. Retrieves the value associated with a specified key. Checks if a hash is compatible with an associative array. Retrieves the AutoAdd attribute of a hash. Retrieves the case sensitivity attribute of a hash. Retrieves the key from a hash by its ordinal position. Collects all keys from a hash in an array. Retrieves a key/value pair from a hash by its ordinal position. Checks if a hash is partitioned. Retrieves the ordinal position of a key in a hash. Retrieves the sort order of all keys in an associative array. Retrieves the value from a hash by its ordinal position. Collects all values from a hash in an array. Determines if a key is present in a hash. 1381

Hash functions HMerge() HScan() HSet() HSetAACompatibility() HSetAutoAdd() HSetCaseMatch() HSetPartition() HSetValueAt() Len()

Merges the contents of an entire hash into another hash. Searches a value in a hash. Associates a value with a key in a hash. Enables or disables associative array compatibility for an empty hash. Changes the AutoAdd attribute of a hash. Changes the case sensitivity attribute of a hash. Partitions a linear hash for improved performance. Changes the value in a hash by its ordinal position. Returns the number of items contained in an array, hash or string

Index commands DELETE TAG INDEX REINDEX SEEK SET DESCENDING SET INDEX SET ORDER SET SCOPE SET SCOPEBOTTOM SET SCOPETOP SET SOFTSEEK SET UNIQUE

Deletes a tag from an index. Creates an index and/or index file. Rebuilds all open indexes in the current work area. Searches a value in an index. Changes the descending flag of the controlling index at runtime. Opens one or more index files in the current work area. Selects the controlling index. Changes the top and/or bottom scope for navigating in the controlling index. Changes the bottom scope for navigating in the controlling index. Changes the top scope for navigating in the controlling index. Enables or disables relative seeking. Includes or excludes non-unique keys to/from an index.

Index functions DbClearIndex() DbCreateIndex() DbReindex() DbSeek() DbSetIndex() DbSetOrder() Found() IndexExt() IndexKey() IndexOrd() OrdBagExt() OrdBagName() OrdCondSet() OrdCount() OrdCreate() OrdCustom() OrdDescend() OrdDestroy() OrdFindRec() OrdFor() OrdIsUnique() OrdKey() OrdKeyAdd() OrdKeyCount() OrdKeyDel() OrdKeyGoTo() OrdKeyNo() OrdKeyRelPos() OrdKeyVal() 1382

Closes all indexes open in the current work area. Creates a new index and/or index file. Rebuilds indexes open in a work area. Searches a value in the controlling index. Opens an index file. Selects the controlling index. Checks if the last database search operation was successful Retrieves the default index file extension in a work area. Returns the index expression of an open index. Returns the ordinal position of the controlling index in a work area. Retrieves the default extension for index files. Retrieves the file name of an open index. Sets the conditions for index creation. Determines the number of indexes open in a work area. Creates a new index. Determines if an index is a custom index. Determines the navigational order of a work area. Deletes an index from an index file. Searches a record number in the controlling index. Retrieves the FOR expression of an index. Retrieves the UNIQUE flag of an index. Returns the key expression of an index. Adds an index key to a custom built index. Retrieves the total number of keys included in an index. Removes an index key from a custom built index. Moves the record pointer to a logical record number. Returns the logical record number of the current record. Returns or sets the relative position of the current record. Retrieves the index value of the current record from the controlling index. xHarbour Language Reference Guide

Index functions OrdListAdd() OrdListClear() OrdListRebuild() OrdName() OrdNumber() OrdScope() OrdSetFocus() OrdSetRelation() OrdSkipRaw() OrdSkipUnique() OrdWildSeek()

Opens and optionally activates a new index in a work area. Closes all indexes open in a work area. Rebuilds all indexes open in the current work area Returns the symbolic name of an open index by its ordinal position. Returns the ordinal position of an open index by its symbolic name. Defines the top and/or bottom scope for navigating in the controlling index. Sets focus to the controlling index in a work area Defines a scoped relation between child work area and parent work area. Moves the record pointer via the controlling index. Navigates to the next or previous record that has another index value. Searches a value in the controlling index using wild card characters.

Indirect execution & (macro operator) @() Eval() HB_AExpressions() HB_Exec() HB_ExecFromArray() HB_FuncPtr() HB_MacroCompile() HB_ObjMsgPtr() HB_SetMacro() HB_VMExecute() {|| }

Macro operator (unary): compiles a character string at runtime. Extended literal code block. Function-reference operator (unary): obtains a function pointer. Evaluates a code block. Parses a character string into an array of macro expressions. Executes a function, procedure or method from its pointer. Executes a function, procedure or method indirectly. Obtains the pointer to a function or procedure. Compiles a macro string into a PCode sequence. Retrieves the pointer to a method. Enables or disables runtime behavior of the macro compiler. Executes a PCode string. Literal code block.

Info functions DbInfo() DbOrderInfo() DbRecordInfo() RddInfo()

Queries and/or changes information about a database file open in a work area. Queries and/or changes information about indexes open in a work area. Queries and/or changes information about a record of an open database file. Queries and/or changes configuration data of RDDs.

Input commands @...GET @...PROMPT ACCEPT CLEAR TYPEAHEAD INPUT KEYBOARD MENU TO READ SET CONFIRM SET EVENTMASK SET FUNCTION WAIT

xHarbour Language Reference Guide

Creates a Get object (entry field) and displays it to the screen Displays a menu item for a text mode menu. Basic user input routine. Empties the keyboard buffer. Assigns the result of an input expression to a variable. Writes a string or numeric key codes into the keyboard buffer. Activates a text-mode menu defined with @...PROMPT commands. Activates editing of @...GET entry fields in text mode. Determines how a GET entry field is exited. Sets which events should be returned by the Inkey() function. Associates a character string with a function key. Suspend program execution until a key is pressed.

1383

Keyboard functions

Keyboard functions FkLabel() FkMax() HB_KeyPut() Inkey() LastKey() NextKey()

Returns a function key name. Returns the number of available function keys. Puts an inkey code into the keyboard buffer. Retrieves a character from the keyboard buffer or a mouse event. Returns the last Inkey() code retrieved. Returns the next pending key or mouse event.

Language specific HB_LangSelect() HB_SetCodePage()

Queries or changes the current national language . Queries or changes the current code page.

Logical functions Empty() HB_IsArray() HB_IsBlock() HB_IsByRef HB_IsDate() HB_IsHash() HB_IsLogical() HB_IsMemo() HB_IsNIL() HB_IsNull() HB_IsNumeric() HB_IsObject() HB_IsPointer() HB_IsString() If() | IIf()

Checks if the passed argument is empty. Tests if the value returned by an expression is an array. Tests if the value returned by an expression is a Code block. Tests if a parameter is passed by reference. Tests if the value returned by an expression is a Date. Tests if the value returned by an expression is a Hash. Tests if the value returned by an expression is a logical value. Tests if the value returned by an expression is a Memo value. Tests if the value returned by an expression is NIL. Tests if the value returned by an expression is empty. Tests if the value returned by an expression is a numeric value. Tests if the value returned by an expression is an object. Tests if the value returned by an expression is a pointer. Tests if the value returned by an expression is a character string. Returns the result of an expression based on a logical expression

Logical operators .AND. .NOT. .OR.

Logical AND operator (binary). Logical NOT operator (unary). Logical OR operator (binary).

Low level file functions FClose() FCreate() FErase() FError() FileStats() FOpen() FRead() FReadStr() FRename() FSeek() FWrite() HB_FReadLine() 1384

Closes a binary file. Creates an empty binary file. Deletes a file from disk. Retrieves the error code of the last lo w-level file operation. Retrieves file information for a single file. Opens a file on the operating system level. Reads characters from a binary file into a memory variable. Reads characters up to Chr(0) from a binary file. Renames a file. Changes the position of the file pointer. Writes data to an open binary file. Extracts the next line from a text file. xHarbour Language Reference Guide

Low level file functions HB_FSize() HB_FTempCreate()

Returns the size of a file in bytes. Creates and opens a temporary file.

Mathematical functions Exp() Log() Sqrt()

Calculates the value of e raised by an exponent. Calculates the natural logarithm of a numeric value. Calculates the square root of a positive number

Mathematical operators % * ** + ++ -/ = (compound assignment)

Modulus operator (binary): calculates the remainder of a division. Multiplication operator (binary): multiplys numeric values. Exponentiation (binary): raises a number to the power of an exponent. Plus operator: add values, concatenate values and unary positive. Increment operator (unary): prefix / postfix increment. Minus operator: add values, concatenate values and unary negative. Decrement operator (unary): Prefix / postfix decrement Division operator (binary): divides numeric values. Compound assignment (binary): inline operation with assignment.

Memo functions HardCR() MemoEdit() MemoLine() MemoRead() MemoTran() MemoWrit() MLCount() MLCToPos() MlPos() MPosToLC()

Replaces soft carriage returns with hard CRs in a character string. Displays and/or edits character strings and memo fields in text mode. Extracts a line of text from a formatted character string or memo field. Reads an entire file from disk into memory. Replaces "carriage return/line feed" pairs in a character string. Writes a character string or a memo field to a file. Counts the number of lines in a character string or memo field Determines the position of a single character in a formatted text string or memo field. Determines the starting position of a line in a formatted character string or memo field. Calculates row and column position of a character in a formatted string or memo field.

Memory commands CLEAR ALL CLEAR MEMORY DEFAULT TO QUIT RELEASE RESTORE SAVE STORE

Closes files in all work areas and releases all dynamic memory variables. Releases all dynamic memory variables. Assigns a default value to a NIL argument. Terminates program execution unconditionally. Deletes or resets dynamic memory variables. Loads dynamic memory variables from disk into memory. Saves dynamic memory variables to a memory file. Assigns a value to one ore more variables.

Mouse functions Inkey() LastKey() MCol() xHarbour Language Reference Guide

Retrieves a character from the keyboard buffer or a mouse event. Returns the last Inkey() code retrieved. Determines the screen column position of the mouse cursor. 1385

Mouse functions MDblClk() MHide() MLeftDown() MPresent() MRestState() MRightDown() MRow() MSaveState() MSetBounds() MSetCursor() MSetPos() MShow() NextKey() NumButtons() SetMouse() TBMouse()

Determines the double-click interval for the mouse. Hides the mouse cursor. Determines the status of the left mouse button. Determines if a mouse is available. Restores a previously saved state of the mouse. Determines the status of the left mouse button. Determines the screen row position of the mouse cursor. Saves the current state of the mouse. Sets restricting boundaries for the mouse cursor. Determines the visibility of the mouse cursor. Moves the mouse cursor to a new position on screen. Displays the mouse cursor. Returns the next pending key or mouse event. Returns the number of mouse buttons. Determines the visibility of the mouse cursor. Moves the browse cursor to the mouse pointer.

Multi-threading functions GetCurrentThread() GetSystemThreadID() GetThreadID() HB_MultiThread() HB_MutexCreate() HB_MutexLock() HB_MutexTimeoutLock() HB_MutexTryLock() HB_MutexUnlock() IsSameThread() IsValidThread() JoinThread() KillAllThreads() KillThread() Notify() NotifyAll() SecondsSleep() StartThread() StopThread() Subscribe() SubscribeNow() ThreadSleep() WaitForThreads()

Retrieves the handle of the current thread. Retrieves the numeric system Thread ID of a thread. Retrieves the numeric application Thread ID of a thread. Checks if an application is created for multi-threading. Creates a Mutex. Obtains a permanent lock on a Mutex. Tries to obtain a lock on a Mutex with timeout. Tries to obtain a permanent lock on a Mutex. Unlocks a Mutex. Compares two thread handles. Checks if an expression is the thread handle of a running thread. Suspends the current thread until a second thread has terminated. Kills all running threads except for the main thread. Kills a running thread. Resumes a single thread blocked by a particular Mutex. Resumes all threads blocked by a particular Mutex. Suspends thread execution for a number of seconds. Starts a new thread. Stops a thread from outside. Subscribes for notifications on a Mutex. Subscribes for notifications on a Mutex and discards pending notifications. Puts a thread to sleep. Suspends the current thread until all other threads have terminated.

Mutex functions HB_MutexCreate() HB_MutexLock() HB_MutexTimeoutLock() HB_MutexTryLock() HB_MutexUnlock() Notify() NotifyAll() Subscribe() SubscribeNow()

1386

Creates a Mutex. Obtains a permanent lock on a Mutex. Tries to obtain a lock on a Mutex with timeout. Tries to obtain a permanent lock on a Mutex. Unlocks a Mutex. Resumes a single thread blocked by a particular Mutex. Resumes all threads blocked by a particular Mutex. Subscribes for notifications on a Mutex. Subscribes for notifications on a Mutex and discards pending notifications.

xHarbour Language Reference Guide

Network functions

Network functions DbRLock() DbRLockList() DbRUnlock() DbUnlock() DbUnlockAll() FLock() NetErr() NetName() RLock()

Locks a record for write access. Returns a list of locked records. Unlocks a record based on its indentifier. Releases file and all record locks in a work area. Unlocks all records and releases all file locks in all work areas. Applies a file lock to an open, shared database. Determines if a database command has failed in network operation. Retrieves the current user name or the computer name. Locks the current record for concurrent write access in a work area.

Numeric functions Abs() Chr() Exp() HB_Random() HB_RandomInt() HB_RandomSeed() HexToNum() Int() LenNum() Log() Max() Min() NumToHex() Round() Sqrt()

Returns the absolute value of a numeric expression. Converts a numeric ASCII code to a character. Calculates the value of e raised by an exponent. Generates a random number between two boundaries. Generates a random integer number between two boundaries. Sets the seed for generating random numbers. Converts a Hex string to a numeric value. Converts a numeric value to an integer. Returns the number of characters a numeric value needs for display. Calculates the natural logarithm of a numeric value. Returns the larger value of two Numerics or Dates. Returns the smallerr value of two Numerics or Dates. Converts a numeric value or a pointer to a Hex string. Rounds a numeric value to a specified number of digits Calculates the square root of a positive number

Object functions DbSkipper() Error() ErrorNew() Get() GetNew() HBObject() HBPersistent() HB_ArrayId() HB_QSelf() HB_QWith() HB_ResetWith() HB_SetWith() HB_ThisArray() HB_WithObjectCounter() MenuItem() Popup() TBColumn() TBrowse() TBrowseDB() TBrowseNew() TopBarMenu() TXmlDocument() TXmlIterator() xHarbour Language Reference Guide

Helper function for browse objects to skip a database Creates a new Error object. Creates a new Error object and optionally fills it with data. Creates a new Get object. Creates a new Get object. Abstract base class for user-defined classes. Abstract base class for user-defined persistent object. Returns a unique identifier for an array or an object variable. Retrieves the !Iself!EI object during method execution. Retrieves the !Iwith!EI object during WITH OBJECT execution. Replaces the !Iwith!EI object during WITH OBJECT execution. Changes the !Iwith!EI object during WITH OBJECT execution. Retrieves an array or object from its pointer. Determines the nesting level of WITH OBJECT statements. Creates a new MenuItem object. Creates a new Popup menu object. Creates a new TBColumn object. Creates a new TBrowse object. Creates a new TBrowse object to be used with a database. Creates a new TBrowse object. Creates a new TopBarMenu object. Creates a new TXmlDocument object. Creates a new TXmlIterator object. 1387

Object functions TXmlIteratorRegEx() TXmlIteratorScan() TXmlNode()

Creates a new TXmlIteratorRegEx object. Creates a new TXmlIteratorScan object. Creates a new TXmlNode object.

Operators $ % & (bitwise AND) & (macro operator) () * ** + ++ --> .AND. .NOT. .OR. / : < = >> @ @() HAS IN LIKE [ ] (array) [ ] (string) ^^ {} {=>} {|| } | (bitwise OR)

Substring operator (binary): search substring in string. Modulus operator (binary): calculates the remainder of a division. Bitwise AND operator (binary): performs a logical AND operation. Macro operator (unary): compiles a character string at runtime. Execution or grouping operator. Multiplication operator (binary): multiplys numeric values. Exponentiation (binary): raises a number to the power of an exponent. Plus operator: add values, concatenate values and unary positive. Increment operator (unary): prefix / postfix increment. Minus operator: add values, concatenate values and unary negative. Decrement operator (unary): Prefix / postfix decrement Alias operator (binary): identifies a work area. Logical AND operator (binary). Logical NOT operator (unary). Logical OR operator (binary). Division operator (binary): divides numeric values. Send operator (unary): sends a message to an object. Less than operator (binary): compares the size of two values. Left-shift operator (binary): shifts bits to the left. Less than or equal operator (binary): compares the size of two values. Not equal operator (binary): compares two values for inequality. Extended literal code block. Simple assignment operator (binary): assigns a value to a variable. Equal operator (binary): compares two values for equality. Compound assignment (binary): inline operation with assignment. Exact equal operator (binary): compares two values for identity. Greater than operator (binary): compares the size of two values. Greater than or equal operator (binary): compares the size of two values. Right-shift operator (binary): shifts bits to the right. Pass-by-reference operator (unary): passes variables by reference. Function-reference operator (unary): obtains a function pointer. Searches a character string for a matching regular expression. Searches a value in another value. Compares a character string with a regular expression. Array element operator (unary): retrieves array elements. Character operator (unary): retrieves a character from a string. Bitwise XOR operator (binary): performs a logical XOR operation. Literal array. Literal hash. Literal code block. Bitwise OR operator (binary): performs a logical OR operation.

Output commands @...BOX @...CLEAR @...SAY @...TO CLEAR SCREEN SET COLOR SET CURSOR 1388

Displays a box on the screen. Clears the contents of the screen. Displays data at a particular row and column position. Displays a single or double lined frame on the screen. Clears the screen in text mode. Defines default colors for text-mode applications. Toggles the display of the screen cursor in text-mode applications xHarbour Language Reference Guide

Output commands SET DECIMALS SET DELIMITERS SET DEVICE SET INTENSITY SET MARGIN SET MESSAGE SET SCOREBOARD SET VIDEOMODE SET WRAP

Defines the number of decimal places for displaying numeric values on the screen. Defines delimiting characters for GET entry fields and their visibility. Selects the ouput device for @...SAY commands. Toggles usage of enhanced colors for GET and PROMPT Defines the left margin for text-mode print output. Defines the screen row for @...PROMPT messages. Toggles the display of messages from READ and MemoEdit(). Changes the current video mode of the application. Toggles wrapping of the highligh bar in text-mode menus.

Output functions DevOut() DevOutPict() DevPos() DispOut() DispOutAt() DispOutAtSetPos() OutErr() OutStd() QOut() | QQOut()

Outputs a value to the current device. Outputs a PICTURE formatted value to the current device. Moves the cursor or printhead to a row and column coordinate Displays a value on the screen Displays a value on the screen at a certain position. Toggles update of the screen cursor with DispOutAt(). Writes values to the standard error device. Writes values to the standard output device. Displays values of expressions to the console window.

Pointer functions HB_Exec() HB_ExecFromArray() Valtype()

Executes a function, procedure or method from its pointer. Executes a function, procedure or method indirectly. Determines the data type of the value returned by an expression.

Preprocessor directives #command | #translate #define #error #if #ifdef #ifndef #include #pragma #stdout #uncommand | #untranslate #undef #xcommand | #xtranslate #xuncommand | #xuntranslate

User defined command or translation rule for the preprocessor. Defines a symbolic constant or pseudo-function. Raises an explicit compiler error along with a message. Compile a section of code based on a condition. Compiles a section of code depending on the presence of a #define constant. Compiles a section of code depending on the absence of a #define constant. Inserts the contents of a file into the current source code file. Controls compiler switches at compile time. Sends a compiler message to StdOut. Voids a previously defined #command or #translate directive. Voids a #define constant or pseudo-function. User defined command or translation rule for the preprocessor. Voids a previously defined #xcommand or #xtranslate directive.

Printer commands EJECT SET PRINTER

xHarbour Language Reference Guide

Ejects the current page from the printer. Enables or disables output to the printer or redirects printer output.

1389

Printer functions

Printer functions GetDefaultPrinter() GetPrinters() IsPrinter() PrinterExists() PrinterPortToName() PrintFileRaw()

Retrieves the name of a computer's default printer. Retrieves information about available printers. Determines if print output can be processed. Checks if a particular printer is installed. Retrieves the name of the printer connected to a printer port. Prints a file to a Windows printer in RAW mode.

Random generator HB_Random() HB_RandomInt() HB_RandomSeed()

Generates a random number between two boundaries. Generates a random integer number between two boundaries. Sets the seed for generating random numbers.

Registry functions GetRegistry() QueryRegistry() SetRegistry()

Retrieves the value of a registry entry Checks if a particular registry key with specified value exists. Creates a key/value pair in the registry.

Regular expressions HAS HB_AtX() HB_IsRegExString() HB_RegEx() HB_RegExAll() HB_RegExComp() HB_RegExMatch() HB_RegExSplit() LIKE

Searches a character string for a matching regular expression. Locates a substring within a character string based on a regular expression. Checks if a character string is a compiled regular expression. Searches a string using a regular expression Parses a string and fills an array with parsing information. Compiles a regular expression into a binary search pattern. Tests if a string contains a substring using a regular expression Parses a string using a regular expression and fills an array. Compares a character string with a regular expression.

Screen functions Col() ColorSelect() DispBegin() DispBox() DispCount() DispEnd() DispOut() DispOutAt() DispOutAtSetPos() MaxCol() MaxRow() RestScreen() Row() SaveScreen() Scroll() SetBlink() SetColor() 1390

Returns the current column position of the screen cursor Selects a color from the current SetColor() string. Initiates buffering of console window output. Displays a box on the screen. Retrieves the number of pending DispEnd() calls. Displays buffered screen output. Displays a value on the screen Displays a value on the screen at a certain position. Toggles update of the screen cursor with DispOutAt(). Determines the rightmost column position of the screen buffer. Determines the bottom row position of the screen buffer. Displays a SaveScreen() string. Returns the current row position of the screen cursor. Saves a rectangular screen region for later display. Scrolls a screen region horizontally and/or vertically. Determines how to treat the asterisk in a SetColor() string. Retrieves and/or changes the current color setting for text mode. xHarbour Language Reference Guide

Screen functions SetCursor() SetMode() SetPos()

Queries or changes the shape of the cursor on the screen. Changes the size of a console window. Changes the position of the screen cursor in text mode.

SET commands SET AUTOPEN SET AUTORDER SET AUTOSHARE SET BACKGROUND TASKS SET BACKGROUNDTICK SET BELL SET CENTURY SET COLOR SET CONFIRM SET CURSOR SET DATE SET DBFLOCKSCHEME SET DECIMALS SET DEFAULT SET DELETED SET DELIMITERS SET DESCENDING SET DIRCASE SET DIRSEPARATOR SET EOL SET EPOCH SET ERRORLOG SET ERRORLOOP SET ESCAPE SET EVENTMASK SET EXACT SET EXCLUSIVE SET FILECASE SET FILTER SET FIXED SET FUNCTION SET INTENSITY SET KEY SET MARGIN SET MEMOBLOCK SET MESSAGE SET OPTIMIZE SET PATH SET PRINTER SET SCOREBOARD SET SOFTSEEK SET STRICTREAD SET TRACE SET TYPEAHEAD SET UNIQUE SET VIDEOMODE SET WRAP

xHarbour Language Reference Guide

Toggles automatic opening of a structural index file. Defines the default controlling index for automatically opened index files. Defines network detection for shared file access. Enables or disables the activity of background tasks. Defines the processing interval for background tasks. Toggles automatic sounding of the bell in the GET system. Sets the date format to include two or four digits. Defines default colors for text-mode applications. Determines how a GET entry field is exited. Toggles the display of the screen cursor in text-mode applications Specifies the date format for input and display. Selects the locking scheme for shared database access. Defines the number of decimal places for displaying numeric values on the screen. Sets the default drive and directory. Specifies visibility of records marked for deletion. Defines delimiting characters for GET entry fields and their visibility. Changes the descending flag of the controlling index at runtime. Specifies how directories are accessed on disk. Specifies the default separator for directories. Defines the end-of-line character(s) for ASCII text files. Determines the interpretation of date values without century digits. Defines the default error log file. Defines the maximum recursion depth for error handling. Sets the ESC key as a READ exit key. Sets which events should be returned by the Inkey() function. Determines the mode for character string comparison. Sets the global EXCLUSIVE open mode for databases. Specifies how files are accessed on disk. Defines a condition for filtering records in the current work area. Toggles fixed formatting for displaying numbers in text-mode. Associates a character string with a function key. Toggles usage of enhanced colors for GET and PROMPT Associates a key with a procedure. Defines the left margin for text-mode print output. Defines the default block size for memo files. Defines the screen row for @...PROMPT messages. Toggles filter optimization with indexed databases. Set the search path for opening files. Enables or disables output to the printer or redirects printer output. Toggles the display of messages from READ and MemoEdit(). Enables or disables relative seeking. Toggles read optimization for database access. Toggles output of function TraceLog(). Dimensions the size of the keyboard buffer. Includes or excludes non-unique keys to/from an index. Changes the current video mode of the application. Toggles wrapping of the highligh bar in text-mode menus.

1391

Special operators

Special operators & (macro operator) () -> : @ @() [ ] (array) [ ] (string) {} {=>} {|| }

Macro operator (unary): compiles a character string at runtime. Execution or grouping operator. Alias operator (binary): identifies a work area. Send operator (unary): sends a message to an object. Extended literal code block. Pass-by-reference operator (unary): passes variables by reference. Function-reference operator (unary): obtains a function pointer. Array element operator (unary): retrieves array elements. Character operator (unary): retrieves a character from a string. Literal array. Literal hash. Literal code block.

Statements ANNOUNCE BEGIN SEQUENCE DO DO CASE DO WHILE EXIT PROCEDURE EXTERNAL FIELD FOR FOR EACH FUNCTION GLOBAL IF INIT PROCEDURE LOCAL MEMVAR PARAMETERS PRIVATE PROCEDURE PUBLIC RETURN RUN STATIC SWITCH TRY...CATCH WITH OBJECT

Declaration of a module identifier name. Declares a control structure for error handling. Executes a function or procedure. Executes a block of statements based on one or more conditions. Executes a block of statements while a condition is true. Declares a procedure to execeute when a program terminates. Declares the symbolic name of an external function or procedure for the linker. Declares a field variable Executes a block of statements a specific number of times. Iterates elements of data types that can be seen as a collection. Declares a function along with its formal parameters. Declares and optionally initializes a GLOBAL memory variable. Executes a block of statements based on one or more conditions. Declares a procedure to execeute when a program starts. Declares and optionally initializes a local memory variable. Declares PRIVATE or PUBLIC variables. Declares PRIVATE function parameters. Creates and optionally initializes a PRIVATE memory variable. Declares a procedure along with its formal parameters. Creates and optionally initializes a PUBLIC memory variable. Branches program control to the calling routine. Executes an operating system command. Declares and optionally initializes a STATIC memory variable. Executes one or more blocks of statements. Declares a control structure for error handling. Identifies an object to receive multiple messages.

UI functions AChoice() Alert() Browse() DbEdit() GetNew() MemoEdit() MenuModal() ReadModal() 1392

Displays a list of items to select one from. Displays a text-mode dialog box with a message. Browse a database file Browse records in a table. Creates a new Get object. Displays and/or edits character strings and memo fields in text mode. Activates the menu system represented by a TopBarMenu object. Activates editing of @...GET entry fields in text mode. xHarbour Language Reference Guide

xHarbour extensions

xHarbour extensions #if #pragma #uncommand | #untranslate #xuncommand | #xuntranslate & (bitwise AND) (struct) > @() ACCESS ALenAlloc() ASizeAlloc() ASSIGN ASSOCIATE CLASS C Structure class CLASS CLASSDATA CLASSMETHOD CStr() DATA DbCopyExtStruct() DbCopyStruct() DbSkipper() DefPath() DELEGATE DESTRUCTOR DirectoryRecurse() DiskChange() DispOutAt() DispOutAtSetPos() DllCall() DllExecuteCall() DllLoad() DllPrepareCall() DllUnload() ENABLE TYPE CLASS ERROR HANDLER EXPORTED:

Compile a section of code based on a condition. Controls compiler switches at compile time. Voids a previously defined #command or #translate directive. Voids a previously defined #xcommand or #xtranslate directive. Bitwise AND operator (binary): performs a logical AND operation. Creates a new structure object Left-shift operator (binary): shifts bits to the left. Extended literal code block. Right-shift operator (binary): shifts bits to the right. Function-reference operator (unary): obtains a function pointer. Declares an ACCESS method of a class. Determines for how much array elements memory is pre-allocated. Pre-allocates memory for an array. Declares an ASSIGN method of a class. Defines a scalar class for a native data type. Abstract class for C structure support. Declares the class function of a user-defined class. Declares a class variable of a class. Declares the symbolic name of a class method. Converts a value to a character string. Declares an instance variable of a class. Creates a structure extended database file. Creates a new database based on the current database structure. Helper function for browse objects to skip a database Returns the SET DEFAULT directory. Declares a message to be directed to a contained object. Declares a method to be called by the garbage collector. Loads file information recursively into a two-dimensional array. Changes the current disk drive. Displays a value on the screen at a certain position. Toggles update of the screen cursor with DispOutAt(). Executes a function located in a dynamically loaded external library. Executes a DLL function via call template. Loads a DLL file into memory. Creates a call template for an external DLL function. Releases a dynamically loaded external DLL from memory. Activates scalar classes for native data tyes. Declares the method for error handling within a class. Declares the EXPORTED attribute for a group of member variables and/or methods. EXTEND CLASS...WITH DATA Adds a new member variable to an existing class. EXTEND CLASS...WITH METHOD Adds a new method to an existing class. FCharCount() Counts the number of characters in a text file ignoring white space characters. FieldDec() Retrieves the number of decimal places of a field variable. FieldLen() Retrieves the number of bytes occupied by a field variable. FieldType() Retrieves the data type of a field variable. FileStats() Retrieves file information for a single file. FLineCount() Counts the lines in an ASCII text file. FOR EACH Iterates elements of data types that can be seen as a collection. FParse() Parses a delimited text file and loads it into an array. FParseEx() Parses a delimited text file and loads it into an array (optimized). FParseLine() Parses one line of a delimited text and loads it into an array. FreeLibrary() Releases a dynamically loaded external DLL from memory. FWordCount() Counts the words in a text file. xHarbour Language Reference Guide

1393

xHarbour extensions GetCurrentThread() GetDefaultPrinter() GetLastError() GetPrinters() GetProcAddress() GetRegistry() GetSystemThreadID() GetThreadID() GLOBAL HaaDelAt() HaaGetKeyAt() HaaGetPos() HaaGetRealPos() HaaGetValueAt() HaaSetValueAt() HAllocate() HAS Hash() HBObject() HBPersistent() HB_AExpressions() HB_AnsiToOem() HB_AParams() HB_ArgC() HB_ArgCheck() HB_ArgString() HB_ArgV() HB_ArrayId() HB_ArrayToStructure() HB_AtX() HB_BackGroundActive() HB_BackGroundAdd() HB_BackGroundDel() HB_BackGroundReset() HB_BackGroundRun() HB_BackGroundTime() HB_BitAnd() HB_BitIsSet() HB_BitNot() HB_BitOr() HB_BitReset() HB_BitSet() HB_BitShift() HB_BitXOr() HB_BuildDate() HB_BuildInfo() HB_CheckSum() HB_CmdArgArgV() HB_Compiler() Hb_CRC32() HB_Crypt() HB_Decrypt() HB_DeSerialize() HB_EnumIndex() HB_Exec() HB_ExecFromArray() HB_FNameMerge() 1394

Retrieves the handle of the current thread. Retrieves the name of a computer's default printer. Retrieves the error code of the last dynamically called DLL function. Retrieves information about available printers. Retrieves the memory address of a function in a dynamically loaded DLL. Retrieves the value of a registry entry Retrieves the numeric system Thread ID of a thread. Retrieves the numeric application Thread ID of a thread. Declares and optionally initializes a GLOBAL memory variable. Removes a key/value pair from an associative array. Retrieves the key from an associative array by its ordinal position. Retrieves the ordinal position of a key in an associative array. Retrieves the sort order of a key in an associative array. Retrieves the value from an associative array by its ordinal position. Changes the value in an associative array by its ordinal position. Pre-allocates memory for a large hash. Searches a character string for a matching regular expression. Creates a new hash. Abstract base class for user-defined classes. Abstract base class for user-defined persistent object. Parses a character string into an array of macro expressions. Converts a character string from the ANSI to the OEM character set. Collects values of all parameters passed to a function, method or procedure. Returns the number of command line arguments. Checks if an internal switch is set on the command line. Retrieves the vale of an internal switch set on the command line. Retrieves the value of a command line argument. Returns a unique identifier for an array or an object variable. Converts an array to a binary C structure. Locates a substring within a character string based on a regular expression. Queries and/or changes the activity of a single background task. Adds a new background task. Removes a background task from the internal task list. Resets the internal counter of background tasks. Enforces execution of one or all background tasks. Queries or changes the wait interval in milliseconds after which the task is executed. Performs a bitwise AND operation with numeric integer values. Checks if a bit is set in a numeric integer value. Performs a bitwise OR operation with a numeric integer value. Performs a bitwise OR operation with numeric integer values. Sets a bit in a numeric integer value to 0. Sets a bit in a numeric integer value to 1. Shifts bits in a numeric integer value. Performs a bitwise XOR operation with numeric integer values. Retrieves the formatted build date of the xHarbour compiler Retrieves build information of the xHarbour compiler. Calculates the checksum for a stream of data using the Adler32 algorithm. Returns the first command line argument (EXE file name). Retrieves the version of the C compiler shipped with xHarbour. Calculates the checksum for a stream of data using the CRC 32 algorithm. Encrypts a character string. Decrypts an encrypted character string. Converts a binary string back to its original data type. Returns the current ordinal position of a FOR EACH iteration. Executes a function, procedure or method from its pointer. Executes a function, procedure or method indirectly. Composes a file name from individual components. xHarbour Language Reference Guide

xHarbour extensions HB_FNameSplit() HB_FReadLine() HB_FSize() HB_FTempCreate() HB_FuncPtr() HB_GCAll() HB_GCStep() HB_IdleAdd() HB_IdleDel() HB_IdleReset() HB_IdleSleep() HB_IdleSleepMSec() HB_IdleState() HB_IsArray() HB_IsBlock() HB_IsByRef HB_IsDate() HB_IsHash() HB_IsLogical() HB_IsMemo() HB_IsNIL() HB_IsNull() HB_IsNumeric() HB_IsObject() HB_IsPointer() HB_IsRegExString() HB_IsString() HB_LangSelect() HB_LibDo() HB_MacroCompile() HB_MD5() HB_MD5File() HB_MultiThread() HB_MutexCreate() HB_MutexLock() HB_MutexTimeoutLock() HB_MutexTryLock() HB_MutexUnlock() HB_ObjMsgPtr() HB_OemToAnsi() HB_OsNewLine() HB_QSelf() HB_QWith() HB_Random() HB_RandomInt() HB_RandomSeed() HB_ReadIni() HB_RegEx() HB_RegExAll() HB_RegExComp() HB_RegExMatch() HB_RegExSplit() HB_ResetWith() HB_RestoreBlock() HB_SaveBlock() HB_Serialize() HB_SetCodePage() HB_SetIniComment() xHarbour Language Reference Guide

Splits a file name into individual components. Extracts the next line from a text file. Returns the size of a file in bytes. Creates and opens a temporary file. Obtains the pointer to a function or procedure. Scans the memory and releases all garbage memory blocks. Invokes the garbage collector for one collection cycle. Adds a background task for being executed during idle states. Removes a task from the list of idle tasks. Resets the internal counter of idle tasks. Halts idle task processing for a number of seconds. Queries or changes the default time interval for idle task processing. Signals an idle state. Tests if the value returned by an expression is an array. Tests if the value returned by an expression is a Code block. Tests if a parameter is passed by reference. Tests if the value returned by an expression is a Date. Tests if the value returned by an expression is a Hash. Tests if the value returned by an expression is a logical value. Tests if the value returned by an expression is a Memo value. Tests if the value returned by an expression is NIL. Tests if the value returned by an expression is empty. Tests if the value returned by an expression is a numeric value. Tests if the value returned by an expression is an object. Tests if the value returned by an expression is a pointer. Checks if a character string is a compiled regular expression. Tests if the value returned by an expression is a character string. Queries or changes the current national language . Executes a function located in a dynamically loaded xHarbour DLL. Compiles a macro string into a PCode sequence. Calculates a message digest for a stream of data using the MD5 algorithm. Calculates a message digest for a file using the MD5 algorithm. Checks if an application is created for multi-threading. Creates a Mutex. Obtains a permanent lock on a Mutex. Tries to obtain a lock on a Mutex with timeout. Tries to obtain a permanent lock on a Mutex. Unlocks a Mutex. Retrieves the pointer to a method. Converts a character string from the OEM to the ANSI character set. Returns the end-of-line character(s) to use with the current operating system. Retrieves the !Iself!EI object during method execution. Retrieves the !Iwith!EI object during WITH OBJECT execution. Generates a random number between two boundaries. Generates a random integer number between two boundaries. Sets the seed for generating random numbers. Reads an INI file from disk. Searches a string using a regular expression Parses a string and fills an array with parsing information. Compiles a regular expression into a binary search pattern. Tests if a string contains a substring using a regular expression Parses a string using a regular expression and fills an array. Replaces the !Iwith!EI object during WITH OBJECT execution. Converts binary information back to a code block. Utility function for code block serialization. Converts an arbitrary value to a binary string. Queries or changes the current code page. Defines the delimiting characters for comments and inline comments. 1395

xHarbour extensions HB_SetMacro() HB_SetWith() HB_SizeofCStructure() HB_StructureToArray() HB_ThisArray() HB_VMExecute() HB_VMMode() HB_WithObjectCounter() HB_WriteIni() HB_XmlErrorDesc() HClone() HCopy() HDel() HDelAt() HEval() HexToNum() HexToStr() HFill() HGet() HGetAACompatibility() HGetAutoAdd() HGetCaseMatch() HGetKeyAt() HGetKeys() HGetPairAt() HGetPartition() HGetPos() HGetVaaPos() HGetValueAt() HGetValues() HHasKey() HIDDEN: HMerge() HScan() HSet() HSetAACompatibility() HSetAutoAdd() HSetCaseMatch() HSetPartition() HSetValueAt() IN INLINE METHOD IsAlNum() IsAscii() IsCntrl() IsDirectory() IsDisk() IsGraph() IsPrint() IsPunct() IsSameThread() IsSpace() IsValidThread() IsXDigit() JoinThread() KillAllThreads() 1396

Enables or disables r untime behavior of the macro compiler. Changes the !Iwith!EI object during WITH OBJECT execution. Calculates the amount of memory required to store a C structure. Converts values contained in a binary C structure string to an array. Retrieves an array or object from its pointer. Executes a PCode string. Indicates the creation mode of the xHarbour virtual machine. Determines the nesting level of WITH OBJECT statements. Creates an INI file and writes hash data to it. Retrieves a textual error description for XML file parsing errors. Creates an entire copy of a hash. Copies key/value pairs from a hash into another hash. Removes a key/value pair from the hash by its key. Removes a key/value pair from the hash by its key. Evaluates a code block with each hash element. Converts a Hex string to a numeric value. Converts a Hex encoded character string to an ASCII string. Copies the same value into all key/value pairs. Retrieves the value associated with a specified key. Checks if a hash is compatible with an associative array. Retrieves the AutoAdd attribute of a hash. Retrieves the case sensitivity attribute of a hash. Retrieves the key from a hash by its ordinal position. Collects all keys from a hash in an array. Retrieves a key/value pair from a hash by its ordinal position. Checks if a hash is partitioned. Retrieves the ordinal position of a key in a hash. Retrieves the sort order of all keys in an associative array. Retrieves the value from a hash by its ordinal position. Collects all values from a hash in an array. Determines if a key is present in a hash. Declares the HIDDEN attribute for a group of member variables and/or methods. Merges the contents of an entire hash into another hash. Searches a value in a hash. Associates a value with a key in a hash. Enables or disables associative array compatibility for an empty hash. Changes the AutoAdd attribute of a hash. Changes the case sensitivity attribute of a hash. Partitions a linear hash for improved performance. Changes the value in a hash by its ordinal position. Searches a value in another value. Declares and implements an inline method that spans across multiple lines. Checks if the first character of a string is alpha-numeric. Checks if the first character of a string is a 7-bit ASCII character. Checks if the first character of a string is a control character. Checks if a character string contains the name of an existing directory. Verify if a drive is ready Checks if the first character of a string is a 7-bit graphical ASCII character. Checks if the first character of a string is a printable 7-bit ASCII character. Checks if the first character of a string is a punctuation character. Compares two thread handles. Checks if the first character of a string is a white-space character. Checks if an expression is the thread handle of a running thread. Checks if the first character of a string is a hexadecimal digit. Suspends the current thread until a second thread has terminated. Kills all running threads except for the main thread. xHarbour Language Reference Guide

xHarbour extensions KillThread() LenNum() LibFree() LibLoad() LIKE LoadLibrary() Memory() MESSAGE METHOD (declaration) METHOD (implementation) METHOD...OPERATOR METHOD...VIRTUAL Notify() NotifyAll() NumToHex() OPERATOR OrdCount() OrdCustom() OrdFindRec() OrdKeyRelPos() OrdSkipRaw() OrdWildSeek() Os_IsWin2000() Os_IsWin2000_Or_Later() Os_IsWin2003() Os_IsWin95() Os_IsWin98() Os_IsWin9X() Os_IsWinME() Os_IsWinNT() Os_IsWinNT351() Os_IsWinNT4() Os_IsWinVista() Os_IsWinXP() Os_IsWtsClient() Os_VersionInfo() OVERRIDE METHOD pragma pack() PrinterExists() PrinterPortToName() PrintFileRaw() ProcFile() PROTECTED: PValue() QueryRegistry() RAscan() RddInfo() SecondsSleep() SET AUTOPEN SET AUTORDER SET AUTOSHARE SET BACKGROUND TASKS SET BACKGROUNDTICK SET DBFLOCKSCHEME SET DIRCASE SET DIRSEPARATOR SET EOL xHarbour Language Reference Guide

Kills a running thread. Returns the number of characters a numeric value needs for display. Releases a dynamically loaded xHarbour DLL from memory. Loads an xHarbour DLL file into memory. Compares a character string with a regular expression. Loads an external DLL file into memory. Returns memory statistics. Declares a message name for a method. Declares the symbolic name of a method. Declares the implementation code of a method. Declares a method to be executed with an operator. Declares a method as virtual. Resumes a single thread blocked by a particular Mutex. Resumes all threads blocked by a particular Mutex. Converts a numeric value or a pointer to a Hex string. Overloads an operator and declares a method to be invoked for it. Determines the number of indexes open in a work area. Determines if an index is a custom index. Searches a record number in the controlling index. Returns or sets the relative position of the current record. Moves the record pointer via the controlling index. Searches a value in the controlling index using wild card characters. Checks if the application is running on Windows 2000. Checks if the application is running on Windows version 2000 or later Checks if the application is running on Windows 2003. Checks if the application is running on Windows 95. Checks if the application is running on Windows 98. Checks if the application is running on a Windows 9x platform. Checks if the application is running on Windows ME. Checks if the application is running on a Windows NT platform. Checks if the application is running on Windows NT 3.51. Checks if the application is running on Windows NT 4.0. Checks if the application is running on Windows Vista. Checks if the application is running on Windows XP. Checks if the application is running on a Windows Terminal Server client. Retrieves specific version information about the operating system. Replaces a method in an existing class. Defines the byte alignment for the next structure declaration. Checks if a particular printer is installed. Retrieves the name of the printer connected to a printer port. Prints a file to a Windows printer in RAW mode. Determines the current PRG source code file. Declares the PROTECTED attribute for a group of member variables and methods. Retrieves the value of a parameter passed to a function, method or procedure. Checks if a particular registry key with specified value exists. Searches a value in an array beginning with the last element. Queries and/or changes configuration data of RDDs. Suspends thread execution for a number of seconds. Toggles automatic opening of a structural index file. Defines the default controlling index for automatically opened index files. Defines network detection for shared file access. Enables or disables the activity of background tasks. Defines the processing interval for background tasks. Selects the locking scheme for shared database access. Specifies how directories are accessed on disk. Specifies the default separator for directories. Defines the end-of-line character(s) for ASCII text files. 1397

xHarbour extensions SET ERRORLOG SET ERRORLOOP SET FILECASE SET STRICTREAD SET TRACE SetErrorMode() SetLastError() SetRegistry() StartThread() StopThread() StrToHex() Subscribe() SubscribeNow() SWITCH TBMouse() ThreadSleep() Throw() TraceLog() TRY...CATCH TXmlDocument() TXmlIterator() TXmlIteratorRegEx() TXmlIteratorScan() TXmlNode() typedef struct ValToPrg() ValToPrgExp() WaitForThreads() WildMatch() WITH OBJECT [ ] (string) ^^ {=>} | (bitwise OR)

1398

Defines the default error log file. Defines the maximum recursion depth for error handling. Specifies how files are accessed on disk. Toggles read optimization for database access. Toggles output of function TraceLog(). Queries or changes the behavior with operating system errors. Sets a numeric value as last error code. Creates a key/value pair in the registry. Starts a new thread. Stops a thread from outside. Converts a character string to a Hex string. Subscribes for notifications on a Mutex. Subscribes for notifications on a Mutex and discards pending notifications. Executes one or more blocks of statements. Moves the browse cursor to the mouse pointer. Puts a thread to sleep. Throws an exception. Traces and logs the contents of one or more variables. Declares a control structure for error handling. Creates a new TXmlDocument object. Creates a new TXmlIterator object. Creates a new TXmlIteratorRegEx object. Creates a new TXmlIteratorScan object. Creates a new TXmlNode object. Declares a new structure in C syntax. Converts a value to PRG code. Converts a value to charecter string holding a macro-expression. Suspends the current thread until all other threads have terminated. Tests if a string begins with a search pattern. Identifies an object to receive multiple messages. Character operator (unary): retrieves a character from a string. Bitwise XOR operator (binary): performs a logical XOR operation. Literal hash. Bitwise OR operator (binary): performs a logical OR operation.

xHarbour Language Reference Guide

Index

Index - (operator)................................................................. 26 -- (operator) ............................................................... 28 ! != (comparison) .......................................................... 43 # # (comparison) ........................................................... 43 #command ............................................................. 1331 #command | #translate ......................................... 1331 #define ................................................................... 1338 #error ..................................................................... 1341 #if1342 #ifdef ...................................................................... 1344 #ifndef .................................................................... 1346 #include.................................................................. 1347 #pragma ................................................................. 1349 #stdout ................................................................... 1351 #translate ............................................................... 1331 #uncommand | #untranslate ................................. 1352 #undef .................................................................... 1353 #xcommand | #xtranslate ...................................... 1354 #xuncommand | #xuntranslate.............................. 1355 $ $ (operator)................................................................ 10 % % (operator) ............................................................... 11 %= (operator) ............................................................. 50 & & (bitwise AND) .......................................................... 12 & (macro operator) .................................................... 14 & (operator) ......................................................... 12, 14 ( ( ) (operator)............................................................... 19 (struct)........................................................................ 81 * * (operator)................................................................ 21 ** (operator) .............................................................. 22 **= (operator) ............................................................ 50 *= (operator) .............................................................. 50 . ... (parameter list) .................................................... 133 .AND. .......................................................................... 31 xHarbour Language Reference Guide

.NOT. ...........................................................................32 .OR. .............................................................................33 / / (operator) .................................................................34 : : (operator)..................................................................35 := (assignment) ...........................................................37 :aAttributes TXmlNode().........................................................1319 :aCMembers C Structure class .................................................1206 :aCTypes C Structure class .................................................1206 :addBelow() TXmlNode().........................................................1322 :addColumn() TBrowse() ...........................................................1273 :addItem() Popup()...............................................................1253 TopBarMenu() ....................................................1290 :applyKey() TBrowse() ...........................................................1283 :args Error() .................................................................1212 :array() C Structure class .................................................1207 :assign() Get()....................................................................1228 :autoLite TBrowse() ...........................................................1266 :backspace() Get()....................................................................1233 :badDate Get()....................................................................1220 :block Get()....................................................................1220 TBColumn().........................................................1260 :border Popup()...............................................................1251 TBrowse() ...........................................................1266 :bottom Popup()...............................................................1251 :buffer Get()....................................................................1221 :buffer() C Structure class .................................................1207 :canDefault Error() .................................................................1212 :canRetry 1399

Index Error() .................................................................1213 :canSubstitute Error() .................................................................1213 :capCol Get() ...................................................................1221 :capRow Get() ...................................................................1221 :caption Get() ...................................................................1221 MenuItem() ........................................................1247 :cargo Error() .................................................................1213 Get() ...................................................................1222 MenuItem() ........................................................1247 Popup()...............................................................1251 TBColumn()......................................................... 1261 TBrowse() ...........................................................1266 TopBarMenu() ....................................................1288 :cData TXmlNode() ........................................................1319 :changed Get() ...................................................................1222 :checked MenuItem() ........................................................1247 :className() HBObject() ..........................................................1239 :classSel() HBObject() ..........................................................1239 :clear Get() ...................................................................1222 :clone() TXmlIterator() ..................................................... 1309 TXmlNode() ........................................................1323 :cloneTree() TXmlNode() ........................................................1323 :close() Popup()...............................................................1256 :cName TXmlNode() ........................................................1319 :col Get() ...................................................................1222 :colCount TBrowse() ...........................................................1266 :colorBlock TBColumn()......................................................... 1261 :colorDisp() Get() ...................................................................1228 :colorRect() TBrowse() ...........................................................1275 :colorSpec Get() ...................................................................1223 Popup()...............................................................1251 TBrowse() ...........................................................1267 1400

TopBarMenu() .................................................... 1289 :colPos TBrowse() ...........................................................1267 :colSep TBColumn() ........................................................ 1261 TBrowse() ...........................................................1267 :colWidth() TBrowse() ...........................................................1273 :configure() TBrowse() ...........................................................1276 :control Get() ................................................................... 1223 :current Popup()...............................................................1252 TopBarMenu() .................................................... 1289 :data MenuItem() ........................................................ 1248 :decPos Get() ................................................................... 1223 :defColor TBColumn() ........................................................ 1261 :deHilite() TBrowse() ...........................................................1276 :delColumn() TBrowse() ...........................................................1273 :delEnd() Get() ................................................................... 1234 :delete() Get() ................................................................... 1234 :delItem() Popup()...............................................................1254 TopBarMenu() .................................................... 1291 :delLeft() Get() ................................................................... 1234 :delRight() Get() ................................................................... 1234 :delWordLeft() Get() ................................................................... 1235 :delWordRight() Get() ................................................................... 1235 :depth() TXmlNode() ........................................................ 1326 :description Error() ................................................................. 1213 :deValue() C Structure class ................................................. 1208 :display() Get() ................................................................... 1229 Popup()...............................................................1257 TopBarMenu() .................................................... 1294 :down() TBrowse() ...........................................................1279 :enabled xHarbour Language Reference Guide

Index MenuItem() ........................................................ 1248 :end() Get() ................................................................... 1232 TBrowse()........................................................... 1279 :error() HBObject() ......................................................... 1240 :exitState Get() ................................................................... 1224 :fileName Error() ................................................................ 1214 :find() TXmlIteratorRegEx()........................................... 1312 TXmlIteratorScan()............................................. 1315 :findFirst() TXmlDocument() ................................................ 1303 :findFirstRegEx() TXmlDocument() ................................................ 1304 :findNext() TXmlDocument() ................................................ 1305 :footing TBColumn() ........................................................ 1262 :footSep TBColumn() ........................................................ 1262 TBrowse()........................................................... 1267 :forceStable() TBrowse()........................................................... 1276 :freeze TBrowse()........................................................... 1268 :genCode Error() ................................................................ 1214 :getAccel() Popup() .............................................................. 1257 TopBarMenu().................................................... 1294 :getAttribute() TXmlNode() ........................................................ 1321 :getColumn() TBrowse()........................................................... 1274 :getFirst() Popup() .............................................................. 1254 TopBarMenu().................................................... 1291 :getItem() Popup() .............................................................. 1254 TopBarMenu().................................................... 1291 :getLast() Popup() .............................................................. 1255 TopBarMenu().................................................... 1292 :getNext() Popup() .............................................................. 1255 TopBarMenu().................................................... 1292 :getNode() TXmlIterator() .................................................... 1309 :getPointer() C Structure class ................................................ 1208 xHarbour Language Reference Guide

:getPrev() Popup()...............................................................1255 TopBarMenu() ....................................................1292 :getShortct() Popup()...............................................................1257 :goBottom() TBrowse() ...........................................................1279 :goBottomBlock TBrowse() ...........................................................1268 :goTop() TBrowse() ...........................................................1280 :goTopBlock TBrowse() ...........................................................1268 :hasFocus Get()....................................................................1224 :heading TBColumn().........................................................1262 :headSep TBColumn().........................................................1262 TBrowse() ...........................................................1268 :hilite() TBrowse() ...........................................................1277 :hitBottom TBrowse() ...........................................................1269 :hitTest() Get()....................................................................1229 Popup()...............................................................1258 TBrowse() ...........................................................1284 TopBarMenu() ....................................................1294 :hitTop TBrowse() ...........................................................1269 :home() Get()....................................................................1232 TBrowse() ...........................................................1280 :id MenuItem() ........................................................1248 :init() HBObject() ..........................................................1238 :initClass() HBObject() ..........................................................1238 :insColumn() TBrowse() ...........................................................1274 :insert() Get()....................................................................1235 :insertAfter() TXmlNode().........................................................1323 :insertBefore() TXmlNode().........................................................1323 :insertBelow() TXmlNode().........................................................1324 :insItem() Popup()...............................................................1255 TopBarMenu() ....................................................1293 1401

Index :invalidate() TBrowse() ...........................................................1277 :isDerivedFrom() HBObject() ..........................................................1239 :isKindOf() HBObject() ..........................................................1240 :isOpen() Popup()...............................................................1258 :isPopUp() MenuItem() ........................................................1249 :itemCount Popup()...............................................................1252 TopBarMenu() ....................................................1289 :killFocus() Get() ...................................................................1229 :left Popup()...............................................................1252 TopBarMenu() ....................................................1290 :left() Get() ...................................................................1232 TBrowse() ...........................................................1280 :leftVisible TBrowse() ...........................................................1269 :loadFromFile() HBPersistent() ....................................................1244 :loadFromText() HBPersistent() ....................................................1244 :mColPos TBrowse() ...........................................................1269 :message Get() ...................................................................1225 MenuItem() ........................................................1248 TBrowse() ...........................................................1270 :minus Get() ...................................................................1224 :modal() TopBarMenu() ....................................................1295 :moduleName Error() .................................................................1215 :mRowPos TBrowse() ...........................................................1270 :msgNotFound() HBObject() ..........................................................1241 :nAlign C Structure class ................................................. 1207 :name Get() ...................................................................1225 :nBeginLine TXmlNode() ........................................................1320 :nBottom TBrowse() ...........................................................1270 :nError TXmlDocument() ................................................1300 1402

:new() HBObject().......................................................... 1237 :next() TXmlIterator()..................................................... 1310 TXmlIteratorRegEx()........................................... 1313 TXmlIteratorScan() ............................................. 1316 :nextInTree() TXmlNode() ........................................................ 1324 :nLeft TBrowse() ...........................................................1270 :nLine TXmlDocument() ................................................ 1301 :nNodeCount TXmlDocument() ................................................ 1301 :nRight TBrowse() ...........................................................1271 :nStatus TXmlDocument() ................................................ 1300 :nTop TBrowse() ...........................................................1271 :nType TXmlNode() ........................................................ 1320 :oChild TXmlNode() ........................................................ 1320 :oErrorNode TXmlDocument() ................................................ 1301 :oNext TXmlNode() ........................................................ 1321 :oParent TXmlNode() ........................................................ 1321 :open() Popup()...............................................................1259 :operation Error() ................................................................. 1215 :oPrev TXmlNode() ........................................................ 1321 :original Get() ................................................................... 1225 :oRoot TXmlDocument() ................................................ 1300 :osCode Error() ................................................................. 1215 :overStrike() Get() ................................................................... 1235 :pageDown() TBrowse() ...........................................................1280 :pageUp() TBrowse() ...........................................................1281 :panEnd() TBrowse() ...........................................................1281 :panHome() TBrowse() ...........................................................1281 :panLeft() xHarbour Language Reference Guide

Index TBrowse()........................................................... 1281 :panRight() TBrowse()........................................................... 1282 :path() TXmlNode() ........................................................ 1326 :picture Get() ................................................................... 1225 TBColumn() ........................................................ 1263 :pointer() C Structure class ................................................ 1208 :pos Get() ................................................................... 1226 :postBlock Get() ................................................................... 1226 TBColumn() ........................................................ 1263 :preBlock Get() ................................................................... 1226 TBColumn() ........................................................ 1263 :procLine Error() ................................................................ 1216 :procName Error() ................................................................ 1216 :read() TXmlDocument() ................................................ 1301 :reader Get() ................................................................... 1226 :refreshAll() TBrowse()........................................................... 1277 :refreshCurrent() TBrowse()........................................................... 1277 :rejected Get()................................................................... 1227 :reset() C Structure class ................................................ 1209 Get() ................................................................... 1230 :rewind() TXmlIterator() .................................................... 1310 :right Popup() .............................................................. 1253 TopBarMenu().................................................... 1290 :right() Get() ................................................................... 1232 TBrowse()........................................................... 1282 :rightVisible TBrowse()........................................................... 1271 :row Get() ................................................................... 1227 TopBarMenu().................................................... 1290 :rowCount TBrowse()........................................................... 1271 :rowPos TBrowse() ........................................................... 1272 :saveToFile() xHarbour Language Reference Guide

HBPersistent().....................................................1243 :saveToText() HBPersistent().....................................................1243 :select() Popup()...............................................................1259 TopBarMenu() ....................................................1296 :setAttribute() TXmlNode().........................................................1322 :setColumn() TBrowse() ...........................................................1275 :setContext() TXmlIterator().....................................................1310 :setFocus() Get()....................................................................1230 :setItem() Popup()...............................................................1256 TopBarMenu() ....................................................1293 :setKey() TBrowse() ...........................................................1284 :setStyle() TBColumn().........................................................1264 TBrowse() ...........................................................1278 :severity Error() .................................................................1216 :shortCut MenuItem() ........................................................1249 :sizeOf() C Structure class .................................................1209 :skipBlock TBrowse() ...........................................................1272 :stabilize() TBrowse() ...........................................................1278 :stable TBrowse() ...........................................................1272 :style MenuItem() ........................................................1249 :subCode Error() .................................................................1217 :subscript Get()....................................................................1227 :subSystem Error() .................................................................1217 :toArray() TXmlNode().........................................................1326 :toDecPos() Get()....................................................................1233 :top Popup()...............................................................1253 :toString() TXmlDocument() ................................................1302 TXmlNode().........................................................1325 :tries Error() .................................................................1217 1403

Index :type Get() ...................................................................1227 :typeOut Get() ...................................................................1228 :undo() Get() ...................................................................1230 :unlink() TXmlNode() ........................................................1324 :unTransform() Get() ...................................................................1230 :up() TBrowse() ...........................................................1282 :updateBuffer() Get() ...................................................................1231 :value() C Structure class ................................................. 1209 :varGet() Get() ...................................................................1231 :varPut() Get() ...................................................................1231 :width Popup()...............................................................1253 TBColumn()......................................................... 1263 :wordLeft() Get() ...................................................................1233 :wordRight() Get() ...................................................................1233 :write() TXmlDocument() ................................................1303 TXmlNode() ........................................................1325 ? ? | ?? ......................................................................... 186 @ @ (operator)...............................................................59 @() (operator).............................................................60 @...BOX.....................................................................188 @...CLEAR .................................................................190 @...GET ................................... 192, see also: Get object @...PROMPT .............................................................196 @...SAY .....................................................................197 defining output device ......................................... 303 @...TO ....................................................................... 200 [ [ ] (array) .....................................................................68 [ ] (string) ....................................................................69 ^ ^^ 71 ^= 50 1404

{ { } (array) ..................................................................... 73 {|| } (code block) ........................................................ 76 {=>} (hash) ..................................................................74 | | 78 | (bitwise OR) .............................................................78 + + (operator) ................................................................ 23 ++ (operator) .............................................................. 25 += (operator) .............................................................. 50 < < (comparison) ............................................................ 38 (extended code block)....................................... 45 (comparison) ............................................................ 54 -> (operator) ...............................................................29 >= (comparison) .......................................................... 56 >> (operator) .............................................................. 58 A AAdd()....................................................................... 370 Abs() ......................................................................... 371 Abstract class.......................................................... 1237 ACCEPT ..................................................................... 202 ACCESS........................................................................82 AChoice() ..................................................................372 AClone() ....................................................................377 ACopy() ..................................................................... 379 Addition ......................................................................23 ADel()........................................................................381 ADir() ........................................................................383 Adler32 ..................................................................... 725 AEval()....................................................................... 385 AFields()....................................................................387 AFill()......................................................................... 389 AIns() ........................................................................391 ALenAlloc() ...............................................................393 xHarbour Language Reference Guide

Index Alert() ....................................................................... 394 Alias name of a work area ...................................................... 396 Alias operator............................................................. 29 Alias() ....................................................................... 396 AllTrim().................................................................... 397 Alt+C ....................................................................... 1128 AltD() ........................................................................ 398 AmPm() .................................................................... 400 AND operator ............................................................. 31 ANNOUNCE ................................................................ 84 ANSI conversion of character strings ................... 450, 688 Antilogarithm ........................................................... 604 APPEND BLANK ........................................................ 203 APPEND FROM ......................................................... 205 Application setting the exit code ............................................ 597 Argument getting all ............................................................. 690 getting the value ................................................ 1078 number of passed .............................................. 1068 Array........................................................................... 73 add one element .................................................. 370 changing the number of elements....................... 405 contents of last element ...................................... 411 copying elements................................................. 379 creating................................................................ 401 deep copy ............................................................ 377 deleting elements ................................................ 381 executable ........................................................... 736 executing a code block for each array element... 385 filling with a value ................................................ 389 filling with database structure ............................. 537 filling with directory information......................... 383 filling with field information ................................ 387 from pointer ........................................................ 832 inserting an element ............................................ 391 number of elements ............................................ 926 pre-allocated memory ......................................... 393 pre-allocating memory ........................................ 406 searching from bottom ...................................... 1084 searching from top .............................................. 403 sorting.................................................................. 407 unique identifier .................................................. 696 Array element operator ................................................................. 68 Array() ...................................................................... 401 Asc() ......................................................................... 402 AScan() ..................................................................... 403 ASize() ...................................................................... 405 ASizeAlloc()............................................................... 406 ASort() ...................................................................... 407 xHarbour Language Reference Guide

ASSIGN........................................................................85 Assignment compound ..............................................................50 inline.......................................................................37 simple .....................................................................47 to a field variable..................................................269 ASSOCIATE CLASS........................................................88 Associative array.......................................................873 change value by ordinal position..........................680 deleting an element .............................................670 ordinal key position..............................................674 retrieve key by ordinal position............................672 retrieve value by ordinal position ........................678 sort order of all keys.............................................863 sort order of keys .................................................676 At()............................................................................409 ATail()........................................................................411 AVERAGE...................................................................208 B Background tasks 704, see also: Idle tasks, see also: Idle tasks (de)activating........................................................703 activating ..............................................................285 changing processing interval................................286 deleting.................................................................706 forced execution...................................................708 resetting ...............................................................707 time interval to wait.............................................709 Begin of file...............................................................436 BEGIN SEQUENCE........................................................92 Bin2I()........................................................................412 Bin2L().......................................................................413 Bin2U()......................................................................414 Bin2W() .....................................................................415 Binary large object changing data .......................................................423 exporting to file ....................................................416 importing from file ...............................................421 load into memory.................................................419 Binary large object file deleting root area.................................................430 locking the root area ............................................432 reading the root area ...........................................431 storing data in the root area ................................433 unlocking the root area ........................................435 Binary string deserialize.............................................................731 serialize.................................................................820 Bit functions AND ......................................................................710 NOT.......................................................................713 OR .........................................................................714 1405

Index set bit to 0 ............................................................715 set bit to 1 ............................................................717 shifting bits...........................................................719 test if bit is set ......................................................711 XOR....................................................................... 721 Bitwise AND ................................................................12 Bitwise OR...................................................................78 Bitwise XOR.................................................................71 Blank spaces removing from character strings ..........................397 removing leading..................................................935 removing trailing ......................................1110, 1180 Blink attribute for colors ............................................................1127 BlobDirectExport() ....................................................416 BlobDirectGet()......................................................... 419 BlobDirectImport()....................................................421 BlobDirectPut() ......................................................... 423 BlobExport() ..............................................................425 BlobGet()...................................................................427 BlobImport() .............................................................428 BlobRootDelete() ......................................................430 BlobRootGet()...........................................................431 BlobRootLock() ......................................................... 432 BlobRootPut() ...........................................................433 BlobRootUnlock()......................................................435 BoF()..........................................................................436 BREAK ......................................................................... 92 Break() ......................................................................438 Browse().......................... 440, see also: TBrowse object Browser for text mode (simple)..........................................440 in text mode (with user function) ........................478 C C structure converting to array ............................................... 830 C Structure creating from array............................................... 697 size of ...................................................................828 C Structure class ..................................................... 1205 Calendar day .............................................................458 Calendar year................................................... see: year CANCEL .....................................................................210 Carriage return replacing in a character string ..............................957 replacing soft with hard ....................................... 683 CATCH ....................................................................... 178 CDoW() .....................................................................442 Character and ASCII Code ..................................................... 402 first position in a character string ........................409 last position in a character string ....................... 1086 1406

wild match pattern............................................. 1200 Character operator ..................................................... 69 Character string check if it begins with a 7-bit ASCII character ......896 check if it begins with a control character ........... 897 check if it begins with a digit ................................ 899 check if it begins with a grahpical 7-bit ASCII character .......................................................... 903 check if it begins with a hex-digit character......... 915 check if it begins with a letter .............................. 895 check if it begins with a lowercase letter............. 904 check if it begins with a printable 7-bit ASCII character .......................................................... 905 check if it begins with a punctuation character ... 908 check if it begins with a white-space character ... 911 check if it begins with an alpha-numeric character ......................................................................... 894 check if it begins with an uppercase letter .......... 912 comparison with RegEx ..........................................66 consisting of blank spaces ..................................1148 converting to a numeric value ...........................1189 converting to ANSI ....................................... 450, 688 converting to date value ......................................454 converting to lower case ......................................934 converting to OEM ....................................... 451, 792 converting to upper case ................................... 1187 deleting of characters ........................................ 1162 extracting substring from the left ........................ 925 extracting substring from the right .................... 1104 extracting substrings .......................................... 1167 inserting of characters ....................................... 1162 number of characters........................................... 926 padding with a fill character .............................. 1064 phonetic similarity ............................................. 1147 removing blank spaces......................................... 397 removing leading blank spaces ............................ 935 removing trailing blank spaces ................. 1110, 1180 replacing characters........................................... 1158 replicating .......................................................... 1101 search substring with RegEx ..................................62 sorting weight ...................................................... 822 starting position of a line ..................................... 969 tokenize................................................................ 699 Character string comparison activating exact comparison ................................ 314 Character value converting to Hex string..................................... 1157 Checksum using Adler32 algorithm....................................... 725 using CRC32 algorithm ......................................... 728 using MD5 algorithm............................................ 780 Child work area......................................................... 519 Chr().......................................................................... 443 xHarbour Language Reference Guide

Index Class adding member variables .................................... 121 adding methods ................................................... 123 CLASS.......................................................................... 94 CLASSDATA................................................................. 99 CLASSMETHOD ......................................................... 102 CLEAR ALL ................................................................. 211 CLEAR MEMORY ....................................................... 212 CLEAR SCREEN .......................................................... 213 CLEAR TYPEAHEAD ................................................... 214 CLOSE ....................................................................... 215 Closing all or a group of files ............................................ 215 CLS............................................................................ 213 CMonth() .................................................................. 445 Code block.................................................................. 76 associating with a key ........................................ 1135 creating for field access ............................... 613, 623 executing ............................................................. 602 extended................................................................ 45 for dynamic memory variables ............................ 959 for error handling ................................................ 594 restoring from binary........................................... 818 Code page ................................................................ 822 Col() .......................................................................... 447 Collection ................................................................. 130 index of item ........................................................ 732 Color Blink attribute in text mode ............................... 1127 in text mode....................................................... 1130 selecting in text mode ......................................... 448 setting in text mode............................................. 289 Color index for text mode ........................................ 448 ColorSelect()............................................................. 448 command ..............................................see: #command Command line EXE file name ....................................................... 726 number of arguments .......................................... 691 test internal switches........................................... 692 value of arguments .............................................. 694 value of internal switch ....................................... 693 Command shell ........................................................ 273 COMMIT ................................................................... 217 Comparison equal ...................................................................... 48 for identity ............................................................. 52 greater than ........................................................... 54 greater than or equal............................................. 56 less than ................................................................. 38 less than or equal................................................... 41 not equal................................................................ 43 Compiler build date............................................................. 722 xHarbour Language Reference Guide

build information..................................................723 C compiler used for build .....................................727 conditional compilation..................1342, 1344, 1346 displaying message.............................................1351 Compiling conditional......................................1342, 1344, 1346 Concatenation.......................................................23, 26 CONTINUE.................................................................218 Control structure branch...................................................110, 139, 176 for error handling...........................................92, 178 iteration ........................................................128, 130 iteration index ......................................................732 loop.......................................................................112 terminate a function.............................................173 Controlling index.............................................332, 1037 automatic selecting ..............................................283 position in index list..............................................890 Converting 16 bit integer (signed) to numeric value ..............412 16 bit integer (unsigned) to numeric....................415 32 bit integer (signed) to numeric value ..............413 32 bit integer (unsigned) to numeric....................414 any value to macro-expression ..........................1193 any value to PRG code........................................1191 any value to string ................................................452 ASCII Code to character........................................443 character in date value.........................................454 character string to a numeric value....................1189 character string YYYYMMDD to date value ........1153 character to ASCII Code........................................402 character value to Hex string .............................1157 date into numeric calendar day ...........................458 date value in character string (current date format) .........................................................................586 date value in character string (YYYYMMDD) ........587 date value in numeric weekday............................585 date value into name of the month .....................445 date value into numeric month............................972 date value into the weekday name ......................442 date value to numeric year ................................1203 date value without century digits.........................308 Hex string to character string ...............................850 Hex string to Numeric value .................................849 numeric value to 16 bit integer (signed) ..............883 numeric value to 16 bit integer (unsigned) ........1198 numeric value to 32 bit integer (signed) ..............920 numeric value to 32 bit integer (unsigned) ........1185 numeric value to character string ......................1155 numeric value to Hex string..................................993 seconds to days ....................................................459 with PICTURE format..........................................1178 ConvToAnsiCP().........................................................450 1407

Index ConvToOemCP()........................................................451 COPY FILE ..................................................................219 COPY STRUCTURE ..................................................... 220 COPY STRUCTURE EXTENDED ...................................221 COPY TO ....................................................................223 Copying a multi-dimensional array ....................................377 database structure ............................................... 220 one-dimensional arrays........................................379 COUNT ......................................................................227 CRC32........................................................................728 CREATE......................................................................229 CREATE FROM...........................................................231 Creating a compiler error ....................................... 1341 CStr() ......................................................................... 452 CSV files ....................................................................638 CtoD()........................................................................454 Ctrl+Break ...............................................................1128 CurDir() .....................................................................455 CurDrive()..................................................................456 Current work area ..................................................... 524 Cursor (text mode) changing the position ......................................... 1142 changing the shape ............................................1132 positioning on current output device................... 551 switching on or off................................................292 Custom index adding a key ....................................................... 1014 deleting a key ..................................................... 1018 Cyclic Redundancy Code ........................................... 728 D DATA ......................................................................... 103 Data types and scalar classes ................................................... 88 as scalar classes ....................................................114 checking for Array ................................................758 checking for Character ......................................... 772 checking for Code block ....................................... 759 checking for Date ................................................. 762 checking for Hash ................................................. 763 checking for Logical ..............................................764 checking for Memo ..............................................765 checking for NIL ....................................................766 checking for null values ........................................767 checking for Numeric ........................................... 768 checking for Object ..............................................769 checking for Pointer ............................................. 770 of expressions..................................................... 1183 of values .............................................................1195 testing empty values ............................................590 Database appending a record ......................................203, 460 1408

ascending or descending navigation.................. 1005 automatic opening of index ................................. 281 clearing a relation ................................................ 464 closing .......................................................... 215, 466 closing all.............................................................. 211 closing of .............................................................. 465 copying structure to file ....................................... 221 copying the structure ........................................... 220 creating from a file ............................................... 470 creating from an array ......................................... 472 creating from structure extended file.................. 231 creating from two work areas.............................. 250 creating structure extended file...........................229 date of the last change......................................... 936 defining a link ............................................. 531, 1039 defining relation ................................................... 337 descending navigation ......................................... 302 field information .................................................. 486 file extension ........................................................ 539 filtering records .................................................... 318 indexing...................................................... 245, 1002 indexing (compatibility) ....................................... 475 length of the file header ......................................846 locking file ............................................................ 632 locking scheme..................................................... 295 number of records ............................................. 1098 opening ........................................................ 365, 542 opening exclusively by default .............................316 opening index....................................................... 323 read optimization................................................. 346 writing all file buffers ........................................... 217 writing file buffers ................................................ 467 Database Drivers available .............................................................1091 default driver ..................................................... 1094 used in work area............................................... 1093 Database operation calculating the average ........................................208 calculating the sum of numeric expressions ........357 creating sum for numeric fields ...........................360 number of records matching a condition ............ 227 sorting records ..................................................... 354 writing records from two work areas to file ........250 Database processing sequential search ................................................. 254 Database structure copying to new database ..................................... 470 defining in an array .............................................. 472 loading to array .................................................... 537 Date format defining country-specific......................................293 Date value xHarbour Language Reference Guide

Index converting to character string (current date format) ......................................................................... 586 converting to character string (YYYYMMDD)....... 587 converting to numeric weekday .......................... 585 extracting calendar day as numeric ..................... 458 extracting month as numeric ............................... 972 extracting the year............................................. 1203 name of the month .............................................. 445 name of the weekday .......................................... 442 retrieving the system date ................................... 457 without century digits.......................................... 308 Date() ....................................................................... 457 Day() ......................................................................... 458 Days() ....................................................................... 459 DbAppend().............................................................. 460 DbClearFilter() .......................................................... 462 DbClearIndex() ......................................................... 463 DbClearRelation() ..................................................... 464 DbCloseAll().............................................................. 465 DbCloseArea() .......................................................... 466 DbCommit().............................................................. 467 DbCommitAll().......................................................... 468 DbCopyExtStruct() .................................................... 469 DbCopyStruct()......................................................... 470 DbCreate()................................................................ 472 DbCreateIndex() ....................................................... 475 DbDelete()................................................................ 477 DbEdit() ...........................478, see also: TBrowse object DbEval() .................................................................... 483 Dbf() ......................................................................... 485 DbFieldInfo() ............................................................ 486 DbFileGet() ............................................................... 488 DbFilePut() ............................................................... 489 DbFilter() .................................................................. 490 DbGoBottom() .......................................................... 492 DbGoto() .................................................................. 493 DbGoTop()................................................................ 495 DbInfo() .................................................................... 496 DbOrderInfo()........................................................... 503 DbRecall() ................................................................. 510 DbRecordInfo()......................................................... 511 DbReindex().............................................................. 513 DbRelation() ............................................................. 514 DbRLock() ................................................................. 516 DbRLockList() ............................................................ 518 DbRSelect()............................................................... 519 DbRUnlock() ............................................................. 521 DbSeek() ................................................................... 522 DbSelectArea() ......................................................... 524 DbSetDriver() ........................................................... 526 DbSetFilter() ............................................................. 527 DbSetIndex()............................................................. 529 DbSetOrder() ............................................................ 530 xHarbour Language Reference Guide

DbSetRelation().........................................................531 DbSkip().....................................................................533 DbSkipper() ...............................................................535 DbStruct()..................................................................537 DbTableExt() .............................................................539 DbUnlock() ................................................................540 DbUnlockAll() ............................................................541 DbUseArea()..............................................................542 Debugger ..................................................................398 Decimal numbers rounding .............................................................1107 declaring a class variable........................................................99 Declaring a class .....................................................................94 a dynamic memory variable .................................147 a field variable ......................................................126 a function .............................................................132 a lexical memory variable.....................135, 145, 174 a procedure ..........................................................167 a virtual method...................................................158 an instance method..............................................150 an instance variable..............................................103 external functions.........................................125, 172 Decrement ..................................................................28 Decrypting a character string..................................................730 Default output device.............................................1063 for errors ............................................................1062 DEFAULT TO ..............................................................234 Default values ...........................................................234 Deferred method ......................................................158 define.......................................................... see: #define Defining current work area.......................................277 DefPath()...................................................................544 DELEGATE .................................................................106 DELETE ......................................................................235 DELETE FILE...............................................................237 DELETE TAG...............................................................238 Deleted() ...................................................................545 Deleting all records.............................................................368 characters in a character string..........................1162 dynamic memory variable....................................211 entire screen output in text mode .......................213 file......................................................... 237, 241, 611 index from an index file......................................1007 index key from index file ......................................238 of records .............................................235, 258, 477 recalling records...................................................262 removing the deletion flag for records.................510 screen output in text mode..................................190 Deletion flag 1409

Index checking if set ....................................................... 545 Descend() ..................................................................547 Deserialization ..........................................................731 DESTRUCTOR ............................................................108 DevOut() ...................................................................549 DevOutPict() .............................................................550 DevPos()....................................................................551 DirChange()...............................................................552 Directives for commands ....................................................1331 Directory change current ..................................................... 552 check if it exists ....................................................900 creating a directory ..............................................937 defining default directory.....................................298 determining or changing current ......................... 455 loading into array ................................................. 553 loading recursively into array ...............................555 reading to arrays ..................................................383 removing ..............................................................557 Directory().................................................................553 DirectoryRecurse() ....................................................555 DirRemove()..............................................................557 Disk changing current ..................................................558 check if drive is ready ........................................... 901 get current............................................................560 DiskChange().............................................................558 DiskName() ...............................................................560 DiskSpace() ...............................................................561 DispBegin()................................................................ 563 DispBox()...................................................................565 DispCount()...............................................................567 DispEnd()...................................................................568 DispOut()...................................................................569 DispOutAt() ...............................................................570 DispOutAtSetPos() ....................................................572 Division .......................................................................34 DLL file loading external at runtime..................................931 loading xHarbour DLL at runtime ......................... 930 unloading external ............................................... 647 unloading xHarbour DLL ....................................... 929 DLL function calling dynamically at runtime ..................... 573, 777 memory address of ..............................................663 preparing a call template .....................................579 retrieving error code ............................................658 setting error code ............................................... 1138 using a call template ............................................576 DllCall()......................................................................573 DllExecuteCall()......................................................... 576 DllLoad()....................................................................578 1410

DllPrepareCall()......................................................... 579 DllUnload() ...............................................................581 DO ............................................................................. 233 DO CASE....................................................................110 DO WHILE ................................................................. 112 DosError() ................................................................. 582 DoW() ....................................................................... 585 Drive changing current .................................................. 558 check if drive is ready........................................... 901 current directory .................................................. 455 defining default drive........................................... 298 determining available storage space ................... 561 determining or changing current ......................... 456 get current ...........................................................560 DtoC() ....................................................................... 586 DtoS()........................................................................587 Dynamic memory variable creating set/get code block..................................959 declaring...............................................................147 deleting ................................................ 211, 212, 265 determining the data type................................. 1183 initializing and creating ................................ 165, 170 loading from a MEM file ......................................271 saving to file ......................................................... 274 E EJECT......................................................................... 240 ElapTime()................................................................. 589 ellipsis ....................................................................... 133 Empty values ............................................................ 590 Empty() ..................................................................... 590 ENABLE TYPE CLASS .................................................. 114 Encrypting a character string ................................................. 729 End of file..................................................................592 Entry field activating.............................................................. 260 with Get command .............................................. 192 Eof() .......................................................................... 592 Equal ........................................................................... 48 ERASE........................................................................241 error....................................................... see also: #error Error codes of operating system ............................................. 582 ERROR HANDLER ...................................................... 116 Error handling database error in network ................................... 984 default error code block....................................... 601 default error log file ............................................. 309 error code of the opera ting system ..................... 582 in classes .............................................................. 116 maximum recursion in ......................................... 310 xHarbour Language Reference Guide

Index setting error code block....................................... 594 throwing an exception....................................... 1174 Error message displaying during compiling ............................... 1341 Error object ............................................................ 1211 creating................................................................ 599 Error() ..................................................................... 1211 ErrorBlock() .............................................................. 594 ErrorLevel()............................................................... 597 ErrorNew() ............................................................... 599 ErrorSys().................................................................. 601 Esc key for READ ...................................................... 311 Eval() ........................................................................ 602 Events filtering ................................................................ 312 EXE file name of................................................................ 726 Executable array....................................................... 736 Existence of a Directory ....................................................... 625 of a file ................................................................. 625 of a value in a database ....................................... 636 EXIT PROCEDURE ...................................................... 118 Exp() ......................................................................... 604 Exponentiation ........................................................... 22 EXPORTED: ............................................................... 120 exporting records ................................................................. 223 Expression depending on a condition .................................... 885 determining the data type ....................... 1183, 1195 displaying on screen .................................. 186, 1079 formatting result with PICTURE format ............. 1178 EXTEND CLASS...WITH DATA .................................... 121 EXTEND CLASS...WITH METHOD .............................. 123 Extension for database files ................................................. 539 for index files ....................................................... 994 for index files (compatibility) ............................... 887 EXTERNAL ................................................................. 125 Extracting lines from text ...................................................... 951 F FCharCount() ............................................................ 605 FClose()..................................................................... 606 FCount() ................................................................... 608 FCreate()................................................................... 609 FErase() .................................................................... 611 FError() ..................................................................... 612 Field declaring .............................................................. 126 export to external file .......................................... 488 xHarbour Language Reference Guide

import an external file..........................................489 FIELD .........................................................................126 Field information ......................................................486 Field structure copying to file.......................................................221 Field variable assigning a value...................................................269 FieldBlock() ...............................................................613 FieldDec()..................................................................615 FieldGet() ..................................................................616 FieldLen() ..................................................................617 FieldName() ..............................................................618 FieldPos() ..................................................................619 FieldPut()...................................................................620 Fields............................................. see also: Memo field creating a set/get code block ...............................613 creating a set/get-code block ...............................623 data type of ..........................................................622 determining the data type..................................1183 determining the number of..................................608 length of field .......................................................617 number of decimal places ....................................615 reading the value..................................................616 retrieving the name by ordinal position...............618 retrieving the ordinal position by name...............619 writing a value ......................................................620 FieldType() ................................................................622 FieldWBlock()............................................................623 File copying to an output device.................................219 defining search path.............................................334 deleting.........................................................237, 241 information on......................................................627 loading name and attributes into array................553 loading name and attributes recursively into array .........................................................................555 reading completely from disk...............................954 renaming ......................................................267, 648 testing the existence ............................................625 File handle.................................................................634 file header.................................................................846 File lock releasing .......................................................362, 540 releasing all...........................................................541 setting...................................................................632 File name composing ............................................................740 splitting.................................................................741 temporary.............................................................746 File pointer positioning in a file ...............................................650 File size......................................................................745 File()..........................................................................625 1411

Index FileStats() ..................................................................627 Fill character ...........................................................1064 Filter defining or releasing ............................................. 318 optimization ......................................................... 331 Filter condition clearing of.............................................................462 retrieving current ................................................. 490 setting current ......................................................527 FINALLY .....................................................................178 FIND ..........................................................................242 FkLabel() ...................................................................629 FkMax().....................................................................630 FLineCount() .............................................................631 FLock()....................................................................... 632 FOpen() .....................................................................634 FOR ........................................................................... 128 FOR condition and index creation................................................997 for index creation ................................................. 245 for sequential search............................................254 in database processing ......................................... 483 of an index ..........................................................1010 FOR EACH..................................................................130 Formatted output choosing the date format .....................................293 fixed number of decimal places ...........................320 number of decimal places ....................................297 to current output device ......................................550 Found() .....................................................................636 FParse() .....................................................................638 FParseEx() .................................................................640 FParseLine() ..............................................................641 FRead() ......................................................................643 FReadStr() .................................................................645 FreeLibrary() .............................................................647 FRename().................................................................648 FSeek() ......................................................................650 Function number of passed arguments ............................1068 FUNCTION.................................................................132 getting all parameters ..........................................690 getting the pointer ............................................... 748 Function key associating with a procedure ...............................321 Function pointer executing ..............................................................734 obtaining ..............................................................748 operator .................................................................60 FWordCount() ...........................................................652 FWrite().....................................................................653

1412

G Garbage collector ..................................................... 749 calling a method................................................... 108 incremental collection ......................................... 750 Get object ...............................................................1219 create with function............................................. 659 creating and displaying ........................................192 editing ..................................................................260 Get system activating.................................................... 260, 1096 delimiters for entry fields..................................... 301 Get()........................................................................ 1219 GetCurrentThread() .................................................. 655 GetDefaultPrinter()................................................... 656 GetEnv()....................................................................657 GetLastError() ...........................................................658 GetNew() ..................................................................659 GetPrinters() .............................................................661 GetProcAddress() ..................................................... 663 GetRegistry().............................................................665 GetSystemThreadID() ............................................... 667 GetThreadID() ...........................................................668 GLOBAL ..................................................................... 135 GO ............................................................................. 243 Greater than ...............................................................54 Greater than or equal................................................. 56 H HaaDelAt() ................................................................ 670 HaaGetKeyAt() .......................................................... 672 HaaGetPos().............................................................. 674 HaaGetRealPos()....................................................... 676 HaaGetValueAt()....................................................... 678 HaaSetValueAt() ....................................................... 680 HAllocate()................................................................ 682 HardCR() ................................................................... 683 HAS ............................................................................. 62 Hash............................................................................ 74 as associative array .............................................. 873 associate value with key ......................................871 automatic creation of elements ...........................854 case sensitive keys ............................................... 855 change value by ordinal position ......................... 881 check if a key exists .............................................. 867 check partitioning ................................................ 860 copy entirely ........................................................ 868 copy partially ........................................................ 841 creating ................................................................ 684 entire copy ...........................................................839 evaluate a code block........................................... 847 filling with a unique value ....................................851 number of key/value pairs ................................... 926 ordinal key position.............................................. 861 xHarbour Language Reference Guide

Index partitioning .......................................................... 879 pre-allocating memory ........................................ 682 removing key/value pair by key ........................... 844 removing key/value pair by ordinal ..................... 845 retrieve all keys .................................................... 858 retrieve all values................................................. 866 retrieve key by ordinal position ........................... 857 retrieve key/value pair by ordinal position ......... 859 retrieve value by ordinal position........................ 865 retrieving value by key......................................... 852 search a value in a hash....................................... 869 test for associative array...................................... 853 toggle automatic creation of elements ............... 875 toggle case sensitivity .......................................... 877 Hash() ....................................................................... 684 HB_AExpressions() ................................................... 686 HB_AnsiToOem() ...................................................... 688 HB_AParams() .......................................................... 690 HB_ArgC() ................................................................. 691 HB_ArgCheck() ......................................................... 692 HB_ArgString() ......................................................... 693 HB_ArgV()................................................................. 694 HB_ArrayId()............................................................. 696 HB_ArrayToStructure()............................................. 697 HB_ATokens()........................................................... 699 HB_AtX() ................................................................... 701 HB_BackGroundActive()........................................... 703 HB_BackGroundAdd() .............................................. 704 HB_BackGroundDel() ............................................... 706 HB_BackGroundReset()............................................ 707 HB_BackGroundRun() .............................................. 708 HB_BackGroundTime()............................................. 709 HB_BitAnd().............................................................. 710 HB_BitIsSet() ............................................................ 711 HB_BitNot() .............................................................. 713 HB_BitOr() ................................................................ 714 HB_BitReset() ........................................................... 715 HB_BitSet() ............................................................... 717 HB_BitShift()............................................................. 719 HB_BitXOr() .............................................................. 721 HB_BuildDate()......................................................... 722 HB_BuildInfo() .......................................................... 723 HB_CheckSum() ........................................................ 725 HB_CmdArgArgV() .................................................... 726 HB_Compiler() .......................................................... 727 Hb_CRC32() .............................................................. 728 HB_Crypt()................................................................ 729 HB_Decrypt() ............................................................ 730 HB_DeSerialize()....................................................... 731 HB_EnumIndex() ...................................................... 732 HB_Exec() ................................................................. 734 HB_ExecFromArray() ................................................ 736 HB_FNameMerge() .................................................. 740 xHarbour Language Reference Guide

HB_FNameSplit().......................................................741 HB_FReadLine().........................................................743 HB_FSize() .................................................................745 HB_FTempCreate() ...................................................746 HB_FuncPtr().............................................................748 HB_GCAll() ................................................................749 HB_GCStep() .............................................................750 HB_IdleAdd().............................................................751 HB_IdleDel()..............................................................753 HB_IdleReset() ..........................................................754 HB_IdleSleep() ..........................................................755 HB_IdleSleepMSec()..................................................756 HB_IdleState()...........................................................757 HB_IsArray()..............................................................758 HB_IsBlock() ..............................................................759 HB_IsByRef................................................................760 HB_IsDate()...............................................................762 HB_IsHash()...............................................................763 HB_IsLogical()............................................................764 HB_IsMemo() ............................................................765 HB_IsNIL() .................................................................766 HB_IsNull() ................................................................767 HB_IsNumeric().........................................................768 HB_IsObject() ............................................................769 HB_IsPointer()...........................................................770 HB_IsRegExString()....................................................771 HB_IsString() .............................................................772 HB_KeyPut()..............................................................773 HB_LangSelect()........................................................774 HB_LibDo() ................................................................777 HB_MacroCompile() .................................................779 HB_MD5() .................................................................780 HB_MD5File()............................................................781 HB_MultiThread() .....................................................782 HB_MutexCreate() ....................................................783 HB_MutexLock() .......................................................786 HB_MutexTimeoutLock()..........................................787 HB_MutexTryLock() ..................................................788 HB_MutexUnlock()....................................................789 HB_ObjMsgPtr()........................................................790 HB_OemToAnsi() ......................................................792 HB_OsNewLine().......................................................793 HB_QSelf().................................................................794 HB_QWith()...............................................................795 HB_Random()............................................................796 HB_RandomInt() .......................................................798 HB_RandomSeed()....................................................800 HB_ReadIni().............................................................802 HB_RegEx() ...............................................................804 HB_RegExAll() ...........................................................807 HB_RegExComp() ......................................................811 HB_RegExMatch().....................................................812 HB_RegExSplit() ........................................................814 1413

Index HB_ResetWith() ........................................................816 HB_RestoreBlock() ....................................................818 HB_SaveBlock()......................................................... 819 HB_Serialize()............................................................820 HB_SetCodePage() ....................................................822 HB_SetIniComment() ................................................824 HB_SetMacro() ......................................................... 825 HB_SetWith() ............................................................826 HB_SizeofCStructure() ..............................................828 HB_StructureToArray() ............................................. 830 HB_ThisArray() ..........................................................832 HB_VMExecute() ....................................................... 833 HB_VMMode() ..........................................................834 HB_WithObjectCounter() ......................................... 835 HB_WriteIni() ............................................................836 HB_XmlErrorDesc() ................................................... 838 HBObject() .............................................................. 1237 HBPersistent()......................................................... 1243 HClone() ....................................................................839 HCopy() .....................................................................841 HDel() ........................................................................844 HDelAt() ....................................................................845 Header() ....................................................................846 HEval()....................................................................... 847 Hex string converting to character string ..............................850 converting to Numeric value................................ 849 HexToNum()..............................................................849 HexToStr().................................................................850 HFill()......................................................................... 851 HGet() ....................................................................... 852 HGetAACompatibility() ............................................. 853 HGetAutoAdd() ......................................................... 854 HGetCaseMatch() ..................................................... 855 HGetKeyAt() ..............................................................857 HGetKeys() ................................................................ 858 HGetPairAt() .............................................................859 HGetPartition() ......................................................... 860 HGetPos()..................................................................861 HGetVaaPos()............................................................863 HGetValueAt()...........................................................865 HGetValues().............................................................866 HHasKey() .................................................................867 HIDDEN: ....................................................................137 HMerge()...................................................................868 HScan()......................................................................869 HSet() ........................................................................871 HSetAACompatibility() ..............................................873 HSetAutoAdd()..........................................................875 HSetCaseMatch() ......................................................877 HSetPartition() ..........................................................879 HSetValueAt() ...........................................................881 1414

I I2Bin() ....................................................................... 883 Idle tasks ................................................................... 751 default wait period............................................... 756 deleting ................................................................ 753 resetting ...............................................................754 signalling .............................................................. 757 wait state .............................................................755 if see: #if IF 139 If() ............................................................................. 885 If() | IIf() ....................................................................885 ifdef ............................................. see: #ifdef, see: #ifdef IIf() ............................................................................ 885 Importing records ................................................................. 205 IN 64 include ....................................................... see: #include Increment ................................................................... 25 Index activating............................................................ 1027 automatic opening ............................................... 281 automatic selecting .............................................. 283 changing custom status ..................................... 1004 changing descend order..................................... 1005 closing ..................................................................215 closing files ......................................................... 1029 closing files (compatibility) ..................................463 creating ...................................................... 245, 1002 creating (compatibility) ........................................475 current value ...................................................... 1026 custom key ......................................................... 1014 defining UNIQUE status ....................................... 349 deleting from an index file ......................... 238, 1007 descending flag .................................................... 302 determining the TAG name................................ 1031 extension.............................................................. 994 getting position by name ................................... 1033 open file ...............................................................529 opening file .......................................................... 323 position of the controlling....................................890 remove custom key ............................................ 1018 reorganizing ............................................... 264, 1030 reorganizing (compatibility) ................................. 513 retrieving FOR condition ....................................1010 searching a record ........................................ 275, 522 searching a record number ................................ 1008 selecting the controlling............................. 332, 1037 selecting the controlling (compatibility) .............. 530 setting conditions for index creation ................... 997 testing UNIQUE flag ........................................... 1011 total number of keys .......................................... 1016 wild card searching ............................................ 1044 xHarbour Language Reference Guide

Index INDEX ....................................................................... 245 Index key creating for descending order ............................. 547 name of the corresponding index file.................. 995 retrieve expression ............................................ 1012 retrieving (compatibility) ..................................... 888 IndexExt() ................................................................. 887 IndexKey() ................................................................ 888 IndexOrd() ................................................................ 890 INI file comment delimiters ............................................ 824 reading ................................................................. 802 writing.................................................................. 836 INIT PROCEDURE ...................................................... 141 Inkey() ........................... 891, see also: SET EVENTMASK Inline assignment ....................................................... 37 INLINE METHOD ....................................................... 143 INPUT ....................................................................... 249 Inserting characters in a character string ......................... 1162 include file in a program file .............................. 1347 Instance method declaring .............................................................. 150 Int()........................................................................... 893 Integers .................................................................... 893 Is identical .................................................................. 52 IsAlNum() ................................................................. 894 IsAlpha() ................................................................... 895 IsAscii() ..................................................................... 896 IsCntrl()..................................................................... 897 IsColor().................................................................... 898 IsDigit() ..................................................................... 899 IsDirectory() ............................................................. 900 IsDisk()...................................................................... 901 IsGraph()................................................................... 903 IsLower()................................................................... 904 IsPrint() ..................................................................... 905 IsPrinter() ................................................................. 906 IsPunct() ................................................................... 908 IsSameThread() ........................................................ 909 IsSpace() ................................................................... 911 IsUpper() .................................................................. 912 IsValidThread() ......................................................... 913 IsXDigit() ................................................................... 915 Iteration for databases ....................................................... 483 J JOIN .......................................................................... 250 JoinThread() ............................................................. 916 K Key xHarbour Language Reference Guide

associating with a procedure call .........................326 associating with code block................................1135 KEYBOARD.................................................................252 Keyboard buffer defining the size ...................................................348 reading and removing next key............................891 removing all characters ........................................214 retrieve last key ....................................................922 retrieve next key...................................................987 writing characters.................................................252 KillAllThreads() ..........................................................918 KillThread()................................................................919 L L2bin().......................................................................920 Language...................................................................774 Larger value of two values........................................939 Last record ................................................................924 LastKey() ...................................................................922 LastRec() ...................................................................924 Left shift......................................................................40 Left()..........................................................................925 Len()..........................................................................926 Length of a record ..........................................................1100 of an array character string or hash .....................926 LenNum()..................................................................928 Less than .....................................................................38 Less than or equal.......................................................41 Lexical memory variable determining the data type..................................1195 initializing and declaring.......................135, 145, 174 LibFree()....................................................................929 LibLoad() ...................................................................930 LIKE .............................................................................66 Line end characters...................................................793 Link expression of a relation .....................................514 Listbox in text mode .........................................................372 Literal value array .......................................................................73 code block ..............................................................76 hash........................................................................74 LoadLibrary().............................................................931 LOCAL........................................................................145 Localization ...............................................................774 LOCATE......................................................................254 Locking schemes .......................................................295 Log()..........................................................................933 Logarithm natural..................................................................933 Logical AND.................................................................31 Logical NOT .................................................................32 1415

Index Logical OR ...................................................................33 Logical order of records ..........................................1037 Low level File information on ..................................................... 627 Lower case converting to upper case....................................1187 Lower()......................................................................934 Low-level file closing...................................................................606 counting text lines ................................................631 creating.................................................................609 deleting.................................................................611 navigating the file pointer ....................................650 opening.................................................................634 reading .................................................................643 reading a text line................................................. 743 reading up to Chr(0) ............................................. 645 renaming ..............................................................648 retrieving last error code......................................612 size........................................................................745 writing ..................................................................653 LTrim()....................................................................... 935 LUpdate() ..................................................................936 M Macro operator ..........................................................14 accessing variables ................................................. 15 calling functions ..................................................... 17 creating variables ................................................... 15 runtime compilation ............................................... 16 sending message to object .....................................17 text substitution ..................................................... 16 toggle features ..................................................... 825 Macro string..............................................................686 compiling ..............................................................779 MakeDir() ..................................................................937 Max()......................................................................... 939 MaxCol()....................................................................940 MaxRow()..................................................................941 MCol() ....................................................................... 942 MD5 ..........................................................................780 MDblClk() ..................................................................943 MEM file load into memory ................................................. 271 Member variable ......................................................103 Memo field displaying and editing (text mode)....................... 944 exporting to file ....................................................425 extracting one line of text ....................................951 importing a file ..................................................... 428 number of lines ....................................................964 position of a character ......................................... 966 position of a line ................................................... 969 1416

reading the value ................................................. 427 replacing characters........................................... 1158 replacing of carriage returns ................................ 957 replacing soft carriage return .............................. 683 row and column position of a character .............. 973 writing to a file ..................................................... 958 Memo file block size .............................................................. 328 MemoEdit() .............................................................. 944 MemoLine() .............................................................. 951 MemoRead().............................................................954 Memory()..................................................................955 MemoTran() .............................................................957 MemoWrit().............................................................. 958 MEMVAR ..................................................................147 MemVarBlock()......................................................... 959 Menu activating in text mode ........................................256 displaying in text mode ........................................196 Menu classes (text-mode) activating menu system ....................................... 960 menu item.......................................................... 1246 popup menu....................................................... 1250 top bar menu ..................................................... 1288 MENU TO ..................................................................256 MenuItem() ............................................................ 1246 MenuModal() ...........................................................960 MESSAGE ..................................................................148 Message digest of a file ................................................................. 781 of a string .............................................................780 METHOD getting the pointer ............................................... 790 METHOD (declaration) ............................................. 150 METHOD (implementation) ......................................153 Method declaration ACCESS ................................................................... 82 ASSIGN ................................................................... 85 METHOD...OPERATOR .............................................. 156 METHOD...VIRTUAL .................................................. 158 MHide()..................................................................... 962 Min() ......................................................................... 963 Minus operator...........................................................26 MLCount()................................................................. 964 MLCToPos() .............................................................. 966 MLeftDown() ............................................................ 968 MlPos() ..................................................................... 969 Mod()........................................................................971 Modal dialog box in text mode ......................................................... 394 Modulus operator ...................................................... 11 Month() ....................................................................972 Mouse xHarbour Language Reference Guide

Index number of buttons............................................... 992 retrieving event ................................................... 891 Mouse (text mode) check if it exists .................................................... 975 double click interval............................................. 943 restore saved settings.......................................... 976 restricting boundaries.......................................... 980 save current settings............................................ 979 status of left button............................................. 968 status of right button........................................... 977 Mouse cursor turning on/off .................................................... 1141 Mouse cursor (text mode) current column position ...................................... 942 current row position ............................................ 978 determine visibility .............................................. 981 displaying mouse cursor ...................................... 983 hiding mouse cursor ............................................ 962 set position .......................................................... 982 Mouse events filtering ................................................................ 312 MPosToLC() .............................................................. 973 MPresent() ............................................................... 975 MRestState() ............................................................ 976 MRightDown() .......................................................... 977 MRow()..................................................................... 978 MSaveState() ............................................................ 979 MSetBounds() .......................................................... 980 MSetCursor() ............................................................ 981 MSetPos() ................................................................. 982 MShow() ................................................................... 983 Multi-dimensional array copying................................................................. 377 Multi-dimensional Array creating................................................................ 401 Multiplication ............................................................. 21 Multi-threading ........................................................ 782 Mutex creating................................................................ 783 locking permanently ............................................ 786 locking with timeout ............................................ 787 subscribing ......................................................... 1164 trying to lock ........................................................ 788 unlocking.............................................................. 789 Mutual exclusive ...................................................... 783 N Name changing for a file ........................................ 267, 648 of an index ......................................................... 1031 of an index file from index key ............................ 995 of fields in a work area ........................................ 618 of the operating systems ................................... 1046 xHarbour Language Reference Guide

National language.....................................................774 Navigation absolute........................................................243, 493 ignoring filter ......................................................1040 logical .................................................................1020 relative..........................................................352, 533 to unique records...............................................1042 with TBrowse objects...........................................535 NetErr() .....................................................................984 NetName() ................................................................986 Network error in database command .................................984 file lock during concurrent access........................632 locking schemes....................................................295 obtain user name or computer name ..................986 releasing a record lock..........................................521 NextKey() ..................................................................987 Not equal ....................................................................43 NOT operator..............................................................32 Notify()......................................................................989 NotifyAll()..................................................................990 NumButtons() ...........................................................992 Numeric value antilogarithm........................................................604 calculating the natural logarithm .........................933 calculating the square root.................................1149 converting to character ........................................443 converting to character string............................1155 converting to Hex string .......................................993 converting to integer............................................893 determining the absolute value ...........................371 padding with a fill character...............................1064 padding with leading zeros.................................1160 required places for display ...................................928 rounding .............................................................1107 NumToHex()..............................................................993 O Object declaring a method...............................................150 from pointer .........................................................832 method pointer ....................................................790 unique identifier...................................................696 OEM conversion of character strings ....................451, 792 One-dimensional Array copying elements .................................................379 Operating system check for Windows 2000 ....................................1047 check for Windows 2000 or later .......................1048 check for Windows 2003 ....................................1049 check for Windows 95 ........................................1050 check for Windows 98 ........................................1051 1417

Index check for Windows 9x ........................................1052 check for Windows ME ....................................... 1053 check for Windows NT ....................................... 1054 check for Windows NT 3.51................................ 1055 check for Windows NT 4.0..................................1056 check for Windows Terminal Server Client ........1059 check for Windows Vista ....................................1057 check for Windows XP........................................1058 retrieving error code ............................................582 retrieving the contents of environment variables657 retrieving the version ......................................... 1046 version information............................................1060 OPERATOR ................................................................ 159 Operator overloading ............................................... 156 Optimization .............................................................331 OR operator ................................................................33 OrdBagExt()...............................................................994 OrdBagName() ..........................................................995 OrdCondSet() ............................................................997 OrdCount() .............................................................. 1000 OrdCreate().............................................................1002 OrdCustom() ...........................................................1004 OrdDescend()..........................................................1005 OrdDestroy()...........................................................1007 OrdFindRec()...........................................................1008 OrdFor() ..................................................................1010 OrdIsUnique() ......................................................... 1011 OrdKey()..................................................................1012 OrdKeyAdd() ...........................................................1014 OrdKeyCount() ........................................................1016 OrdKeyDel() ............................................................1018 OrdKeyGoTo() ......................................................... 1020 OrdKeyNo() .............................................................1022 OrdKeyRelPos()....................................................... 1024 OrdKeyVal().............................................................1026 OrdListAdd()............................................................1027 OrdListClear() ..........................................................1029 OrdListRebuild()......................................................1030 OrdName() .............................................................. 1031 OrdNumber() ..........................................................1033 OrdScope() .............................................................. 1035 OrdSetFocus() ......................................................... 1037 OrdSetRelation() ..................................................... 1039 OrdSkipRaw() ..........................................................1040 OrdSkipUnique() ..................................................... 1042 OrdWildSeek()......................................................... 1044 Os() ......................................................................... 1046 Os_IsWin2000() ......................................................1047 Os_IsWin2000_Or_Later() ......................................1048 Os_IsWin2003() ......................................................1049 Os_IsWin95() ..........................................................1050 Os_IsWin98() ..........................................................1051 Os_IsWin9X() ..........................................................1052 1418

Os_IsWinME() ......................................................... 1053 Os_IsWinNT().......................................................... 1054 Os_IsWinNT351() .................................................... 1055 Os_IsWinNT4() ........................................................ 1056 Os_IsWinVista() ...................................................... 1057 Os_IsWinXP() .......................................................... 1058 Os_IsWtsClient() ..................................................... 1059 Os_VersionInfo()..................................................... 1060 OutErr()................................................................... 1062 Output (text mode) changing the position......................................... 1142 defining output device ......................................... 303 displaying a box on screen ........................... 188, 565 displaying a frame on screen ...............................200 formatted to current output device..................... 550 list of expressions............................................... 1079 of a list of expressions .......................................... 186 on screen...................................................... 569, 570 on screen or on the printer ..................................197 to current output device......................................549 Output device defining for @...SAY ............................................. 303 standard Error .................................................... 1062 standard Out ...................................................... 1063 OutStd() ..................................................................1063 Overloading methods ...............................................................161 operators.............................................................. 159 OVERRIDE METHOD .................................................. 161 P PACK ......................................................................... 258 Pad() ....................................................................... 1064 PadC() ..................................................................... 1064 PadC() | PadL() | PadR() ......................................... 1064 PadL()......................................................................1064 PadR() ..................................................................... 1064 Parameter formal parameter list ........................................... 132 getting all .............................................................690 getting the value ................................................ 1078 number of passed .............................................. 1068 passing to code block ........................................... 602 undefined parameter list ..................................... 133 PARAMETERS............................................................ 163 Parent and child work areas................... 337, 531, 1039 Path search path for files ............................................. 334 PCode compiling.............................................................. 779 executing.............................................................. 833 PCol() ......................................................................1066 resetting internal counter ..................................1143 xHarbour Language Reference Guide

Index PCount() ................................................................. 1068 Persistent objects................................................... 1243 PICTURE format for transforming values ..................................... 1178 Plus operator .............................................................. 23 Pointer to array or object ................................................. 696 to function ........................................................... 748 to method ............................................................ 790 Popup()................................................................... 1250 Position of the record pointer logical ................................................................. 1022 relative ............................................................... 1024 Postfix notation .................................................... 25, 28 pragma pack() .......................................................... 164 Prefix notation ..................................................... 25, 28 Printer available printers ................................................. 661 check for installation ......................................... 1069 check if printer exists........................................... 906 column position of the print head ..................... 1066 counter for print head position ......................... 1143 default.................................................................. 656 getting the name from a port ............................ 1070 raw printing ....................................................... 1071 row position of the print head ........................... 1076 PrinterExists() ......................................................... 1069 PrinterPortToName() ............................................. 1070 PrintFileRaw()......................................................... 1071 PRIVATE.................................................................... 165 Procedure associating with a function key............................ 321 associating with a key .......................................... 326 for the end of a program ..................................... 118 for the start of a program .................................... 141 PROCEDURE ............................................................. 167 ProcFile() ................................................................ 1073 ProcLine() ............................................................... 1074 ProcName() ............................................................ 1075 Program setting the exit code ............................................ 597 terminating with Alt+C....................................... 1128 Program code current file ......................................................... 1073 current line number........................................... 1074 for error handling .......................................... 92, 178 name of current function - method or procedure ....................................................................... 1075 Program flow branching ..............................................110, 139, 176 interrupting BEGIN SEQUENCE ............................ 438 repeating a section of a program ........................ 112 repeating section of a program ................... 128, 130 xHarbour Language Reference Guide

terminating program ............................................259 throwing an exception........................................1174 Program termination ................................................259 and Alt+C ............................................................1128 Programming commands........................................1331 PROTECTED: ..............................................................169 PRow().....................................................................1076 resetting internal counter ..................................1143 PUBLIC.......................................................................170 PValue()...................................................................1078 Q QOut() .....................................................................1079 QOut() | QQOut()....................................................1079 QQOut() ..................................................................1079 QueryRegistry().......................................................1081 QUIT..........................................................................259 R Random number creating float ........................................................796 creating integer ....................................................798 defining seed value...............................................800 RAscan()..................................................................1084 RAt()........................................................................1086 RDD current RDD ........................................................1093 default driver......................................................1094 list available RDDs ..............................................1091 RddInfo().................................................................1088 RddList()..................................................................1091 RddName()..............................................................1093 RddSetDefault() ......................................................1094 READ .........................................................................260 ReadModal() ...........................................................1096 RECALL ......................................................................262 RecCount() ..............................................................1098 RecNo() ...................................................................1099 Record retrieving specific data.........................................511 Record lock for new records ............................................203, 460 releasing .......................................................362, 521 releasing all...........................................................540 setting multiple ....................................................516 Record number .......................................................1099 Record pointer checking if begin-of-file was reached ...................436 logical position....................................................1022 logical positioning...............................................1020 moving relative.............................................352, 533 navigating to the begin of file...............................495 navigating to the end of file .................................492 1419

Index positioning....................................................243, 493 relative position..................................................1024 skipping with index............................................. 1040 testing the end of file ........................................... 592 unique records ................................................... 1042 Records browsing in a work area ....................................... 478 combining from two work areas ..........................250 creating new................................................. 203, 460 creating sum......................................................... 360 current index value............................................. 1026 deleting all ............................................................368 deleting physically ................................................258 displaying in a window ......................................... 440 exporting ..............................................................223 importing ..............................................................205 last in a work area ................................................924 Length in bytes ................................................... 1100 locking multiple ....................................................516 locking one ......................................................... 1105 locking scheme ..................................................... 295 logical count ....................................................... 1016 logical order........................................................1037 marking as deleted ....................................... 235, 477 number of current ..............................................1099 reading value from field ....................................... 616 recalling ................................................................ 262 recalling a deleted ................................................510 retrieving all locked ..............................................518 searching ......................................................275, 522 searching in index ............................................... 1008 searching with wild cards ...................................1044 selecting ...............................................................243 selecting current................................................... 493 selecting first ........................................................495 selecting last......................................................... 492 sorting ..................................................................354 updating ...............................................................363 writing values to fields ......................................... 620 RECOVER.....................................................................92 RecSize()..................................................................1100 Reference parameters ..........................................59, 60 testing...................................................................760 Registry creating key/value pair....................................... 1145 existence of key value ........................................1081 retrieving key value ..............................................665 Regular expression....................................................804 comparing a string..................................................66 compiled...............................................................771 compiling ..............................................................811 parsing a string ............................................. 807, 814 searching in a character string .............................701 1420

searching in a string ............................................... 62 testing for a match ............................................... 812 REINDEX....................................................................264 Relation clearing of ............................................................ 464 creating ................................................................ 531 creating scoped .................................................. 1039 defining ................................................................ 337 determining the child work area.......................... 519 retrieving the linking expression.......................... 514 RELEASE ....................................................................265 RENAME ................................................................... 267 Reorganizing index file .............................................................1030 REPLACE....................................................................269 Replaceble Database Driver configuration of.................................................. 1088 Replaceble Database Drivers available .............................................................1091 default driver ..................................................... 1094 Replacing of characters in a character string ..................... 1158 soft carriage return .............................................. 683 Replicate() .............................................................. 1101 REQUEST ................................................................... 172 RESTORE ................................................................... 271 RestScreen() ...........................................................1102 RETURN ....................................................................173 Right shift ................................................................... 58 Right() ..................................................................... 1104 RLock() ....................................................................1105 Round() ................................................................... 1107 Rounding numeric values ....................................... 1107 Row() ......................................................................1109 RTrim()....................................................................1110 RUN .......................................................................... 273 Runtime error ...........................................................594 S SAVE ......................................................................... 274 SaveScreen() ...........................................................1112 Scalar classes ............................................................ 114 User defined ...........................................................88 Scope of class members ................................................... 95 setting ................................................................ 1035 setting both .......................................................... 339 setting bottom ..................................................... 341 setting top............................................................ 342 Screen (text mode) displaying saved screen contents....................... 1102 maximum (bottom) screen row ...........................941 maximum (rightmost) screen column.................. 940 xHarbour Language Reference Guide

Index saving the contents............................................ 1112 setting the number of rows and columns.......... 1139 Screen cursor (text mode) column position ................................................... 447 row position ....................................................... 1109 Screen output (text mode) activating or suppressing ..................................... 291 additionally on the printer ................................... 335 deleting display .................................................... 190 displaying a box ........................................... 188, 565 displaying a frame................................................ 200 displaying a value......................................... 569, 570 displaying screen buffers ..................................... 568 erasing the display ............................................... 213 initiating buffered ................................................ 563 number of open screen buffers ........................... 567 writing additionally to file.................................... 279 Scroll() .................................................................... 1114 Scrolling screen in text modde ......................................... 1114 Search an array.............................................................. 1084 Searching an array................................................................ 403 file ........................................................................ 625 in indexed database............................275, 522, 1008 resuming in database .......................................... 218 testing for success ............................................... 636 value in another..................................................... 64 Seconds .................................................................. 1116 converting to days ............................................... 459 converting to time string ................................... 1182 Seconds()................................................................ 1116 SecondsSleep() ....................................................... 1117 Secs() ...................................................................... 1118 see also SET OPTIMIZE....................................................... 346 SEEK. 275, see also: SET SOFTSEEK, see also: SET SCOPE SELECT ...................................................................... 277 Select() ................................................................... 1119 Self object................................................................. 794 Send operator ............................................................ 35 Sequential search beginning ............................................................. 254 resuming .............................................................. 218 Serialization.............................................................. 820 of code blocks ...................................................... 819 SET ALTERNATE ........................................................ 279 SET AUTOPEN ........................................................... 281 SET AUTORDER......................................................... 283 SET AUTOSHARE....................................................... 284 SET BACKGROUND TASKS......................................... 285 SET BACKGROUNDTICK ............................................ 286 xHarbour Language Reference Guide

SET BELL....................................................................287 SET CENTURY ............................................................288 SET COLOR ................................................................289 SET CONFIRM............................................................290 SET CONSOLE ............................................................291 SET CURSOR ..............................................................292 SET DATE...................................................................293 SET DBFLOCKSCHEME...............................................295 SET DECIMALS...........................................................297 SET DEFAULT.............................................................298 SET DELETED .............................................................299 SET DELIMITERS ........................................................301 SET DESCENDING ......................................................302 SET DEVICE ................................................................303 SET DIRCASE..............................................................305 SET DIRSEPARATOR...................................................306 SET EOL .....................................................................307 SET EPOCH ................................................................308 SET ERRORLOG..........................................................309 SET ERRORLOOP........................................................310 SET ESCAPE ...............................................................311 SET EVENTMASK .......................................................312 SET EXACT .................................................................314 SET EXCLUSIVE ..........................................................316 SET FILECASE.............................................................317 SET FILTER ..........................318, see also: SET OPTIMIZE SET FIXED ..................................................................320 SET FUNCTION ..........................................................321 SET INDEX..................................................................323 SET INTENSITY...........................................................325 SET KEY......................................................................326 SET MARGIN..............................................................327 SET MEMOBLOCK......................................................328 SET MESSAGE............................................................330 SET OPTIMIZE............................................................331 SET ORDER ................................................................332 SET PATH...................................................................334 SET PRINTER..............................................................335 SET RELATION ...........................................................337 SET SCOPE.................................................................339 SET SCOPEBOTTOM ..................................................341 SET SCOPETOP ..........................................................342 SET SCOREBOARD .....................................................343 SET SOFTSEEK............................................................344 SET STRICTREAD........................................................346 SET TRACE .................................................................347 SET TYPEAHEAD ........................................................348 SET UNIQUE ..............................................................349 SET VIDEOMODE.......................................................350 SET WRAP..................................................................351 Set().........................................................................1120 SetBlink().................................................................1127 SetCancel() ..............................................................1128 1421

Index SetColor() ................................................................ 1130 SetCursor() .............................................................. 1132 SetErrorMode()....................................................... 1134 SetKey()...................................................................1135 SetLastError() ..........................................................1138 SetMode() ...............................................................1139 SetMouse() .............................................................1141 SetPos()...................................................................1142 SetPrc() ...................................................................1143 SetRegistry()............................................................1145 Settings changing of system settings ...............................1120 colors in text mode..................................... 289, 1130 filtering deleted records ....................................... 299 for date values......................................................293 for numeric values................................................297 for RDDs .............................................................1088 for records ............................................................511 for work areas ......................................................496 Shift operator left ..........................................................................40 right ........................................................................58 SKIP ........................................................................... 352 Skipping ....................................................................533 using index ......................................................... 1040 Smaller value of two values......................................963 Soft carriage return................................................... 944 SORT..........................................................................354 Sorting database logically ....................................... 245, 1002 of arrays................................................................ 407 of records .............................................................354 SoundEx() ................................................................ 1147 Space() ....................................................................1148 Speaker tone...........................................................1176 Sqrt() ....................................................................... 1149 Square root .............................................................1149 Standard devices....................................................... 653 StartThread()...........................................................1150 STATIC ....................................................................... 174 STATIC FUNCTION ..................................................... 132 STATIC PROCEDURE ..................................................167 stdout.......................................................... see: #stdout StoD() ......................................................................1153 StopThread()...........................................................1154 Storage space available on disk ................................................... 561 STORE........................................................................356 Str() ......................................................................... 1155 StrToHex()...............................................................1157 StrTran() ..................................................................1158 Structural index automatic opening ............................................... 281 1422

Structure extended file............................................. 469 creating and opening ........................................... 229 Structures abstract class ...................................................... 1205 byte alignment ..................................................... 164 creation ..................................................................81 declaration ...........................................................180 StrZero()..................................................................1160 Stuff()......................................................................1162 Subscribe().............................................................. 1164 SubscribeNow() ...................................................... 1166 SubStr() ................................................................... 1167 Substring extracting ...........................................................1167 extracting from the left ........................................925 extracting from the right....................................1104 Substring operator ..................................................... 10 Subtraction ................................................................. 26 SUM .......................................................................... 357 SWITCH ..................................................................... 176 Symbolic constants ................................................. 1338 Symbolic name declaring for a PRG file........................................... 84 declaring for external function .................... 125, 172 System date .............................................................. 457 System settings changing .............................................................1120 System time............................................................ 1116 as formatted character string ............................ 1175 T TAG name of an index ............................................ 1031 TBColumn object .................................................... 1260 TBColumn() .............................................................1260 TBMouse() .............................................................. 1169 TBrowse object ....................................................... 1265 for databases...................................................... 1170 mouse click......................................................... 1169 TBrowse() ...............................................................1265 function for :skipBlock ......................................... 535 TBrowseDB() ...........................................................1170 TBrowseNew() ........................................................ 1172 Temporary file .......................................................... 746 Testing the data type ............................................ 1183, 1195 Text displaying and editing (text mode) ...................... 944 extracting single lines........................................... 951 number of lines .................................................... 964 position of a character ......................................... 966 position of a line................................................... 969 replacing of carriage returns ................................ 957 row and column position of a character .............. 973 xHarbour Language Reference Guide

Index writing to a file..................................................... 958 TEXT.......................................................................... 359 Text files loading into array................................................. 638 loading into array (optimized) ............................. 640 number of characters .......................................... 605 parsing a single line ............................................. 641 reading from disk................................................. 954 word count .......................................................... 652 Thread check if it is running ............................................. 913 comparing thread handles ................................... 909 handle of current................................................. 655 killing all from outside ......................................... 918 killing one from outside....................................... 919 putting to sleep .................................................. 1173 resume a single .................................................... 989 resume all ............................................................ 990 starting new ....................................................... 1150 stopping from outside ....................................... 1154 subscribe to a Mutex ......................................... 1164 subscribe to a Mutex immediately .................... 1166 suspending for seconds ..................................... 1117 synchronizing with second thread ....................... 916 system ID ............................................................. 667 using mutex ......................................................... 783 waiting for all ..................................................... 1199 xHarbour ID.......................................................... 668 ThreadSleep() ......................................................... 1173 Throw()........................................................... 178, 1174 Time ....................................................................... 1175 am/pm formatting ............................................... 400 converting to seconds........................................ 1118 difference............................................................. 589 seconds elapsed since midnight ........................ 1116 Time() ..................................................................... 1175 Tokenizer.................................................................. 699 Tone() ..................................................................... 1176 TopBarMenu() ........................................................ 1288 TOTAL ....................................................................... 360 Trace file................................................................... 347 adding an entry .................................................. 1177 TraceLog()............................................................... 1177 Transfer data .................................................... 488, 489 Transform() ............................................................ 1178 translate ..................................................see: #translate Trim()............................................................ 1110, 1180 TRY...CATCH ............................................................. 178 TString().................................................................. 1182 TXmlDocument() .................................................... 1299 TXmlIterator()......................................................... 1309 TXmlIteratorRegEx() ............................................... 1312 TXmlIteratorScan() ................................................. 1315 xHarbour Language Reference Guide

TXmlNode().............................................................1318 Type()......................................................................1183 typedef struct ...........................................................180 U U2bin()....................................................................1185 UNIQUE...................................................................1011 UNIQUE index .........................................................1011 UNLOCK.....................................................................362 UPDATE.....................................................................363 Updating of records .............................................................363 Upper case converting to lower case ......................................934 Upper()....................................................................1187 USE............................................................................365 Used()......................................................................1188 User-defined class........................................................................94 command............................................................1331 function ................................................................132 method .................................................................153 V Val().........................................................................1189 ValToPrg() ...............................................................1191 ValToPrgExp()..........................................................1193 Valtype() .................................................................1195 Version operating system................................................1060 Version() .................................................................1197 Virtual method..........................................................158 Visibility attribute for classes EXPORTED:............................................................120 HIDDEN:................................................................137 PROTECTED:..........................................................169 W W2bin() ...................................................................1198 WAIT .........................................................................367 WaitForThreads()....................................................1199 Waiting until a key is pressed ............................................367 WHILE condition and index creation................................................997 for index creation .................................................245 for sequential search............................................254 in database processing.........................................483 Wild card search .....................................................1044 WildMatch() ............................................................1200 Windows registry ....................................... see: Registry WITH OBJECT ............................................................183 changing the With object .....................................826 1423

Index nesting level ......................................................... 835 replacing the With object .....................................816 Word()..................................................................... 1202 Work area activating indexes ............................................... 1027 closing all files ..............................................211, 465 closing file..................................................... 215, 466 closing index files ............................................... 1029 closing index files (compatibility)......................... 463 determining the alias name..................................396 determining the field structure ............................387 evaluating a code block for each record ..............483 number of open indexes ....................................1000 number of records..............................................1098 opening database file ........................................... 542 opening file...........................................................365 retrieving configuration data ...............................496 retrieving number by alias name ....................... 1119 selecting ...............................................................277 selecting current................................................... 524 setting a scope....................................................1035 testing if a file is open ........................................1188 writing all file buffers ........................................... 217

1424

writing file buffers into the files ...........................467 X xHarbour C compiler used for build ..................................... 727 version................................................................ 1197 XML error description .................................................. 838 node in document .............................................. 1318 open document .................................................. 1299 searching document with RegEx ........................ 1312 searching node in document.............................. 1315 traversing document .......................................... 1309 Y Year displaying two or four digits ................................. 288 extracting from date value................................. 1203 Year() ......................................................................1203 Z ZAP............................................................................ 368

xHarbour Language Reference Guide

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF