Lotus Script Language Guide
Lotus Script Language Guide
Lotus Script Language Guide
Version7
G210-2374-00
Note: Before using this information and the product it supports, read the information in "Notices" at the end of this document.
First Edition (December, 2005) This edition applies to IBM Lotus Domino Designer 7 (product number L-GHUS-5RWNHM), and to all subsequent releases and modifications, until otherwise indicated in new editions. Copyright International Business Machines Corporation 1994, 2005. All rights reserved. US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
Contents
Chapter 1. Introduction to LotusScript. . 1
What is LotusScript? . . . . Advantages of LotusScript . . Working with scripts . . . Working in the script editor Working with Lotus software . Determining which product Debugging applications . . . . . . . . file . . . . . . is . . . . . . . . . . . being . . . . . . . . . . . . used . . . . . . . . . . . . . . . . 1 1 2 3 4 4 5 Dates/Time . . . . Referring to Variants . . . . . . . . . . . . . . . . . . 52 . 54
57
57 57 58 58 59 60 61 62 62 63 63 64 64 65 66 66 66 66 67 67 68 68 69 70 71 73 73 74 75 76 77 78 79 80 81 83 83 83 83 84 84 84 84 84 84
iii
Passing arguments by reference and by value . . 87 Assigning a return value to a function . . . . 89 Executing a user-defined function . . . . . . 90 Values that a function can manipulate . . . . 93 Subs . . . . . . . . . . . . . . . . . 96 Defining subs. . . . . . . . . . . . . 96 Executing a sub . . . . . . . . . . . . 97 Specialized subs . . . . . . . . . . . . 98 Properties . . . . . . . . . . . . . . . 99 Declaring and defining properties . . . . . . 99 Using properties . . . . . . . . . . . 100
Managing memory for objects . . . . Derived Classes . . . . . . . . . Property and method overriding . . . Arrays and lists of classes . . . . . . Working with object reference variables . Creating objects . . . . . . . . Using the Set statement . . . . . . Using Variants to hold object references Language cross-reference . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
147
. . . . . . . . 147 147 147 147 148 148 148 148
. . . . . . .
. 167 . 168
177
iv
Lotus software environments . . . . . . . . Determining which product file is being used Product classes and objects . . . . . . . . Interacting with the user . . . . . . . . . MsgBox on Notes server context . . . . . . Interacting with other programs . . . . . . . Functions and statements for working with other programs . . . . . . . . . . . . OLE Automation . . . . . . . . . . . Calling external C language functions . . . . . Example . . . . . . . . . . . . . . Declaring C functions . . . . . . . . . Passing arguments to C functions . . . . . Passing strings . . . . . . . . . . . . Passing arrays, types, and objects. . . . . . Using user-defined data type variables . . . . Return values . . . . . . . . . . . . Calling C language functions extended example LS2J: Connecting with Java . . . . . . . . . About LS2J . . . . . . . . . . . . . System requirements . . . . . . . . . . Using LS2J . . . . . . . . . . . . . LS2J classes . . . . . . . . . . . . . Data type mappings . . . . . . . . . . LS2J extended example . . . . . . . . .
177 177 177 180 182 182 182 184 185 186 186 187 188 190 192 193 194 195 195 195 195 200 225 227
Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . ArrayUnique function . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Language cross-reference . . . Examples: ArrayUnique function . Asc function . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Examples: Asc function . . . . ASin function . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: ASin function. . . . ATn function . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: ATn function . . . . ATn2 function . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: ATn2 function . . . Beep statement . . . . . . . . Syntax . . . . . . . . . . Usage . . . . . . . . . . Examples: Beep statement . . . Bin function . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Examples: Bin function . . . . Boolean data type . . . . . . . Usage . . . . . . . . . . Examples: Boolean data type . . Bracket notation . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Usage . . . . . . . . . . Examples: Bracket notation . . . Byte data type . . . . . . . . Usage . . . . . . . . . . Examples: Byte data type . . . Call statement . . . . . . . . Syntax 1 . . . . . . . . . Syntax 2 . . . . . . . . . Syntax 3 . . . . . . . . . Syntax 4 (functions only) . . . Elements . . . . . . . . . Usage . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
240 240 240 242 242 242 242 243 243 243 243 243 244 244 244 244 244 244 244 244 244 245 245 245 245 245 245 245 245 245 245 246 246 246 246 246 246 247 247 247 247 247 247 247 247 248 248 248 248 248 249 249 249 249 250 250 250 250 250 250 251
Contents
Referencing a function that returns an array, list, or collection . . . . . . . . . . Examples: Call statement . . . . . . . CBool function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Examples: CBool function . . . . . . . CByte function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Examples: CByte function . . . . . . . CCur function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Examples: CCur function . . . . . . . CDat function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Language cross-reference . . . . . . . Examples: CDat function . . . . . . . CDbl function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Language cross-reference . . . . . . . Examples: CDbl function . . . . . . . ChDir statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: ChDir statement . . . . . . . ChDrive statement . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: ChDrive statement . . . . . . Chr function. . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Chr function . . . . . . . . CInt function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Language cross-reference . . . . . . . Examples: CInt function . . . . . . . . Class statement . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Class statement . . . . . . . CLng function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
251 251 252 252 252 252 252 253 253 253 253 253 254 254 254 254 254 255 255 255 255 255 256 256 256 256 256 256 256 257 257 257 257 257 258 258 258 258 258 258 258 258 258 259 259 259 259 259 260 260 260 260 260 260 261 261 262 263 263 263
Return value . . . . . . . Language cross-reference . . . Examples: CLng function . . . Close statement . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Usage . . . . . . . . . . Examples: Close statement . . . CodeLock function . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return values . . . . . . . Usage . . . . . . . . . . Extended examples: lock functions CodeLockCheck function . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return values . . . . . . . Usage . . . . . . . . . . CodeUnlock function . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return values . . . . . . . Usage . . . . . . . . . . Command function . . . . . . Syntax . . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Examples: Command function . . Const statement . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Functions that can be evaluated as constants . . . . . . . . . Usage . . . . . . . . . . Examples: Const statement . . . Cos function . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: Cos function . . . . CreateLock function . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return values . . . . . . . Usage . . . . . . . . . . CreateObject function. . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Examples: CreateObject function . CSng function . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: CSng function . . . CStr function . . . . . . . . Syntax . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . LotusScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
263 263 263 264 264 264 264 264 264 264 264 264 265 265 266 266 266 266 266 266 266 266 266 267 267 267 267 267 267 267 267 267 268 268 269 269 269 269 269 270 270 270 270 270 270 270 270 270 270 271 271 272 272 272 272 272 272 272 273 273
vi
Return value . . . . . . Language cross-reference . . Examples: CStr function . . . CurDir function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: CurDir function . . CurDrive function . . . . . . Syntax . . . . . . . . . Return value . . . . . . Examples: CurDrive function . Currency data type . . . . . Usage . . . . . . . . . Examples: Currency data type . CVar function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Examples: CVar function . . DataType function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: DataType function . About data types . . . . . Date function . . . . . . . Syntax . . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Examples: Date function . . . Date statement . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Usage . . . . . . . . . Examples: Date statement . . DateNumber function . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Language cross-reference . . Examples: DateNumber function DateValue function . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: DateValue function . Day function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Language cross-reference . . Examples: Day function . . . Declare statement (external C calls) Syntax . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
273 273 273 273 273 273 274 274 274 274 274 274 274 274 274 275 275 275 275 275 275 275 276 276 276 276 276 277 277 277 278 278 278 278 279 279 279 279 279 279 279 279 280 280 280 280 280 280 281 281 281 281 281 281 281 281 282 282 282 282 282
Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Passing arguments . . . . . . . . . . Using LMBCS or Unicode strings . . . . . . Calling exported library functions in 32-bit versions of Windows . . . . . . . . . . Examples: Declare statement (external C calls) Declare statement (forward reference) . . . . . Syntax . . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Examples: Declare statement (forward reference) Deftypestatements . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Examples: Deftype statements . . . . . . . Delete statement . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Examples: Delete statement . . . . . . . . DestroyLock function . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Return values . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Dim statement . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Explicit declarations and implicit declarations Specifying the data type . . . . . . . . . Declaring arrays . . . . . . . . . . . Declaring lists . . . . . . . . . . . . Declaring object reference variables . . . . . Initializing variables . . . . . . . . . . Visibility of declarations . . . . . . . . . Examples: Dim statement . . . . . . . . Dir function . . . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Return value . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Examples: Dir function . . . . . . . . . Do statement . . . . . . . . . . . . . Syntax 1 . . . . . . . . . . . . . . Syntax 2 . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Terminating the loop . . . . . . . . . . Language cross-reference . . . . . . . . Examples: Do statement . . . . . . . . . Dot notation . . . . . . . . . . . . . . Syntax 1 . . . . . . . . . . . . . . Syntax 2 . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . . Examples: Dot notation . . . . . . . . . Double data type . . . . . . . . . . . . Usage . . . . . . . . . . . . . . .
Contents
282 284 284 284 285 285 285 285 285 287 287 287 287 288 288 289 289 289 289 289 289 290 290 290 290 290 290 290 291 292 292 292 292 293 293 293 293 294 295 295 295 296 296 296 296 296 296 297 297 297 297 297 297 297 298 298 298 298 298 298
vii
Examples: Double data type . . . . . End statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: End statement . . . . . . Environ function . . . . . . . . . . Syntax 1 . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Language cross-reference . . . . . . Examples: Environ function . . . . . EOF function . . . . . . . . . . . Syntax . . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: EOF function . . . . . . . Erase statement. . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Erase statement . . . . . . Erl function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Erl function . . . . . . . Err function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Err function . . . . . . . Err statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Err statement . . . . . . . Error function . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Language cross-reference . . . . . . Examples: Error function . . . . . . Error statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Error statement . . . . . . Evaluate function and statement . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Examples: Evaluate function and statement Execute function and statement . . . . . Statement Syntax . . . . . . . . . Function Syntax . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
299 299 299 299 299 299 299 299 299 300 300 300 300 300 300 301 301 301 301 301 301 302 302 302 302 302 302 302 303 303 303 303 303 303 304 304 304 304 304 304 304 304 305 305 305 305 305 305 306 306 306 306 307 307 307 307 307 307 307 308 308
Examples: Execute function and statement. Exit statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Exit statement . . . . . . Exp function . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Exp function . . . . . . . FileAttr function . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Examples: FileAttr function . . . . . . FileCopy statement . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: FileCopy statement . . . . . FileDateTime function . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Examples: FileDateTime function . . . . FileLen function . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Examples: FileLen function . . . . . . Fix function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Fix function . . . . . . . For statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Executing the loop the first time . . . . Executing the loop more than once . . . Exiting the loop early . . . . . . . Nested For loops . . . . . . . . . Language cross-reference . . . . . . Examples: For statement . . . . . . . ForAll statement . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Exiting the loop early . . . . . . . Using refVar . . . . . . . . . . . Language cross-reference . . . . . . Examples: ForAll statement. . . . . . Format function . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
308 309 309 309 309 310 310 310 310 310 310 311 311 311 311 311 311 311 311 312 312 312 312 312 312 312 313 313 313 313 313 313 313 313 313 313 314 314 314 314 314 315 315 315 315 315 315 315 316 316 316 316 316 317 317 317 317 318 319 319 319
viii
Return value . . . . . . . . . . . Formatting codes . . . . . . . . . . Numeric formats . . . . . . . . . . Named numeric formats . . . . . . . . Custom numeric formatting codes . . . . Date/time formats. . . . . . . . . . Named date/time formats . . . . . . . Custom date/time formatting codes . . . . String formatting codes . . . . . . . . Formatting dates and times in Asian languages Date/time format codes . . . . . . . . Examples: Format function . . . . . . . Fraction function . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Fraction function . . . . . . FreeFile function . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: FreeFile function . . . . . . FullTrim function . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Element . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Function statement . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Function statement . . . . . . Get statement . . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Get statement . . . . . . . GetFileAttr function . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: GetFileAttr function . . . . . GetObject function . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: GetObject function . . . . . . GetThreadInfo function . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return values . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: GetThreadInfo function . . . . GoSub statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: GoSub statement . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
319 319 319 319 320 321 321 322 323 324 324 325 327 327 327 327 327 327 327 327 327 328 328 328 328 328 328 328 329 329 329 330 330 331 332 332 332 333 334 334 334 334 334 334 335 335 335 335 335 336 337 337 337 337 337 338 338 338 338 338 338
GoTo statement . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Examples: GoTo statement . . . . Hex function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Examples: Hex function . . . . . Hour function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Language cross-reference . . . . Examples: Hour function . . . . If...GoTo statement . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Language cross-reference . . . . Examples: If...GoTo statement . . . If...Then...Else statement . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Language cross-reference . . . . Examples: If...Then...Else statement . If...Then...ElseIf statement . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Language cross-reference . . . . Examples: If...Then...ElseIf statement %If directive . . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Examples: %If directive . . . . . IMESetMode function . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return values . . . . . . . . Usage . . . . . . . . . . . Examples: IMESetMode . . . . . IMEStatus function . . . . . . . Syntax . . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Example . . . . . . . . . . Implode function . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Error handling . . . . . . . . Examples: Implode function . . . %Include directive . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
339 339 339 339 339 340 340 340 340 340 340 340 340 341 341 341 341 341 341 341 342 342 342 342 343 343 343 343 343 343 343 344 344 344 344 344 344 345 345 346 347 347 347 348 348 348 348 348 348 348 349 349 349 349 349 350 350 350 350 350 350
Contents
ix
Usage . . . . . . . . Examples: %Include directive Input # statement . . . . . Syntax . . . . . . . . Elements . . . . . . . Usage . . . . . . . . Examples: Input # statement Input function . . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: Input function . InputB function . . . . . Syntax . . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: InputB function . InputBox function . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Language cross-reference . Examples: InputBox function InputBP function . . . . . Syntax . . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: InputBP function InStr function . . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Language cross-reference . Examples: InStr function . InStrB function . . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: InStrB function . InStrBP function . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: InStrBP function . InStrC function . . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Int function . . . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: Int function . . Integer data type . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
351 351 351 351 351 352 353 353 353 354 354 354 354 354 354 355 355 355 355 355 355 356 356 356 356 356 357 357 357 357 357 357 357 358 358 358 359 359 359 359 359 360 360 360 360 360 360 361 361 361 361 361 361 361 362 362 362 362 362 362 362
Usage . . . . . . . . . Examples: Integer data type . IsArray function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Examples: IsArray function . . IsDate function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Examples: IsDate function . . IsDefined function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Examples: IsDefined function . IsElement function . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Examples: IsElement function . IsEmpty function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Examples: IsEmpty function . IsList function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Examples: IsList function . . IsNull function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: IsNull function . . IsNumeric function . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: IsNumeric function . IsObject function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Examples: IsObject function . IsScalar function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Examples: IsScalar function . . IsUnknown function . . . . . Syntax . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
362 363 363 363 363 363 363 363 363 363 363 364 364 364 364 364 364 364 365 365 365 365 366 366 366 367 367 367 367 367 367 367 367 367 368 368 368 368 368 368 368 368 368 368 369 369 369 369 369 370 370 370 370 370 370 370 370 370 371 371 371
Elements . . . . . . . . Return value . . . . . . Examples: IsUnknown function Join function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Error handling . . . . . . Language cross-reference . . Examples: Join function . . . Kill statement . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Usage . . . . . . . . . Example: Kill statement . . . LBound function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Example: LBound function . . LCase function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Example: LCase function . . Left function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Example: Left function . . . LeftB function . . . . . . . LeftBP function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Example: LeftBP function . . LeftC function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Example: LeftC function . . . Len function . . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Examples: Len function . . . LenB function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Examples: LenB function . . LenBP function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
371 371 371 372 372 372 372 372 372 372 373 373 373 373 373 373 373 373 373 373 373 374 374 374 374 374 374 374 374 374 374 374 375 375 375 375 375 375 375 376 376 376 376 376 376 376 376 376 377 377 377 377 378 378 378 378 378 379 379 379 379
Usage . . . . . . . . . . . LenC function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Let statement . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Example: Let statement . . . . . Line Input # statement . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Example: Line Input # statement . . ListTag function . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Example: ListTag function . . . . LOC function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Example: LOC function . . . . . Lock and Unlock statements . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Example: Lock and unlock statements LOF function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Example: LOF function . . . . . Log function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Example: Log function . . . . . Long data type . . . . . . . . . Usage . . . . . . . . . . . Example: Long data type . . . . LSet statement . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Example: LSet statement. . . . . LTrim function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Example: LTrim function . . . . MessageBox function and statement . . Function Syntax . . . . . . . Statement Syntax . . . . . . . Elements . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
379 379 380 380 380 380 380 380 380 381 381 381 381 382 382 382 382 382 382 382 382 383 383 383 383 383 383 384 384 384 384 384 385 385 385 385 385 385 386 386 386 386 386 386 386 386 386 387 387 387 387 387 387 387 388 388 388 388 388 388 388
Contents
xi
Return value . . . . . . . . Usage . . . . . . . . . . . Examples: MessageBox function and Mid function . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Language cross-reference . . . . Examples: Mid function . . . . . Mid statement . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Language cross-reference . . . . Examples: Mid statement . . . . MidB function . . . . . . . . . MidB statement . . . . . . . . MidBP function. . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Examples: MidBP function . . . . MidC function . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Minute function . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Language cross-reference . . . . Examples: Minute function . . . MkDir statement . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Examples: MkDir statement . . . Month function . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Language cross-reference . . . . Examples: Month function . . . . Name statement . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Usage . . . . . . . . . . . Examples: Name statement . . . Now function . . . . . . . . . Syntax . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Language cross-reference . . . . Examples: Now function . . . . Oct function . . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . . Return value . . . . . . . . Usage . . . . . . . . . . . Examples: Oct function . . . . .
. . . . . . . . statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
389 390 390 391 391 391 391 391 391 391 391 391 392 392 392 392 392 392 393 393 393 393 393 393 393 394 394 394 394 394 394 394 394 395 395 395 395 395 395 395 395 396 396 396 396 396 396 396 397 397 397 397 397 397 397 397 397 397 397 398 398
On Error statement . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . How does On Error work? . . . . . . . How does the error-handling routine work? Where are error numbers and messages defined? . . . . . . . . . . . . . Language cross-reference . . . . . . . Examples: On Error statement . . . . . On Event statement . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: On Event statement . . . . . On...GoSub statement . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: On...GoSub statement . . . . On...GoTo statement . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: On...GoTo statement . . . . . Open statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Open statement . . . . . . . Option Base statement . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Option Base statement . . . . Option Compare statement . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Option Compare statement . . . Option Declare statement . . . . . . . . Syntax . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Option Declare statement . . . Option Public statement . . . . . . . . . Syntax . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Option Public statement . . . . Print statement . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Print statement . . . . . . . Print # statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Print # statement . . . . . . Property Get/Set statements . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . .
. . . . .
398 398 398 398 399 399 399 399 399 400 400 400 401 401 401 401 401 402 402 402 402 402 403 403 403 404 404 406 406 407 407 407 407 407 407 407 408 408 408 409 409 409 410 410 410 410 410 410 410 411 411 412 412 412 412 413 413 413 414 415
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xii
Using Property Get . . . . . . . . . Using Property Set . . . . . . . . . Referencing a property that returns an array, list, or collection . . . . . . . . . . Passing a property to a function . . . . . Examples: Property Get/Set statements . . Put statement . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Put statement . . . . . . . Randomize statement . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Randomize statement . . . . . ReDim statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: ReDim statement . . . . . . Rem statement . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Language cross-reference . . . . . . . Examples: Rem statement . . . . . . . %Rem directive. . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Language cross-reference . . . . . . . Examples: %Rem directive . . . . . . . Replace function . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Language cross-reference . . . . . . . Examples: Replace function . . . . . . . Reset statement . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Reset statement . . . . . . . Resume statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Resume statement . . . . . . Return statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . . Usage . . . . . . . . . . . . . . Examples: Return statement . . . . . . Right function . . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . . Return value . . . . . . . . . . . Usage . . . . . . . . . . . . . . Language cross-reference . . . . . . . Examples: Right function . . . . . . . RightB function. . . . . . . . . . . .
. 415 . 415 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 416 416 416 417 417 417 418 419 419 419 419 419 419 420 420 420 421 421 421 422 422 422 422 422 422 422 422 423 423 423 423 423 424 424 425 425 425 425 425 425 426 426 426 426 426 427 427 427 427 427 427 428 428 428 428 428 428
RightBP function . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Language cross-reference . Examples: RightBP function RightC function . . . . . Syntax . . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: RightC function . RmDir statement . . . . . Syntax . . . . . . . Elements . . . . . . . Usage . . . . . . . . Examples: RmDir statement Rnd function . . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Language cross-reference . Examples: Rnd function . Round function . . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Language cross-reference . Examples: Round function . RSet statement . . . . . . Syntax . . . . . . . Elements . . . . . . . Usage . . . . . . . . Examples: RSet statement . RTrim function . . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Examples: RTrim function . Run statement . . . . . . Second function . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Language cross-reference . Examples: Second function . Seek function . . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: Seek function . Seek statement . . . . . . Syntax . . . . . . . Elements . . . . . . . Usage . . . . . . . . Examples: Seek statement . Select Case statement . . . . Syntax . . . . . . . Elements . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
428 428 428 429 429 429 429 429 429 429 429 429 430 430 430 430 430 430 430 430 430 430 431 431 431 431 431 431 432 432 432 432 432 432 432 433 433 433 433 433 433 433 433 433 434 434 434 434 434 434 434 435 435 435 435 435 436 436 436 436 437
Contents
xiii
Usage . . . . . . . . . . . . . Examples: Select Case statement . . . . SendKeys statement . . . . . . . . . Syntax . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: SendKeys statement . . . . Set statement . . . . . . . . . . . Syntax 1: Create an object and assign a reference . . . . . . . . . . . . Elements . . . . . . . . . . . . Syntax 2: Copy an existing object reference another variable . . . . . . . . . Elements . . . . . . . . . . . . Syntax 3: Associate a product object with a variable . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Set statement . . . . . . . SetFileAttr statement . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: SetFileAttr statement . . . . Sgn function . . . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Language cross-reference . . . . . . Examples: Sgn function . . . . . . . Shell function . . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Shell function . . . . . . Shellid function . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Shellid function . . . . . . Sin function . . . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Language cross-reference . . . . . . Examples: Sin function . . . . . . . Single data type . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Single data type . . . . . . Sleep statement . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Sleep statement . . . . . . Space function . . . . . . . . . . . Syntax . . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . .
. . . . . . . . . to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. 440 . 440 . 440 . 441 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 441 441 442 442 442 442 442 443 443 443 443 443 444 444 444 444 444 444 445 445 445 445 445 445 445 446 446 446 446 446 447 447 447 447 447 447 447 447 447 447 448 448 448 448 448 448
Examples: Space function . . Spc function . . . . . . . . Syntax . . . . . . . . Elements . . . . . . . . Usage . . . . . . . . . Examples: Spc function . . . Split function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Error Handling: . . . . . Language cross-reference . . Examples: Split function . . . Sqr function . . . . . . . . Syntax . . . . . . . . Elements . . . . . . . . Return value . . . . . . Language cross-reference . . Examples: Sqr function . . . Stop statement . . . . . . . Syntax . . . . . . . . . Usage . . . . . . . . . Str function . . . . . . . . Syntax . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: Str function . . . StrCompare function . . . . . Syntax . . . . . . . . Elements . . . . . . . . Return value . . . . . . Language cross-reference . . Examples: StrCompare function StrConv function . . . . . . Syntax . . . . . . . . Elements . . . . . . . . Return value . . . . . . Usage . . . . . . . . . Language cross-reference . . Examples: StrConv function . StrLeft function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Language cross-reference . . StrLeftBack function . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Language cross-reference . . StrRight function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . Language cross-reference . . StrRightBack function . . . . Syntax . . . . . . . . . Elements . . . . . . . . Language cross-reference . . StrToken function . . . . . . Syntax . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
448 448 448 448 449 449 449 449 449 450 450 450 450 451 451 451 451 451 451 451 451 451 451 452 452 452 452 452 452 452 452 453 453 453 453 453 454 454 454 454 455 455 455 455 455 455 456 456 456 456 457 457 457 457 457 457 457 458 458 458 458
xiv
Elements . . . . . . . Return value . . . . . Usage . . . . . . . . Error Handling . . . . . Language cross-reference . Examples: StrToken function String data type . . . . . Usage . . . . . . . . Examples: String data type . String function . . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Examples: String function . Sub statement . . . . . . Syntax . . . . . . . Elements . . . . . . . Usage . . . . . . . . Examples: Sub statement . Sub Delete . . . . . . . Syntax . . . . . . . . Usage . . . . . . . . Examples: Sub Delete. . . Sub Initialize . . . . . . Syntax . . . . . . . . Usage . . . . . . . . Examples: Sub Initialize . . Sub New . . . . . . . . Syntax . . . . . . . . Elements . . . . . . . Usage . . . . . . . . Examples: Sub New . . . Sub Terminate . . . . . . Syntax . . . . . . . Usage . . . . . . . . Examples: Sub Terminate . Tab function . . . . . . . Syntax . . . . . . . Elements . . . . . . . Usage . . . . . . . . Language cross-reference . Examples: Tab function . . Tan function . . . . . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Language cross-reference . Examples: Tan function . . Time function . . . . . . Syntax . . . . . . . Return value . . . . . Usage . . . . . . . . Examples: Time function . Time statement . . . . . . Elements . . . . . . . Examples: Time statement . TimeNumber function . . . Syntax . . . . . . . Elements . . . . . . . Return value . . . . . Usage . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
458 459 459 459 459 459 460 460 460 460 460 461 461 461 461 461 461 462 462 463 464 464 464 464 465 465 465 465 465 465 466 466 467 467 467 467 468 468 468 468 468 468 469 469 469 469 469 469 469 469 469 469 470 470 470 470 470 470 470 470 470
Examples: TimeNumber function Timer function . . . . . . . . Syntax . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Examples: Timer function . . . TimeValue function . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Language cross-reference . . . Examples: TimeValue function . Today function . . . . . . . . Syntax . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Language cross-reference . . . Examples: Today function . . . Trim function . . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: Trim function . . . Type statement . . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . . Usage . . . . . . . . . . Defining types . . . . . . . Declaring type members . . . Declaring a type variable . . . Referring to type members . . Examples: Type statement . . . TypeName function . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Language cross-reference . . . Examples: TypeName function . UBound function . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Examples: UBound function . . UCase function . . . . . . . . Syntax . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Usage . . . . . . . . . . Language cross-reference . . . Examples: UCase function . . . UChr function . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . . Return value . . . . . . . Examples: UChr function . . . Uni function . . . . . . . . . Syntax . . . . . . . . . . Elements . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
471 471 471 471 471 471 471 471 471 471 472 472 472 472 472 472 472 472 472 472 472 473 473 473 473 473 473 473 474 474 474 474 474 475 475 476 476 476 476 477 477 477 477 477 478 478 478 478 478 478 478 478 478 478 479 479 479 479 479 479 479
Contents
xv
Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Uni function . . . . . . . Unlock statement . . . . . . . . . . Use statement . . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Loading a used module . . . . . . . Referring to Public names in a used module Declaring Public names . . . . . . . Examples: Use statement . . . . . . UseLSX statement . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: UseLSX statement . . . . . UString function . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: UString function . . . . . Val function . . . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Val function . . . . . . . Variant data type . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Variant data type . . . . . Weekday function . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Return value . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: Weekday function . . . . . While statement . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Language cross-reference . . . . . . Examples: While statement . . . . . Width # statement . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: Width # statement . . . . . With statement . . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . . Examples: With statement . . . . . . Write # statement . . . . . . . . . . Syntax . . . . . . . . . . . . Elements . . . . . . . . . . . . Usage . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
479 479 479 479 480 480 480 480 480 480 480 480 480 480 481 481 481 482 482 482 482 482 482 482 482 482 482 483 483 483 483 483 483 484 485 485 485 485 485 485 485 485 485 486 486 486 486 486 486 486 487 487 487 487 487 488 488 488 488 488 489
Examples: Write # statement . . . . Year function . . . . . . . . . . Syntax . . . . . . . . . . . Elements . . . . . . . . . . . Return value . . . . . . . . . Language cross-reference . . . . . Examples: Year function . . . . . Yield function and statement . . . . . Syntax . . . . . . . . . . . Return value . . . . . . . . . Usage . . . . . . . . . . . . Examples: Yield function and statement
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
489 490 490 490 490 490 491 491 491 491 491 491
Appendix C LotusScript/REXX Integration . . . . 505 Appendix D LotusScript Aliases . . . . . . . . . . . . . . 507 Appendix E MIME Charset Names . . . . . . . . . . . . . . 509 Appendix F Compile-time Error Messages . . . . . . . . . . 511
DELETE not valid on: <name> . Too many nested INCLUDEs . . . . . . . . . . . . . . 511 . 511
xvi
File contains too many source lines . . . . . . Illegal OPTION BASE after array declaration . . . Illegal OPTION DECLARE after implicit declaration . . . . . . . . . . . . . . Too many items specified in input/output statement . . . . . . . . . . . . . . . Illegal value for OPTION BASE . . . . . . . Too many labels specified in ON...GOTO statement SUB NEW arguments do not match parents SUB NEW arguments . . . . . . . . . . . . Name previously declared: <name> . . . . . . Class is not a parent of this class: <class name> . . Illegal name for class or type: <name> . . . . . Public symbol is declared in another module: <name> . . . . . . . . . . . . . . . Member is not a subprogram: <member name> . . Illegal executable code at the module level . . . Illegal PUBLIC instance of PRIVATE class or type: <instance name>. . . . . . . . . . . . . Illegal type suffix on name: <name> . . . . . . ISELEMENT argument is not a list or variant: <name> . . . . . . . . . . . . . . . Illegal scope for PUBLIC or PRIVATE on: <name> Illegal constructor clause on: <sub name> . . . . Parent SUB NEW has arguments, SUB NEW is required for: <class name> . . . . . . . . . Illegal USE or UseLSX statement after declaration Member declared in a parent class . . . . . . Event handler must be a LotusScript SUB or FUNCTION: <handler name> . . . . . . . . Member of PUBLIC class or type is instance of a PRIVATE class or type: <member name> . . . . . FORALL alias variable was previously declared: <name> . . . . . . . . . . . . . . . FORALL alias variable already in use: <variable name> . . . . . . . . . . . . . . . . CASE ELSE must be the last CASE in a SELECT statement . . . . . . . . . . . . . . . TYPE declaration has no members . . . . . . Declaration of external subprogram is not legal inside a class . . . . . . . . . . . . . Illegal use of array or list element as FORALL target . . . . . . . . . . . . . . . . Illegal use of property: <property name>. . . . . Wrong data type for argument <argument name> in event handler <event handler name> . . . . . . Maximum array dimensions (8) exceeded: <array name> . . . . . . . . . . . . . . . . Illegal array bound for: <array name> . . . . . Array size exceeds maximum: <array name> . . . Illegal specification of array bounds for: <array name> . . . . . . . . . . . . . . . . Declaration not valid in TYPE scope: <name> . . . Statement is illegal in TYPE block: <keyword> . . Statement is illegal in CLASS block: <keyword> . . TYPE may not have instance of itself as a member: <instance name>. . . . . . . . . . . . . Out of memory . . . . . . . . . . . . . Size of data cannot exceed 64K in this scope . . . Size of data cannot exceed 32K in this scope . . . Illegal constant expression for: <CONST name> . .
511 511 511 511 512 512 512 512 513 513 513 514 514 514 514 514 514 515 515 515 515 516 516 516 516 517 517 517 517 517 518 518 518 518 518 518 519 519 519 519 520 520 520
Arguments not legal in declaration of: <sub name> Undefined label: <label name> . . . . . . . . Illegal data type for argument: <argument name> Too many arguments for: <subprogram name> . . . Cannot subclass: <class name> . . . . . . . . Derived class may not be PUBLIC when parent is PRIVATE: <class name> . . . . . . . . . . Illegal use of NEW or DELETE . . . . . . . DIM required on declarations in this scope . . . Illegal PRIVATE declaration of: <name> . . . . . Illegal PUBLIC declaration of: <name> . . . . . Name was forward declared as something else: <name> . . . . . . . . . . . . . . . Duplicate forward declaration: <name> . . . . . Storage class or visibility does not match forward declaration: <subprogram name> . . . . . . . Return type does not match forward declaration: <function name> . . . . . . . . . . . . Number of arguments does not match forward declaration: <subprogram name> . . . . . . . Argument does not match forward declaration: <argument name> . . . . . . . . . . . . Illegal function return type for: <function name> Method was declared as something else in a parent: <method name> . . . . . . . . . . Method signature does not match parent method: <method name> . . . . . . . . . . . . . PROPERTY GET and SET must have same storage class and visibility . . . . . . . . . . . . Illegal property type for: <property name> . . . . PROPERTY GET and SET must have same data type . . . . . . . . . . . . . . . . Property was declared as something else in a parent: <property name> . . . . . . . . . . Property type does not match parent property: <property name> . . . . . . . . . . . . Illegal pass by value: <argument name> . . . . . Illegal STATIC on: <name> . . . . . . . . . Illegal external argument: <argument name> . . . Illegal construction of type instance: <instance name> . . . . . . . . . . . . . . . . Class or type name not found: <name> . . . . . Illegal range specifier . . . . . . . . . . . Illegal DEFtype statement after declaration. . . . Duplicate range specifier . . . . . . . . . Label is illegal outside of a subprogram . . . . Error number must be INTEGER constant: <name> Error number must be INTEGER . . . . . . . Illegal ON ERROR statement . . . . . . . . Statement is illegal outside of a subprogram . . . Not a product class: <name> . . . . . . . . Not a product class instance: <name> . . . . . Not an event name: <name> . . . . . . . . Not a sub or function name: <name> . . . . . Illegal REDIM on: <name> . . . . . . . . . Illegal RESUME statement . . . . . . . . . FOR count variable already in use: <name> . . . FORALL alias variable is not of same data type: <name> . . . . . . . . . . . . . . . FOR count variable must be a scalar variable: <name> . . . . . . . . . . . . . . .
Contents
520 520 521 521 521 521 521 521 521 522 522 522 522 522 523 523 523 524 524 524 525 525 525 525 526 526 526 526 527 527 527 528 528 528 528 528 528 529 529 529 529 529 530 530 530 530
xvii
Illegal type suffix on FORALL alias variable: <name> . . . . . . . . . . . . . . . Not a PUBLIC member: <name> . . . . . . . Illegal reference to FORALL alias variable: <name> Type suffix does not match data type: <name> . . Not a member: <name> . . . . . . . . . . Variable not declared: <name> . . . . . . . . Illegal single-line IF . . . . . . . . . . . Name does not match FOR count variable: <name> Not an array, list, collection or variant: <name> . . ME not valid outside of class scope . . . . . . .. not valid outside of class scope . . . . . . . Reference must contain exactly one subscript: <name> . . . . . . . . . . . . . . . Illegal parenthesized reference: <name> . . . . . Wrong number of array subscripts for: <array name> . . . . . . . . . . . . . . . . Not an instance name: <name> . . . . . . . Bounds must be specified in REDIM of: <array name> . . . . . . . . . . . . . . . . Variable required: <name> . . . . . . . . . Named product class instance not valid here . . . Illegal reference to: <name> . . . . . . . . . Numeric overflow . . . . . . . . . . . . Numeric underflow . . . . . . . . . . . Illegal numeric constant . . . . . . . . . . Illegal product constant: <name> . . . . . . . Name too long: <name> . . . . . . . . . . Token is too long . . . . . . . . . . . . Declaration may not contain type suffix and data type: <name> . . . . . . . . . . . . . Illegal string length constant for: <name> . . . . Illegal use of NEW on array or list declaration: <name> . . . . . . . . . . . . . . . INCLUDE filename must be a string constant . . Cannot open included file: <file name> . . . . . Unterminated %REM block . . . . . . . . . Unterminated string constant . . . . . . . . Unterminated multiline string . . . . . . . . Unterminated square bracket reference . . . . . Illegal character after continuation character . . . Illegal character after %INCLUDE directive . . . SET required on class instance assignment. . . . Unterminated <keyword> block . . . . . . . Unexpected: <token>; Expected: <token> . . . . Parser stack overflow at: <token name> . . . . . Unknown statement . . . . . . . . . . . Maximum number of errors reached. . . . . . PROPERTY SET not defined for: <property name> PROPERTY GET not defined for: <property name> Duplicate option . . . . . . . . . . . . Missing argument for: <function name> . . . . . Expected expression before end of argument list for: <function name> . . . . . . . . . . . Wrong number of arguments for: <name> . . . . LISTTAG argument is not a FORALL alias variable Type mismatch on: <name> . . . . . . . . . Illegal BYVAL on arguments to: <subprogram name> Illegal TO in reference to: <name> . . . . . . Illegal BYVAL . . . . . . . . . . . . . Duplicate label: <label name> . . . . . . . .
530 531 531 531 531 531 531 532 532 532 532 532 533 533 533 533 533 534 534 534 535 535 535 535 535 535 536 536 536 536 536 536 537 537 537 537 537 538 538 539 539 539 539 539 539 540 540 540 540 540 542 542 542 542
Illegal EXIT <EXIT type> . . . . . . . . . Illegal OPTION PUBLIC after declaration . . . . Illegal use of ERASE . . . . . . . . . . . SET may only be used on class instance assignments . . . . . . . . . . . . . . Illegal pass by value . . . . . . . . . . . Wrong number of arguments to constructor for class: <class name> . . . . . . . . . . . . Illegal reference to array or list: <array or list name> Illegal type suffix on keyword: <keyword> . . . . Compiler statement stack overflow at: <token name> . . . . . . . . . . . . . . . . Maximum allowable code size exceeded . . . . Maximum allowable data size exceeded . . . . Maximum allowable symbol table size exceeded PUBLIC is not allowed in this module . . . . . Illegal call to: <sub name> . . . . . . . . . Empty parentheses not legal on: <name> . . . . Illegal use of parentheses . . . . . . . . . Class not specified on BIND into: <name>. . . . Illegal Directive . . . . . . . . . . . . Unterminated %IF, %ELSEIF, or %ELSE directive Illegal character after directive . . . . . . . . LIB name must be a string constant . . . . . . USE or USELSX name must be a string constant EVALUATE argument must be a string constant Illegal second parenthesized expression . . . . Statement is illegal in a subprogram . . . . . . Illegal use of UNICODE or LMBCS keyword . . . UNICODE and LMBCS strings must be declared BYVAL . . . . . . . . . . . . . . . Too many nested WITHs . . . . . . . . . Illegal use of escape character in identifier: <name> Illegal use of escape character . . . . . . . . Error in EVALUATE macro . . . . . . . . . Name previously referenced in this scope . . . . Wrong number of arguments for event handler: <sub name> . . . . . . . . . . . . . . Property is read-only: <property name> . . . . Missing array subscript or collection index for: <name> . . . . . . . . . . . . . . . Missing argument to constructor for: <class name> Missing array bound for: <array name> . . . . LEN argument must be a variable or string expression . . . . . . . . . . . . . . Missing collection index for: <name> . . . . . Missing list subscript for ISELEMENT argument: <list name> . . . . . . . . . . . . . . Cannot assign into collection item . . . . . . Cannot forward declare CLASS or TYPE . . . . CLASS or TYPE declaration may not be inside a control block . . . . . . . . . . . . . Procedure declaration may not be inside a control block . . . . . . . . . . . . . . . . Product class does not have a New method: <class name> . . . . . . . . . . . . . . . . Collection item is not an instance . . . . . . . Illegal on declarations in this scope: <keyword> . . Wrong return type in event handler <handler_name> . . . . . . . . . . . . . Event handler must be a FUNCTION . . . . .
543 543 543 543 543 544 544 545 545 545 545 545 545 546 546 546 546 547 547 547 547 547 548 548 548 548 549 549 549 549 549 549 550 550 550 550 551 551 551 551 552 552 552 552 552 552 552 553 553
xviii
Event handler must be a SUB . . . . . . . . Conflicting option . . . . . . . . . . . . PROPERTY GET and SET arguments do not match: <property_name> . . . . . . . . . . . . Number of arguments do not match for PROPERTY GET and SET <property_name> . . . Property signature does not match parent property: <property name> . . . . . . . . . . . . Type suffix character required on: <name> . . . . Must be a sub: <procedure_name> . . . . . . .
Unable to open file . . . . . . . . . . Illegal operation for file mode . . . . . . . Data too big for record . . . . . . . . . Bad attribute . . . . . . . . . . . . Cannot set attribute for file . . . . . . . . List item does not exist . . . . . . . . . Cannot find module <module name> . . . . . Cannot find external name <name> . . . . . Type mismatch on external name <name> . . . Module already loaded . . . . . . . . . Invalid module file . . . . . . . . . . Compiler error . . . . . . . . . . . . Opcode <opcode name> not implemented . . . Named product object does not exist . . . . ADT error: Control procedure missing . . . . Bad argument to external function . . . . . Unsupported argument type to external function Unsupported return type for external function . External function not found . . . . . . . Event handler not attached . . . . . . . . Module in use . . . . . . . . . . . . Illegal circular USE: <module name> . . . . . Too many calls into module . . . . . . . LISTTAG argument not a list element . . . . Illegal REDIM of fixed array . . . . . . . Array size exceeds maximum limit . . . . . Illegal LIKE pattern . . . . . . . . . . Error in constant expression evaluation . . . . Operation not supported on this platform . . . Type suffix does not match actual data type . . Instance member does not exist . . . . . . Variant does not contain an object . . . . . Variant does not contain a container . . . . . Wrong number of arguments for method . . . Name used as a method is not a method . . . Illegal use of sub . . . . . . . . . . . Illegal use of function . . . . . . . . . Illegal use of property . . . . . . . . . Illegal use of read-only property . . . . . . List reference must contain exactly one subscript Illegal DELETE . . . . . . . . . . . . Not a product object . . . . . . . . . . Event does not exist . . . . . . . . . . Event handler argument count mismatch . . . Event handler argument type mismatch . . . Not a PUBLIC member . . . . . . . . . Missing argument . . . . . . . . . . . Operation is disallowed in this session . . . . Attempt to access an uninitialized dynamic array Error loading USE or USELSX module . . . . Wrong number of collection indices . . . . . Not a collection object . . . . . . . . . Collection item not found . . . . . . . . Underflow . . . . . . . . . . . . . SET required on class instance assignment. . . Invalid Collection item . . . . . . . . . Automation-Object error. . . . . . . . . Automation-Object cannot create . . . . . . Automation-Object file name error . . . . . Automation-Object member not found . . . . Automation-Object argument count . . . . .
Contents
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
563 563 563 564 564 564 564 564 564 564 565 565 565 565 565 565 565 565 566 566 566 566 566 566 567 567 567 567 568 568 568 568 568 568 569 569 569 570 570 570 570 571 571 571 571 572 572 572 572 573 573 573 573 573 573 574 574 574 574 574 574
xix
Automation-Object argument type mismatch . ForAll container invalid or modified . . . Out of system stack space . . . . . . . Illegal REDIM . . . . . . . . . . . Error creating product object . . . . . . Error accessing product object property . . Error accessing product object method . . . Error accessing product object . . . . . . Error in EVALUATE macro . . . . . . . Event handler return type mismatch . . . . Event handler procedure type mismatch . . Wrong number of arguments for PROPERTY .
. . . . . . . . . . . .
. . . . . . . . . . . .
575 575 575 575 576 576 576 576 576 576 576 576
Illegal use of MEMBER . . . . PROPERTY SET not defined . . PROPERTY GET not defined . . String too large . . . . . . . Variable is read-only . . . . . Unknown class instance . . . . Cannot assign into collection item Wrong number of array subscripts
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
Index . . . . . . . . . . . . . . . 579
xx
What is LotusScript?
LotusScript is an embedded, BASIC scripting language with a powerful set of language extensions that enable object-oriented application development within and across Lotus software applications. LotusScript allows you to place more complex scripts in a greater variety of locations and events than traditional macros. LotusScript and its development toolset provide a common programming environment across Lotus applications on all platforms supported by Lotus software (such as Windows, AIX, Linux). It is available in: v IBM Lotus Notes Release 4 and later v IBM Lotus Approach 96 Edition and later v IBM Lotus Freelance Graphics 96 Edition and later v IBM Lotus Word Pro 96 Edition and later v IBM Lotus 1-2-3 97 Edition and later v IBM Lotus Enterprise Solution Builder LotusScript offers a wide variety of features. Its interface to Lotus software is through predefined object classes. The products oversee the compilation and loading of user scripts and automatically include class definitions to allow more efficient coding. LotusScript extends the development capabilities of Lotus software by providing: v The ability to place scripts in a variety of objects and events in many Lotus software applications. LotusScript has a set of extensions beyond Visual Basic, that provide additional power and utility when writing applications using Lotus software. v A debugger and syntax-directed editor. v Access to a broad range of product functions through the classes defined for each product. v Access to external class libraries defined using the the LSX Toolkit. The environment in which you write, debug, and run scripts depends on your Lotus software application. To learn about your products programming environment, see your product documentation.
Advantages of LotusScript
LotusScript offers the following advantages: v Superset of BASIC Since LotusScript is a superset of the BASIC language, it is easy to learn, especially for Visual Basic users. You can write sophisticated scripts using conditions, branches, subroutines, while loops, and other conventions. v Cross-platform LotusScript is a multi-platform BASIC-like scripting language. It works with platforms such as Windows, Macintosh, OS/2, UNIX, z/OS, and OS/400. Scripts developed on Windows execute unchanged on any other supported platform. This portability is important as desktop applications become workgroup-enabled and documents are e-mailed to or shared by users.
v Object-oriented Lotus software provides Object Classes that are available to LotusScript. You can write scripts to access and manipulate these objects. The scripts are event-driven, such as by an action, clicking the object or button, opening a document, or opening a view. LotusScript gives you the ability to create your own classes and objects, and easily subclass these classes. v Included in Lotus software applications LotusScript is supported by Lotus software, so these products can access product classes using a product-supplied LotusScript extension. You can use one language to write scripts in different Lotus software applications. v OLE support Using LotusScript, you can create Notes containers for documents created with IBM Lotus SmartSuite applications and other OLE-enabled applications, such as Microsoft Office. You can use external OLE 2.0 automation objects by scripting them, such as 1-2-3 worksheet objects. Notes registers itself as an OLE automation server. External applications can use these objects in scripts to create and reference them. LotusScript can combine all the parts and provide the means for controlling and manipulating objects. v Interoperability with other languages You can call formula language and @functions from LotusScript. You can also call Java and JavaScript. v Integrated Development Environment The LotusScript Integrated Development Environment (IDE) provides an interface to create, edit, and debug scripts, and to browse variables and properties of classes. The IDE allows you to write more complex scripts in Notes. v LotusScript libraries You can create function and class libraries in the language and reuse them in other applications or Lotus software applications via the USE statement language extension. v Extendable through Lotus Software Extensions (LSXs) LotusScript allows users to create their own classes and objects, called Lotus software extensions (LSXs). LotusScript classes support single inheritance, constructors/destructors and method overriding. This functionality allows users to take advantage of object-oriented programming, and to rapidly prototype their own custom business objects. For more information about LSXs, visit the Lotus Developer Network at http://www.lotus.com/home.nsf/welcome/developernetwork.
Besides direct user manipulation, Lotus software applications or the system can also initiate events. For example, editing a document in a database is an event that is internal to a database application.
Compiling scripts
An application must be compiled before it will load and execute. When you compile a script, LotusScript displays messages about any errors it finds, listed in the order in which they are found. There are two types of errors: v Compile-time error Occurs when a script contains an error that LotusScript detects during compilation. You need to fix it before the script can compile and run. v Run-time error Occurs when a script contains an error that could not be predicted during compilation. When one occurs, script execution ends unless your script includes statements to handle the error. As you fix errors, you recompile until there are no more errors in the script. You can compile your scripts explicitly, using your products menu commands, or you can compile them automatically when you save the application or when you run it. For information about whether your product allows you to compile scripts explicitly or implicitly, see the product documentation. For more information about errors, see Error Processing.
You create the script using your script editor, or any text editor. The script can contain LotusScript declarations, subs, and functions, and can define and declare product classes, properties, subs, and functions. Note: Notes does not allow you to save .lso files directly. Notes saves the object modules within itself. To load a compiled LotusScript module, put a Use statement in a script at module level, before all implicit declarations. For more information, see the product documentation.
If you place the Use statement in a declarations section, any public declarations, subs, and procedures in the used module are available to the scripts in the corresponding module. If your Lotus software provides a Public script, place the Use statement in this script to make Public declarations and procedures in the used module available to the scripts in the application. If you then change the name or extension of the module, LotusScript cant use the script module, because the original file name is embedded in the compiled module. To change the file name, you must rename the source file and compile the .LSO file.
Dim message As String, messageTitle As String messageTitle$ = Command$ ... ... Use messageTitle$ as the title of a message box. message = "This is a test." MessageBox message$, messageTitle$
Debugging applications
The debugger helps you find logic errors in an application. If your application compiles without errors but does not yield the results you expect, the debugger can help locate the place in your scripts where something went wrong. The debugger can: v Run the application until LotusScript reaches a breakpoint or Stop statement. A breakpoint is a statement at which you want to interrupt application execution. v Execute one statement, then stop and give control to the debugger. When you run an application with the debugger, the application is either running or interrupted. When you debug an application, some Lotus software applications allow you to inspect variables and edit their values. For more information, see the product documentation.
Example
One statement on one line Print "One line" One statement on two lines; extra white space Print "One" & _ Comment allowed here "Two" Two statements on one line Print "One" : Print "Two"
Example 7.77E+02
Binary number
&B1100101
Long
The legal range is the range % forces Integer for Long values. A binary & forces Long integer is expressible in 32 binary digits of 0 or 1. Values >= &B100000 ... (31 zeroes) represent negative numbers. The legal prefix is &B. An octal integer is % forces Integer expressible in up to 11 octal digits of 0 to 7. If the number & forces Long falls within the range for Integer values, its data type is Integer; otherwise, its data type is Long.
Octal number
&O1411
Long Values >= &O40000000000 are out of range. Values >= &O20000000000 represent negative numbers.
Hexadecimal number
&H309
Long. Values = > &H80000000 represent negative numbers. Negative signs (-) are not allowed.
A hexadecimal number is % forces Integer expressible in 1 to 8 significant hexadecimal digits & forces Long (excluding leading zeroes). If the number falls within the range for Integer values, its data type is Integer; otherwise, its data type is Long.
To include one of the closing delimiter characters , |, or } as text within a string delimited by that character, double it.
|A bar string with a bar || in it|
The empty string has no characters at all; it is represented by . Strings delimited by vertical bars, braces, or double quotation marks cannot be nested.
"A "A |A {A
quoted string with {braces} and a bar | in it" quoted string with ""quotes"" in it" bar string with a bar || in it| brace string with {braces}} in it}
Examples
$ is illegal as character in identifier Call ProductClass.LoMethod$ Illegal Call ProductClass.LoMethod~$ Legal X = OLEClass.Hi@Prop X = OLEClass.Hi~@Prop Illegal Legal
Labels
A label gives a name to a statement. A label is built in the same way as an identifier. These statements transfer control to a labeled statement by referring to its label: v GoSub v v v v v v GoTo If...GoTo On Error On...GoSub On...GoTo Resume
The following rules govern the use of labels in a script: v A label can only appear at the beginning of a line. It labels the first statement on the line. v A label can appear on a line by itself. This labels the first statement starting after the line. v The last character of a label must be a colon (:). v A label cant be suffixed with a data type suffix character. v A given statement can have more than one label preceding it; but the labels must appear on different lines.
Chapter 2. Script and Statement Construction Rules
v A given label cant be used to label more than one statement in the same procedure.
Keywords
A keyword is a word with a reserved meaning in the LotusScript language. The keywords name LotusScript statements, built-in functions, built-in constants, and data types. The keywords New and Delete can be used to name subs that you can define in a script. Other keywords are not names, but appear in statements: for example, NoCase or Binary. Some of the LotusScript operators are keywords, such as Eqv and Imp. Note: You cannot redefine keywords in a script, with one exception: keywords can name variables within a type, and variables and procedures within a class.
C Call CDat Chr$ CodeLock Compare CStr Currency Case CDbl CInt CodeLockCheck Const CurDir CVar CBool ChDir Class CodeUnlock Cos CurDir$ CVDate CByte ChDrive CLng Command CreateLock CurDrive CCur Chr Close Command$ CSng CurDrive$
D DataType DateValue DefCur DefStr Dir Date Day DefDbl DefVar Dir$ Date$ Declare DefInt Delete Do DateNumber DefBool DefLng DestroyLock DoEvents DateSerial DefByte DefSng Dim Double
E Else %End Erase %Else Environ Erl ElseIf Environ$ Err %ElseIf EOF Error End Eqv Error$
10
F FALSE Fix Fraction FileAttr For FreeFile FileCopy ForAll From FileDateTime Format FullTrim FileLen Format$ Function
I If Implode Input$ InputBP InStrC IsArray IsNull %If Implode$ InputB InputBP$ Int IsDate IsNumeric IMESetMode In InputB$ InStr Integer IsElement IsObject IMEStatus %Include InputBox InStrB Is IsEmpty IsScalar Imp Input InputBox$ InStrBP IsA IsList IsUnknown
J Join
K Kill
L LBound LeftB LeftC$ Let ListTag Log LSServer LCase LeftB$ Len Lib LMBCS Long LTrim LCase$ LeftBP LenB Like LOC Loop LTrim$ Left LeftBP$ LenBP Line Lock LSet Left$ LeftC LenC List LOF LSI_Info
11
M MidB$ - (Minus sign) MsgBox MidBP Minute MidBP$ MkDir MidC Mod MidC$ Month
P PI Private Pitch Property + (Plus sign) Public Preserve Published Print Put
R Random Remove Right RightBP$ Round Randomize Replace Right$ RightC RSet Read Reset RightB RightC$ RTrim ReDim Resume RightB$ RmDir RTrim$ Rem Return RightBP Rnd
S Second SetAttr Sin Spc Stop StrConv StrLeftBack StrRightBack$ Seek SetFileAttr Single Split Str String StrLeftBack$ StrToken Select Sgn Sleep Sqr Str$ String$ StrRight StrToken$ SendKeys Shared Space Static StrComp StrLeft StrRight$ Sub Set Shell Space$ Step StrCompare StrLeft$ StrRightBack
T Tab Time$ To Type Tan TimeNumber Today TypeName Text Timer Trim Then TimeSerial Trim$ Time TimeValue TRUE
12
X Xor
Y Year Yield
Special characters
LotusScript uses special characters, such as punctuation marks, for several purposes: v To delimit literal strings v v v v To To To To designate variables as having particular data types punctuate lists, such as argument lists and subscript lists punctuate statements punctuate lines in a script
Note: Special characters within literal strings are treated as ordinary text characters. The following table summarizes the special characters used in LotusScript:
Character (quotation mark) | (vertical bar) {} (braces) : (colon) $ (dollar sign) Opening and closing delimiter for a multi-line literal string. To include a vertical bar in the string, use double bars ( || ). Delimits a multi-line literal string. To include an open brace in the string, use a single open brace ({). To include a close brace in the string, use double close braces (}}). (1) Separates multiple statements on a line. (2) When following an identifier at the beginning of a line, designates the identifier as a label. (1) When suffixed to the identifier in a variable declaration or an implicit variable declaration, declares the data type of the variable as String. (2) When prefixed to an identifier, designates the identifier as a product constant. Usage Opening and closing delimiter for a literal string on a single line.
13
Usage (1) When suffixed to the identifier in a variable declaration or an implicit variable declaration, declares the data type of the variable as Integer. (2) When suffixed to either the identifier or the value being assigned in a constant declaration, declares the constants data type as Integer. (3) Designates a compiler directive, such as %Rem or %If.
& (ampersand)
(1) When suffixed to the identifier in a variable declaration or an implicit variable declaration, declares the data type of the variable as Long. (2) When suffixed to either the identifier or the value being assigned in a constant declaration, declares the constants data type as Long. (3) Prefixes a binary (&B), octal (&O), or hexadecimal (&H) number. (4) Designates the string concatenation operator in an expression.
! (exclamation point)
(1) When suffixed to the identifier in a variable declaration or an implicit variable declaration, declares the data type of the variable as Single. (2) When suffixed to either the identifier or the value being assigned in a constant declaration, declares the constants data type as Single.
# (pound sign)
(1) When suffixed to the identifier in a variable declaration or an implicit variable declaration, declares the data type of the variable as Double. (2) When suffixed to either the identifier or the value being assigned in a constant declaration, declares the constants data type as Double. (3) When prefixed to a literal number or a variable identifier, specifies a file number in certain file I/O statements and functions.
@ (at sign)
(1) When suffixed to the identifier in a variable declaration or an implicit variable declaration, declares the data type of the variable as Currency. (2) When suffixed to either the identifier or the value being assigned in a constant declaration, declares the constants data type as Currency.
*(asterisk)
(1) Specifies the string length in a fixed-length string declaration. (2) Designates the multiplication operator in an expression.
() (parentheses)
(1) Groups an expression, controlling the order of evaluation of items in the expression. (2) Encloses an argument in a sub or function call that should be passed by value. (3) Encloses the argument list in function and sub definitions, and in calls to functions and subs. (4) Encloses the array bounds in array declarations, and the subscripts in references to array elements. (5) Encloses the list tag in a reference to a list element.
. (period)
(1) When suffixed to a type variable or an object reference variable, references members of the type or object. (2) As a prefix in a product object reference, designates the selected product object. (3) As a prefix in an object reference within a With statement, designates the object referred to by the statement. (4) Designates the decimal point in a floating-point literal value.
14
Usage Within a reference to a procedure in a derived class that overrides a procedure of the same name in a base class, specifies the overridden procedure. Delimit names used by certain Lotus software applications to identify product objects.
(1) Separates arguments in calls to functions and subs, and in function and sub definitions. (2) Separates bounds in array declarations, and subscripts in references to array elements. (3) Separates expressions in Print and Print # statements. (4) Separates elements in many other statements.
Separates expressions in Print and Print # statements. Designates the beginning of a comment. The comment continues to the end of the current line. When preceded by at least one space or tab, continues the current line to the next line.
Note: Use white space to separate names and keywords, or to make the use of a special character unambiguous. White space is not needed with most non-alphanumeric operators. Avoid using white space around a special character, such as a data type suffix character appended to a name.
15
16
8 bytes
2 bytes/ character
LotusScript also supports the following data types and data structures:
Data type or structure Array Description Size
A set of elements having the same data type. An array Dynamic or global (public) can comprise up to 8 dimensions whose subscript bounds arrays limited by available can range from -32,768 to 32,767. memory A one-dimensional set whose elements have the same data type and are referred to by name rather than by subscript. A special data type that can contain a value of any scalar value, array, list, or object reference. Variants can also hold Boolean and date/time values. Limited by available memory
List
Variant
16 bytes
User-defined data type A set of elements of possibly disparate data types. Comparable to a record in Pascal or a struct in C. User-defined class A set of elements of possibly disparate data types together with procedures that operate on them.
17
Description
Size
A pointer to an OLE Automation object or an instance of 4 bytes a product-defined class or user-defined class, or an object reference to a Java Object.
For more information about language and script limits, see Appendix A.
Numeric operations
When numeric values with different data types are used in a numeric operation, LotusScript converts the values to the same data type for evaluation. In general, LotusScript converts to the higher data type, based on this list (lowest to highest): Byte, Integer, Long, Single, Double, Currency. For example, in an operation with one Integer operand and one Double operand, LotusScript converts the Integer value to a Double before evaluating the expression. Specific rules for conversion in operations are detailed in the documentation of the individual operators.
Argument passing
When a numeric argument is passed by value to a procedure, LotusScript tries to convert the value if it is not the expected data type. If the value is too large, the operation generates an error. When a numeric argument is passed by reference to a procedure, the data type of the reference must match that of the declared argument, unless the declared argument is Variant.
Variant variables
When a value is contained in a Variant variable, LotusScript tries to convert the value to a number or a string, depending on the context. Data type conversion treats a value of one data type as though it were a value of a different data type or performs an operation on a value of one data type to produce a value of another data type. Some form of data type conversion is involved when you add two numbers of different data types together, print the hexadecimal representation of a decimal number as a string, or calculate a date/time value (by treating that value as though it were a number). You can perform a data type conversion explicitly with the functions that LotusScript provides, you can choose between the two methods of conversion, or LotusScript can perform the conversion automatically. For example:
Dim Dim Dim Dim aString As String aDouble As Double aFloat As Currency aVariantV As Variant
aString$ = "123.45" aDouble# = 678.90 Explicitly convert a string to a Currency value. That is, assign the return value of the conversion function CCur, which takes a String argument, to a variable of type Currency. aFloat@ = CCur(aString$) Print aFloat@ Output: 123.45 Automatically convert a Double value to a Currency value by assignment. You
18
could explicitly convert the value of aDouble# to a Currency value before assigning it to aFloat@. You might do this for the purposes of documentation. aFloat@ = aDouble# Print aFloat@
Output: 678.9 Automatically convert a Variant value of type String to a Currency value by addition, and then convert the resulting Currency value to a value of type Double by assignment. You can make both of these conversions explicit if you want. aVariantV = aString$ aDouble# = aVariantV + aFloat@ Print aDouble# Output: 802.35
aString$ = "123" Convert the string "123" to a value of type Double. aDouble# = CDbl(aString$) Add the prefix &H to that string, to prepare the string for conversion to a hexadecimal number. aString$ = "&H" & aString$ Convert the string "&H7B" to an integer, add 12.46 to that integer, explicitly convert the result to a value of type Currency, and assign it to a variable of type Currency. If you omit the step of explicitly converting the integer to a value of type Currency, the conversion happens automatically when the assignment takes place. myFixedPoint@ = CCur(CInt(aString$) + 12.46) Print myFixedPoint@ Output: 135.46 Explicitly convert a value of type Currency to an integer, with automatic rounding off, and assign the result to a variable of type Integer. If you dont explicitly convert the Currency value to an integer, conversion (with rounding) happens automatically when the assignment takes place. anInt% = CInt(myFixedPoint@) + 300 Print anInt% Output: 435 Convert an integer to a date value and assign it to a Variant variable. aVariantV = CDat(anInt%) Print format$(aVariantV, "mm/dd/yyyy") Output: 03/10/1901
Some conversion facts to keep in mind: v Format[$] converts almost anything to a string.
Chapter 3. Data Types, Constants, and Variables
19
v v v v
Fix truncates a floating point value to an integer always truncating towards zero. Int truncates a floating point value to an integer smaller than the input value. DateValue converts a string into a date (variant type 7). DateNumber converts a set of numbers into a date value (variant type 7).
v You increment the value of a Variant variable of some numeric type beyond the allowable limit for values of that type. For example, the statement aVariantV = aVariantV + 5 assigns a value of type Long, rather than a value of type Integer, to the Variant variable aVariantV because the largest value an Integer can have in LotusScript is 32767:
aVariantV = 32767 Print TypeName(aVariantV) aVariantV = aVariantV + 5 Print TypeName(aVariantV) Output: INTEGER Output: LONG
v You add or concatenate the values of two Variant variables, one of which is of type String and the other of which is one of the numeric data types. Addition is performed when one of the following is true: Both operands contain numeric values. One operand is numeric, and the other is a Variant containing a string that can be interpreted as a number. Both operands are Variants, with a numeric value in one and a string value that can be interpreted as a number in the other. Concatenation is performed when one of the following is true: Both operands are strings. One operand is a string that cant be interpreted as a number, and the other is a Variant containing a numeric value. Note: It is not always possible to convert values. If the conversion is not possible, a type mismatch error is raised.
20
Note: It is highly recommended that you use explicit conversion as much as possible to avoid unexpected results.
Example 1
This example illustrates the automatic conversion of decimal numbers to integers that happens when you perform integer division and when you assign a decimal number value to an integer variable.
Dim anInt As Integer Dim aDouble As Double Do floating-point division. anInt% = 12/7 Print anInt% Output: 2 aDouble# = 12/7 Print aDouble# Output: 1.71428571428571 Do integer division. anInt% = 12\7 Print anInt% Output: 1 aDouble# = 12\7 Print aDouble# Output: 1 Do floating-point division. anInt% = 12.5/2 Print anInt% Output: 6 aDouble# = 12.5/2 Print aDouble# Output: 6.25 Do integer division. anInt% = 12.5\2 Print anInt% Output: 6 aDouble# = 12.5\2 Print aDouble# Output: 6
Example 2
In this example, the value 1.6 is assigned to X. Since X is a variable of type Integer, 1.6 is converted to an integer before the assignment takes place. Conversion of floating-point values (Single and Double values) to integer values (Integer and Long values) rounds the value to the nearest integer, which is 2 in this case. When 1.5 is assigned to Y, LotusScript rounds it to 2, the nearest even integer. A floating-point value exactly halfway between two integer values is always rounded to the nearest even integer value. So the value 2.5 is also rounded to 2 when it is assigned to Z. A value of 3.5 would be rounded to 4, a value of -3.5 would be rounded to -4, and so on. A value of .5 or -.5 is rounded to 0.
Dim X As Integer Dim Y As Integer Dim Z As Integer X% = 1.6 Print X% Output: 2 Y% = 1.5 Print Y% Output: 2 Z% = 2.5 Print Z% Output: 2
Chapter 3. Data Types, Constants, and Variables
21
Example 3
This example illustrates the way in which LotusScript handles data type conversion in Variant variables to accommodate numeric values.
Dim sumV As Variant Dim sInt As Integer sInt% = 42 sumV = sInt% Print TypeName(sumV) Output: INTEGER Assign the largest integer value to sInt%. sInt% = 32767 sumV = sInt% + 1 LotusScript converts sumV to a Long to prevent an overflow. Print TypeName(SumV) Output: LONG
Example 4
This example shows how LotusScript does number-to-string and string-to-number conversion when a Variant variable is an operand in an operation involving the + operator, which can be used for both addition and string concatenation.
Dim aVariantV As Variant aVariantV = 1040 Print TypeName(aVariantV) Output: INTEGER Print aVariantV + "A" Output: 1040A because "A" is a string and 1040 can be interpreted as a string. aVariantV = "43" Print TypeName(aVariantV) Output: STRING Print aVariantV + 5 Output: 48 because 48 is a number and 5 can be interpreted as a number.
22
Scope of declarations
Scope is the context in which a variable, procedure, class, or type is declared. Scope affects the accessibility of an items value outside that context. For example, variables declared within a procedure are typically not available outside of the scope of that procedure. LotusScript recognizes three kinds of scope: v Module scope v Procedure scope v Type or class scope
Module scope
A variable is declared in module scope if the declaration is outside of any procedure, class, or type definition in the module. The variable name has a meaning as long as the module is loaded. The variable name is visible anywhere within the module and has the meaning specified in the declaration, except within a procedure, type, or class where the same variable name is also declared. The variable is Private by default and can be referred to only within the module that defines it. A variable can be referred to in other modules only if it is declared as Public and the other modules access the defining module with the Use statement.
Chapter 3. Data Types, Constants, and Variables
23
The following situations result in a name conflict across modules: v Two Public constants, variables, procedures, types, or classes with the same name v A Public type with the same name as a Public class v A Public module-level variable with the same name as a Public module-level constant or procedure v A Public module-level constant with the same name as a Public module-level procedure The following situations result in a name conflict within a module: v A type with the same name as a class v A module-level variable with the same name as a module-level constant or procedure v A module-level constant with the same name as a module-level procedure
Procedure scope
A variable is declared in procedure scope if it is declared within the definition of a function, a sub, or a property. Only inside the procedure does the variable name have the meaning specified in the declaration. The variable name is visible anywhere within the procedure. Ordinarily, the variable is created and initialized when the procedure is invoked, and deleted when the procedure exits. This behavior can be modified with the Static keyword: v If the variable is declared with the Static keyword, its value persists between calls to the procedure. The value is valid as long as the module containing the procedure is loaded. v If the procedure itself is declared Static, the values of all variables in the procedure (whether explicitly or implicitly declared) persist between calls to the procedure. The following situations result in a name conflict within a procedure: v Two procedure arguments with the same name v Two labels with the same name v Two variables with the same name v A procedure argument and a variable with the same name v A function that contains a variable or argument of the function name v A property that contains a variable of the property name
24
v If the instance variable is declared Public, then the member variable is visible wherever the instance variable is visible: it can be referred to in the other modules where the module that owns this instance variable is accessed with the Use statement. The following situation results in a name conflict within a type: v Two type members with the same name. The following situation results in a name conflict within a class: v Two class members (variables or procedures) with the same name.
Constants
A constant names a location in memory that contains a value that is known at compile time and cannot be changed while the application is running. In less formal terms, a constant is a named fixed value. Constants are defined in the following ways: v By LotusScript, internally. These constants are built into the language and are always available to an application. v By LotusScript, in the file LSCONST.LSS. These constants are available in a module only when the module explicitly includes the file in which they are defined. v By LotusScript, in the file LSPRVAL.LSS. These constants contain information about a thread. v By an individual product, internally or in a file that that product makes available. The file in which these constants are defined may or may not have to be included explicitly in the module in which you want to use them. v By the application developer, in an application module or in a file that you explicitly include in a module. The value of a constant is actually compiled into the object code. If you want to change the value of a particular constant, all modules that use that constant must be recompiled.
Built-in constants
LotusScript provides several built-in constants that you can use in your scripts. LotusScript predefines other constants in the file LSCONST.LSS. To include this in your scripts, use the %Include directive.
Constant NOTHING Value The initial value of an object reference variable, before it has been assigned. As soon as you assign a specific reference to the variable, the variable no longer contains NOTHING. If you delete an object reference variable, its value reverts to NOTHING. You can explicitly assign the value NOTHING to an object reference variable. To test an object reference variable for the NOTHING value, use the Is operator, for example: (objname Is NOTHING). A special value that represents unknown or missing data. Various operations return a NULL value, but you can only assign the NULL value to a Variant variable that does not contain an object reference variable. To determine if a variable contains the NULL value, use the IsNull function. Do not use the IsNull function with an object reference variable argument as IsNull(objname) will always return FALSE. The ratio of the circumference of a circle to its diameter. This constant can be assigned to any numeric variable, or used in numeric expressions. The Boolean values True and False, which LotusScript evaluates as the integer values -1 and 0, respectively. These values are returned by all comparison and logical operations. In an If, Do, or While statement, which test for TRUE or FALSE, any nonzero value is considered True.
NULL
25
LotusScript also includes an internal value named EMPTY. This is the initial value of a Variant variable. LotusScript converts EMPTY to the empty string () in string operations and to 0 in numeric operations. To test a variable for the EMPTY value, use the IsEmpty function. You cannot assign EMPTY as a value.
Language cross-reference
@Pi function in formula language @Yes function in formula language @True function in formula language @False function in formula language IsNull function in LotusScript language Testing object references in LotusScript language
These constants are defined in the file LSCONST.LSS. Use the %Include directive to incorporate this file into your application in a module that must be loaded when you need to use the constants, which are all explicitly defined to be Public. The syntax for including this file is:
%Include "LSCONST.LSS"
Product-specific constants
Individual Lotus software applications may provide additional constants that you can use by including the file in which they are defined in your application with the %Include directive. A product may also provide internally defined constants that are automatically available to your application. For more information, see the product documentation.
User-defined constants
You can define your own constants within a module or a procedure, as long as the constants are the scalar data types that LotusScript recognizes. Use the following syntax to define a constant: [Public | Private] Const constName = expression
26
Where:
Element Public, Private Description Only an option when you declare a constant at module level, not within a procedure. Public means that the constant can be used outside the module in which it is defined. Private means the constant can only be used inside the module in which it is defined. Constants are Private by default. The name of the constant. The name, which can include a data type suffix character, must be a legal LotusScript identifier (see Script and Statement Construction Rules). A constant cannot have the same name as another constant, variable, or procedure of the same scope used in the same module. An expression indicating the value of the constant. The expression can be a literal or another constant. You can use arithmetic and logical operators in the expression. The expression can contain a LotusScript function (such as Abs or UCase$) if that function can be evaluated at compile time and its arguments (if any) are constant.
constName
expression
You can define a constant to be of a particular data type by appending a data type suffix to constName:
Suffix % & ! # @ $ Data type Integer Long Single Double Currency String
For example:
Define a String constant, MYNAME. Const MYNAME$ = "Andrea" Define a Single constant, MYPERCENT. Const MYPERCENT! = 0.125 Define a Currency constant, MYMONEY. Const MYMONEY@ = 123.45
Alternatively, if the constant is numeric, and expression is a numeric literal, you can specify the particular numeric data type by appending the appropriate data type suffix character to expression. For example:
Define a Currency constant, MYCUR, with the value 123.45. Const MYCUR = 123.45@
If you dont append a suffix character to constName or expression, LotusScript determines the data type of the constant by the value of expression. v For a string, the data type is String. v For a Single or Double value, the data type is Double. v For an integer, the data type is Integer or Long, depending on the magnitude of the value. For example:
Const MYNAME = "Sara" MYNAME is a constant of type String. Const MYDOUBLE = 123.45 MYDOUBLE is a constant of type Double.
27
Const MYINT = 123 MYINT is an constant of type Integer. Const MYLONG = 123456 MYLONG is a constant of type Long.
You can always include a data type suffix character when you refer to a constant in a LotusScript application, whether or not you used the suffix in the Const statement that defined the constant. You need not use the suffix, though it makes your code easier to read. For example:
Const MYADDRESS$ = "722 Smith Place" Print MYADDRESS Output: 722 Smith Place Const YOURADDRESS = "75 rue St. Viateur" Print YOURADDRESS$ Output: 75 rue St. Viateur Print MYADDRESS%, YOURADDRESS@ would cause an error.
By default, a constant that you define at module level is Private, that is, accessible only within that module. You can override this default in either of two ways to make the constant available to other modules in the application: v Include the keyword Public in the statement that defines the constant, for example:
Public Const GLOBALINT% = 123
v Include the Option Public statement at the beginning of a module that must be loaded when the application runs. This makes all identifiers in the module Public by default.
28
To access a Public constant defined in another module, you compile that module and then refer to the compiled module in a Use statement in the accessing module. (This is how you access any item defined as Public, whether a constant, variable, procedure, user-defined data type definition, or class definition.) For example, to access the Public constants in module A from module B, you compile module A and then include the following statement in module B:
Use "A"
Variables
A variable names an area of storage whose value can change during execution of an application. You declare a variable to be of a particular type, which restricts the kind of value the variable can hold (except for variables of type Variant). You also determine the scope and lifetime of a variable, that is, when and how long the variable exists and in what parts of your application it is accessible. Typically, if you do not choose a type or scope for the variable, LotusScript chooses by default. A variable name can be any valid LotusScript identifier. The name cannot be the same as the name of another variable, constant, or procedure in the same scope used in the same module. A variable can be of any of the following data types or structures: v The scalar types that LotusScript recognizes: Boolean, Byte, Integer, Long, Single, Double, Currency, or String v An array or a list v A Variant v A user-defined data type, that is, a type defined with a Type...End Type statement v A class defined with a Class...End Class statement, or a class defined by the Lotus software with which LotusScript is running The next two sections describe the two ways you can declare a scalar variable in LotusScript: with an explicit statement or by implication. Subsequent sections describe how to declare arrays, lists, and variables of type Variant.
29
The syntax elements in the declaration of a scalar variable are summarized in the following table:
Element Dim Public, Private Static Description Declares a variable with Private scope. Public declares a variable with Public scope. Private declares a variable with Private scope. Only applicable to variables declared inside a procedure. Static variables retain their values (rather than going out of existence) between calls to the procedure while the module in which the procedure is defined remains loaded. The name of the variable. At module level or within a procedure, varName can end in any of the data type suffixes that LotusScript recognizes. This determines the type of data that the variable can hold. You can append a data type suffix to a variable name when you declare it only if you do not include the As dataType clause in the declaration. Specifies the type of data the variable can hold. If you include this clause, varName cannot end in a data type suffix character. This clause is required in the declaration of a variable within the definition of a user-defined data type or class, but optional in the declaration of a variable at module level or within a procedure.
varName
As dataType
30
Note: Because LotusScript assigns initial values to variables, you can encounter unexpected errors if the initial value is not what you wanted, or if the variable name is later misspelled, in which case it will be treated as a new variable. Whether or not you append a data type suffix to the name of the variable when you declare it, you can always do so (or not) when referring to an explicitly declared scalar variable. For example:
Public firstName$ Public lastName As String Dim age% Dim money As Currency firstName$ = "Roman" lastName$ = "Minsky" age% = 12 money@ = 150.75 Print firstName & " " & lastName & ", " & age &", $" & money Output: Roman Minsky, 12, $150.75 Print firstName$ & " " & lastName$ & ", " & age% &", $" & money Output: Roman Minsky, 12, $150.75
String variables
A variable of type String contains a sequence of characters in the Unicode character set. Unicode is a character-encoding system that uses two bytes to represent each character in the set. LotusScript converts input to Unicode format before compiling an application. A String variable can be of variable or fixed length. The syntax for declaring a variable-length String variable is shown in the preceding diagram. The syntax for declaring a fixed-length String variable is shown below:
The charNum argument specifies that varName is a fixed-length String variable of charNum characters. When you assign a string to a fixed-length String variable, LotusScript truncates the string or pads it to the declared length with trailing spaces if necessary. For example:
Chapter 3. Data Types, Constants, and Variables
31
Dim myName$ Dim myTown As String myName and myTown are variable-length string variables. Dim myState As String * 2 myState is a 2-character fixed-length String variable. Dim myZIP As String * 5 myZIP$ is a 5-character fixed-length String variable. If myZIP$ is assigned a value of more than 5 characters, that value will be truncated to its first 5 characters. myName$ = "Mark" myTown$ = "Centerville" myState$ = "MA" myZIP$ = "02100-9999" Print myName$ Output: Mark Print myTown$ & ", " & myState$ & " " & myZIP$ Output: Centerville, MA 02100
results in Y being data-typed as INTEGER but X as Variant. The correct syntax is:
DIM X AS INTEGER, Y AS INTEGER
The conventions for appending a data type suffix character to a variable name in the absence of an As dataType clause (and not appending a data type suffix in the presence of an As dataType clause) are the same as in the declaration of a single scalar variable. For example:
Dim aString$, anInt%, aDouble As Double, aCurrency@ aString$ = "Hello" Print TypeName(aString$) & ": " & aString$ Output: STRING: Hello anInt% = 123 Print TypeName(anInt%) & ": " & anInt% Output: INTEGER: 123 aDouble# = 123.45 Print TypeName(aDouble) & ": " & aDouble# Output: DOUBLE: 123.45 aCurrency@ = 456.78 Print TypeName(aCurrency@) & ": " & aCurrency@ Output: CURRENCY: 456.78 Sub MySub Dim aString As String * 2, anotherString$, anInt% Static aDouble#, anotherDouble# aString$ = "Hi" Print TypeName(astring$) & ": " & aString$ anotherString$ = "World" Print TypeName(anotherstring$) & ": " & anotherString$ anInt% = 234
32
Print TypeName(anInt%) & ": " & anInt% aDouble# = aDouble# + 1 anotherDouble# = aDouble# * 2 Print TypeName(anotherDouble#) & ": " & anotherDouble# End Sub Call MySub Output: STRING: Hi STRING: World INTEGER: 234 DOUBLE: 2 Call MySub Output: STRING: Hi STRING: World INTEGER: 234 DOUBLE: 4
This has the same effect as the following explicit declaration and statement:
Dim counter% counter% = 1
As with explicitly declared variables, the identifier has to be a legal one and not already in use as the name of a constant, variable, or procedure in the same scope in the same module. If you append a data type suffix to the variable name when you declare it, that suffix determines data type of the variable. If you dont append a data type suffix, one of two things happens: if the name begins with a character covered by an existing Deftype statement, the variable is implicitly declared to be of the data type appropriate to that statement. Otherwise, the variable is implicitly declared to be of type Variant. The same rules apply to explicitly declared variables if the declaration doesnt contain an As dataType clause and the variable name doesnt end in a data type suffix character:
Declare a variable of type Variant. Dim myVarV
Implicit declaration is a handy shortcut when youre writing a simple script, saving you the line of code that it would take to declare the variable explicitly. However, the line of code you save by collapsing the declaration of a variable and the assignment of a value into a single statement can be costly in an application of even moderate complexity for two reasons: v When you implicitly declare a variable of one of the scalar types by including the appropriate data type suffix, LotusScript requires you to use that character whenever you subsequently refer to that variable. Omitting the data type suffix in referring to such a variable produces an error. The opposite is true of implicitly declared variables covered by Deftype statements: they are declared without a data type suffix, and you cant include one when you refer to them later in the application without producing an error. v If you omit the data type suffix in an implicit declaration and the identifier isnt covered by an existing Deftype statement, you implicitly declare a variable of type Variant, which is not necessarily what you want to do. While useful in many ways, Variants take up more storage space in memory than the other scalar types. And if you include a data type suffix when referring to a variable of type Variant, you receive an error. For example:
33
Create the Integer variable anInt without explicitly declaring it and initialize it to 10. anInt% = 10 Print anInt Produce "Name previously declared" error because LotusScript reads anInt (without suffix character) as an implicitly declared Variant variable, not the Integer variable anInt% (with suffix character). Create the Variant variable myVariantV without explicitly declaring it and initialize it to 10. myVariantV = 10 Print myVariantV% Produce "Type suffix mismatch" error because myVariantV (without suffix character) was declared as type Variant, but the suffix character % is only appropriate for variables declared as type Integer.
If you want to disallow implicit declaration in a LotusScript application, include the Option Declare statement at module level in a module that you plan to have loaded when the application runs. This statement tells LotusScript to require explicit declarations for all your variables. Note: The Boolean and Byte data types do not have a data type suffix character and therefore cannot be declared implicitly.
Deftype statements
You use a LotusScript Deftype statement at module level to assign a default data type to variables whose names begin with a particular letter of the alphabet, dont end with a data type suffix character, and dont appear in an explicit declaration containing an As dataType clause. The statement must appear before any variables are declared in the module. The syntax is Def type range [, range]... where type is a suffix such as Cur or Dbl, which is an abbreviation of the name of a data type, and range is one or more consecutive letters of the alphabet. For example:
Implicitly declared variables beginning with A, a, B, b, C, or c will be of type Integer. DefInt A-C Create the Integer variable anInt on the fly and initialize it to 10. anInt = 10 Create a variable of type Variant on the fly and initialize it to 2. Its a Variant because it doesnt have a data type suffix character and doesnt begin with any of the characters in the specified DefInt range. smallIntV = 2
34
The following examples contain a representative sampling of the LotusScript numeric and string functions and illustrate some of the things you can do with them. Each example is a Print statement, which causes LotusScript to display the return value of the particular function.
Dim anInt As Integer Dim aDouble As Double aDouble# = -123.654 anInt% = 6 Ascertain if aDouble# is a numeric data type: True (-1) or False (0). Print IsNumeric(aDouble#) Output: True Ascertain if anInt% is positive (1), negative (-1), or neither (0). Print Sgn(anInt%) Output: 1 Print the absolute value of aDouble#. Print Abs(aDouble#) Output: 123.654 Print aDouble# rounded to 1 decimal place. Print Round(aDouble#,1) Output: 123.7 Print the nearest integer equal to or less than aDouble#. Print Int(aDouble#) Output: -124 Print the integer part of aDouble#. Print Fix(aDouble#) Output: -123 Print the decimal part of aDouble#. Print Fraction(aDouble#) Output: -.653999999999996 Print the exponential (base e) of anInt%. Print Exp(anInt%) Output: 403.428793492735 Print a random whole number between 1 and 5 by seeding the random number generator, calling the Rnd function to generate a random number, and performing various operations on the result. First, seed the random number generator. Randomize Generate a random decimal number; take its decimal part and round it to one decimal place; multiply the result by 10 to make it a one-digit whole number; divide that number by 5 and add 1 to the remainder. The result is a random whole number between 1 and 5. Print ((round(Fraction(Rnd),1) * 10) Mod 5) + 1 Output: a random integer between 1 and 5. Dim aString As String Dim theNewString As String Assign aString the value (space)(space) abcdef(space)(space). aString$ = chr$(32) + chr$(32) + "abcdef" + chr$(32) + chr$(32) Print aString$ Output: (space) (space) abcdef (space) (space) Ascertain the number of characters that aString$ contains. Print Len(aString$)
Chapter 3. Data Types, Constants, and Variables
35
Output: 10 Strip leading and trailing spaces from aString$. aString$ = Trim$(aString$) Print aString$ Output: abcdef Print Len(aString$) Output: 6 Convert all the alphabetic characters in aString$ to uppercase. aString$ = UCase$(aString$) Print aString$ Output: ABCDEF Print the leftmost 3 characters of aString$. Print Left$(aString$, 3) Output: ABC Print the position in aString$ where the substring "DE" begins. Print InStr(aString$, "DE") Output: 4 Print the first two characters of the substring that starts at the fourth character of aString$. Print Mid$(aString$,4, 2) Output: DE Assign theNewString$ a value of a string of 10 asterisks. theNewString$ = String$(10, "*") Print theNewString$ Output: ********** Starting at the third character of aString$, replace the next 2 characters of aString$ with the first 2 characters of theNewString$. Mid$(aString$,3,2 ) = theNewString$ Print aString$ Output: AB**EF
Arrays
An array is a named collection of elements of the same data type, where each element can be accessed individually by its position within the collection. A LotusScript array can have a maximum of eight dimensions. The position of an element in an array can be identified by one or more coordinates called subscripts (or indexes). The number of subscripts necessary to identify an element is equal to the number of the arrays dimensions. In a one-dimensional array, a given elements position can be described by one subscript; in a two-dimensional array, it takes two subscripts to locate an element. For example, in a one-dimensional array whose elements are the names of the states of the United States, a single subscript identifies the position of a given state in the collection:
Dim states(1 to 50) As String states(1) = "Alabama" states(2) = "Alaska" states(3) = "Arizona" and so on. Print states(2) Output: Alaska
In a two-dimensional array whose elements are the names of the ten most populous cities in each state, the first subscript identifies the state, and the second subscript identifies the city:
36
Dim statesAnd10Cities(1 to 50, 1 to 10) As String statesAnd10Cities(1,1) = "Alabama, Birmingham" statesAnd10Cities(1,2) = "Alabama, Mobile" ... statesAnd10Cities(2,1) = "Alaska, Anchorage" statesAnd10Cities(2,2) = "Alaska, Fairbanks" and so on. Print statesAnd10Cities(1,2) Output: Alabama, Mobile
A three-dimensional array might contain the numbers of adult females, adult males, and children in each of the ten most populous cities in each state:
Dim statesAnd10CitiesAndPeople(1 to 50, 1 to 10, 1 to 3) _ As Double statesAnd10CitiesAndPeople(1,1,1) = 120748 Number of adult males in Birmingham, Alabama. statesAnd10CitiesAndPeople(1,1,2) = 145104 Number of adult females in Birmingham, Alabama. ... statesAnd10CitiesAndPeople(2,1,1) = 116381 Number of adult males in Anchorage, Alaska. statesAnd10CitiesAndPeople(2,1,2) = 109957 Number of adult females in Anchorage, Alaska. ... Print StatesAnd10CitiesAndPeople(1,1,2) Output: 145104
The size of an array (the number of dimensions and the extent of each individual dimension) is defined by the arrays bounds list. Each dimension has a lower bound and an upper bound, specified as integer values. LotusScript supports both fixed and dynamic arrays. v You declare a fixed array once. At compile time, its size and storage requirements are set according to the specifications of its bounds list and the data type of its elements. At run time, storage is allocated for its elements, which are initialized like any ordinary variable of that data type. The array cannot be resized while the application is running. v You declare a dynamic array once, but it can be sized and resized many times (with the ReDim statement) while the application is running. When you declare a dynamic array, you specify the data type of its future elements but include an empty bounds list, so LotusScript doesnt allocate space in memory for those elements. You resize a dynamic array at run time when you know how many elements you want it to hold, at which time LotusScript allocates the necessary storage space. The values of the elements of the array can be reinitialized or preserved each time you resize the array. You declare an array with the Dim statement or one of its variations, as summarized in the following diagram:
37
arrayName
bounds
38
int a[5]
specifies 5 elements in array a, beginning with a[0] and continuing through a[4]. In LotusScript and other BASIC-type languages, declaring
DIM a(5) as Integer
specifies 6 elements in array a, beginning with a[0] and continuing through a[5]. In this case the lower bound of the array is 0 and the upper bound is 5. You can change the base default to 1 instead by using the Option Base statement.
Fixed arrays
You typically use a fixed array to manipulate a set of elements whose number is known at compile time and not subject to change while the application is running. For example, you might use a fixed array to match the names of employees with parking spaces in the companys garage by floor, section, and space number. For example, suppose that the garage has three floors, each floor is divided into four equal sections, and each section holds ten parking spaces. Here are two ways you can organize the information about these 120 parking spaces and the employees assigned to them: The first way uses a two-dimensional array. The array contains 480 elements, representing 4 pieces of information about each of 120 parking spaces. When you refer to a given element in this array by its two subscripts, the first subscript identifies the parking space, and the second subscript identifies its floor, section, space number, or the person assigned to it.
Dim empSpacesA(1 To 120, 1 To 4) As String empSpacesA(1,1) = "Floor 1" empSpacesA(1,2) = "Section 1" empSpacesA(1,3) = "Space 1" empSpacesA(1,4) = "Maria Jones" empSpacesA(2,1) = "Floor 1" empSpacesA(2,2) = "Section 1" empSpacesA(2,3) = "Space 2" empSpacesA(2,4) = "Fred Smith" And so on down to the last space. empSpacesA(120,1) = "Floor 3" empSpacesA(120,2) = "Section 4" empSpacesA(120,3) = "Space 10" empSpacesA(120,4) = "Sal Piccio" Print information about Fred Smiths space. Print empSpacesA(2,1) & " " & empSpacesA(2,2) & " " _ empSpacesA(2,3) & " " empSpacesA(2,4) Output: Floor 1 Section 1 Space 2 Fred Smith
The second way uses a three-dimensional array. The array contains 120 elements, each holding the name of the person assigned to a parking space. The three subscripts that identify a given element in this array correspond to the floor, section, and space to which that person has been assigned.
Dim empSpacesB(1 To 3, 1 To 4, 1 To 10) As String empSpacesB(1,1,1) = "Maria Jones" empSpacesB(1,1,2) = "Fred Smith" And so on down to the last space. empSpacesB(3,4,10) = "Sal Piccio" Print information about Fred Smiths space. Print "Floor 1 Section 1 Space 2 " & empSpacesB(1,1,2) Output: Floor 1 Section 1 Space 2 Fred Smith
Each of these two approaches involves declaring a multidimensional fixed array whose elements are of type String. While each array contains the same amount of information about each parking space, they have a different number of dimensions and elements, and they require you to use somewhat different strategies for entering and retrieving the information about each parking space.
Chapter 3. Data Types, Constants, and Variables
39
If the values that the array is going to hold belong to one of the scalar data types that LotusScript recognizes, you can omit the As dataType clause and instead specify the data type by appending the appropriate data type suffix to the name of the array:
Declare a one-dimensional array of strings. Dim aStringArray$(1 To 10) Declare a two-dimensional array of integers. Dim anIntArray%(1 To 10, 1 To 10)
If you omit both the suffix and the As dataType clause, LotusScript checks to see if the array name is covered by any applicable Deftype statement. If it is, LotusScript defines the arrays elements to be of the appropriate data type. Otherwise, LotusScript defines them to be of type Variant:
DefInt A-C Declare an array of integers. Dim arrayOfInts(1 To 10) Declare an array of Variants. Dim otherArrayV(1 To 10)
You specify the number of elements in an array and the number of dimensions along which they are organized in the bounds list. The lower and upper bounds of an array dimension can be any numeric constant between -32768 and 32767, inclusive, though the constraint that a fixed-sized array local to a procedure can take up no more than 32K bytes of storage means that the range between lower and upper bounds in a multidimensional array must be smaller than this. The memory needed for an array depends on the size of the array and the storage needed for an element of the array. The size of an array is the total size of the elements in it. It is the product of the sizes of all the dimensions. For example:
Dim arrayOfSingles(1 To 5, 1 To 10, 1 To 2) As Single
The dimensional lengths are 5, 10, and 2, so arrayOfSingles holds 100 elements. The actual storage needed for all of these elements is 400 bytes, since one value of Single data type takes up four bytes of storage. For example:
Dim myStats(1980 To 1983, 1 To 4, -2 To 2) As Currency
Here the dimensional lengths are 4, 4, and 5 (1980, 1981, 1982, 1983; 1, 2, 3, 4; -2, -1, 0, 1, 2) for a total of 80 elements, each of which requires 8 bytes of storage. The amount of memory necessary to store myStats is therefore 640 bytes. You might use such an array as myStats to hold some number of values distributed over a bell curve for each quarter of the years from 1980 to 1983 inclusive. The reason why you might use the subscript ranges 1980 To 1983, 1 To 4, and -2 To 2 instead of 1 To 4, 1 To 4, and 1 To 5 is to have a mnemonic device to make entering and retrieving values in the array more intuitive: to enter the value for the bottom of the curve in the second quarter of 1982, you would use a statement like this:
myStats(1982, 2, -2) = 123.456
40
This example demonstrates that a dimensions lower bound doesnt have to be 1, although it is usually convenient to have a dimensions lower bound be 1 or 0. LotusScript lets you set 1 or 0 as the default lower bound for the dimensions of all arrays that you declare in a module by including the appropriate Option Base statement in the module. Option Base 0 is the LotusScript language default but your product may choose a different setting, which you can override. For example:
Option Base 0 Declare a 120 x 4 array, both of whose dimensions are zero origin. This is the same as saying Dim empSpacesA(0 To 119, 0 To 3) As String Dim empSpacesA(119, 3) As String Declare a 3 x 4 x 10 array, all of whose dimensions are zero origin. This is the same as saying Dim EmpSpacesB(0 To 2, 0 To 3, 0 To 9) As String Dim empSpacesB(2, 3, 9) As String
You can mix explicit and implicit lower bound specifications in a declaration:
Option Base 0 Dim myStats(3, 1 To 2, -2 To 2) As Currency The first dimension of this 4 x 2 x 5 array is 0 To 3. Dim arrayOfSingles(1 To 5, 9, 1) As Single The second and third dimensions of this 5 x 10 x 2 array are 0 To 9 and 0 To 1, respectively.
Use the LBound function to ascertain the lower bound of a dimension. The syntax is: LBound ( arrayName [ , dimension ] ) where arrayName is the name of the array, and dimension is an integer that represents the dimension whose lower bound you want to ascertain. The default value of dimension is 1. So, for example:
Option Base 1 Dim myStats(1980 To 1983, 2, -2 To 2) As Currency Print LBound(myStats) Output: 1980 (the lower bound of the first dimension). Print LBound(myStats, 2) Output: 1 (the lower bound of the second dimension).
You can ascertain the upper bound of a dimension with the UBound function.
41
arrayName( S1, S2, S3,... ) = value where arrayName is the name of the array; S1, S2, S3,... are subscripts, one for each dimension of the array; and value is the value you want to assign to the element whose location in the array is defined by S1, S2, S3,... For example:
Option Base 1 Dim empSpacesB(3,4,10) As String empSpacesB(1,1,1) = "Maria Jones" empSpacesB(1,1,2) = "Fred Smith"
Or:
Dim empSpacesA(120,4) As String Dim counter As Integer Dim LB1 As Integer Dim LB2 As Integer Get lower bound of first dimension. LB1% = LBound(empSpacesA, 1) Get lower bound of second dimension. LB2% = LBound(empSpacesA, 2) For the first 40 elements in the first dimension, assign the value "Floor 1" to the first element in the second dimension; for the next 40 elements in the first dimension, assign the value "Floor 2" to the first element in the second dimension; and for the last 40, assign the value "Floor 3". For counter% = LB1% to LB1% + 39 empSpacesA(counter%, LB2%) = "Floor 1" empSpacesA(counter% + 40, LB2%) = "Floor 2" empSpacesA(counter% + 80, LB2%) = "Floor 3" Next
You refer to the value of a scalar element in an array by the elements subscripts, as in the following example which searches for parking spaces to which no employee has been assigned:
Option Base 1 Dim empSpacesB(3,4,10) As String Declare three String variables the quickest way to hold values for floor, section, and space. Dim Flo$, Sec$, Spa$ Declare six Integer variables the quickest way to hold values for the lower and upper bounds of the dimensions of empSpacesB for easy reference. Dim LB1%, LB2%, LB3%, UB1%, UB2%, UB3% Initialize the array. Typically you do this by reading the data from a file rather than by hard-coding the values. empSpacesB(1,1,1) = "Maria Jones" empSpacesB(1,1,2) = "" empSpacesB(1,1,3) = "Joe Smith" And so on down to the last space. empSpacesB(3,4,10) = "Sal Piccio" Assign the lower and upper bounds of each dimension of empSpacesB to a variable. LB1% = LBound(empSpacesB, 1) LB2% = LBound(empSpacesB, 2) LB3% = LBound(empSpacesB, 3) UB1% = UBound(empSpacesB, 1) UB2% = UBound(empSpacesB, 2) UB3% = UBound(empSpacesB, 3) Loop through all the array elements and print the floor, section, and location of each space that has the empty string, that is, no employee name, as its value. Convert the floor, section, and space
LotusScript Language Guide
42
numbers to strings by calling the cStr function and passing it the appropriate subscript. For counter1% = LB1% to UB1% For counter2% = LB2% to UB2% For counter3% = LB3% to UB3% If empSpacesB(counter1%, counter2%, counter3%) = "" Then Flo$ = "Floor " & cStr(counter1%) & " " Sec$ = "Section " & cStr(counter2%) & " " Spa$ = "Space " & cStr(counter3%) & " " Print Flo$ & Sec$ & Spa$ & "is empty." End If Next Next Next
Dynamic arrays
You use a dynamic array if you want to defer declaring the number of the arrays elements and dimensions until run time, or if you want to vary the array size at one or more points during execution of the application. To declare a dynamic array, you use a Dim statement (or one of its variations) with an empty subscript list (empty parentheses), as in the following example:
Dim myDynamicArray() As String
Since this Dim statement contains no information about the dimensions of the array, the statement simply reserves the name myDynamicArray as the name of a dynamic array whose elements will be of type String: When you declare a dynamic array, it has no dimensions or elements, and no storage is allocated for it. The array is unusable until you specify its dimensions and their bounds in a ReDim statement, which defines the array size and allocates storage for the elements and initializes them. The syntax of the ReDim statement is: ReDim [ Preserve ] arrayName ( bounds ) [ As dataType] where arrayNameis the name of an array that you previously declared with an empty bounds list, bounds is the bounds list with which you now want to define the number and extent of the arrays dimensions, and As dataType specifies the data type of the elements that the array will hold. This must be the same as the data type in the original Dim statement. The optional Preserve keyword instructs LotusScript to retain the current values of the elements in arrayName. This is useful if you have declared a dynamic array with Dim, defined its size with ReDim, assigned values to its elements, and then want to expand the array to accommodate additional elements and assign them values, as in the following example:
Option Base 1 Declare a dynamic String array. Later, this is defined as a one-dimensional array whose elements are assigned values that the user enters. Dim myNames() As String Dim ans1 As Integer Dim ans2 As Integer Dim counter As Integer Dim userInput As String Ask the user to enter a number and assign it to ans1%. ans1% = CInt(InputBox$ _ ("How many names would you like to enter?")) Use ans1% as the upper bound of the arrays only dimension. ReDim myNames(ans1%) Elicit ans1% strings from the user, and assign them to successive elements in the array. For counter% = 1 to ans1% myNames(counter%) = InputBox$("Enter a name: ") Next Print the contents of the array on a single line with a space between the value of each element.
Chapter 3. Data Types, Constants, and Variables
43
For counter% = 1 to ans1% Print myNames(counter%) " " ; Next Output: a newline Print "" Ask the user for another number and assign it to ans2%. ans2% = CInt(InputBox$("How many more names?")) If the number is greater than 0, resize the array, preserving its original values, so that the user can enter additional values. If ans2% > 0 Then ReDim Preserve myNames(ans1% + ans2%) Elicit the new values and assign them to the elements that have been allocated after the old ones. For counter% = 1 to ans2% myNames(counter% + ans1%) = InputBox$("Enter a name: ") Next Print the contents of the array on a single line with a space between the value of each element. For counter% = 1 to ans1% + ans2% Print myNames(counter%) " " ; Next Print "" End If
44
by 10, dividing by 10 and adding 1 to the remainder to yield a whole number between 1 and 10. For counter% = 1 To 10 anIntArray(counter%) = _ ((Round(myDblArray(counter%), 1) * 10) Mod 10) + 1 Next Test the first element of anIntArray for its data type. Print TypeName(anIntArray(1)) Output: INTEGER Print the contents of myDblArray and anIntArray. For counter% = 1 To 10 print myDblArray(counter%) & " " & anIntArray(counter%) Next Output: something like the following: .402520149946213 5 .530154049396515 6 .309299051761627 4 5.76847903430462E-02 2 2.41877790540457E-02 1 .988802134990692 1 .688120067119598 8 .493557035923004 6 .28598952293396 4 .610387742519379 7 Dim aStringArray(1 to 5, 1 to 2) aStringArray(1,1) = "Roman" aStringArray(1,2) = "Minsky" aStringArray(2,1) = "Sara" aStringArray(2,2) = "Nala" aStringArray(3,1) = "Raymond" aStringArray(3,2) = "Nala" aStringArray(4,1) = "Sandra" aStringArray(4,2) = "Brooks" aStringArray(5,1) = "Simon" aStringArray(5,2) = "Anders" Check to see if the first two characters of each element in the first dimension of aStringArray would be SA if they were uppercase. If so, print the corresponding element in the second dimension of the array, making its first character uppercase and the rest lowercase. For counter% = 1 to 5 If UCase$(Left$(aStringArray(counter%, 1), 2)) = "SA" Then Print UCase$(Left$(aStringArray(counter%, 2), 1)) _ & LCase$(Mid$(aStringArray(counter%, 2), 2, _ Len(aStringArray(counter%, 2)))) End If Next Output: Nala Brooks
Lists
A list is a one-dimensional collection of elements of the same data type. You can change the size of a list at any time while the application is running and LotusScript does not allocate any storage space at compile time for the elements of a list. Lists automatically shrink or grow when elements are deleted from or added to them. You access each element in a list by a unique String value, called a list tag. You can declare a list at module level, in a procedure, or in the definition of a class (but not in the definition of a user-defined data type). You declare a list with the Dim statement or one of its variations:
45
If you omit the As dataType clause from the Dim statement and do not include a data type suffix character in the lists name, LotusScript checks to see if the list name is covered by any applicable Deftype statement. If the name of the list is covered by a Deftype statement, then LotusScript assigns that data type to the lists elements; otherwise, LotusScript makes them type Variant. A list is initially empty. You add elements to it with statements of the following form: listName ( listTag ) = value where listName is the name of the list, listTag is a string that uniquely identifies the element, and value is the value you want to assign to the element. A List tag is essentially a key of type STRING. You use this this key to uniquely retrieve its associated data once it gets stored. List tags can be case sensitive or case insensitive, depending on the setting for case sensitivity in the module in which the list is declared. If case sensitivity is in effect for the module, the list tags A123 and a123 are different tags; if case sensitivity is not in effect, they are the same and are used interchangeably. You can control whether case sensitivity is observed in string comparison in a module by including the Option Compare statement in that module. The syntax is: Option Compare { Case | NoCase | Binary } If you include the Case or Binary keyword, string comparison is case sensitive in the module. NoCase means that such comparisons are case insensitive. Option Compare Case is the default.
46
The following example illustrates how to declare a list, add elements to it, and refer to those elements. The elements in the list are of one of the scalar data types (String).
Make string comparison case insensitive in this module. Option Compare NoCase Declare a list, myList, to hold first names. The list tags will be unique IDs. Dim myList List As String Dim newTag As String Dim newValue As String Put some elements in the list. myList("A1234") = "Andrea" myList("A2345") = "Vera" myList("A3456") = "Isabel" Ask the user to enter an ID and a name. newTag$ = InputBox$("Please enter your ID:") newValue$ = InputBox$("Please enter your first name:") Add a new element to the list with the users ID as the list tag and the users name as the value of the new element. myList(newTag$) = newValue$ Print myList(newTag$) Output: the name that the user entered
47
Erase listName removes all the elements in listName and reclaims the storage previously allocated to them. Erase listName( listTag ) removes the individual element identified by listTag from the list and reclaims the storage previously allocated to it, leaving the rest of the list intact. These functions are illustrated in the following example, which removes an employees access to a parking space when the user enters a valid employee name (a valid list tag) and matching employee ID:
Declare a list to hold employee IDs. The list tags will be the names of the employees. Dim empList List As Double Make absolutely sure empList is Double. If TypeName(empList) <> "DOUBLE LIST" Then Print "Warning: empList is " & TypeName(empList) End If If DataType(empList) <> 2053 Then Print "Warning: empList is " & CStr(DataType(empList)) We expected 2053 (that is, 2048 + 5). End If Declare a String variable for user name. Dim ans As String Declare a Double variable for user ID. Dim yourID As Double Declare an Integer variable to serve as a flag. Dim found As Boolean Create some list elements and assign them values. empList("Maria Jones") = 12345 empList("Roman Minsky") = 23456 empList("Joe Smith") = 34567 empList("Sal Piccio") = 91234 Ask the user to enter the name to be removed from the list of employees who have been assigned parking spaces. ans$ = InputBox$("Which employee no longer needs a space?") Check to see if the employees name appears as a list tag in the list. If not, display a message and stop. Otherwise, validate the employees ID. If everything checks out, remove the employee item from the parking list. If IsElement(empList(ans$)) = True then Print ans$ & " is a valid employee name." yourID# = CDbl(InputBox$("Whats " & ans$ & "s ID?")) The following ForAll block does two things: it checks to see if yourID# is a valid ID and, if so, if it matches the ID for the employee whose name is ans$. If so, that element is removed (erased) from the list. The found flag is initially FALSE (0). If yourID# is a valid ID, found is set to TRUE (-1). The variable empID is the reference variable in the ForAll loop. found = FALSE ForAll empID In empList If empID = yourID# then
48
found = TRUE If ListTag(empID) = ans$ then Erase empList(ans$) Verify the removal of the list element. If IsElement(empList(ans$)) = FALSE then Print ans$ & " is no longer on the list." End If Else Print "Valid ID but wrong employee." End If No need to look further for yourID#, so get out of the ForAll loop. Exit ForAll End If End ForAll If found = False then Print "No such employee ID." End If Else Print "No such employee." End if
Variants
Variant is a special data type: variables of type Variant can hold values of any of the following data types that LotusScript recognizes, except for user-defined data types: v A value of any of the scalar data types that LotusScript supports: Boolean, Byte, Integer, Long, Single, Double, Currency, String v A date/time value v An array or list v An object reference, that is, a pointer to an OLE Automation object or to an instance of a product-defined or user-defined class, or an object reference to a Java Object. v The NULL value v The EMPTY value You declare a Variant variable the same way you declare a scalar variable, explicitly or implicitly. If no Deftype statements are applicable, a variable that you declare without using an As dataType clause or a data type suffix is of type Variant. Here, Variant variables appear with the suffix V to distinguish them from object reference variables or variables of some user-defined data type. For example:
Dim myVariant1V As Variant Dim myVariant2V Public myVariant3V As Variant myVariant4V = 123.45
When you declare a Variant variable explicitly, LotusScript initializes it to the special value EMPTY. (Use the function IsEmpty to test a Variant variable for this value.) Declaring a Variant variable is less efficient than assigning it another data type, but is convenient. When you assign a Variant variable a value, LotusScript determines the data type of that value in either of two ways, depending on the available information: v If the data type of the value is known, then the value retains its original data type. v If the value is a literal, it is assigned a default data type appropriate to that value.
Chapter 3. Data Types, Constants, and Variables
49
You can determine the data type of a value assigned to a Variant variable with the DataType or TypeName function, as in the following example:
Dim numVarV As Variant Dim anAmount As Currency anAmount@ = 20.05 numVarV = anAmount@ Print TypeName(numVarV) Output: CURRENCY numVar = 20.05 Print TypeName(numVar) Output: DOUBLE
Under certain circumstances, the data type of a value assigned to a Variant variable can change to accommodate the requirements of a particular operation on it. For instance, in the following example the user enters a sequence of numeric characters, which are then treated as a String value for some operations and as a numeric value for others:
Declare a Boolean variable and assign it an initial value of FALSE (0). The application subsequently tests this variable, taking appropriate action depending on the variables value, True (-1) or False (0). quitFlag = FALSE Dim ansV As Variant Have the user enter some numeric characters. ansV = InputBox("Enter a number.") See how many characters the user entered and assign that number to the Integer variable UB%. This involves treating the value of ansV as a String. UB% = Len(ansV) Test the value of ansV to see if it can be interpreted as being of one of the numeric data types. If so, declare a dynamic array of Variants, then allocate space for as many elements as there are characters in ansV, and then assign the successive digits in ansV to the elements in the array. If IsNumeric(ansV) = True then Dim digitArrayV() As Variant ReDim digitArrayV(1 To UB%)As Variant For x% = 1 to UB% digitArrayV(x%) = Mid(ansV, x%, 1) Next Else Print "You entered some nonnumeric characters." quitFlag = TRUE End If If ansV was able to be interpreted as a numeric, print its digits and their sum; then print the result of adding that sum to the original number that the user entered. If quitFlag = False Then Dim theSum As Integer theSum% is initialized to 0. For x% = 1 to UB% theSum% = theSum% + digitArrayV(x%) Print digitArrayV(x%) ; Next Print "" Print "Their sum is: " & theSum% Print "Their sum added to the original number is: " _ & ansV + theSum% End If
50
Output, supposing the user enters 12345: 12345 Their sum is: 15 Their sum added to the original number is: 12360
Boolean values
LotusScript recognizes the Boolean values True and False, which it evaluates as -1 and 0, respectively. When you assign a Boolean value to a variable of type Variant, you can display that value as text (True or False) or as an integer (-1 or 0). Note: As of LotusScript 5.0 (Domino/Notes 6.0), LotusScript also has a Boolean data type. This data type is used for variables with values of True (-1) or False (0). See Boolean data type in the LotusScript Language Reference for more information and examples.
Dim varV As Variant varV = 1 > 2 The expression 1 > 2 (1 is greater than 2) evaluates to False, so varV is assigned a value of False. Print varV Output: False Print TypeName(varV) Output: BOOLEAN Print DataType(varV) Output: 11 varV = True Print varV Output: True Print CInt(varV) Output: -1 Print varV + 2 Output: 1
You can assign a Boolean value of True or False to a variable of any of the numeric data types that LotusScript recognizes. LotusScript converts that value to an integer (-1 or 0).
Dim anInt As Integer varV = True anInt% = varV Print anInt% Output: 0 Print TypeName(anInt%) Output: INTEGER
51
Dates/Time
LotusScript does not have a date/time data type as such: you cant declare a variable with date/time values. However, LotusScript does recognize dates internally and provides a set of functions for entering, retrieving, and manipulating date/time values, which are stored as eight-byte (double) floating-point values. The integer part represents a serial day counted from 1/1/100 AD, and the fractional part represents the time as a fraction of a day, measured from midnight. The range of allowable values for a date is -657434 (January 1, 100 AD) to 2958465 (December 31, 9999). 0 is December 30, 1899. You use Variant variables to hold and manipulate date/time values, which you can produce by calling one or another of the following functions:
Function/Statement CDat Function Date Function Date Statement DateNumber Function DateValue Function Day Function FileDateTime Function Format Function Hour Function IsDate Function Minute Function Month Function Now Function Second Function Time Function Time Statement TimeNumber Function Timer Function TimeValue Function Today Function WeekDay Function Year Function Purpose Converts a numeric or string expression to a date/time Variant value Returns the system date Sets the system date Converts year, month, and day, to a date value Converts a string to a date value Returns the day of the month (1-31) from a date/time expression Returns the date and time a file was most recently saved Formats a number, a date/time value, or a string Returns the hour of the day (0-24) of a date/time expression Returns True (-1) if a Variant date/time value, otherwise False (0) Returns the minute of the hour (0-59) from a date/time expression Returns the month of the year (1-12) from a date/time expression Returns the current system date and time Returns the current second of the minute (0-59) from a date/time expression Returns the system time. The date part of the value is set to 0 or December 30, 1899. Sets the system date Converts hours, minutes, and seconds to a fractional date/time value Returns the time elapsed since midnight in seconds Converts a string to a fractional date/time value Returns the system date (equivalent to the Date function) Returns the day of the week (1-7) from a date/time expression Returns the year as a four-digit integer from a date/time expression
Note: Variant variables containing date/time values may be added to produce another Variant variable containing a date/time value. However subtracting one Variant variable containing a date/time value from another will produce a Variant of type Double. You must use the Cdat function to convert the variable back to a date/time value. You can use the DataType or TypeName functions to determine if a Variant variable holds a date or date/time value. If it does, DataType returns a value of 7, and TypeName returns DATE. The following examples illustrate the various ways you can derive date and date/time values, how you can assign them to Variant variables, and some of the operations you can then perform on them, such as calculating a time span or determining the day of the week on which a given date will fall.
52
Suppose that today is October 26, 1994, the time is 7:49:23 AM, and you declare the following variables:
Dim Dim Dim Dim theInstantV As Variant theDateV As Variant theDateValV As Variant myDate As String
This example gets the current date and time by calling the function Now and then assigns the result to a Variant variable, the InstantV:
theInstantV = Now Print theInstantV Output: 10/26/94 7:49:23 AM
This example prints the integers corresponding to the day of the month and the hour of the day:
Print Day(theInstantV) & " " & Hour(theInstantV) Output: 26 7
This example assigns the current date to the Variant variable, theDateV:
theDateV = Date Print theDateV Output: 10/26/94 Print theDateV - 1 Output: 10/25/94
This example converts the value of the current date to a value of type Double:
Print CDbl(theDateV) Output: 34633 Convert a value of type Double to a date value, assign it to a Variant variable, and print it. theDateV = CDat(34633) Print theDateV Output: 10/26/94
This example gets the integer representation of the current year, month, and day; increments the month and day values and assigns the results to some Integer variables; passes them to DateNumber, which calculates the date on the basis of those values and returns it, assigning it to the Variant variable theDateV:
y% = Year(theDateV) m% = Month(theDateV) + 1 d% = Day(theDateV) + 1 theDateV = DateNumber(y%, m%, d%) Print theDateV Output: 11/27/94
This example assigns a string that can be interpreted as a date to a String variable, myDate$; then converts it to a date/time value and performs a calculation on it (subtract a day), and returns the resulting date:
myDate$ = "October 28, 1994" Print DateValue(myDate$) - 1 Output: 10/27/94 theDateV = DateValue(myDate$) Check the data type of the value held by the Variant variable theDateV. Print TypeName(theDateV) Output: DATE
53
Note: Various products have different interpretations of two-digit years. Notes, for instance, would write the same value as Oct-18-2014. This example converts the date/time value of the current date to a value of type Double:
Print CDbl(Date) Output: 34633
This example converts the date/time value of a particular date to a value of type Double by passing it as a String to DateValue and then passing the result to CDbl, which converts it to a value of type Double:
Print CDbl(DateValue("10-18-14")) Output: 5405 Print CDbl(Date) - CDbl(DateValue("10-18-14")) Output: 29228
Note: If the dates are subtracted from each other without first converting to Double, the result will be a Variant of type Double. This example determines which day of the week a particular day falls on; Sunday is 1.
Print Weekday(theDateValV) Output: 1
Referring to Variants
You can assign a Variant variable a value of any of the scalar data types where assigning a value of one scalar data type to a variable of another scalar data type would produce an error, as in the following example:
Dim myVariantV As Variant Dim myVariantArrayV(1 to 5) As Variant Dim aString As String Dim anInt As Integer myVariantV = 1234567 myVariantArrayV(1) = 1234567 myVariantV = "Hello" myVariantArrayV(1) = myVariantV aString$ = 1234567
54
Produce an error, because 1234567 is not a String. anInt% = 1234567 Produce an error because 1234567 is too large to be treated as an Integer.
The Variant data type allows you a great deal of freedom in manipulating values of different types (such as dates) without having to concern yourself with type checking and compatibility issues. The Variant data type also makes it possible for arrays and lists to hold items of different data types (rather than being restricted to a single type) and significantly expands the range of data that you can include in a user-defined data type. However, Variants take up more storage than scalars, and operations involving Variants tend to be slower than those involving scalars. It is easy to lose track of the specific data type of a value that you are manipulating, which can sometimes produce unexpected results. Consider whether you really need to use a Variant variable, rather than a variable of one of the explicitly declared scalar types, to perform a given operation with efficiency.
55
56
LotusScript operators
LotusScript uses the following operators: v Arithmetic, for performing basic addition operations
Print 3 + 4 Prints 7
v Boolean, for testing two operand expressions for their truth value (True or False)
(4 > 0) And (4 < 10) Print 7 <= 8 Print "My cat " & "Geoffrey" Print "kid" < "kit" newInt% = 8 + 12 Print newInt% Class ClassA ... End Class Dim X As New ClassA Prints 20 Output is True Prints True Prints My cat Geoffrey Prints True
v Relational (comparison), for comparing values v String concatenation, for joining discrete elements to form a single string v String relational (comparison), for determining the relative positions of two strings in ASCII sort order v Assignment, for assigning values to variables and properties
v The Is operator, for comparing the values of object reference variables to see if they are equal.
57
Logical negation or ones complement Boolean or bitwise And Boolean or bitwise Or Boolean or bitwise exclusive Or Boolean or bitwise logical equivalence Boolean or bitwise logical implication Assignment
Assignment
Examples
This example shows the order of precedence for Arithmetic operators.
Print 6 + 4 / 2 Print (6 + 4) / 2 Print -2 ^ 2 Print (-2) ^ 2 Prints 8 Prints 5 Prints -4 Prints 4
58
Print "Alphabet" = "Alpha" & "bet" Prints True Print 4 And 10 - 2 * 3 / 2 Output: 4 because 2 * 3 = 6 6 / 2 = 3 10 - 3 = 7 (binary 111) 4 (binary 100) And 7 (binary 111) = 4 (binary 100).
You can alter the default order in which operations are performed by enclosing the expressions you want evaluated first in parentheses. For example:
anInt% = 5 anotherInt% = 10 aThirdInt% = 7 print anInt% - (anotherInt% + aThirdInt%) Output: -12
or, alternatively:
theResult% = -1 Or Print theResult% Output: False because -1 Or -1 theResult% = -1 Or Print theResult% Output: True because -1 Imp 0 -1 Imp 0 = True, and True Imp 0 is False. (-1 Imp 0) is False, and -1 Or False is True.
59
Type of operator
Operation Greater than Greater than or equal to Greater than or equal to Ones complement Bitwise And Bitwise Or Bitwise exclusive Or Bitwise equivalence Bitwise implication Logical negation Logical And Logical Or Logical exclusive Or Logical equivalence Logical implication
Logical (bitwise)
Logical (Boolean)
Arithmetic Operators
v v v v Exponentiation raises a number to a power. Negation returns a numbers negative value. Multiplication multiplies two numbers. Division divides a number and returns a floating-point number.
v Integer division rounds numbers to integers before dividing them. v Modulo divides numbers and returns the remainder. v Addition finds the sum of two numbers. v Subtraction finds the difference between two numbers. When an arithmetic expression contains a NULL operand, the expression as a whole evaluates to NULL. For example:
Dim varV Dim anInt% varV = NULL varV = varV ^ 2 Test to see if varV is NULL. Print IsNull (varV) Output: True anInt% = 5 Print IsNull(varV * anInt%) Output: True
Only variables of type Variant may be assigned a value of NULL without causing an error. This example is valid:
varV = NULL varV = varV * 5
60
When the result of an arithmetic operation is too large for the type of variable to which it is assigned, LotusScript automatically converts the data type, if possible, or an overflow error results.
Dim anInt As Integer Dim aNumericV As Variant aNumericV = 10000 ^ 10 Print aNumericV Output: 1E+40 Print TypeName(aNumericV) Output: DOUBLE anInt% = 10000 ^ 10 Generate an error.
LotusScript also rounds numbers when performing floating point division on integer operands:
aDouble# = 42.5 anInt% = 64 anInt% = anInt% / 7 Print anInt% Output: 9 The Mod operator rounds its two operands to Integer expressions, divides the first Integer by the second, and returns the remainder. Print aDouble# Mod anInt% Output: 6
For more information on data type conversion and rounding, see Automatic data type conversion in Data Types, Constants, and Variables.
Exponentiation operator
Raises a number to a power.
Syntax
number ^ exponent
Elements
number Any numeric expression. exponent Any numeric expression. If number is negative, exponent must be an integer value.
Return value
The resulting data type is a Double or a Variant of type Double. If either or both operands are NULL expressions, the result is a NULL.
Usage
Multiple ^ operators in a single expression are evaluated from left to right.
Language cross-reference
@Power function in formula language
61
Example
Print Print Print Print Use Print 4 ^ 3 4.5 ^ 3 -2 ^ 3 2 ^ 3 ^ 2 parentheses 2 ^ (3 ^ 2) Prints 64 Prints 91.125 Prints -8 Prints 64 to change order of evaluation. Prints 512
Negation operator
Returns the negative value of a number.
Syntax
- numExpr
Elements
numExpr Any numeric expression. An EMPTY operand (DataType 0) is considered a 0.
Return value
The result is of the same data type as numExpr. The data type of -v, where v has the value EMPTY, is Long. If numExpris a NULL, the result is a NULL.
Example
Dim x As Integer x% = 56 Print -x% Prints -56
Multiplication operator
Multiplies two numbers.
Syntax
numExpr1 * numExpr2
Elements
numExpr1, numExpr2 Any numeric expressions. An EMPTY operand is considered a 0.
Return value
The result is a value whose data type is generally the same as that of the operand whose data type is latest in this ordering: Integer, Long, Single, Currency, Double. For example, if one operand is a Double and the other is a Long, then the data type of the result is Double. The exceptions are: v If either numExpr1or numExpr2 are NULL expressions, the result is a NULL. v If numExpr1 and numExpr2 are both EMPTY, the result is Integer. v When the result has a Variant data type of Long, Single, or Date/Time that overflows its legal range, its converted to a Variant of Double. When the result is a Variant of type Integer that overflows its legal range, its converted to a Variant of Long.
62
Example
Dim x As Integer x% = 2 * 3 Print x% * 3.4 Prints 20.4
Division operator
Divides two numbers and returns a floating-point result.
Syntax
numExpr1 / numExpr2
Elements
numExpr1, numExpr2 Any numeric expressions. An EMPTY operand is considered a 0.
Return value
The resulting data type is a Double or a Variant of Double. If either or both operands are NULL expressions, the result is a NULL.
Example
This example contrasts ordinary division with integer division. Integer division rounds, divides, and then drops the fractional part. Because the operands are rounded before division, the result may differ from the integer part of an ordinary division operation.
Print Print Print Print 8 / 5 8 \ 5 16.9 / 5.6 16.9 \ 5.6 Prints Prints Prints Prints 1.6 1 3.01785714285714 2
Syntax
numExpr1 \ numExpr2
Elements
numExpr1, numExpr2 Any numeric expressions. An EMPTY operand is considered a 0.
Return value
The result is of data type Integer, Long, or Variant of type Integer or Long. If either or both operands are NULL expressions, the result is a NULL.
Usage
LotusScript rounds the value of each operand to an Integer or Long value. Then numExpr1 is divided by numExpr2 as an ordinary numerical division; and any fractional part of the result is dropped.
Example
This example contrasts ordinary division with integer division. Integer division rounds, divides, and then drops the fractional part. Because the operands are rounded before division, the result may differ from the integer part of an ordinary division operation.
63
1.6 1 3.01785714285714 2
Mod operator
Divides two numbers and returns the remainder.
Syntax
numExpr1 Mod numExpr2
Elements
numExpr1, numExpr2 Any numeric expressions. An EMPTY operand is considered a 0.
Return value
The result is of data type Integer, Long, or Variant of type Integer or Long. If either or both operands are NULL expressions, the result is a NULL.
Usage
The remainder operator divides numExpr1 by numExpr2 and returns the remainder. The operands are rounded to Integer expressions before the division takes place.
Language cross-reference
@Modulo function in formula language
Example
This example contrasts Modulo division with ordinary division. Mod returns the remainder, while ordinary division returns the dividend.
Print 12 Mod 8 Print 12 / 8 Prints 4 Prints 1.5
Addition operator
Finds the sum of two numbers.
Syntax
numExpr1 + numExpr2
Elements
numExpr1, numExpr2 Any numeric expressions. An EMPTY operand is considered a 0.
Return value
When adding expressions of numeric data types, the result is a value whose data type in most cases is the same as that of the operand whose data type is latest in this ordering: Integer, Long, Single, Double, Currency. For example, if one operand is a Double and the other is an Integer, then the data type of the result is Double. The exceptions are: v When the resulting data type is a Variant of Integer that overflows its legal range, the result is converted to a Variant of Long. v If numExpr1 and numExpr2 are both EMPTY, the result has Integer.
64
v When the resulting data type is a Variant of Long, Single, or Date/Time that overflows its legal range, the result is converted to a Variant of Double.
Usage
LotusScript interprets the + operator as either addition or string concatenation, depending on the data types of expr1 and expr2. The following table lists these interpretations. The numeric data types are Integer, Long, Single, Double, Currency, and (in a Variant variable only) Date/Time.
One expression Numeric Numeric Numeric String String Any type Any type Variant of numeric data type Variant of numeric data type Other expression Numeric String Variant (other than NULL) Variant (other than NULL) String Variant that contains EMPTY NULL Variant of numeric data type Variant of String data type Operation Addition (Type mismatch error occurs) Addition String concatenation String concatenation Returns first expression Returns NULL Addition Addition, if string can be converted to a numeric data type; otherwise a type mismatch error occurs String concatenation
To avoid confusion, use the & operator, not the + operator, for string concatenation.
Language cross-reference
@Sum function in formula language
Example
Dim a As Variant Dim b As Integer a = "8" b% = 7 Use Print Print Print Print operator for addition. 8 + 7 a + 7 8 + b% a + b% Prints Prints Prints Prints 15 15 15 15
Use operator for string concatenation. Print "Hello " + "there" Prints "Hello there" Print a + "7" Prints "87"
Subtraction operator
Finds the difference between two numbers.
Syntax
numExpr1 - numExpr2
Elements
numExpr1, numExpr2 Any numeric constant, variable, or expression; or any function that returns a number. An EMPTY operand is considered a 0.
65
Return value
The result is a value whose data type is generally the same as that of the operand whose data type is latest in this ordering: Integer, Long, Single, Double, Currency. For example, if one operand is a Long and the other is a Currency, then the data type of the result is Currency. The exceptions are: v When the result is a Variant of Integer that overflows its legal range, the result is converted to a Variant of Long. v When the result is a Variant of Long, Single, or Date/Time that overflows its legal range, the result is converted to a Variant of Double. v If numExpr1 and numExpr2 are both EMPTY, the result has Integer. v If either or both operands are NULL expressions, the result is a NULL. v If numExpr1 and numExpr2 are both Variants of date/time values, the result is a Variant of Double.
Example
Print 5 - 3.4 Prints 1.6
Syntax
expr1 operator expr2
Elements
expr1, expr2 Any expressions. operator One of the following operators: <, >, <=, =<, >=, =>, <>, ><, =.
Return value
An expression consisting of two numeric operands and a relational (comparison) operator evaluates to True (-1), False (0), or, if either or both of the operands is NULL, to NULL. For a description of the way in which LotusScript treats the values True (-1) and False (0), see Boolean values in the chapter Data Types, Constants, and Variables. Comparing two expressions, neither of which is NULL, returns the following values:
Operator < <= or =< > >= or => = <> or >< Operation Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to TRUE if expr1 < expr2 expr1 <= expr2 expr1 > expr2 expr1 >= expr2 expr1 = expr2 expr1 <> expr2 FALSE if expr1 >= expr2 expr1 > expr2 expr1 <= expr2 expr1 < expr2 expr1 <> expr2 expr1 = expr2
66
Usage
LotusScript interprets the relational operator as either numeric comparison or string comparison, depending on the data types of expr1 and expr2. The following table lists these interpretations. The numeric data types are Integer, Long, Single, Double, Currency, and (in a Variant variable only) Date/Time.
One expression Numeric Numeric Numeric Numeric String String String Variant containing string value Variant that contains EMPTY Variant of numeric data type Variant that contains EMPTY Variant of numeric data type Variant that contains EMPTY Other expression Numeric Variant of numeric data type or Variant containing string value that can be converted to a number Variant containing String value that cannot be converted to a number Variant that contains EMPTY String Variant (other than NULL) Variant that contains EMPTY Variant containing string value Variant containing string value Operation Numeric comparison. Numeric comparison. Type mismatch error occurs. Numeric comparison, with 0 substituted for the EMPTY expression. String comparison. String comparison. String comparison. String comparison. String comparison, with the empty string () substituted for the EMPTY expression. Numeric comparison. Numeric comparison, with 0 substituted for the EMPTY expression. Numeric comparison. The numeric expression is less than the string expression. Expressions are equal.
Variant of numeric data type Variant of numeric data type Variant containing string value
String comparison
For string comparison, the Option Compare statement sets the comparison method: v Option Compare Case and Option Compare NoCase specify comparison using the character collating sequence determined by the Lotus software that you are using. Case specifies case-sensitive comparison, and NoCase specifies case-insensitive comparison. v Option Compare Pitch and Option Compare NoPitch specify comparison using the character collating sequence determined by the Lotus software that you are using. Pitch specifies pitch-sensitive comparison, and NoPitch specifies pitch-insensitive comparison. These options apply to Asian (double byte) characters. v Option Compare Binary specifies string comparison in the platforms collating sequence. The effect is platform sort-order, case-sensitive comparison. If you omit the Option Compare statement, the default method of string comparison is the same as Option Compare Case, Pitch. To compare strings, LotusScript examines the two strings character by character, starting with the first character in each string. The collating sequence values (positions in the character sort sequence) of the two characters are compared.
Chapter 4. Expressions and Operators
67
v If these values are not equal, the string whose character has the larger collating sequence value (appears later in the sort sequence) is the larger string. v If the collating sequence values of the pair of characters are the same, and both strings contain more characters, then the character comparison proceeds to the next character. If the end of both strings is reached simultaneously by this process, then neither string has been found larger than the other, and the strings are equal. Otherwise the longer string is the larger string.
Examples
This example compares numbers.
Print Print Print Print Print Print 1 2 1 2 2 2 < 2 > 1 <> 2 >= 2 <= 2 = 2 Prints Prints Prints Prints Prints Prints True True True True True True
68
anInt% = 10 anotherInt% = 15 Dim theResultV As Variant If anInt% > anotherInt% Then Print anInt% & " is greater than " & anotherInt% & "." Else Print anInt% & " is less than or equal to " & _ anotherInt% & "." End If Output: 10 is less than or equal to 15. theResultV = (anInt% > anotherInt%) Print theResultV Output: False Print CInt(anInt% > anotherInt%) Output: 0 Print (anInt% > anotherInt%) = False Output: True because the expression (anInt% > anotherInt%) = False is True.
Logical Operators
You use the logical operators And, Or, Xor, Eqv, and Imp to perform two kinds of operations: v Bitwise Compares the bits in the binary representation of two numeric values and returns a new number derived from that comparison. For example:
Calculate the logical product of binary 10 and 11 and display the result in binary representation. Print Bin$(2 And 3) Output: 10
v Boolean Tests the truth value of a two-operand expression and returns a value of True (-1), False (0), or NULL. LotusScript compares the bits in the binary representation of the truth values for each operand and returns a value derived from that comparison. For example:
Dim anInt% As Integer anInt% = 5 Print (anInt% > 2) And (anInt% < 10) Both operands are True. Output: True Print CInt((anInt% > 2) And (anInt% < 10)) Output: True Print CInt(True And True) Output: True
You use the logical operator Not to perform the same sorts of operations on expressions consisting of a single operand. Not reverses the values of the bits in the binary representation of its operand. For example:
Print Bin$(Not 3) Output: 11111111 11111111 11111111 11111100 Print Bin$(Not False) Output: 11111111 11111111 11111111 11111111 Print (Not True) Output: 0
69
Bitwise Operators
An expression consisting of the bitwise operator Not and a numeric operand evaluates to an Integer or Long value (or to NULL if the operand is NULL). This number is the result of reversing the values of the bits in the binary representation of the operand (ones complement). For example:
anInt% = 8 Print Bin$(anInt%) Output: 1000 anotherInt% = Not anInt% Print Bin$(anotherInt%) Output: 11111111 11111111 11111111 11110111
An expression consisting of two numeric operands and a bitwise operator evaluates to an Integer or Long value (or to NULL if one of the operands is NULL). The rules that determine the data type of the result of a bitwise operation are: v LotusScript converts an EMPTY-valued operand to 0. v LotusScript rounds a floating-point operand to an integer. The data type of the operand is Long. v If an operand is a date/time value, LotusScript uses the numeric value of the date as the operand. The data type of the operand is Long. The results of bitwise operations on two-operand expressions are:
Operator And If bit n in expr1 is 0 0 1 1 Or 0 0 1 1 Xor 0 0 1 1 Eqv 0 0 1 1 Imp 0 0 1 1 And bit n in expr2 is 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Then bit n in the result is 0 0 0 1 0 1 1 1 0 1 1 0 1 0 0 1 1 1 0 1
For example:
70
anInt% = 10 anotherInt% = 5 aDouble# = 2.6 Print Bin$(anInt%) Output: 1010 Print Bin$(anotherInt%) Output: 101 Print Bin$(aDouble#) Output: 11 theResult% = anInt% And anotherInt% Print Bin$(theResult%) Output: 0 theResult% = anInt% And aDouble# Print Bin$(theResult%) Output: 10 theResult% = anInt% Or anotherInt% Print Bin$(theResult%) Output: 1111 theResult% = anInt% Or aDouble# Print Bin$(theResult%) Output: 1011 theResult% = anInt% Xor anotherInt% Print Bin$(theResult%) Output: 1111 theResult% = anInt% Xor aDouble# Print Bin$(theResult%) Output: 1001 theResult% = anInt% Eqv anotherInt% Print Bin$(theResult%) Output: 11111111 11111111 11111111 11110000 theResult% = anInt% Eqv aDouble# Print Bin$(theResult%) Output: 11111111 11111111 11111111 11110110 theResult% = anInt% Imp anotherInt% Print Bin$(theResult%) Output: 11111111 11111111 11111111 11110101 theResult% = anInt% Imp aDouble# Print Bin$(theResult%) Output: 11111111 11111111 11111111 11110111
Boolean Operators
An expression consisting of two operands and a Boolean operator evaluates to True if the expression is true, and False if it is false, unless one of the operands is NULL. In that case, the result may be NULL or True or False, depending on the operator and the operand. The possibilities are:
Operator And If expr1 is True True False False Or True True False False Xor True And expr2 is True False True False True False True False True The expression evaluates to True False False False True True True False False
71
Operator
And expr2 is False True False True False True False True False True False
The expression evaluates to True True False True False False True True False True True
Eqv
Imp
When an operand in a numeric expression including a Boolean operator is NULL, the whole expression evaluates to NULL except under the following circumstances: v v v v If If If If the the the the operator operator operator operator is AND and the other operand is False, then the expression evaluates to False. is OR and the other operand is True, then the expression evaluates to True. is IMP and the first operand is False, then the expression evaluates to True. is IMP and the second operand is True, then the expression evaluates to True.
This example has the user enter two integers between 1 and 10. It tests to see if the first (num1%) is less than 6 and if the second (num2%) is greater than 5. Then it displays a message according to the truth value of the two tests.
Dim num1 As Integer Dim num2 As Integer num1% = InputBox("Enter an integer between 1 and 10:") num2% = InputBox("Enter an integer between 1 and 10:") Print "num1 = " & num1% & " num2 = " & num2% If num1% <6 And num2% >5 Then Print "And:" & num1% & " is less than 6 and " & num2% " is greater than 5." End If If num1% <6 Or num2% >5 Then Print "Or:" & num1% & " is less than 6 or " & num2% & " is greater than 5, or both." End If If num1% <6 XOr num2% >5 Then Print "XOr: " & num1% & " is less than 6 or " & num2% " is greater than 5, but not both." End If If num1% <6 Eqv num2% >5 Then Print "Eqv:" & num1% & " is less than 6 and " & num2% " is greater than 5, or " & num1% & _ " is greater than 5 and " & num2% & " is less than End If If num1% <6 Imp num2% >5 Then Print "Imp:" & num1% & " is less than 6 and " & num2% " is greater than 5, or " & num1% & _ " is greater than 5 and " & num2% & _ " is less than 6, or " & num1% & _ " is greater than 5 and " & num2% & _ " is greater than 5." End If Sample Output: num1 = 6 num2 = 6
& _
& _
72
Or: 6 is less than 6 or 6 is greater than 5, or both. XOr: 6 is less than 6 or 6 is greater than 5, but not both. Imp: 6 is less than 6 and 6 is greater than 5, or 6 is greater than 5 and 6 is less than 6, or 6 is greater than 5 and 6 is greater than 5. num1 = 10 num2 = 1 Eqv: 10 is less than 6 and 1 is greater than 5, or 10 is greater than 5 and 1 is less than 6. Imp: 10 is less than 6 and 1 is greater than 5, or 10 is greater than 5 and 1 is less than 6, or 10 is greater than 5 and 1 is greater than 5. num1 = 5 num2 = 9 And: 5 is less than 6 and 9 is greater than 5. Or: 5 is less than 6 or 9 is greater than 5, or both. Eqv: 5 is less than 6 and 9 is greater than 5, or 5 is greater than 5 and 9 is less than 6. Imp: 5 is less than 6 and 9 is greater than 5, or 5 is greater than 5 and 9 is less than 6, or 5 is greater than 5 and 9 is greater than 5.
Not operator
Performs logical negation on an expression. The Not operator has the effect of rounding its argument to the nearest integer, changing the sign, and subtracting 1.
Syntax
Not expr
Elements
expr Any expression. Its value must lie within the range for Long values.
Usage
The following table explains how LotusScript determines the result of the Not operation.
expr TRUE FALSE NULL Result FALSE TRUE NULL
In addition to performing logical negation, the Not operator reverses the bit values of any variable and sets the corresponding bit in the result according to the following table.
Bit n in expr 0 1 Bit n in result 1 0
Example
Print Not TRUE Print Not 12.4 Prints False Prints -13
And operator
Performs a logical conjunction on two expressions. LotusScript rounds to the nearest integer before performing the And operation.
Chapter 4. Expressions and Operators
73
Syntax
expr1 And expr2
Elements
expr1, expr2 Any expressions. Their values must lie within the range for Long.
Usage
When using the And operator, any FALSE expression will cause the result to be FALSE.
expr1 TRUE TRUE FALSE FALSE TRUE NULL FALSE NULL NULL expr2 TRUE FALSE TRUE FALSE NULL TRUE NULL FALSE NULL Result TRUE FALSE FALSE FALSE NULL NULL FALSE FALSE NULL
Besides combining expressions, And compares identically positioned bits in two numeric expressions (known as a bit-wise comparison) and sets the corresponding bit in the result.
Bit n in expr1 1 1 0 0 Bit n in expr2 1 0 1 0 Bit n in result 1 0 0 0
Example
Boolean usage Dim johnIsHere As Boolean, jimIsHere As Boolean Dim bothAreHere As Boolean johnIsHere = TRUE jimIsHere = FALSE bothAreHere = johnIsHere And jimIsHere Print bothAreHere Bit-wise usage Dim x As Integer, y As Integer x% = &b11110000 y% = &b11001100 Print Bin$(x% And y%) Prints 0 (False)
Prints 11000000
Or operator
Performs a logical disjunction on two expressions.
74
Syntax
expr1 Or expr2
Elements
expr1, expr2 Any expressions. Their values must lie within the range for Long values.
Usage
In using the Or operation, both expressions must be FALSE for the result to be FALSE.
expr1 TRUE TRUE FALSE FALSE TRUE NULL FALSE NULL NULL expr2 TRUE FALSE TRUE FALSE NULL TRUE NULL FALSE NULL Result TRUE TRUE TRUE FALSE TRUE TRUE NULL NULL NULL
In addition to performing a logical disjunction, the Or operator compares identically positioned bits in two numeric expressions (known as a bit-wise comparison) and sets the corresponding bit in the result according to the following table.
Bit n in expr1 1 1 0 0 Bit n in expr2 1 0 1 0 Bit n in result 1 1 1 0
Example
Boolean usage Dim johnIsHere As Boolean, jimIsHere As Boolean Dim oneOrMoreIsHere As Boolean johnIsHere = TRUE jimIsHere = FALSE oneOrMoreIsHere = johnIsHere Or jimIsHere Print oneOrMoreIsHere Bit-wise usage Dim x As Integer, y As Integer x% = &b11110000 y% = &b11001100 Print Bin$(x% Or y%) Prints True
Prints 11111100
Xor operator
Performs a logical exclusion on two expressions.
75
Syntax
expr1 Xor expr2
Elements
expr1, expr2 Any expressions. Their values must lie within the range for Long values.
Usage
The following table explains how LotusScript determines the result of the Xor operation.
expr1 TRUE TRUE FALSE FALSE TRUE NULL FALSE NULL NULL expr2 TRUE FALSE TRUE FALSE NULL TRUE NULL FALSE NULL Result FALSE TRUE TRUE FALSE NULL NULL NULL NULL NULL
In addition to performing a logical exclusion, the Xor operator compares identically positioned bits in two numeric expressions (known as a bit-wise comparison) and sets the corresponding bit in the result according to the following table.
Bit n in expr1 1 1 0 0 Bit n in expr2 1 0 1 0 Bit n in result 0 1 1 0
Example
Boolean usage Dim johnIsHere As Boolean, jimIsHere As Boolean Dim oneButNotBothIsHere As Boolean johnIsHere = TRUE jimIsHere = FALSE oneButNotBothIsHere = johnIsHere Xor jimIsHere Print oneButNotBothIsHere Bit-wise usage Dim z As Integer, y As Integer z% = &b11110000 y% = &b11001100 Print Bin$(z% Xor y%) Prints True
Prints 111100
Eqv operator
Performs a logical equivalence on two expressions.
76
Syntax
expr1 Eqv expr2
Elements
expr1, expr2 Any expressions. Their values must lie within the range for Long values.
Usage
The following table explains how LotusScript determines the result of the Eqv operation.
expr1 TRUE TRUE FALSE FALSE TRUE NULL FALSE NULL NULL expr2 TRUE FALSE TRUE FALSE NULL TRUE NULL FALSE NULL Result TRUE FALSE FALSE TRUE NULL NULL NULL NULL NULL
In addition to performing a logical equivalence, the Eqv operator compares identically positioned bits in two numeric expressions (known as a bit-wise comparison) and sets the corresponding bit in the result according to the following table.
Bit n in expr1 1 1 0 0 Bit n in expr2 1 0 1 0 Bit n in result 1 0 0 1
Example
Dim a As Variant, b As Variant, c As Variant a = &HF b = &HF0 c = &H33 Print TRUE Eqv TRUE Prints True Print FALSE Eqv FALSE Prints True Print TRUE Eqv FALSE Prints False Print Hex$(a Eqv b) Prints FFFFFF00 Print Hex$(a Eqv c) Prints FFFFFFC3 Print Hex$(b Eqv c) Prints FFFFFF3C
Imp operator
Performs a logical implication on two expressions.
Syntax
expr1 Imp expr2
77
Elements
expr1, expr2 Any expressions. Their values must lie within the range for Long values.
Usage
The following table explains how LotusScript determines the result of the Imp operation.
expr1 TRUE TRUE FALSE FALSE TRUE NULL FALSE NULL NULL expr2 TRUE FALSE TRUE FALSE NULL TRUE NULL FALSE NULL Result TRUE FALSE TRUE TRUE NULL TRUE TRUE NULL NULL
In addition to performing a logical implication, the Imp operator compares identically positioned bits in two numeric expressions (known as a bit-wise comparison) and sets the corresponding bit in the result according to the following table.
Bit n in expr1 1 1 0 0 Bit n in expr2 1 0 1 0 Bit n in result 1 0 1 1
Example
Dim youCanSee As Boolean, lightIsOn As Boolean You dont need the light to see. youCanSee = TRUE lightIsOn = FALSE Print youCanSee Imp lightIsOn You need the light to see. youCanSee = FALSE lightIsOn = FALSE Print youCanSee Imp lightIsOn Prints True Prints False
78
Type of operator
Operation Not equal to (not same as) Earlier in the sort order than Earlier in the sort order than or same as Earlier in the sort order than or same as Later in the sort order than Later in the sort order than or same as Later in the sort order than or same as Contains (substring matching with wildcards)
Elements
expr1, expr2 Any String expressions, or any of the following: v Numeric expression: LotusScript converts it to its text representation. In the case of Boolean data types, 0 becomes False, and any other number becomes True. v NULL: LotusScript treats it as an zero-length String value when concatenated with the other expression. If both expressions are NULL, the result is NULL. v EMPTY: LotusScript treats it as a zero-length String value.
Return value
The result is a String or a Variant of type String, if either of the operands is a Variant.
Usage
Use the ampersand (&) operator to ensure a concatenation operation. The plus (+) operator also concatenates two character strings, but LotusScript determines whether to interpret the plus as a concatenation operator or an addition operator on the basis of the operands in the expression in which it appears.
Examples
Dim x As Variant x = 56 & " Baker St." Print x Prints "56 Baker St."
anInt% = 123 aString$ = "Hello" anotherString$ = "world" varV = NULL Print aString$ & ", " & anInt% & " " & varV & _ anotherString$ & "." Output: Hello, 123 world.
79
Elements
expr1, expr2 Any String expressions, or any of the following: v Numeric expression: LotusScript converts it to its text representation (if plus is interpreted as concatenation). v NULL: LotusScript treats it as NULL. If either expression is NULL, the result is NULL. v EMPTY: LotusScript treats it as a zero-length String value.
Return value
The result is a String or a Variant of type String, if either of the operands is a Variant.
Usage
Use the ampersand (&) operator to ensure a concatenation operation. The plus (+) operator concatenates two character strings, but LotusScript determines whether to interpret the plus as a concatenation operator or an addition operator on the basis of the operands in the expression in which it appears. For example:
Print 100 & "200" Output is 100200, because & is always a concatenation operator
while
Print 100 + "200" Output is 300, because + was interpreted as addition operator Print "100" + "200" Output is 100200, because + was interpreted as concatenation operator
80
ElseIf ((theChar$ >= "a") And (theChar$ <= "z")) Then Print "You entered a lowercase character." Else Print "You entered a nonalphabetic character." End If
Like operator
Determines whether a string expression matches a pattern string.
Syntax
stringExpr Like patternString
Elements
stringExpr Any String expression. patternString A string expression that can include any individual ANSI characters and any of the wildcard characters or collections that follow. You can use as many wildcards as you need within a single patternString.
Wildcard ? # * [ characters ] [! characters ] Matches Any one character Any one digit from 0 through 9 Any number of characters (zero or more) Any one of the characters in the list or range specified here Any one character not included in the list or range of characters specified here
81
v v v v
Be sure to place the hyphen at the beginning of the list; if youre using the [!characters] format, the hyphen immediately follows the exclamation point, as in [!-123]. The other characters can appear anywhere in the characters list. For example, [-?A-Z]matches the hyphen, the question mark, and any uppercase letter from A through Z. To match one of these characters, place the character anywhere within your wildcard specification except in a characters list or range: v Comma ( , ) v Close bracket ( ]) v Exclamation mark ( ! ) For example, !,[1-6] matches the exclamation point, the comma, and any digit from 1 through 6.
Return value
If stringExpr matches patternString, the result is TRUE; if not, the result is FALSE. If either stringExpr or patternString is NULL, the result is NULL.
Usage
By default, the comparison is case sensitive. You can modify case sensitivity with the Option Compare statement.
Language cross-reference
@Like function in formula language @IsMember function in formula language @Matches function in formula language
Examples Example 1
This example prints the two-digit numbers from 1 to 100 that end in 3 and dont begin with 2.
For x = 1 To 100 If CStr(x) Like "[!2]3" Then Print x Next x Output: 13 33 43 53 63 73 83 93
Example 2
This example uses Like as a validation formula for city and zip fields.
if doc.city(0) like "*[0-9]*" then messagebox _ "city field contains a number" if doc.zip(0) like "*[a-z,A-Z]*" then messagebox _ "zip code field contains a character"
Example 3
This example shows some ways you can test a string with Like to see if it contains a given substring:
Make string comparison case-sensitive. Option Compare Case Dim anArray(1 To 6) As String anArray(1) = "Juan"
82
anArray(2) = "Joan" anArray(3) = "Alejandro" anArray(4) = "Jonathan" anArray(5) = "Andrea" anArray(6) = "Jane" UB% = UBound(anArray) Test each name in anArray$ to see if it contains a substring consisting of any characters followed by uppercase J followed by any characters followed by lowercase n followed by any characters. For counter% = 1 to UB% If anArray(counter%) Like "*J*n*" Then Print anArray(counter%) & " " ; End If Next Print "" Output: Juan Joan Jonathan Jane Test each name in anArray$ to see if it contains a numeric character. badRec% = 0 For counter% = 1 to UB% If anArray(counter%) Like "*#*" Then Print anArray(counter%) & " contains a numeral." badRec% = badRec% + 1 End If Next If badRec% = 0 Then Print "No name contains a numeral." End If Output: No name contains a numeral. Test the lowercase representation of each name in anArray$ to see if it ends in a vowel. For counter% = 1 to UB% If anArray(counter%) Like "*[aeiou]" Then Print anArray(counter%) & " " ; End If Next Print "" Output: Alejandro Andrea Jane
Is operator
Compares two object reference variables.
Syntax
obj1 Is obj2
Elements
obj1, obj2 Expressions whose values are object references.
Usage
The result of the Is operator is TRUE only if obj1 and obj2 refer to the same object or if both operands evaluate to NOTHING. Otherwise, the Is operation returns False (0).
83
The operands obj1 and obj2 may be Variant variables, object reference variables, the constant NOTHING, or any variable elements that accept an object reference, such as an element of an array, list, or user-defined type.
Example
Class MyClass ... End Class Dim x As MyClass Dim y As MyClass Set x = New MyClass Set y = New MyClass Print x Is y Prints False Set x = y x now refers to the same object as y. Print x Is y Prints True
IsA operator
Determines if an object reference variable is of a specified class or a class derived from the specified class.
Syntax
obj IsA objName
Elements
obj Expression whose value is an object reference. objName String expression representing an object name.
Usage
The result of the IsA operator is TRUE if obj is of the class objName or a class derived from objName. Obj can be a native (user defined) object, a product object, or an OLE object. Obj can be a Variant variable, an object reference variable, or any variable element that accepts an object reference, such as an element of an array, list, or user-defined type or class. Obj can be an expression, for example, a function that returns an object or array of objects. ObjName represents the class that is visible in the current scope if the class name defines more than one class.
Example
Sub PrintIt(objA) If objA IsA "ClassA" Then objA.Print Else Print "Not a ClassA object" End If End Sub
84
Procedures
Procedures are named sections of a script that you can invoke by name. A procedure in LotusScript takes the form of a function, a sub, or a property. Procedures are primarily ways to organize your code to make it easier to understand and maintain. A function is a named procedure that returns a single value. A sub is a named procedure that performs one or more operations without returning a value to its caller. A property is a language element whose main purpose is to allow the indirect manipulation of variables that you dont want to expose to the application as a whole.
Functions
A function is a named procedure that returns a single value. LotusScript provides a set of built-in functions that you can use to perform a variety of common numeric, date/time, string, data-conversion, and value-testing operations. LotusScript also lets you create your own functions. You define a function by specifying a series of one or more statements that are executed as a block when the application calls the function. You enclose these statements between the function signature and the End Function statement. A function signature specifies the function name, its scope, the data types of the values that it expects the application to pass it (if any), the lifetime of the variables that it defines (if any), and the data type of the value it returns to the application. The statements that comprise the body of a function can include the following: v Variable declarations v Assignment statements (including statements that assign values to the function itself) v Calls to built-in functions v Calls to user-defined procedures and functions (including calls to the function itself) v Looping and branching statements (including Exit Function and End, which cause execution of the function to terminate before reaching the block terminator) v Statements for performing standard file operations and for communicating with the end user Statements and directives that declare or define a function, sub, property, or user-defined data type or class are not allowed within the body of a function, including: v Declare v Function v Sub v Property Get v Property Set Additionally, you may not include the following statements in the body of a function: v Option
85
Defining functions
When you define a function, you provide the functions signature and the set of statements that are to be executed when the application calls the function. The syntax for defining a function is: [ Public | Private ] [Static ] Function functionName [ ( parameters ) ][As dataType ] statements
Element Public, Private Description When you declare a function at module level, Public lets the application refer to the function outside the module in which the function is defined, as long as that module is loaded. Private means that the function is available only within the module in which it is defined. When you declare a function inside the definition of a user-defined class, Public means that the function is available outside the class definition. Private means that the function is only available within the class definition. By default, functions defined at module level are Private, and functions defined within a class are Public. Declares variables defined within the function to be static by default. Static variables retain their values (rather than going out of existence) between calls to the function while the module in which it is defined remains loaded. The name of the function, which can end in a LotusScript data type suffixes (%, &, !, #, @, and $). These determine the data type of the functions return value. You can append a data type suffix to a function name when you declare the function only if you do not include the AsdataType clause in the declaration. A comma-delimited list of the functions formal parameters (if any), enclosed in parentheses. (The list can be empty.) This list declares the variables for which the function expects to be passed values when it is called. Each member of the list has the following form: [ByVal] paramName[() | List] [As dataType] ByVal means that paramName is passed by value; that is, the value assigned to paramName is a local copy of a value in memory rather than a pointer to that value. ByVal is optional. paramName() is an array variable. List identifies paramName as a list variable; otherwise, paramName can be a variable of any of the other data types that LotusScript supports. You cant pass an array, a list, an object reference, or a user-defined data type structure by value. As dataType specifies the variables data type. You can omit this clause and use a data type suffix to declare the variable as one of the scalar data types. If you omit this clause and paramName doesnt end in a data type suffix (and isnt covered by an existing Deftype statement), its data type is Variant. As dataType Specifies the data type of the functions return value. A function can return a scalar value, a Variant, or an object reference. If you include this clause, functionName cannot end in a data type suffix. If you omit this clause and functionName doesnt end in a data type suffix (and isnt covered by an existing Deftype statement), the functions return value is Variant.
Static
functionName
parameterList
In releases of LotusScript before 4.0, there were situations where it was required to declare functions before they were referenced. In LotusScript 4.0, this is no longer needed and forward declarations of LotusScript functions are accepted and ignored.
86
The syntax for declaring a function is: Declare[Public | Private ] [Static ] Function functionName [ ( parameterList ) ][As dataType ]
Passing by reference
The variable must have the same data type as the corresponding parameter in the function definition, unless the parameter is declared as Variant or is an object variable. An object variable can be passed to an object of the same, base, or derived class. In the latter, the base class must contain an instance of the derived class or a class derived from the derived class. If the variable is then modified by the function or sub, the variable has the modified value when the function or sub returns.
Passing by value
You can do the following: v Use the ByVal keyword in the arguments declaration in the function or sub definition. The argument is passed by value whenever the function or sub is called. v Insert parentheses around the argument in the function or sub call. You can control whether an argument is passed by reference or by value at the time when the function or sub is called. A value passed to a function or sub is automatically converted to the data type of the function or sub argument if conversion is possible. A Variant argument will accept a value of any built-in data type; and any list, array, or object. A Variant argument will not accept a value of a user-defined type. Keep in mind, however, that lists, arrays, objects, and user-defined types cannot, and therefore should not, be passed by value. If the variable argument is then modified by the function or sub, the variable has its original value after the function or sub returns. The function or sub operates only on the passed copy of the variable, so the variable itself is unchanged.
87
Examples Example 1
Define a function FOver with three Integer parameters: a variable, an array variable, and a list variable. Function FOver(a As Integer, b() As Integer, c List As Integer) ... End Function Dim x As Integer Dim y(5) As Integer Dim z List As Integer Call the function FOver correctly, with arguments whose types match the types of the declared parameters. Call FOver(x, y, z)
Example 2
Define a function GLevel with one Integer list parameter. Function GLevel (b List As Integer) ... End Function Dim z List As Integer Call the function GLevel incorrectly, passing a list argument by value. Call GLevel ((z)) Output: Error: Illegal pass by value: Z A list argument cannot be passed by value.
Example 3
Define a function FExpr with two Integer parameters; the second must always be passed by value. Function FExpr(a As Integer, ByVal b As Integer) ... End Function Dim x As Integer, w As Integer Dim y(5) As Integer Dim z List As Integer Call the function FExpr correctly with two Integer arguments: a constant and a variable. Call FExpr(TRUE, x) Both arguments are passed by value: the first, TRUE, because it is a constant; and the second, x, because of the ByVal declaration in FExpr. The following call produces two error messages: Call FExpr(TRUE, y) Output: Error: Illegal pass by value: Y Error: Type mismatch on: Y Because Y is an array variable, it is an illegal argument to pass by value and its type does not match the declared parameter type.
Example 4
When a function modifies one of its parameters, the argument value is changed after the function returns if the argument was passed by reference. The value is not changed if the argument was passed by value.
88
Dim x As Integer, y As Integer Show results of passing argument by reference. Print x, FTRefOrVal(x), x Output: 0 1 5 The value of x was changed from 0 to 5 in FTRefOrVal. Show results of calling with argument by value (note the extra parentheses around y%). Print y, FTRefOrVal((y)), y Output: 0 1 0 The value of the copy of y was changed from 0 to 5 in FTRefOrVal. The value of y is unchanged.
or
Function Left5(aString As String) As String Return the leftmost 5 characters of aString$. Left5$ = Left$(aString$, 5) End Function
You can cause a function to return an array or a list. To do so, you need to make the functions return value a Variant, which can hold an array or list, as in the following example, which passes an array of names in one format (first name, space, last name) to a function that returns another array in which the names appear in a different format (last name, comma, space, first name):
Dim myVariantVarV As Variant Dim anArray(1 to 3) As String Dim X As Integer anArray$(1) = "Alex Smith" anArray$(2) = "Elizabeth Jones" anArray$(3) = "Martin Minsky" Function SwitchNames(arrayOfNames() As String) As Variant Declare a local array variable to pass back to the application as the return value of SwitchNames. Performing the operation on arrayOfNames, which is passed by reference, would change anArray if arrayOfNames were the return value of the function. Dim newArrayOfNames(1 to 3) As String Dim tempArray(1 to 2, 1 to 3) as String Dim aSpace As Integer For X% = 1 to 3 Locate the space that separates first name from last name in arrayOfNames, then extract everything before the space to tempArray, then extract everything after the space to the corresponding
Chapter 5. Procedures: Functions, Subs, and Properties
89
location in tempArrays second dimension. aSpace% = Instr(arrayOfNames$(X%), " ") tempArray$(1, X%) = Mid$(arrayOfNames$(X%), 1 , _ aSpace% - 1) tempArray$(2, X%) = Mid$(arrayOfNames$(X%), aSpace% + 1, _ Len(arrayOfNames$(X%))) Next For X% = 1 to 3 newArrayOfNames(X%) = tempArray(2, X%) & ", " & _ tempArray(1, X%) Next SwitchNames = newArrayOfNames End Function MyVariantVarV = SwitchNames(anArray()) For X% = 1 to 3 print myVariantVarV(x%) Next Output: Smith, Alex Jones, Elizabeth Minsky, Martin For x% = 1 to 3 Print anArray(x%) Next Output: Alex Smith Elizabeth Jones Martin Minsky
A function need not contain a statement that assigns it a return value. If you dont include a statement when you define the function, LotusScript assigns the function the default return value appropriate to the data type specified or implied in the function signature. The default values are 0 for a numeric data type, the empty string () for a String, EMPTY for a Variant, and NOTHING for an object reference. For example:
Dim anInt As Integer Dim anotherInt As Integer Function PrintCube(intArg%) As Integer Print intArg% ^ 3 End Function anInt% = CInt(InputBox$("Enter a number:")) Suppose the user enters 3. anotherInt% = PrintCube%(anInt%) Output: 27 Print anotherInt% 0
90
Print anInt% & " cubed = " & Cubit1# & "." End Function anInt% = 4 aDouble# = Cubit1# Output: 4 cubed is 64. aDouble# = Cubit1# Output: 4 cubed is 64. Print aDouble# Output: 64 Print Cubit1# Output: 4 cubed is 64. 64
You can call a parameterless function by entering the function name, which must not include empty parentheses. For example:
Cubit1# Output: 4 cubed is 64
You can call a one-parameter function in any of the following additional ways: v With a Call statement. You must enclose the argument in parentheses. v By entering the name of the function followed by the argument that it expects with no parentheses. v By entering the name of the function followed by the argument it expects enclosed in parentheses. This notation means that you are passing the argument by value rather than by reference. For example:
Call Cubit2#(anInt%) Output: 4 cubed is 64. (anInt% is passed by reference.) Cubit2# anInt% Output: 4 cubed is 64. (anInt% is passed by reference.) Cubit2#(anInt%) Output: 4 cubed is 64. (anInt% is passed by value.)
91
For example:
Dim anotherInt As Integer Function Cubit3(X As Integer, Y As Integer) As Double Return the product of X% and Y%. Cubit3# = X% * Y% Print X% & " times " Y% & " = " & Cubit3# & "." End Function anInt% = 4 anotherInt% = 6 Print Cubit3#(anInt%, anotherInt%) Output: 4 times 6 = 24. 24
You can also call a function that expects multiple arguments with a Call statement or by entering the function name followed by the arguments. The Call statement requires parentheses; the function name by itself does not allow parentheses. For example:
Call Cubit3#(anInt%, anotherInt%) Output: 4 times 6 = 24. Cubit3# anInt%, anotherInt% Output: 4 times 6 = 24.
Example 1
Function Facto# (theNum%) Calculate theNum% factorial and make it the return value of Facto#. If theNum% <= 0 Then Facto# = 0 ElseIf theNum% = 1 Then Facto# = 1 Else Facto# = theNum% * Facto#(theNum% -1) End If End Function
Example 2
This example shows a recursive function without arguments:
Function Recurse As Integer ... Call Recurse and assign the return value to x. x = Recurse() ... Assign the current value of the Recurse variable to x. x = Recurse ... End Function
92
Module-level variables
As long as a function doesnt define a local variable with the same name, it can access a variable defined at module level. For example:
Dim anInt As Integer Function ThreeTimes1 As Double Multiply the module-level variable anInt% by 3 and assign the result as the functions return value. ThreeTimes1# = anInt% * 3 End Function anInt% = 5 Print ThreeTimes1# Output: 15
Using procedures to directly manipulate module-level variables is not recommended because you can introduce errors into your application, especially if you dont always declare your variables explicitly.
Parameters
When you define a function, you can declare a list of variables (sometimes called formal parameters or, simply, parameters) as part of its signature. These variables are placeholders for values that the application passes to the function at run time and that the function then uses when it executes. The run-time values that the application passes the function are known as actual parameters or arguments.
Local variables
A procedure can define variables for its own use. By default, a local variable exists only as long as the procedure in which it is defined is executing. If you include the Static keyword in the declaration of a local variable, that variable retains its address in memory, and its value persists between calls to the procedure. In either case, local variables are not visible outside of the procedure in which you define them though you can pass them as arguments to other procedures that the procedure calls. When you define a local variable with the same name as a module-level variable, the procedure uses the local variable and ignores the module-level variable. This is known as shadowing. For example, defining counter% as a local variable makes this example work properly. The calling While loop executes three times, because BadCount no longer has any effect on the counter variable in the calling loop:
Dim counter As Integer Function BadCount As Integer Dim counter As Integer counter% = 1 While counter% < 4 Module-level variable Local variable
93
Do something. counter% = counter% +1 Wend BadCount% = counter% End Function counter% = 1 While counter% < 4 Print "BadCount% = " & BadCount% counter% = counter% +1 Wend
This example shows static and nonstatic local variables and how to pass a local variable as an argument in a call to another procedure. The example consists of two functions, GetID and FindMatch. GetId prompts the user for a password (the first name) and then calls FindMatch, passing it the password. FindMatch determines if the name is in the module-level array theNames. If it is, FindMatch returns a value of True (-1) and GetId displays a confirmation message. If the name is not in the array, FindMatch increments the static variable callCounter% by 1 and returns a value of False (0), at which point GetId displays a message asking the user to try again or quit. If the user tries again, GetId again calls FindMatch to check the name. If the user enters three invalid names in a row (in three successive calls to FindMatch), FindMatch terminates the program.
%Include "LSCONST.LSS" Declare an array of Strings and initialize it with some names. Dim theNames(1 to 6) As String theNames(1) = "Alex" theNames(2) = "Leah" theNames(3) = "Monica" theNames(4) = "Martin" theNames(5) = "Elizabeth" theNames(6) = "Don" Function FindMatch(yourName As String) As Boolean Static callCounter As Integer To count the number of calls to FindMatch. Dim counter As Integer FindMatch = FALSE For counter% = 1 to 6 If yourName$ = theNames(counter%) Then FindMatch = TRUE Exit For End If Next If the user enters an invalid name, increment callCounter%. If FindMatch = False Then callCounter% = callCounter% + 1 After three consecutive invalid names, terminate the script. If callCounter% = 3 Then Print "Go away, friend." End End If End Function Function GetId As String Dim match As Boolean Terminate execution. Exit from the For loop now. Loop counter.
94
Dim goAgain As Boolean Dim pswd As String Dim msg As String Dim msgSet As Integer Dim ans As Integer match = FALSE goAgain = TRUE msg$ = "Thats not a valid name." & _ "Would you like to try again?" msgSet% = MB_YESNO + MB_ICONQUESTION Go through this While loop at least once. While match = FALSE and goAgain = TRUE pswd$ = InputBox$("Please enter your name.") Call FindMatch, passing it the name the user just entered (pswd$). match = FindMatch(pswd$) If the name the user entered isnt in theNames, see if the user would like to try again or quit. If match = False Then ans% = MessageBox(msg$, msgSet%) If No, end the While loop. If ans% = IDNO Then goAgain = FALSE GetID$ = "Have a nice day, " & pswd$ & "." End If Else GetID$ = "Your ID is valid, " & pswd$ & "." End If Wend End Function Print GetID$ Output: (1) The application prompts "Please enter your name." The user enters the name "Martin" The application answers "Your ID is valid, Martin." Output: (2)The application prompts "Please enter your name." The user enters the name "Fred" The application answers "Thats not a valid name. Would you like to try again?" The user selects No The application answers "Have a nice day, Fred." Output: (3)he application prompts "Please enter your name." The user enters the name "Fred" The application answers "Thats not a valid name. Would you like to try again?" The user selects Yes, then enters "Frank," The application answers "Thats not a valid name. Would you like to try again?" The user selects Yes, then enters "Joe":
Chapter 5. Procedures: Functions, Subs, and Properties
95
Subs
A sub is a named procedure that performs one or more operations without returning a value to its caller. You define a sub by specifying a series of one or more statements that are to be executed as a block and enclose these statements between the sub signature and the End Sub statement. You cant include a statement that assigns the sub a value. A sub signature specifies the sub name, its scope, the sorts of values that it expects the application to pass it (if any), and the lifetime of the variables that it defines (if any). You can define a sub at module level or as a member of a user-defined class. Declaring a sub before you define it lets you refer to that sub before you actually define it. You use the Declare statement to explicitly declare a sub as a member of a user-defined class or at module level in a product that does not support the Integrated Development Environment (IDE). The IDE automatically generates a Declare statement for each sub that you define at module level, so you should not include any. For information on the four specialized kinds of sub that you can define, Sub Initialize, Sub Terminate, Sub New, and Sub Delete, see Specialized subs later in this chapter.
Defining subs
The syntax for defining a sub is [ Public | Private ] [ Static] Sub subName [ ( parameters ) ] statements End Sub
Element Public, Private Description When you declare a sub at module level, Public lets the application refer to the sub outside the module in which it is defined, as long as that module is loaded. Private means the sub is available only within the module in which it is defined. When you declare a sub inside the definition of a user-defined class, Public means that the sub is available outside the class definition. Private means that the sub is only available within the class definition. By default, subs defined at module level are Private, and subs defined within a class are Public. Declares variables defined within the sub to be static by default. Static variables retain their values (rather than going out of existence) between calls to the sub while the module in which it is defined remains loaded. The name of the sub. A comma-delimited list of the subs formal parameters (if any), enclosed in parentheses. (The list can be empty.) This list declares the variables for which the sub expects to be passed values when it is called. Each member of the list has the following form: [ByVal] paramName[() | List] [As dataType] ByVal means that paramName is passed by value: that is, the value assigned to paramName is a local copy of a value in memory rather than a pointer to that value. paramName() is an array variable; List identifies paramName as a list variable; otherwise, paramName can be a variable of any of the other data types that LotusScript supports. You cant pass an array, a list, an object reference, or a user-defined data type structure by value. As dataType specifies the variables data type. You can omit this clause and use a data type suffix character to declare the variable as one of the scalar data types. If you omit this clause and paramName doesnt end in a data type suffix character (and isnt covered by an existing Deftype statement), its data type is Variant.
Static
subName parameterList
96
Declaring a sub
In releases of LotusScript before 4.0, there were situations where it was required to declare subs before they were referenced. In LotusScript 4.0, this is no longer needed and forward declarations of LotusScript subs are accepted and ignored. The syntax for declaring a sub is: Declare[ Public | Private ] [ Static] Sub subName [ ( parameters ) ]
Executing a sub
You can execute a user-defined sub in either of two ways: by including it in a Call statement or by entering its name followed by the arguments that it expects to be passed (if any). Calling conventions differ according to the number of arguments the sub expects to be passed and whether you use the Call statement to do the calling.
You can call a parameterless sub by entering the sub name, which must not include empty parentheses. For example:
PrintName1 Output: DAVID
97
Output: DAVID firstName$ = "David" Call PrintName2((firstName$)) Output: DAVID Print firstName$ Output: David
You can call a sub that expects a single argument by simply entering the subs name and the argument. If you enclose the argument in parentheses, it gets passed by value to the sub. For example:
firstName$ = "David" PrintName2(firstName$) firstName$ is passed by value. Output: DAVID Print firstName$ Output: David PrintName2 firstName$ firstName$ is passed by reference. Output: DAVID Print firstName$ Output: David
Specialized subs
LotusScript recognizes four specialized kinds of user-defined subs to automate set-up and clean-up in an application.
Sub Initialize
Sub Initialize lets you perform set-up operations on loading a module. LotusScript automatically executes a Sub Initialize when the application loads the module in which you defined it, performing the operations specified in the sub. You can define only one Sub Initialize per module. The syntax is: Sub Initialize statements End Sub Sub Initialize is Private in scope. Its signature cant include a parameter list; LotusScript has no way of passing arguments to a Sub Initialize when it calls it. A Sub Initialize is not subject to the usual restrictions concerning the sorts of statements and directives that a user-defined procedure can contain.
98
Sub Terminate
Sub Terminate lets you perform clean-up operations when the application unloads a module. As with Sub Initialize, LotusScript automatically executes a Sub Terminate when the application unloads the module in which it is defined, performing the operations specified in the sub. You can define only one Sub Terminate per module. The syntax for Sub Terminate is: Sub Terminate statements End Sub Sub Terminate is Private in scope. Its signature cant include a parameter list, and it is not subject to the usual restrictions concerning the sorts of statements and directives that a user-defined procedure can contain.
Properties
A property is a language element whose main purpose is to allow the indirect manipulation of variables that you dont want to expose to the application as a whole. This is especially useful in object-oriented programming. To the application, a property looks like a variable to which you can assign and from which you can retrieve a value, but it is actually more than that. You create a property by defining two procedures: Property Set assigns the value of the property to a variable you want to manipulate, and Property Get assigns the current value of that variable to the property. You execute the Property Set procedure by assigning the property a value, and you execute the Property Get procedure by including the property in a statement that uses its value. The application operates on the property (which operates on the variable) rather than on the variable itself. Because Property Set and Property Get are procedures, you can make them perform operations in addition to assigning and retrieving values.
99
End Property and [ Public | Private ] [ Static] Property Get propertyName [ As dataType ] statements End Property
Element Public, Private Description When you declare a property at module level, Public lets the application refer to the property outside the module in which it is defined, as long as that module is loaded. Private means the property is available only within the module in which it is defined. When you declare a property inside the definition of a user-defined class, Public means that the property is available outside the class definition; and Private means that the property is only available within the class definition. By default, properties defined at module level are Private, and properties defined within a class are Public. Declares variables defined within the property to be static by default. Static variables retain their values (rather than going out of existence) between calls to the property while the module in which the property is defined remains loaded. The name of the property, which can end in a LotusScript data type suffix (%, &, !, #, @, and $). These determine the data type of the propertys return value. You can append a data type suffix when you declare the property only if you do not include the As dataType clause in the declaration. Specifies the data type of the propertys return value. A property can return a scalar value, a Variant, or an object reference. If you include this clause, propertyName cannot end in a data type suffix character. If you omit this clause and propertyName doesnt end in a data type suffix character (and isnt covered by an existing Deftype statement), the propertys return value is Variant.
Static
propertyName
As dataType
When you define a property, the signatures of the Property Set and Property Get statements must agree as to scope, lifetime of variables, name, and data type.
Using properties
Properties are good for manipulating protected variables, that is, Private members of a user-defined class to which the application has no direct access. For more information see User-defined Data Types and Classes.
Example 1
In the following example, the sub KeepGoing uses the property theCube# to manipulate three variables (anInt%, aDouble#, and bigNum#) that are not referred to directly by the application.
%Include "LSCONST.LSS" Dim anInt As Integer Dim aDouble As Double Dim bigNum As Double Property Set theCube As Double anInt% = theCube# End Property Property Get theCube As Double aDouble# = anInt% ^ 3 If aDouble# > bigNum# Then
100
bigNum# = aDouble# End If theCube# = anInt% End Property Sub KeepGoing Dim goAgain As Boolean Dim msg As String Dim msgSet As Integer Dim more As Integer goAgain = TRUE msg$ = "Want to go again?" msgSet% = MB_YESNO + MB_ICONQUESTION Prompt the user to enter a number; assign that number to the property theCube# (by executing Property Set theCube#); calculate the cube of that number (by executing Property Get theCube#), assign it to the variable aDouble#, and compare it to the current value of bigNum#, resetting the latter if aDouble# is greater. Prompt the user to repeat the process or quit. While goAgain = True Execute Property Set theCube# by assigning it a value. This assigns a value to anInt%. theCube# = CInt(InputBox$("Enter an integer:")) Execute Property Get theCube# by including theCube# in a Print statement. This assigns a value to aDouble#, may assign a value to bigNum#, and returns the current value of anInt%. Print theCube# & " cubed = " & aDouble# & "." Print bigNum# & " is the biggest cube so far." See if the user would like to do all this again or quit. more% = MessageBox(msg$, msgSet%) If more% = IDNO Then goAgain = FALSE End If Wend Print "All Done." End Sub Call KeepGoing Output: The user types 3 and selects Yes, then 4 and selects Yes, then 2 and selects No. 3 cubed = 27. 27 is the biggest cube so far. 4 cubed = 64. 64 is the biggest cube so far. 2 cubed = 8. 64 is the biggest cube so far. All Done.
101
Example 2
You can perform the same operations using a sub and a function instead of a property.
%Include "LSCONST.LSS" Dim anInt As Integer Dim aDouble As Double Dim bigNum As Double Sub SetTheCube anInt% = CInt(InputBox$("Enter an integer:")) End Sub Function GetTheCube(anInt As Integer) As Double aDouble# = anInt% ^ 3 If aDouble# > bigNum# Then bigNum# = aDouble# End If GetTheCube# = anInt% End Function Sub KeepGoing Dim goAgain As Boolean Dim msg As String Dim msgSet As Integer Dim more As Integer goAgain = TRUE msg$ = "Want to go again?" msgSet% = MB_YESNO + MB_ICONQUESTION While goAgain = True Call SetTheCube Print GetTheCube#(anInt%) & " cubed = " & aDouble# & "." Print bigNum# & " is the biggest cube so far." See if the user would like to do all this again or quit. more% = MessageBox(msg$, msgSet%) If more% = IDNO Then goAgain = FALSE End If Wend Print "All Done." End Sub Call KeepGoing Output: The user types 3 and selects Yes, then 4 and selects Yes, then 2 and selects No. 3 cubed = 27. 27 is the biggest cube so far. 4 cubed = 64. 64 is the biggest cube so far. 2 cubed = 8. 64 is the biggest cube so far. All Done.
102
File operations
The following table describes the three kinds of files in LotusScript: sequential, random, and binary.
File type Sequential Description The simplest and most common. It is the equivalent of a common text file. Data in sequential files are delimited with the platforms end-of-line indicator (carriage return, line feed, or both). You can read the file with a text editor. The most useful for structured data. It is not readable except through LotusScript programs. This is the default. The most complex. It requires detailed programming to manipulate, because access is defined at the level of bytes on the disk.
Random Binary
To store and manipulate data in a file, the file must be opened first. When a file is opened in LotusScript, it has a file number, between 1 and 255, which is used in most input and output operations. (A few file operations use the file name instead of a number.) The number remains until the file is closed. Some file operations that can be performed on these files are:
Close Get, Input Kill Open Put, Write Close one or more open files. Read data from a file. Delete a file. Open a file. Write data to a file.
Sequential files
A sequential file is an ordinary text file. Each character in the file is assumed to be either a text character or some other ASCII control character such as newline. The character is in the character set specified when the file is opened. By default this is the platform-native character set. Sequential files provide access at the level of lines or strings of text: that is, data that is not divided into a series of records. However, a sequential file is not well suited for binary data, because a number in a sequential file is written as a character string.
103
Where Input means read-only access to the file, Output means write-only access, and Append means write-only access starting at the end of the file. Access in all three sequential modes is one line at a time. To get an unused fileNumber, use the FreeFile function. bufferSize is the number of characters loaded into the internal buffer before being flushed to disk. This is a performance-enhancing feature: the larger the buffer, the faster the I/O. However, larger buffer sizes require more memory. The default buffer size for sequential files is 512 bytes. MIMECharsetName designates the character set. The default is the platform-native character set, except that if a UTF-16 or UTF-8 byte order mark (BOM) is present, the BOM character set is used, and on OS/400 the CCSID is used if a BOM is not present. See MIME charset names for a list of valid MIME charset values. When you try to open a file for sequential input, the file must already exist. If it doesnt, you get an error. When you try to open a nonexistent file in output or append mode, the file is created automatically.
The Write # statement generates output compatible with the Input # statement by separating each pair of expressions with a comma, and inserting quotation marks around strings. For example:
Dim supV As Variant, tailV As Variant supV = 456 tailV = NULL Write #idFile, "Testing", 123, supV, tailV
The statements generate the following line in the file numbered idFile:
"Testing",123,456,#NULL#
Note: True, False, and NULL are stored as strings #True#, #False#, and #NULL#.
104
Input # reads in data that was formatted and written with the Write # statement. For example: The file numbered idFile contains the line:
"Testing",123,456,#NULL#
Then the following statements read Testing into liLabel, 123 into infA, 456 into supA, and the value NULL into tailV:
Dim liLabel As String, tailV As Variant Dim infA As Integer, supA As Integer Input #idFile, liLabel, infA, supA, tailV
If you find that you are using Write # and Input # with sequential files often, you should consider using a random file instead. Random files are better suited for record-oriented data. The Input function reads data from a sequential file. This function takes the number of characters to read as an argument, and returns the characters. The Input$ function returns a string to the caller. The Input function returns a Variant variable. This example reads an entire file at once into a string variable.
LOF returns the length of the file in characters. Dim fulFile As String fulFile = Input$(LOF(idFile), idFile)
Random files
A random file is made up of a series of records of identical length. A record can correspond to a scalar data type, such as Integer or String, or to a user-defined type, in which each record is broken down into fields corresponding to the members of the type.
105
Type emploRec id As Integer Integers are 2 bytes long salary As Currency Currency is 8 bytes hireDate As Double Dates are also 8 bytes lastName As String * 15 Fixed-length string of 30 bytes firstName As String * 15 Fixed-length string of 30 bytes End Type
The length of a type can be determined at run time using the Len function. For example, this record is 78 bytes long, so supply Len = 78 in the Open statement.
Dim recLen As Integer, idFile As Integer Dim recHold As emploRec idFile = 1 The file number to use for this file recLen = Len(recHold) The record length for this file Open "DATA.DAT" For Random As idFile Len = recLen
To add new records to a random file, use a record number equal to one more than the number of records in the file. To add a record to a file that contains 5 records, for example, use a position of 6. To replace a record from a random file, create a new file and copy all the valid records from the original file into the new file. Close the original file and use the Kill statement to delete it. Use the Name statement to rename the new file to the same name as the original. You can also move each record, following it up by one position, thus writing over the record. The problem with this technique is that it leaves a duplicate record at the end of the file. For example:
Dim tempRec As For I = recNum Get idFile, Put idFile, Next I emploRec To lastRec - 1 I + 1, tempRec I, tempRec
106
Binary files
Binary files are designed to provide the most control over the organization of your data for both reading and writing. However, you must know exactly how the file was written.
107
108
Sequential
Random X
Binary X
Opening files
Use the FreeFile function to get a file number, and then use an Open statement to open a file. The syntax is: fileNumber% = FreeFile Open fileName$ [ For {Input | Output | Append | Binary | Random }] [ Access {Read | Read Write | Write}] [ {Shared | Lock Read | Lock Read Write | Lock Write }]] As fileNumber% [ Len = recLen%] [Charset = MIMECharsetName] In the Open statement, you specify access mode and the read and/or write operation you intend to perform. If other processes or users have concurrent access to the file (over a network, for example), you can also specify how the file is to be shared. For random access, you specify a record length (unless you are using the default of 128 bytes). To determine record length, you can use the Len or LenB function to return the length of the scalar variable or user-defined data type variable you are using to read and/or write records. To enhance performance during sequential access to a file, you can specify a buffer size for the read/write operations. You can also specify a character set to use for sequential access. See the Open statement for usage details.
To write an extended unstructured string rather than a fixed-length or variable-length record to a text file, you can open the file for binary access and use a Put statement. The following Put statement writes over the previous contents of a text file starting at the first byte. If the new string is shorter than the previous contents, the Put operation does not write over to the end of the file.
Open "DATA.DAT" For Binary Access Write As fileNumber% Put fileNumber%, 1, fileContents$
If a file contains variable-length records, use the Input # and Write # statements to read and write records. The Input # statement reads a record into a list of variables, and the Write # statement writes to a file from a list of variables. Write # statements delimit and format entries so that they can be read by Input # statements. In both cases, the list of variables may be the members of a user-defined data type variable. The following example reads each record from SCORES.DAT into a variable-length user-defined data type variable. If the students score is at least 92, the script writes the record to HISCORES.DAT. The process continues until the EOF function returns TRUE (-1), indicating that the script has reached the end of SCORES.DAT.
109
Type Student ID As Long Name As String Variable-length string variable Score As Single End Type Dim undergrad As Student Sub WriteGoodStudents Dim fileNum1 As Integer, fileNum2 As Integer fileNum1% = FreeFile Open "SCORES.DAT" For Input As fileNum1% fileNum2% = FreeFile Open "HISCORES.DAT" For Append As fileNum2% While Not EOF(fileNum1%) Read until end of file. Input #fileNum1%, undergrad.ID, undergrad.Name, undergrad.Score If undergrad.Score > 92 Then Write #fileNum2%, undergrad.ID, undergrad.Name, undergrad.Score End If Wend Close fileNum1% Close fileNum2% End Sub
You can also use a Print # statement to write to a sequential text file, but Print # does not delimit and format the record to ensure that it can be read with an Input # statement. When you are using sequential access to write to a file, you can open the file in input mode (replace the previous contents of the file) or append to the file. You cannot insert or replace text in the middle of the file. You can also use the Line Input # statement to read each line into a String variable. Write # and Print # statements put a newline character at the end of each operation, so lines normally correspond to variable-length records (unless you write multi-line strings). Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. Note: The Line Input # statement will handle the line end character appropriate for the current platform. It will not necessarily handle line ends properly if the file is written on one platform and read on another. When you open a file for random or binary access, the file position is 1 (the first record or byte). Use a Get statement to read data into a variable, and use the Put statement to write data from a variable to the file. The variable may be a user-defined data type variable. Each Get and Put operation advances the file position accordingly. You can use the Seek statement to set the file position to a fixed-length record (random access) or to a byte (binary access). To get the current file position, use the Seek function. Here is a revision of the preceding example, using fixed-length records and random access. Performance is better and numeric information is stored as such (rather than as strings), but the fixed-length string takes up a little extra space in each record.
110
Type Student ID As Long Name As String * 20 Fixed-length string variable. Score As Single End Type Dim undergrad As Student Sub WriteGoodStudents Dim fileNum1 As Integer, fileNum2 As Integer fileNum1% = FreeFile Open "TESTSCORES.DAT" For Random Access Read As fileNum1% _ Len = Len(undergrad) fileNum2% = FreeFile Open "GOODSCORES.DAT" For Random Access Write _ As fileNum2% Len = Len(undergrad) While Not EOF(fileNum1%) Read until end of file. Get #fileNum1%,, undergrad If undergrad.Score > 92 Then Put #fileNum2%,, undergrad End If Wend Close fileNum1% Close fileNum2% End Sub
Closing files
As soon as you complete your read/write operations, use the Close statement to close the file. If you modified the file, the Close statement also writes modifications to disk. You must close the file before you can open it again. If you want to change access mode or operation (from read to write, for example), you must also close the file, then open it again.
111
112
Types of errors
LotusScript recognizes two kinds of errors: v Compile-time errors Errors that are found and reported when the compiler attempts to compile the script. Common compile-time errors are syntax or naming errors. The compiler reports the error, together with a message and a link to online Help, which explains how to correct the error. You must correct the error and re-compile before the script can run. v Run-time errors Errors that are found when LotusScript attempts to execute the script. A run-time error cant be predicted at compile time (e.g., out of memory). Run-time errors prevent a script from running to normal completion. When a run-time error occurs, script execution ends unless your script includes statements to handle the error. Examples of run-time errors are attempting to open a file that doesnt exist, or attempting to divide a number by a variable with a zero value. LotusScript recognizes many run-time errors, and identifies each with a name, a number, and a standard message to describe it. Within a script, you can also define your own run-time errors and associate a number and a message with each one. Note: Compile-time errors are also possible at run time. LotusScript has an execute statement. If there are syntactic problems inside the string expression, a compile-time error is generated at run time.
113
v Err function Returns the LotusScript error number for the current error, or the number you specify with the Err statement. If there is no current error, Err returns FALSE (0). The value of the function Err persists across scripts. Completing execution of a script does not automatically reset this functions value to 0. The value of Err is reset to 0 only by an Err statement or a Resume statement. v Erl function Returns the current line number within the procedure where the error handler is defined. v Error and Error$ functions Return the error message for the current error, or the message for the error number you specify with the Err statement. If there is no current error, Error and Error$ return the empty string .
Example 2: This example shows the flow of control and the change in the values of the control variables Error, Err, and Erl during error processing. Though it will run and behave exactly as shown here, this is an artificial script. It is written to demonstrate these error-processing features.
This example omits the Exit Sub statement of the preceding example. As a result, execution continues on to the error-handling routine. Sub ShowErr On Error GoTo CheckErr Error 150 This is line 5. Print "Error was handled... Error, Err, Erl are now:" Print Error(), Err(), Erl() This is line 7. Exit Sub statement was dropped here. CheckErr: Print Error(), Err(), Erl() Resume Next This is line 11. End Sub Call ShowErr() Print "Back from call of ShowErr"
After error 150 occurs at line 5, the error-handling routine at CheckErr prints this line:
114
150
After the Resume statement, the Print statements in lines 6 and 7 prints these two lines:
Error was handled... Error, Err, Erl are now: 0 0
Execution continues on normally to the Print statement at CheckErr, which prints the following line:
0 0
Execution then continues normally to the Resume Next statement on line 11. Since there is no current error, there is no Next statement, so the Resume statement itself is invalid and generates an error, which becomes the current error; and the error-handling routine at CheckErr is invoked again. It prints the following line:
RESUME without error 20 11
The error-handling routine ends with the statement Resume Next. The next statement is End Sub. So the sub exits normally, and the Print statement after the sub call prints the following line:
Back from call of ShowErr
Example 3: An Err statement is placed at the beginning of the error-handling routine shown in the preceding example. The result is to invalidate the value of Erl: it no longer describes the error specified by Err.
Sub ShowErr On Error GoTo CheckErr Error 150 This is line 3. Print "Error was handled... Error, Err, Erl are now:" Print Error(), Err(), Erl() This is line 5. CheckErr: Reset the error number, without creating an error. Err 151 Print Error(), Err(), Erl() Resume Next This is line 10. End Sub Call ShowErr() Print "Back from call of ShowErr"
After error 150 occurs at line 3, the error-handling routine starting at CheckErr executes. It first sets the error number (the value of Err) to 151. This resets the Error function also (but not the Erl function). So the Print statement prints the following line:
Cannot find external name 151 3
After the Resume statement, the Print statements on lines 4 and 5 print these two lines:
Error was handled... Error, Err, Erl are now: 0 0
Execution continues normally to the statements starting at CheckErr. The Err statement there resets the error number, and the Print statement therefore prints the following line. (Note that there is no current error, and therefore the value of Erl is still 0.)
Cannot find external name 151 0
The next statement executed, Resume Next, is invalid because there is no current error. So it generates an error, and the error-handling routine beginning at CheckErr is invoked again. It first sets Err to 151, and then prints the following line. (The values of Error and Err represent the latest assignment to Err; but Erl is still 10 because the current error occurred at line 10.)
Cannot find external name 151 10
115
The error-handling routine ends with the statement Resume Next. The Next statement is End Sub. So the sub exits normally, and the Print statement after the sub call prints the following line:
Back from call of ShowErr
If you include msgExpr in the Error statement, you specify the error message to be reported when the error occurs and no error handling for the error is in effect. Handling errors: the On Error statement: Every error recognized at run time has its own error number that identifies it. When a recognized error happens during script execution, LotusScript records the error number, and then proceeds as directed by an On Error statement that refers to that number. For example, you can write either one of these On Error statements to tell LotusScript how to respond to an occurrence of error number 357:
On Error 357 GoTo apoc600 On Error 357 Resume Next
116
When referring to a pre-defined error in an On Error statement, you can use the defined constant for the error instead of the error number. For example, here are the statements in LSERR.LSS that define the error numbers and constants for two common errors:
Public Const ErrDivisionByZero = 11 Division by zero Public Const ErrIllegalFunctionCall = 5 Illegal function call
On Error statements then do not need to mention the numbers 11 and 5. Write the statements in this form instead, making the script easier to read:
On Error ErrDivisionByZero ... On Error ErrIllegalFunctionCall ...
You can define constants for your own error numbers. (You should define your error numbers to be above ErrLast.) Then the constant names can be used instead of numbers in any Error statements and On Error statements that refer to the error. For example:
Const ooBounds = 677 A specific out-of-bounds error ... Error ooBounds ... On Error ooBounds ...
Using On Error Goto label: When the most recently executed On Error statement for the current error has the form On Error GoTo label, LotusScript continues execution at the labeled statement. The statement begins an error-handling routine for the error. The error-handling routine may consist of any number of statements, beginning with the statement executed at the label and continuing through the next Resume, Exit Sub, Exit Function, Exit Property, or End statement encountered at run time. The error is considered handled when one of these statements executes. When an On Error statement specifies the label where the error-handling routine begins, that labeled statement must be in the same procedure as the On Error statement. This is because a GoTo statement cannot transfer control to a labeled statement outside the procedure where it occurs. The compiler verifies that the labeled statement is present in the same procedure, and generates a compile-time error if it is not. Error handling routines outside procedures: LotusScript can handle an error in the procedure where it occurs or in the procedure that called the current procedure. If the current procedure doesnt handle the error, LotusScript returns control to the calling procedure and seeks an error-handling routine there for the error. If the caller doesnt handle the error, LotusScript looks at the callers caller, and so on. If no applicable error-handling routine is found by this process, execution ends, and the error message for the error is generated. For example:
The sub TestHand generates a division-by-zero error. Since TestHand doesnt specify how to handle the error, control returns to the calling procedure SuperHand when the error occurs. SuperHand contains an error-handling routine for division by zero. Control passes to that routine, which prints a message and exits from SuperHand. Sub TestHand Dim num As Single num! = 1 Print num! / 0 End Sub
Chapter 7. Error Processing
117
Sub SuperHand On Error GoTo DivZero Call TestHand() Exit Sub DivZero: Print "Continuing after calling sub TestHand." Exit Sub End Sub Call SuperHand() Output: Continuing after calling sub TestHand.
You can use a special form of the On Error statement to state explicitly that a specified error not be handled in the current procedure. The syntax is: On Error errNumber GoTo 0 This says that the error numbered errNumber is not handled in the current procedure. This example shows that the result of the preceding example is unchanged if the sub TestHand is modified as follows:
Sub TestHand Dim num As Single On Error ErrDivisionByZero GoTo 0 num! = 1 Print num! / 0 End Sub
You can also use a statement in the following form to specify that no error be handled in the current procedure. This statement makes it explicit that the procedure handles no errors, so your error-handling logic is clearer.
On Error GoTo 0
Like any On Error statement, the effect of this statement can be overridden, for any particular error, by a subsequent On Error statement that designates different handling for that error. For example, this pair of On Error statements specifies that division-by-zero errors are handled by an error-handling routine at the label DivZero; and no other errors are handled in the current procedure (an error-handling routine for other errors is sought in the procedures caller).
On Error GoTo 0 On Error ErrDivisionByZero GoTo DivZero
An On Error statement of the special form On Error GoTo 0 does not handle any error that it refers to. It says explicitly that any error it refers to is not handled in the current procedure. When such an error occurs, LotusScript searches upward through the chain of calling procedures for an On Error statement that specifies how to handle the error. Ending the error handling routine: If the statement that ends the error-handling routine is a Resume statement, then the values of Err, Erl, and Error are reset to their initial values: 0, 0, and the empty string (), respectively. If the statement is Exit Sub, Exit Function, or Exit Property, then LotusScript does not reset the values. Errors within error handling routines: If an error occurs during execution of an error-handling routine, that error becomes the current error. Execution ends and the associated error message is displayed.
118
Example 1: This extended example shows how a run-time error can arise in a script, and how you can modify a script to either avoid or handle the error. The straightforward error processing illustrated here uses the On Error and Resume statements, which you typically use to process errors. The script includes a sub named GetLine to retrieve some values from the first line of a file whose name the user specifies. For example:
Sub GetLine Dim number1 As Integer, number2 As Integer, number3 _ As Integer Dim fileName As String Prompt the user to enter a file name, and assign the result. fileName$ = InputBox$("Enter a file name: ") Open fileName$ For Input As #1 This is line 6. Input #1, number1%, number2%, number3% Print number1%, number2%, number3% Print the input values. Close #1 End Sub
When the sub GetLine runs, an error occurs at the Open statement if the user enters the name of a nonexistent file when prompted by the InputBox$ function. Because the script does not contain statements to handle the error, LotusScript ends execution of the script and prints an error message:
Call GetLine() Output: Fail: RunTime Error 101 Unable to open file at Line 6
Example 2: In this example, the script just shown is modified to include an On Error statement to handle a file-open error when it occurs. If the Open statement fails, LotusScript prints some identifying information about the error, and requests a new file name from the user, rather than ending script execution and printing an error message.
Sub GetLine Dim number1 As Integer, number2 As Integer, number3 _ As Integer Dim fileName As String Designate an error-handling routine to handle an error. On Error GoTo NoExist GetName: fileName$ = InputBox$("Enter a file name: ") Open fileName$ For Input As #1 This is line 8. Input #1, number1%, number2%, number3% Print number1%, number2%, number3% Close #1 Done. Exit from the sub GetLine. (Dont continue on to the error-handling routine at the label NoExist.) Exit Sub NoExist: Come here when any error occurs. Print the values of built-in functions that give information about the error: an error message, the error number, and the line number in the script where the error occurred. Print Error(), Err(), Erl() Resume execution at the label GetName. Resume GetName End Sub Call GetLine() The user twice enters a file name that doesnt exist, and then a valid file name. The values read in from the file are 11, 22, and 0.
119
101 101 0
8 8
When execution resumes in this way, the error is considered handled. LotusScript does not reset the values of the Err, Erl, and Error functions that were set when the error occurred.
Similarly, when the statement Resume Next appears within an error-handling routine for an error that occurred in a lower-level procedure, Next refers to the next statement in the calling procedure. The statement Resume 0, or simply Resume, in an error-handling routine means to re-execute the line where the error occurs, even if that line is in a lower-level procedure. For example:
The sub SuperHand calls the sub TestHand with an argument of 0, which produces an error. The error is handled by an error-handling routine in the caller, the sub SuperHand. Handling the error includes resetting the call argument to 1, and then calling TestHand with this argument. On the second call no error occurs. Sub TestHand(num As Integer) Dim num2 As Single
120
If num <> 0 GoTo ProcPo Print "Call argument to sub" & _ "TestHand is 0; will generate error." Theres no error-handling routine in sub TestHand for division-by-zero, so control returns to the calling sub SuperHand when the next statement is executed. num2! = num% / 0 This Print statement is not executed at all. Print "Continue here after division-by-zero error?" Exit Sub Come here if call argument is nonzero. ProcPos: Print "Call argument to sub TestHand is nonzero" & _ " (no error)." Exit Sub End Sub Sub SuperHand Dim numIn As Integer A division-by-zero error not handled in sub TestHand is handled by the error-handling routine at DivZero. On Error GoTo DivZero Call TestHand(numIn%) Exit Sub DivZero: Print "Handling division-by-zero error." numIn% = 1 Re-execute the statement that caused the error being handled. This will be the statement Call TestHand(numIn%) above. The call argument is now 1. Resume 0 End Sub Call SuperHand() Output: Call argument to sub TestHand is 0; will generate error. Handling division-by-zero error. Call argument to sub TestHand is nonzero (no error).
To ensure that all other errors are handled without terminating script execution, include an On Error statement that doesnt specify a particular error. This example shows a script that specifically manages file-open failures and division-by-zero errors. All others are included in a general On Error statement.
Chapter 7. Error Processing
121
%Include "LSERR.LSS" Sub GetLine Dim number1 As Integer, number2 As Integer, number3 _ As Integer Dim fileName As String The error-handling routine at label Leave is for all errors except the two individual errors specified in the second and third On Error statements. Each has a specific error-handling routine designated. On Error GoTo Leave On Error ErrOpenFailed GoTo NoExist On Error ErrDivisionByZero GoTo DivZero GetName: fileName$ = InputBox$("Enter a file name: ") Open fileName$ For Input As #1 Input #1, number1%, number2%, number3% Print number1%, number2%, number3% The next statement causes a division-by-zero error if number 3 is 0. Print (number1% + number2%) / number3% Close #1 Exit Sub NoExist: Print Error(), Err(), Erl() Resume GetName DivZero: number3% = InputBox("Number3 is 0. Enter a new value: ") Resume Leave: The following message is general, because different errors may have occurred. MessageBox("Cannot complete operation.") Exit Sub End Sub
This example of a call to GetLine shows how the sub works. For all errors other than file-open failures errors and division-by-zero errors, the error-handling routine at Leave displays a message box and returns from the sub GetLine.
Call GetLine() The user enters a valid file name, and the values read in from the file are 11, 22, and 0. Output: 11 22 0 The value 0 causes a division-by-zero error. The user then enters the value 2 into the input box specified in the error-handling routine beginning at DivZero. Execution resumes at the Print statement that generated the error. Output: 16.5
However, if the user enters 99999 instead of 2 into the input box in the error-handling routine at DivZero, the result is an overflow error, because 99999 is larger than the maximum legal Integer value for the variable number3%. This error will not be handled, because it occurs within the error-handling routine at DivZero. LotusScript ends execution whenever an error occurs within an error-handling routine. Ordering of On Error statements: The error-handling routine (or none) in effect at any given time for any particular error is the routine specified in the most recently executed On Error statement that applies to that error. Changing the order of the On Error statements can change the processing at run time. In this example, the order of the three On Error statements at the beginning of the preceding example is changed to this:
122
Two routines are designated to handle individual errors. On Error ErrOpenFailed GoTo NoExist On Error ErrDivisionByZero GoTo DivZero The Leave routine is intended to handle all other errors. On Error GoTo Leave
After these three statements execute, all errors are handled by the error-handling routine beginning at the label Leave, because the statement On Error GoTo Leave refers to all errors. The routine named Leave overrides the routines established for ErrOpenFailed and for ErrDivisionByZero that were specified in the preceding two On Error statements.
123
124
Another important difference between user-defined data types and classes is that a variable of a user-defined data type holds actual data, while a classs object reference variable points to an objects data stored in memory. For example, Person1 and Person2 can be object reference variables that point to the same CheckingAccount object. This flexibility allows two different people to access the same checking account.
In general, you create a user-defined data type for operations that dont need properties and methods. For example, you might create a data type named Coordinates that contains member X and Y coordinates in order to perform simple file read/write operations. In most other cases, you will want to create classes.
125
While member variable declarations resemble those of local variables declared in a function, LotusScript allocates space for them only when an application creates the user-defined data type. When this happens, LotusScript allocates space for all the member variables at the same time. User-defined data types cannot contain procedures (properties and methods) and cannot be extended. This example shows how you could create an Employee data type that contains three member variables (ID, lastName, and firstName) to hold database records of employee information:
If you want to hold data from many database records, you can declare an array of member variables. For example:
Dim Staff(10) As Employee Create an array of ten employee records.
126
You can refer to the elements of a member variable that is an array or list:
Staff(1).ID = 1134 Staff(1).lastName = "Robinson" Staff(1).firstName = "Bill" Staff(2).ID = 2297 Staff(2).lastName = "Perez" Staff(2).firstName = "Anna"
You can retrieve data from member variables by assigning a member variable value to a variable or printing the value of a member variable:
Dim X As String X$ = Staff(2).lastName Print X$ Prints Perez.
LotusScript stores a variable of a user-defined data type on a boundary equal to the size of its largest member. This example, continued from above, shows how each variable of user-defined data type T1 is aligned on a 16-byte boundary.
Type T2 m1 As T116-byte boundary;T1s largest member boundary is 16. m2(3) As Long 4 bytes. End Type
When you declare member variables: v A fixed-length string is not aligned on any boundary. v A fixed array is aligned on the boundary of its declared data type. v The order for data types that align on the same boundary is not important. For example:
Dim x As Long Dim y As String
is as efficient as
Chapter 8. User-Defined Data Types and Classes
127
Type RecType empID As Double employee As String theSection As Integer theSpace As Integer theFloor As Integer End Type
Employee ID Employee name Car parking section Designated parking space Car parking level
Dynamic array sizes to fit the lines in the file. Dim arrayOfRecs() As RecType Dim Dim Dim Dim Dim txt As String fileNum As Integer counter As Integer countRec As Integer found As Boolean
fileNum% = FreeFile Get a file number to open a file. counter% = 0 Open "c:\myfile.txt" For Input As fileNum% Do While Not EOF(fileNum%) Line Input #fileNum%, txt$ Read each line of the file. counter% = counter% + 1 Increment the line count. Loop Seek fileNum%, 1 Pointer to beginning of file Since file has counter% number of lines, define arrayOfRecs to have that number of elements. ReDim arrayOfRecs(1 To counter%) Read the file contents into arrayOfRecs. For countRec% = 1 to counter% Input #fileNum%, arrayOfRecs(countrec%).empID, _ arrayOfRecs(countRec%).employee, _ arrayOfRecs(countrec%).theSection, _ arrayOfRecs(countrec%).theSpace, _ arrayOfRecs(countrec%).theFloor Next Close fileNum% Elicit an employees name and look for it in arrayOfRecs. ans$ = InputBox$("Whats your name?") found = False For x% = 1 To counter% If arrayOfRecs(x%).employee = ans$ Then found = True Print "Greetings, " & ans$ & "."
128
Exit For End If Next If found = False Then Print "No such employee.
User-defined classes
You can build object-oriented applications by creating classes. A class is a data type that restricts access to its data to a set of procedures. These procedures control the ways that an instance of a class (an object) is initialized, accessed, and finally deleted when it is no longer needed. You can create two types of LotusScript classes: v Base class Defines common member variables, properties, and methods that can be inherited by other classes. v Derived class Extends and elaborates an existing base class. A derived class has direct access to all members of the existing base class. However, the derived class can add new member variables, properties, and methods, and it can redefine properties and methods from the base class, while leaving the base class unchanged. For example, you could create SavingsAccount and CheckingAccount classes based on an Account class. A class lets your application model real objects, their attributes, and their behaviors. For example, an air traffic-control system creates a flight class, a car rental system creates a car class, and a banks automated teller system creates an account class. For each class, you define its members: variables, properties, and subs and functions (also called methods). Typically, you can retrieve and assign values to an objects properties. Methods perform operations on the object.
Class Flight Properties GateNumber FlightNumber InAir OnGround Car LicensePlate DriverLicense RentalDate Account CustomerNumber Balance AccountNumber WithdrawCash DepositMoney MoveMoney Methods TakeOff Land DelayFlight CancelFlight ServiceCar TransferLocation
In a script, you can declare a variable to refer to an instance of the objects class. The variable is an object reference variable. Each class defines the data used by instances of the class and defines a set of properties and methods that apply to the class.
Benefits of classes
Classes offer several features that can simplify your application programming: v Classes provide more functionality than any other LotusScript data type. A class can hold any type of data, including instances of the class being defined.
129
v Classes are self-contained so its easy to use the same class in another application. For example, a File class that provides general file input/output functions can be shared with other applications. Reusing classes reduces the time to design, write, and test your application, increases the likelihood that your scripts are correct, and saves time when you need to update scripts. v You can simplify the programming interface to your application by creating classes that call the Windows API (Application Programming Interface), or any C-API. Users work only with the member variables, properties, and methods of the class, and do not require knowledge of Windows or C-API programming. v You can build class libraries (a collection of classes) to allow other application developers to use your classes without allowing them to modify the class scripts. To do this, you compile classes into .LSO files and provide access via the Use statement. v You can use classes to build tools for your applications. For example, you can create a class that allows your application to access the spelling checker and dictionary that come with most Lotus software.
Base classes
The syntax is: [ Public | Private ] Class className classBody End Class
Element Public, Private Description Public specifies that the class is accessible outside the module in which it is defined. Private (default) specifies that the class is accessible only within the module where the class is defined. The name of the class. Declares member variables, and declares and defines properties and methods. Member variables can have any data type LotusScript supports, and can be object reference variables of the class being defined. Methods can be functions and subs, including Sub New, which initializes class objects, and Sub Delete, which deletes class objects. You cannot declare a class member as Static.
className classBody
130
A pair of functions used to manipulate protected variables, that is, Private members of a user-defined class to which the application has no direct access. v Method A sub or function that performs operations on objects.
The following Stack class uses several properties and methods to perform simple push and pop operations on a stack data structure.
Class Stack Private idx As Integer Stack List As Variant Public stackName As String Private Sub CheckStack Sub is visible only within the class. If idx% = 0 Then Error 999 End Sub Sub New idx% = 0 End Sub Initialize idx.
Private Property Set topValue As Variant CheckStack Stack(idx%) = topValue Set the top value on the stack. End Property Private Property Get topValue As Variant CheckStack topValue = Stack(idx%) Get the top value on the stack. End Property Same as Get for topValue. Function Top Top = topValue Call the topValue Get method. End Function Sub Push(v) idx% = idx%+1 topValue = v End Sub Push a value on the stack.
Function Pop Pop a value off the stack. Pop = topValue Erase Stack(idx%) idx% = idx%-1
Chapter 8. User-Defined Data Types and Classes
131
End Function Read-only property. There is no Set for Count. Property Get Count Count = idx% Count the values on the stack. End Property End Class Dim St As New Stack Call St.Push("An item on the stack") Call St.Push("Another item on the stack") Print "# of items on the stack is ";St.Count Print "TopValue is ";St.Top
Declaring Sub New and Sub Delete (initializing and deleting objects)
Within a class definition you can create two special subs. They are always Public; you cannot declare them as Private. v Sub New A sub that LotusScript executes automatically when an object is created. Sub New executes when LotusScript executes a Dim statement with the New keyword, or executes a Set statement, referring to the class for which the Sub New is defined. You create Sub New by defining a sub named New and the parameters to initialize the newly created object. A class can have only one Sub New. v Sub Delete A sub that LotusScript executes automatically when the object for which it is defined is deleted. You create a Sub Delete by defining a sub named Delete, without specifying parameters. A class can have only one Sub Delete. You can use these subs as events in your scripts. For example, you could create a File class that uses Sub New to open a file and Sub Delete to close a file. Similarly, you could create a PrintJob class that uses Sub New to start a new page, align text, and set the margins, and that uses Sub Delete to terminate the print job. Sub New in the following script initializes the member variables of the CustomerAccount object. The Set statement that creates a new Account object also passes three arguments required by the Sub New for the Account class. Sub New assigns the values of the arguments to the three member variables of the newly created object: balance@, acctNum&, and customerNum&.
Class Account balance As Currency acctNum As Long customerNum As Long Declare Sub New. Sub New (newBal As Currency, newAcctNum As Long, _ newCustNum As Long) balance@ = newBal@ acctNum& = newAcctNum& customerNum& = newCustNum& Print "New Parms=";balance@, acctNum&, customerNum& End Sub Declare Sub Delete. Sub Delete Print "Deleting account record for customer: ";customerNum End Sub End Class ..... Dim CustomerAccount As Account Create the object. Set customerAccount = New Account(1234.56, 10001991, 5412) Delete customerAccount Explicitly delete the object.
132
Within a property or method, you can use the keyword Me to access the class definition. This is particularly useful in Sub New when you are assigning external values to member variables. For example, you can use
Me.memberVariable = externalValue
to assign a value. You can also use Me when you need to: v Refer to a class member that has the same name as a local variable. For example, if a property or method contains a local variable X, and X is also the name of a class member, use Me.X within the method to refer to the member X. v Pass a reference to the class as an argument to a procedure. You must use Me to access class members that have the same names as LotusScript keywords. This class definition example uses Me to refer to a class member that is a keyword.
Class MyObject ... Reserved keyword Read is used here to name a function. Function Read Dim x As Integer .... Me is required to refer to the function named Read. Me.Read = x% End Function ... End Class Status of operation.
133
If the class is derived from a base class, Sub New of the base class is also called. The Sub New of the subclass is called first, then the Sub New of the parent class is called.
To check for an overdue balance, you can call the Public sub CheckOverdue as in the following example:
Dim Y As Customer Set Y = X Y.CheckOverdue Prints "Overdue balance" Print Y.balance@; X.balance@ Prints 14.92
14.92
This example uses the With statement to refer to members of an object using a dot to represent the object name (startEmp).
134
Class Employee Public empName As String Public newName As String Sub GetName prompts for and accepts input to newName. Sub GetName newName$ = InputBox$("Enter name:" , "New Name" ) End Sub End Class Dim startEmp As New Employee Sub SetEmp puts information into the new employee object. Sub SetEmp (E As Employee) With E Call .GetName Prompts for input to startEmp.newName$. .empName$ = .newName$ End With End Sub Call SetEmp(startEmp)
Outside the With statement, you need to specify the entire reference. For example:
Employee.empName$ = .newName$
Set x = z If (x Is z) Then Print "Both x and z refer to the same object." If (y Is NOTHING) Then Print "y is NOTHING. It refers to no object." If (z Is other) Then Print "This should not print; z and other are" & _ " different objects." End If
You can also use the Is operator in a flow of control statement, for example in a Do statement:
Dim a As New MyClass, b As MyClass ... Do While b Is NOTHING The condition b is NOTHING. Condition is either True or False. ... Set b = a Loop
Language cross-reference
Built-in constants in LotusScript language
Chapter 8. User-Defined Data Types and Classes
135
Deleting objects
You define a Sub Delete to specify the procedure that LotusScript is to execute just before it deletes an object of the specified class. You can use the Delete statement to explicitly delete objects, or you can let LotusScript delete the object automatically when it is no longer needed.
Sub Delete
A classs Sub Delete is called when LotusScript deletes an object of that class. Sub Delete itself does not actually delete the object, it performs termination housekeeping before the system reclaims the objects memory space so that it may be used to hold new objects. Sub Delete receives no parameters and returns no value.
136
End Sub End Class Sub MyDemo localObject reference count is set to 1. Dim localObject As New demoObject If (Not (localObject Is NOTHING)) Then _ Print "In MyDemo sub and localObject exists." End Sub Print "About to call MyDemo." Call MyDemo Sub MyDemo is now out of scope... so the reference count is 0 and the object is deleted. Print "Returned from MyDemo. Delete already ran."
Derived Classes
A derived class is created from a previously defined class. The syntax is: [ Public | Private] Class className As baseClass classBody End Class
Element Public, Private className baseClass classBody Description Public makes the derived class accessible outside the module in which it is defined. Private (default) makes the derived class accessible only within the module in which it is defined. The name of the derived class. The name of the base class from which this class is derived. Member variables can have any data type LotusScript supports and can be object reference variables of the class being defined. You can also specify properties, functions, and subs, including Sub New, which initializes class objects, and Sub Delete, which deletes class objects. You cannot declare a class member as Static.
Here is a derived class called MyClass2 that uses the base class MyClass1:
Class MyClass1 a As Integer Public c As Integer ... End Class Base class.
Class MyClass2 As MyClass1 Class derived from MyClass1. b As Integer Public d As Integer ... End Class Dim x As New MyClass Object x has members a%, b%, c%, and d%. x.c% = 12 x.d% = 35 ...
137
Usually you use a derived class when an existing class provides members that the new class can use, or when you want to extend or embellish existing class properties and methods. This is called inheritance: the new class inherits, and has direct access to, all Public and Private members of the existing base class. For example, you want to create derived classes called CheckingAccount, SavingsAccount, BrokerageAccount, and RetirementAccount based on an existing Account class. Because the derived classes can access all existing properties and methods for the Account class, such as AccountNumber, Balance, and DepositMoney, you can reuse all Account class scripts in the new classes.
You can define new member variables, properties, and methods in a derived class to add operations that the derived classes can use. For example, you can add BuyStock and SellStock methods to the BrokerageAccount class. A derived class can serve as the base class for another derived class. For example, the following illustration shows how the Contractor class, which is derived from the Employee class, serves as the base class for the Subcontractor class. The Subcontractor class has access to the members of both the Contractor class and the Employee class.
A derived class has the same scope as its base class, except that a derived class cannot access the Sub Delete of its base class.
138
139
. Print "The ";weight!;" lb. ";color$; _ " Banana is now peeled." End Sub Sub New(w As Single, c As String) ... End Sub Sub Prepare Peel End Sub End Class To prepare a banana, you peel it.
This derived class Sub New passes two variables declared at module level to the base class.
Class Fruit Public weight As Single Public color As String Sub New(w As Single, c As String) weight! = w! color$ = c$ Print "Fruit New() weight = ";w!, "color =";c$ End Sub End Class
140
Class Banana As Fruit Sub Peel ... End Sub Banana accepts only weight and color to Sub New(w As Single), ... Print "Banana New() End Sub End Class a weight. The Sub New passes both the base class (Fruit). Fruit (w, "Yellow") Weight = ";w!
141
Delete y Executes Apples Sub Delete and then Fruits Sub Delete.
Dim Y As New CheckingAccount Calls CheckingAccounts DepositMoney sub. Y is legal as an argument to PrintAccount, because CheckingAccount is a derived class of Account. Call PrintAccount(Y)
142
The last statement is illegal because, following the Set X = Z statement, the variable X references an object of the derived class, CheckingAccount. But the statement Set Z = X attempts to assign the value of a base class object reference variable, X, to a derived class object reference variable, Z.
143
Prepare all of the fruit in the Bucket. ForAll FruityThing in Bucket FruityThing.Prepare End ForAll Call each objects Prepare sub.
Because the variable you declare contains a reference to an object that does not yet exist, the variable is initialized to the value NOTHING.
Creating objects
After defining a class, you create and assign objects using the LotusScript New keyword. v To create a new object and assign a reference to that object in a variable that you are declaring, use the Dim statement with the following syntax: Dim objRef As New className[(argList)] v To create a new object and assign a reference to it if you have already declared an object reference variable (with a Dim statement without the New keyword), use the Set statement with the following syntax: Set objRef = New className[(argList)] You cant use the New keyword to declare an array of object reference variables or a list of object reference variables. In this example, X can hold only references to Demo objects, or else the value NOTHING. It is initialized to NOTHING.
Class Demo ... End Class Declare an object reference variable X of the class Demo, create an instance of that class, and assign X a reference to the new Demo object. Dim X As New Demo Dim DemoArray(10) As Demo Array of object reference variables Dim DemoList List As Demo List of object reference variables
144
LotusScript initializes each element of DemoArray to NOTHING. However, since a list has no elements when it is declared, LotusScript does not initialize the elements in DemoList. Each element of DemoArray, and each element of DemoList, when created, can hold either the value NOTHING or a reference to a Demo object, for example:
Set DemoArray(0) = New Demo
You can assign an existing object reference to another variable using the Set statement without the New keyword. For example:
Class Customer ... End Class Declare object reference variable C, create a Customer Dim C As New Customer Declare object reference variable myArray and initialize all elements of MyArray to NOTHING. Dim myArray(10) As Customer Dim dTwo As Customer Object reference is set to NOTHING.
Set dTwo = myArray(1) Assign the myArray(1) value, NOTHING, to DTwo. Set myArray(1) = C myArray(1) and C refer to the same Customer. Set dTwo = myArray(1) Now dTwo also refers to the same Customer. Set myArray(1) = NOTHING Set the object reference to NOTHING. Assign myArray(1) a reference to a new Customer object. Set myArray(1) = New Customer Assign dTwo a reference to a new customer object. Now, variables C, myArray(1), and dTwo each refer to different Customer objects. Set dTwo = New Customer
An assignment using Set does not copy an object. The assigned value is a reference to an object, not the object itself. The value stored in an object reference variable is a pointer to the data that makes up the object. Set copies the reference into the target variable.
145
Language cross-reference
Testing object references in LotusScript language
146
Declarations
Declarations include the Declare statement for forward references, the Declare statement for external C calls, the Const statement, and the Dim statement. With one exception, declarations do not produce executable code. The result of a declaration is information about a procedure, a variable, or a constant; for example, its type, dimensions, or value. This governs the behavior of the script that uses the declared item; but the declaration itself is not executed when the script runs.
147
The exception is a Dim statement that includes the keyword New. The result of this statement is to construct a new object of a class; and this is done when the script is executed. This is the only declaration that generates executable code.
Definition statements
A few other statements also produce no executable code. These include Option Base, Option Compare, Option Declare, and Option Public; the Type statement; and the Deftype statements. Besides the Type statement, the definition statements include the Class statement and the procedure definition statements: Function, Sub, Get Property, and Set Property. While these definition statements produce executable code, this code is not executed in place. LotusScript executes a procedure only when it is explicitly invoked. When the procedure completes execution, the script execution continues from the point where the procedure was invoked. There are two pairs of procedures, however, that are executed without being explicitly invoked: v Sub New and Sub Delete These are executed when an object is created or deleted, respectively. v Sub Initialize and Sub Terminate Sub Initialize is executed when the compiled module representing the script is loaded. Sub Terminate is executed when the module is unloaded.
Errors
The flow of execution may also be changed at run time by the occurrence of an error. Either execution ends, or an On Error statement in the script specifies how to respond to the error, in one of these ways: v By continuing execution with the statement following the statement that caused the error v By invoking an error handling routine in the current procedure v By seeking an error handling routine in a procedure within the chain of procedure calls that invoked the current procedure An error handling routine ends with a Resume statement that directs LotusScript to resume execution either at a designated labeled statement, or at the statement that caused the error, or at the statement following the statement that caused the error.
Statement labels
Statement labels can appear only within procedures. A statement at module level in a script, not contained within a procedure, cannot be labeled. Since any given label is known only within the procedure where it is defined, a branching statement that may transfer control to a labeled statement can appear only within the same procedure as the labeled statement. The statements that may transfer control to a labeled statement are GoTo, GoSub, On...GoTo, On...GoSub, If...GoTo...Else, and Resume. If an error occurs that is governed by an On Error...GoTo label statement, the On Error statement and the labeled statement must be in the same procedure.
Block statements Selecting one or the other with the If...Then...Else statement
The block statement If...Then...Else specifies conditional execution of either one group or another group of statements, depending on the value of an expression. Each statement group is usually just one short statement, since the entire If...Then...Else statement must be written on one line. The syntaxes are: If condition Then statements Else statements
148
In this form, either the Then clause is executed (if condition is TRUE); or the Else clause is executed (if condition is FALSE). For example:
If doCount% >= 1000 Then flagForm% = -1 Else flagForm% = 0
If condition Then statements In this form, the Then clause is executed if condition is TRUE; otherwise, nothing is executed. For example:
If doCount% >= 1000 Then flagForm% = -1
For either form, execution continues with the statement on the next line. Nothing can follow the If...Then...Else statement on the same line, since LotusScript recognizes a newline as the If...Then...Else statement terminator. Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. This example shows a Then clause consisting of the single statement Exit Do. There is no Else clause. The script computes the elapsed time to execute 1000 iterations of a simple Do loop. Time may vary, depending on the workstation.
Dim doCount As Integer, startTime As Single startTime! = Timer() doCount% = 0 Do Increment doCount% through 1000 iterations of the Do loop. doCount% = doCount% + 1 If doCount% > 1000 Then Exit Do Loop Come here upon exit from the Do loop. Print Timer() - startTime! "seconds for 1000 iterations" Output: .109375 seconds for 1000 iterations
For more information about the Do and Exit statements, see the sections on these statements in this chapter. To include more than one statement in the Then clause, separate the statements by the colon (:) statement separator.
Do If doCount% >= 1000 Then Print "Done." : Exit Do Loop
You can rewrite the two statements in the Do loop in the preceding example as a single If...Then...Else statement.
Do If doCount% >= 1000 Then Exit Do Else doCount% = _ doCount% + 1 Loop
This is a more compact loop than the one in the preceding example, but it runs more slowly. The condition in the If...Then...Else statement can be simple, as in the preceding example, or complex. This example shows a more complex condition:
If Abs(tempProx! - approx!) >= .00001 And iters% < 40 _ Then Exit Do
149
LotusScript identifies a statement as an If...Then...Else statement provided it has the form If condition Then, or If condition Then statements Else, followed on the same line by more source code. Unless this language appears on the same line, LotusScript interprets the statement as an If...Then...ElseIf statement. You can extend the statement to more than one line, by ending each line except the last with the line-continuation character, an underscore ( _ ). But if the statement is long enough to force continuation onto a second line, it may be more readable to rewrite it as an If...Then...ElseIf statement.
150
If you change the order of the contents of the If clause and the ElseIf clause, you can get a wrong result. For example, a Timer() value of 38017, represents a mid-morning time, but the example prints Afternoon.
Dim timeTest As Single timeTest! = Timer() The Timer function returns the number of seconds elapsed since midnight. If timeTest! < 64800 Then Print "Afternoon" ElseIf timeTest! < 43200 Then Print "Morning" Else Print "Evening" End If
This example uses If...Then...ElseIf statements to demonstrate changing a user-supplied whole number to an ordinal by adding the appropriate English suffix, such as st for 1 and th for 17. The script responds differently to numbers outside the range 0 to 50 (an arbitrary limit) and to numbers with a fractional part. There are three nesting levels of If...Then...ElseIf. Each statement needs its own End If phrase. An End If phrase ends the innermost statement running.
Dim anInt As String, lastDigit As String, printNum As String anInt$ = InputBox$("Enter a whole number between 0 and 50:") Test for a number; print message if not, and do nothing more. If Not IsNumeric(anInt$) Then MessageBox("Thats not a number.") Test for whole number; print message if not, and do nothing more. ElseIf Fraction(CSng(anInt$)) <> 0 Then MessageBox("Thats not a whole number.") Else Test for number within required range. If CInt(anInt$) <= 50 And CInt(anInt$) >= 0 Then Number is within range. Find and append the correct suffix. lastDigit$ = Right$(anInt$, 1) If lastDigit$ = "1" And anInt$ <> "11" Then printNum$ = anInt$ & "st" ElseIf lastDigit$ = "2" And anInt$ <> "12" Then printNum$ = anInt$ & "nd" ElseIf lastDigit$ = "3" And anInt$ <> "13" Then printNum$ = anInt$ & "rd" Else printNum$ = anInt$ & "th" End If Print the ordinal in a message box. MessageBox("This is the " & printNum$ & " number.") Else Number is out of range. Print message, and do nothing more. MessageBox("That numbers out of range.") End If End If Output: (For user input 3): "This is the 3rd number." (For user input -5.1): "Thats not a whole number." (For user input 51): "That numbers out of range." (For user input abacus): "Thats not a number."
151
The example would be easier to read if the conditional processing were not nested three levels deep. If the main logic of this script were made into the contents of a procedure, it could be rewritten more simply.
152
Case "2", "22", "32", "42": printNum$ = anInt$ & "nd" Case "3", "23", "33", "43": printNum$ = anInt$ & "rd" Case Else: printNum$ = anInt$ & "th" End Select SetOrd$ = "This is the " & printNum$ & " number." End Function Call the function. MessageBox(SetOrd(InputBox$("Enter a whole number between" & _ " 0 and 50:")))
The last line of the example is the only executable code outside of the function SetOrd and instructs the MessageBox statement to display a message based on the user input received by the InputBox$ function. The value entered by the user is passed to SetOrd, which determines what MessageBox displays.
The effect of the transfer using GoTo in the example is to skip the If statement that checks whether the supplied approximation is Close but not very. If its already known to be Very close, it makes no sense to check further. This example uses GoTo to iterate through the sequence of calculations .25 ^ .25, .25 ^ (.25 ^ .25), .25 ^ (.25 ^ (.25 ^ .25)), and so on, until either two successive expressions in this sequence are within .0001 of each other, or 40 expressions have been calculated.
Sub PowerSeq Dim approx As Single, tempProx As Single, iters As Integer approx! = .25 iters% = 1 ReIter: tempProx! = approx!
Chapter 9. Managing Flow in Scripts
153
approx! = .25 ^ tempProx! If Abs(tempProx! - approx!) >= .0001 And iters% < 40 Then Iterate again. iters% = iters% + 1 GoTo ReIter End If Print approx!, Abs(approx! - tempProx!), "Iterations:" iters% End Sub Call PowerSeq() Output: .5000286 6.973743E-05 Iterations: 25
The example can be generalized to calculate the sequence of values x ^ x, x ^ (x ^ x), and so on, for any value x between 0 and 1, instead of .25 ^ .25, .25 ^ (.25 ^ .25), and so on.
154
If directTest% < 1 Or directTest% > 2 _ Then Beep : GoTo SpecTest i% = 0 Branch on 1 or 2. On directTest% GoTo TimeCheck, ItersCheck TimeCheck: startTime! = Timer() Do While i% <= 1000 i% = i% + 1 Loop Print "Time in seconds for 1000 iterations: " _ Timer() - startTime! Exit Sub ItersCheck: startTime! = Timer() Do Yield i% = i% + 1 Loop While Timer() < startTime! + 1 Print "Number of Yields in 1 second: " i% End Sub Call RunPerfTest()
Three runs of the sub RunPerfTest might have these results, depending on the speed of the computer where LotusScript is running:
Output: (With input 2) (With input 1) (With input 2) Number of Yields in 1 second: 975 Time in seconds for 1000 iterations: Number of Yields in 1 second: 952
.109375
Transferring control within the same procedure with the GoSub, On...GoSub, and Return statements
The branching statements GoSub and On...GoSub are nonstandard programming techniques with limited usefulness. They enable running a group of statements by transferring control from any number of other locations within the same procedure. Functionally the statements behave as a subroutine, but they cant take arguments, dont establish a separate scope, and arent available from other procedures or scripts. It is more common and useful to write the statements as an ordinary sub. The syntax is: GoSub label On expression GoSub label [ , label ]... Return The statement GoSub label transfers control to the statement labeled label and executes statements beginning at label, continuing until one of the following occurs: v A Return statement is encountered. Control returns to the statement following the GoSub statement. v An End statement is encountered; or an Exit Function, Exit Sub, or Exit Property statement is encountered; or an End Function, End Sub, or End Property statement is encountered. Execution of the script ends (End statement), or execution of the enclosing procedure ends (one of the other statements). The group of statements executed after the labeled statement and before the Return statement, including any other transfers of control, acts as a subroutine within the current procedure. The statement On expression GoSub label, label, ... transfers control similarly to GoSub label, except that the target label is conditioned on the value of expression: control transfers to the first label if expression
Chapter 9. Managing Flow in Scripts
155
is 1, to the second label if expression is 2, and so on. (Any of these labels may be the same.) The Return statement returns control to the statement following On...GoSub. The location of the GoSub statement in the procedure is unrelated to the location of a labeled statement that it transfers control to. The only requirement is that the GoSub and its target labeled statements must be in the same procedure. The actual flow of control is determined at run time. Execution of a GoSub or an On...GoSub statement defines a point of return. Another GoSub or On...GoSub may be executed before a Return statement is executed. When a Return is executed, control returns to the most recently defined point of return. Then that point of return becomes undefined. The Return statement doesnt return from the procedure. It is a run-time error to attempt to execute a Return statement when there is no currently available point of return within the procedure. These statements differ from the GoTo and On...GoTo statements, which transfer control without establishing a point of return. This example uses On...GoSub to run one or the other of two simple performance tests on pieces of the LotusScript language. By typing 1 or 2 into an input box, the user chooses whether to time 1000 iterations of a Do loop, or to count the number of Yields executed within one second. Using On...GoSub, the script branches to run one test or the other. A single Print statement reports the result.
Sub RunPerfTest Dim directTempV As Variant, directTest As Integer, i As Integer Dim startTime As Single, measure As Single, idPace As String SpecTest: directTempV = InputBox$ _ (|Type 1 for iteration time, or 2 for # of yields:|) If Not IsNumeric(directTempV) Then Exit Sub directTest% = CInt(directTempV) If directTest% < 1 Or directTest% > 2 Then _ Beep : GoTo SpecTest i% = 0 Branch on 1 or 2. On directTest% GoSub TimeCheck, ItersCheck Return here to print the performance-test result, and leave. Print idPace$ measure! Exit Sub TimeCheck: startTime! = Timer() Do While i% <= 1000 i% = i% + 1 Loop measure! = Timer() - startTime! idPace$ = "Time in seconds for 1000 Do iterations: " Return ItersCheck: startTime! = Timer() Do While Timer() < startTime! + 1 Yield i% = i% + 1 Loop measure! = i% idPace$ = "Number of Yields in 1 second: " Return End Sub Call RunPerfTest()
156
In this example, each Do statement is equivalent to the Do statement in the preceding example:
Dim doCount As Integer A Do While statement (condition at the beginning) doCount% = 0 Do While doCount% < 1000 doCount% = doCount% + 1 Loop A Do Until statement (condition at the beginning) doCount% = 0 Do Until doCount% >= 1000 doCount% = doCount% + 1 Loop A Do...Loop While statement (condition at the end) doCount% = 0 Do doCount% = doCount% + 1 Loop While doCount% < 1000 A Do...Loop Until statement (condition at the end) doCount% = 0 Do doCount% = doCount% + 1 Loop Until doCount% > 1000
The forms of the Do statement differ with regard to whether the condition is tested before or after the first iteration of the loop. The condition in a Do While or a Do Until condition statement is tested before the first iteration, whereas the condition in a Do...Loop While or a Do...Loop Until condition statement is not tested until after the first iteration. As a result:
Chapter 9. Managing Flow in Scripts
157
v The body of a Do While...Loop or Do Until...Loop statement may not be executed at all. v The body of a Do...Loop While or Do...Loop Until statement is executed at least once. This example shows the difference:
Dim doCount As Integer doCount% = 1 Do While doCount% < 1 doCount% = doCount% + 1 Loop Print "Do While...Loop counter reached" doCount% doCount% = 1 Do doCount% = doCount% + 1 Loop While doCount% < 1 Print "Do...Loop While counter reached" doCount% Output: Do While...Loop counter reached 1 Do...Loop While counter reached 2
The Do statement doesnt establish a separate scope for variables within it. A variable used in a While condition clause or an Until condition clause is like any other variable in the script. If the variable has not been used previously, then its appearance in condition declares it implicitly, and initializes it. For example:
Suppose that the variable named doCount% has not appeared in a script prior to its appearance here. Do While doCount% < 1 doCount% = doCount% + 1 Loop Print "Do While...Loop counter reached" doCount% Output: Do While...Loop counter reached 1
LotusScript declares doCount% implicitly and initializes it to 0, so the body of the loop executes once. However, its risky programming practice to rely on this initialization. You couldnt rely on this behavior without knowing that either doCount% has not appeared earlier during execution, or that the current value of doCount% is 0. In this example, a Do statement calculates successive terms of a sequence of numbers that converges to a limit:
This sub computes the quotient of each successive pair of terms of the Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, ... The sequence of quotients 2, 3/2, 5/3, ... is known to converge to the golden mean (1 + Sqr(5))/2. The sub argument deltaLim! is the tolerance. This example illustrates the Do...Loop Until form of the Do statement, with a condition that is recomputed on each iteration. Sub FibiLim (deltaLim As Single) Dim r1 As Single, r2 As Single, r3 As Single Dim limTrue As Single Dim i As Integer Initialize the Fibonacci numbers and a counter. r1! = 1 r2! = 1 r3! = 1 i% = 2 Do NexTerm: i% = i% + 1 r1! = r2!
158
r2! = r3! r3! is the next Fibonacci number. r3! = r2! + r1! Print i%, "f(" & Str(i%) & "):" r3!, "quotient: " _ r3!/ r2! On the first iteration, disable the standard exit condition. If i% = 3 GoTo NexTerm Iterate until successive quotients are close. The sequence is known to converge, so the iteration will end. Loop Until Abs(r3! / r2! - r2! / r1!) < deltaLim! limTrue! = (1 + Sqr (5)) / 2 When done, show the closeness obtained and the actual limit. Print "Tolerance:" deltaLim! Print "Difference:" CSng(Abs(r3! / r2! - limTrue!)), _ "(Actual limit:" limTrue!")" End Sub Call FibiLim with a tolerance argument. Call FibiLim(.005) Output: 3 f(3): 2 quotient: 2 4 f(4): 3 quotient: 1.5 5 f(5): 5 quotient: 1.66666666666667 6 f(6): 8 quotient: 1.6 7 f(7): 13 quotient: 1.625 8 f(8): 21 quotient: 1.61538461538462 9 f(9): 34 quotient: 1.61904761904762 Tolerance: .005 Difference: 1.013614E-03 (Actual limit: 1.618034)
For...Next loops
The iterative block statement For executes a block of statements a specified number of times. The syntax is: For countVar = first To last [ Step increment ] [ statements ] Next [ countVar [ , countVar ]... ] This example shows a For statement that does not use the Step or Next optional items.
Dim power2 As Integer For iV = 1 To 15 power2 = 2 ^ iV - 1 Print power2% ; Next Output: 1 3 7 15 31 63 127 255 511 1023 2047 4095 8191 16383 32767
The first line of the For statement in the previous example is equivalent to the following:
For iV = 1 To 15 Step 1
That is, if the phrase Step increment is omitted from the statement, the default value of increment is 1. The body of the For statement can be empty: there need be no statements at all between For and Next.
159
In this example, a compiler error results when you attempt to use 2 ^ 15 as the limiting value for an Integer counter variable in a For statement. This is because the maximum Integer value in LotusScript is (2 ^ 15) - 1.
Dim i As Integer For i% = 1 To 2 ^ 15 Next Output: Error 6: Overflow
When the counter variable is a Variant, LotusScript converts its value to the appropriate data type when it executes the For statement. For example:
For iV = 1 To 2 ^ 15 Next Print TypeName(iV), iV Output: LONG 32769
In this example, the value of kV during the second iteration of For is the Double value 2.1:
This loop iterates only twice because the third value of kV is 3.2, which is larger than the limiting value, 3. For kV = 1 To 3 Step 1.1
160
The LotusScript data type conversion rules apply to the counter variable. For example:
In this instance, the Step value, 1.1, is rounded to the Integer value 1 each time it is used to increment k%, because k% is declared as an Integer variable. Dim k As Integer For k% = 1 To 3 Step 1.1 Print TypeName(k%), k% Next Output: INTEGER 1 INTEGER 2 INTEGER 3
161
Dont print 0s. For k% = 0 To 2 * n% If coCalc(k%) > 0 Then Print coCalc(k%); Next k% Next j% End Sub Call CoArray(5) Output: Binomial coefficients for Coefficients for 0 : 1 Coefficients for 1 : 1 1 Coefficients for 2 : 1 2 Coefficients for 3 : 1 3 Coefficients for 4 : 1 4 Coefficients for 5 : 1 5 the integers up to: 5 1 3 1 6 4 1 10 10 5
You can call the sub CoArray with larger argument values to obtain other sets of binomial coefficients. Other features of this algorithm are: v To print the coefficients only for n, rather than for every integer up to n, move the final nested For statement (For k% = 0 To 2 * n...) outside of the current outer For statement (For j% = 0 To n...), after the phrase Next j%. v For small values of n, the algorithm is the easiest way of computing and writing out all of these binomical coefficients by hand in a symmetric triangular array, where the longest, bottom row contains the coefficients for n itself. Each coefficient is the sum of two coefficients already computed: its northwest and northeast neighbors in the array. For n = 15, the left half of the array can be produced by hand addition in a minute or so; the right half is its mirror image. v If the factorials of 1 through n are known, they can be used to compute the binomial coefficients. If a function to compute the factorial is called FactNum, then a binomial coefficient b(n; k) can be expressed as:
FactNum(n%) / (FactNum(k%) * FactNum(n% - k%))
This is a more conventional way of computing the coefficient. You can write a routine using FactNum to compute and print the same set of coefficients generated by the sub CoArray in the example above. FactNum itself can be written as a function using a For statement:
Function FactNum(n As Integer) As Double FactNum# = 1 For i% = 1 To n% FactNum# = FactNum# * i% Next i% End Function
Each method has its advantages: The formula using FactNum is the definition of the binomial coefficient, so that routine may be easier to read and modify. The implementation by CoArray is fast, and involves no calls to other routines. CoArray can take larger arguments than FactNum, since the largest number CoArray computes is a coefficient, rather than the factorial of n. The definition of the sub CoArray ends with two Next statements that complete two For statements. You can rewrite the Next statements in this way:
Next k% Next j%
That is, k% and j% are optional in these statements. The following is also equivalent:
Next k%, j%
162
When you use this construction, you must order the counter variables correctly: from the inside For statement to the outside.
v Within a For statement, its counter variable cannot be used as the counter variable of another For statement.
For i% = 1 To 3 For i% = 1 To 3 Next Next Output: Error 52: FOR count variable already in use: I
163
Dim persStats List As String Declare list of type String. persStats("Name") = "Ian" Assign list elements. persStats("Age") = "36" persStats("Home state") = "MD" ForAll idAttrib In persStats Print ListTag(idAttrib)": " idAttrib For each item in persStats, print its tag and value. End ForAll Output: Name: Ian Age: 36 Home state: MD
This example shows a ForAll statement where the container is an array instead of a list.
Dim numberId(2) As Integer For i% = 0 To 2 numberId(i%) = i% + 1 Next ForAll p2 In numberId Print TypeName(p2) p2 * p2 Print the type and the square of the number in each element. End ForAll Output: INTEGER 1 INTEGER 4 INTEGER 9
If an array or a list has no elements, then a ForAll statement with that array or list for a container variable has no effect. For example:
Dim testNone() As Integer Print "Before "; ForAll iTest In testNone Print iTest, "In ForAll "; End ForAll Print "After" Output: Before After
You cannot declare a reference variable outside a ForAll statement. For example:
Dim p2 As Integer ForAll p2 In numberId Print p2 * p2 ;
164
End ForAll Output: Error 164: FORALL alias variable was previously declared: P2
You can, however, reuse a reference variable from one ForAll statement as the reference variable in another ForAll statement. The container variable in the second ForAll statement must have the same data type as the container variable in the first ForAll statement. The LotusScript compiler generates an error if the data types are different. (The container can be an array or a list.) For example:
ForAll p2 In numberId Print p2 * p2 ; End ForAll Print Dim numShiftV(3) As Variant ForAll p2 In numShiftV p2 = 1 End ForAll Output: 1 4 9 Error 114: FORALL alias variable is not of same data type: P2
Changing the declared data type of numShiftV to Integer would make the second use of p2 legal.
To compare how a With statement can perform a similar task, see the description of With in User-Defined Data Types and Classes.
Chapter 9. Managing Flow in Scripts
165
In this example, the value of an element of the container array cHold is a reference to an object of the class refClass. Initially the two elements of cHold contain different object references. On the first iteration of the ForAll statement, the value of the first element is reset to the value of the second; thereafter, the elements refer to the same object.
Option Base 1 Class refClass Public cVar As Integer End Class Dim cHold(2) As refClass Set cHold(1) = New refClass Set cHold(2) = New refClass The output from the following Print statement shows that cHold(1) and cHold(2) hold different objects references. If cHold(1) Is cHold(2) _ Then Print "Same object" Else Print "Different objects" cHold(1).cVar% = 100 cHold(2).cVar% = 200 ForAll cElem In cHold Print Print cElem.cVar% Set cHold(1) = cHold(2) Now cHold(1) holds the same reference as cHold(2), so cElem refers to that object in the following statements (on both trips through ForAll). Print cElem.cVar% If cHold(1) Is cHold(2) _ Then Print "Same object" Else Print "Different objects" End ForAll Output: Different objects 100 200 Same object 200 200 Same object
The two examples above change the contents of the container array for the ForAll statement, but not the structure. Although you can use the Erase statement on the container or its elements; or use the ReDim statement on an array, it is not recommended, as the results are unpredictable. Similarly, it is possible to transfer control from outside a ForAll statement to a labeled statement inside. This is also not recommended, since by doing so you bypass the built-in initialization of the ForAll reference variable that occurs when the ForAll statement begins execution for a particular element.
166
For j% = 1 To 3 In eyeJay(i,j), store the string "(i,j)". eyeJay(i%, j%) = "(" & Str(i%) & "," & Str(j%) & ")" Print the element value. Print eyeJay(i%, j%), Next j%, i% Print Now print the elements of eyeJay one at a time in the same order as the ForAll statement accesses them. This order is first fastest, the storage order for any array. Print ForAll elem In eyeJay Print elem, End ForAll Output: ( 1, 1) ( 1, 2) ( 1, 3) ( 2, 1) ( 2, 2) ( 2, 3) ( 1, 1) ( 2, 1) ( 1, 2) ( 2, 2) ( 1, 3) ( 2, 3)
Early termination statements Stopping procedure execution early using the End statement
The End statement terminates execution of the current procedure, and also execution of any procedure in the sequence of calls that called the current one. The syntax is: End [ returnCode ] The optional returnCode is an integer expression. The script where this statement appears returns the value of this expression to the Lotus software application that executed the script. Refer to the product documentation to determine whether the product expects a return value when the End statement is executed. If no return code is expected, do not specify one with the End statement. In this example, the sub DoTimer is called, which then calls the sub ElapsedTime. When the End statement in ElapsedTime is executed, execution continues at the Print statement following the DoTimer call.
Compute the time to run some number of iterations of a For loop, and the time to execute the ElapsedTime sub. Dim anInt As String Public startSub As Single, startLoop As Single Public counter As Long
Chapter 9. Managing Flow in Scripts
167
Sub ElapsedTime If 0 or negative number of iterations is specified, print a message and end execution. If counter& <= 0 Then Print "Number of iterations must be >0" End End execution End If startLoop! = Timer() For doCount& = 1 To counter& Next Print Timer() - startLoop! "seconds to run" counter& _ "iterations" End Sub Sub DoTimer DoTimer calls ElapsedTime and reports the result. anInt$ = InputBox$("Enter a whole number:") counter& = CLng(anInt$) startSub! = Timer() Call ElapsedTime() This Print statement will not be executed if the End statement in sub ElapsedTime was executed. Print Timer() - startSub! "seconds for ElapsedTime sub call" End Sub Call DoTimer() Sample output, for 5000 iterations requested by user: .109375 seconds to run 5000 iterations .1601563 seconds for ElapsedTime sub call Output for -1000 iterations requested by user: Number of iterations must be >0
When you use Exit with a procedure, execution continues as it would following a normal return from the procedure.
168
This example incorporates the Do statement from the preceding example within a sub. The Exit Sub statement terminates execution of the sub ElapsedTime after doCount% reaches 1000. Execution continues with the Print statement following the sub call. It is not necessary to terminate execution of the Do loop separately. The Exit Sub statement transfers control from the Do loop out of the sub.
Compute the elapsed time to execute a sub that runs 1000 iterations of a simple Do loop. Public startTime As Single Sub ElapsedTime Dim doCount As Integer doCount% = 0 Do doCount% = doCount% + 1 If doCount% >= 1000 Then Exit Sub Loop Because of the Exit Sub statement above, this Print statement will not be reached. Print Timer() - startTime!, "seconds to run 1000 iterations" End Sub startTime! = Timer() Call ElapsedTime() Print Timer() - startTime! _ |seconds for sub call to run 1000 iterations| Output: .109375 seconds for sub call to run 1000 iterations
When execution continues after an Exit For statement has run, the count variable for the For statement has its most recent value, just as when execution continues after an ordinary termination of the For statement. When execution continues after an Exit ForAll statement has run, the ForAll alias variable is undefined, just as when execution continues after an ordinary termination of the ForAll statement. Following execution of an Exit Function statement, the function returns a value to the caller. As with a normal return, this is the last value assigned before the exit. If none was assigned, the function return value is its initialized value: either 0, EMPTY, the empty string (), or NOTHING. For example:
Function TwoVerge(seqSeed As Integer) As Single Leave if the call argument is not a positive integer. The return value of TwoVerge is its initial value, 0. If seqSeed% < 1 Then Exit Function TwoVerge! = Sqr(seqSeed% + 1) Dim i As Integer For i% = 1 To seqSeed% TwoVerge computes and returns a value that must be 1 or greater, according to the following formula. TwoVerge! = Sqr(1 + (seqSeed% + 1 - i%) * TwoVerge!) Next i% End Function
169
170
171
Time 4 5 6 7
Comments Agent 1 running. Agent 1 ends. Start User Bs Agent 2. Agent 2 ends.
Threaded agents
In this example, User B sees results sooner. User A sees response later, but the time difference is not noticeable.
Time 0 1 2 3 4 5 6 7 Compute Compute Print Compute Compute Compute Print Thread1 Thread2 Comments User A activates Agent 1. Agent 1 starts. User B activates Agent B. Agent 1 running. Agent 1 swapped out. Agent 2 starts. Agent 2 ends. Agent 1 running. Agent 1 running. Agent 1 ends.
Synchronization functions
LotusScript 4.0 (in Domino 5.0) includes a new set of primitives to allow LotusScript agents to synchronize with one another: CreateLock -- finds the lock ID associated with Name. If none exists, the Lock ID is created. DestroyLock -- removes the current link to the lock specified. If the number of links is zero, the lock is destroyed. CodeLock -- acquires the lock specified by ID. If the lock is already held by another agent, the thread stalls until the lock becomes available. CodeUnlock -- releases the lock, making it available for the next agent requesting it. CodeLockCheck -- returns the number of agents waiting for the the specified lock, plus 1. Sleep -- causes a script to pause for at least the number of seconds specified.
172
v If Comm1 is the first agent to start execution, it gets the lock; the second (Comm2) must wait for Comm1 to release it before starting. Comm1 outputs a message that it has the lock and provides the reference count. v As soon as Comm1 is done with the lock, it releases it and Comm2 takes it. Comm1 tries to obtain the lock again, but now must wait until Comm2 is done with it. Comm2 outputs a message that it now has the lock and reports the reference count again. v As soon as Comm2 is done with the lock, it releases it and Comm1 takes it. The process repeats for the duration of For loop, in this case, 5 iterations.
Comm1: Option Public Remove the following line if you do not have a resource library defined. Use "ThreadsLib" Sub Initialize Dim lockName As String Dim lockID As Integer, refcnt As Integer Dim gotLock As Variant, releaseLock As Variant, _ deleteLock As Variant On Error Goto syn_error Provide some unique name here to distinguish the agents. ID = "Comm1 tuvwx:5706 " Msgbox ID & "Started" lockName = "Update" On Error Goto syn_error Create the lock lockID = Createlock(uName) If (lockID <> -1) Then Msgbox ID & "Created lock: " & lockID End If Put agent to sleep for a second. This gives the second agent time to start. Sleep 1 For x = 1 To 5 Attempt to get the lock and report the outcome as well as the reference count gotLock = CodeLock(lockID) If (gotLock) Then Msgbox ID & " Got lock: " & lockID & " - at: " & _ Now() refcnt = Codelockcheck(lockID) Msgbox ID & " Reference count is " & refcnt Do some meaningful work here, or just sleep Sleep 1 Else Msgbox ID & "Failed to get lock" End If Release the lock so the other agent can get it. releaseLock = Codeunlock(lockID) If (releaseLock) Then Msgbox ID & " Releasing lock: " & lockID & _ " - at: " & Now() Sleep here allows the other agents to obtain the lock before this agent has a chance to. Sleep 1 Else Msgbox ID & "Failed to release lock" End If Next
Chapter 10. Managing Asynchronous Web Agents in Domino
173
When we are finished, destroy this agents reference to the lock deleteLock = Destroylock(lockID) If (deleteLock ) Then Msgbox ID & "Destroyed lock " & lockID Else Msgbox ID & "Failed to destroy lock" End If Msgbox ID & "Done " Exit Sub syn_error: errormsg = " * * Error: " & Err & " - " & " in " & ID & " at " & Erl() Msgbox errormsg Resume Next End Sub Error() & _
A sample output of Comm1 (with an ID of tuvwx:5706) and Comm2 (with an ID of uvwxy:5742) running concurrently as agents through the Domino Web server would look something like the following: Note: Your results will not be identical; due to the nature of asynchronous system locks, you can never predict when specific events will occur.
Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Addin: Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent Agent message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message message box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: box: Comm1 tuvwx:5706 Started Comm1 tuvwx:5706 Created lock: 0 Comm2 uvwxy:5742 Started Comm2 uvwxy:5742 Created lock: 0 Comm1 tuvwx:5706 Got lock: 0 - at: 2/10/99 1:57:06 PM Comm1 tuvwx:5706 Reference count is 1 Comm2 uvwxy:5742 Got lock: 0 - at: 2/10/99 1:57:07 PM Comm2 uvwxy:5742 Reference count is 1 Comm1 tuvwx:5706 Releasing update_lock: 0 - at: 2/10/99 1:57:07 PM Comm2 uvwxy:5742 Releasing update_lock: 0 - at: 2/10/99 1:57:08 PM Comm1 tuvwx:5706 Got lock: 0 - at: 2/10/99 1:57:08 PM Comm1 tuvwx:5706 Reference count is 1 Comm2 uvwxy:5742 Got lock: 0 - at: 2/10/99 1:57:09 PM Comm2 uvwxy:5742 Reference count is 1 Comm1 tuvwx:5706 Releasing lock: 0 - at: 2/10/99 1:57:09 PM Comm2 uvwxy:5742 Releasing lock: 0 - at: 2/10/99 1:57:10 PM Comm1 tuvwx:5706 Got lock: 0 - at: 2/10/99 1:57:10 PM Comm1 tuvwx:5706 Reference count is 1 Comm2 uvwxy:5742 Got lock: 0 - at: 2/10/99 1:57:12 PM Comm2 uvwxy:5742 Reference count is 1 Comm1 tuvwx:5706 Releasing lock: 0 - at: 2/10/99 1:57:12 PM Comm2 uvwxy:5742 Releasing lock: 0 - at: 2/10/99 1:57:13 PM Comm1 tuvwx:5706 Got lock: 0 - at: 2/10/99 1:57:13 PM Comm1 tuvwx:5706 Reference count is 1 Comm2 uvwxy:5742 Got lock: 0 - at: 2/10/99 1:57:14 PM Comm2 uvwxy:5742 Reference count is 1 Comm1 tuvwx:5706 Releasing lock: 0 - at: 2/10/99 1:57:14 PM Comm2 uvwxy:5742 Releasing lock: 0 - at: 2/10/99 1:57:15 PM Comm1 tuvwx:5706 Got lock: 0 - at: 2/10/99 1:57:15 PM Comm1 tuvwx:5706 Reference count is 1 Comm2 uvwxy:5742 Got lock: 0 - at: 2/10/99 1:57:16 PM Comm2 uvwxy:5742 Reference count is 1 Comm1 tuvwx:5706 Releasing lock: 0 - at: 2/10/99 1:57:16 PM Comm2 uvwxy:5742 Releasing lock: 0 - at: 2/10/99 1:57:18 PM Comm1 tuvwx:5706 Destroyed lock 0 Comm1 tuvwx:5706 Done Comm2 uvwxy:5742 Destroyed lock 0 Comm2 uvwxy:5742 Done
These primitives are used only for communication between instances of cooperating LotusScript agents within a single process. They are designed specifically for asynchronous Web agents.
174
Supported platforms include Win32, OS/2, UNIX (Solaris, HPUX, AIX), and Alpha-NT.
Thread-specific bugs
Threading problems are usually non-deterministic. Common threading problems include: v v v v Lost updates Partial updates Deadlock Thread calls non-thread-safe code
175
176
177
You can create and assign variable references to product objects, get and set product object properties, use product object methods, attach scripts to product object events, and delete product objects. For detailed information, see the Lotus software documentation.
Creating objects
The product automatically creates some objects (cells in a spreadsheet for example). You can use the product user interface to create objects, and you can create objects in a script. To create an object in a script, you must supply whatever arguments the product requires to create an instance of the particular class, and you must assign an object reference to a variable. The syntax is usually: Dim objRef As prodClass Set objRef = New [ prodClass ] [( argList )] The Dim statement declares an object reference variable. The Set...New statement creates a product object and assigns the variable a reference to that object. You can also combine these operations in a single statement: Dim objRef As New prodClass [( argList ])] You can use a method to create the object. For example, in Lotus Notes Release 4, you use the NotesDatabase Create method to create a new .NSF file. You can also use a container method to create objects in scripts. A container method applies to the object that contains the object you are creating. For example, Freelance Graphics for Windows provides container methods for creating objects.
Referring to objects
To refer in a script to an object that already exists, you can usually use the name that the product or user gave to the object. You can (and in some cases you must) assign your own object reference. One way to assign your own object reference to a variable is to declare an object variable, such as: Dim objRef As prodClass and bind it to the product object. For example: Set objRef = Bind [ prodClass ] [( objName ])] The product can supply a function or method that you can use to set an object reference. The following Initialize sub works with three Notes objects: a database, a view, and a document. The sub uses a Dim...New statement to create a new NotesDatabase object to work with ORGSTRUC.NSF on the HR_ADMIN server, and it uses methods in Set statements to set variable references to a view and a document. GetView is a NotesDatabase class method, and GetFirstDocument is a NotesView class method.
Sub Initialize Dim db As New NotesDatabase("HR_ADMIN", "ORGSTRUC.NSF") Dim view As NotesView, doc As NotesDocument Set view = db.GetView("Main View") Set doc = view.GetFirstDocument End Sub
178
Bracket notation
In some cases, you can use names in brackets rather than object reference variables to identify Lotus software objects. For example, the product might allow you to use:
[A1].Value = 247000
instead of:
Dim myCell As Cell Set myCell = Bind Cell("A1") myCell.Value = 247000
For more information, see Bracket Notation in LotusScript Language Reference, and check your product documentation.
Lotus products normally handle the process of attaching scripts you write to the events you specify. You can also use LotusScript On Event statements to attach subs to object events. For example, a db object is an instance of the Notes/Domino NotesDatabase class. It has a number of properties, including FileName, FilePath, and Title. The value of the Title property is a string specifying the title of the database. In a script, you can get and set the value of Title. You can only get the values of FileName and FilePath, which specify the location the database in the file system.
Deleting objects
You can sometimes use the Delete statement to delete a product object or the object reference variable. The object reference variables that you explicitly declare and bind to product objects have a scope. When all object references (there may be more than one) to an object created in a script are out of scope, the object itself may be deleted. Some products supply methods to remove actual objects. For example, in Notes, you use the NotesDatabase class Remove method to delete an .NSF file.
Collection classes
Some Lotus products provide collection classes, also known as container classes. A collection object (an instance of a collection class) contains a collection of objects. For example, in Freelance Graphics an Application object contains an instance of the Documents collection class. Each Document object contains an instance of the Pages collection class and each page object contains an instance of the ObjectCollection class. The ObjectCollection object can include text boxes, charts, tables, and other objects belonging to classes derived from the DrawObject class.
Chapter 11. Beyond Core LotusScript
179
For more info on deriving classes (also known as class inheritance), see Derived classes in User-defined Data Types and Classes. You can use ForAll loops or indexing to access individual members of a collection class. The following script uses three nested ForAll loops to iterate through the collections. Within individual TextBlock objects, the script uses indexing to set list entries levels 2 through 5 in each TextBox object to italic.
Dim level As Integer ForAll doc In CurrentApplication.Documents ForAll page In Document.Pages ForAll obj In Page.Objects If the object is a TextBlock, set the font to Garamond, and set list entries at levels 2 through 5 to Italic. If obj.IsText Then IsText is a DrawObject property. obj.Font.FontName = "Garamond" For level% = 2 to 5 obj.TextProperties(level%).Font.Italic = TRUE Next level% End If End ForAll End ForAll End ForAll
180
" this month?")) expenses@ = CCur(InputBox("How much did we spend?")) balance@ = revenue@ - expenses@ MessageBox "Our balance this month is " _ & Format(balance@, "Currency") End Sub
The two input boxes with sample entries and the resulting message box are:
If the user enters a string that the CCur function cannot convert to Currency, an error condition occurs. You can use an On Error statement to branch to an error-handling routine in such a case. This expanded version of the example uses the MessageBox function to ask the user whether to try again. The second message box also contains a question mark icon, specified by MB_ICONQUESTION (32). To use constants rather than the numbers to which they correspond as MessageBox arguments, you must include the file that defines these constants, LSCONST.LSS, in the module declarations.
%Include "LSCONST" Sub CalcBalance Dim revenue As Currency, expenses As Currency, balance _ As Currency EnterValues: On Error GoTo BadCur: revenue@ = CCur(InputBox("How much did we make" & _ " this month?")) expenses@ = CCur(InputBox("How much did we spend?")) balance@ = revenue@ - expenses@ MessageBox "Our balance this month is " _ & Format(balance@, "Currency") Exit Sub BadCur: If MessageBox("Invalid entry! Do you want to try again?", _ MB_YESNO + MB_ICONQUESTION) = IDYES Then GoTo _ EnterValues Exit Sub End Sub
When the user enters an invalid entry, the message box offers the option of making another entry:
181
For more information about error processing, see the chapter Error Processing.
The Windows platform supports all of these functions and statements. The OS/2 and UNIX platforms and the Macintosh support some. Also, different client products may choose not to support certain functions. For example, Notes does not support SendKeys and Yield. Additionally, Yield is only useful in a Win 16 environment. For more information, see Appendix B, Platform Differences. The following example uses all of these functions and statements to interact with a Windows accessory, Notepad: v The Environ function returns the Windows Temp directory, the directory where Windows creates and maintains temporary files. Note: On the Windows and OS/2 platforms, the operating system and some programs make use of environment variables that you set. Under MS-DOS, for example, you use CONFIG.SYS,
182
v v v v
AUTOEXEC.BAT, and other batch files to set environment variables. You can use the MS-DOS Set command to see a list of environment variables and their current settings. In a script, you can use the Environ function to return the current value of an environment variable. The Shell function starts NOTEPAD.EXE. The ActivateApp function makes sure that Notepad has the focus so that keystrokes can be sent to it. SendKeys statements save a note the user writes in a text file, minimize the Notepad window, and close Notepad. The Yield function lets Windows pass control to Notepad so the user can use it to compose a note.
There are two module-level variables and four subs. The module-level variables are String variables:
Dim startDir As String The current directory at startup. Dim fileName As String The note file name.
The four subs are Initialize, CreateNote, ReadNote, and Terminate. Initialize automatically executes when the module is loaded. In turn, Initialize calls CreateNote and ReadNote. Terminate executes before the module is unloaded. The Initialize sub makes the Windows Temp directory the current directory, makes sure that a file named _MYNOTE.EXE exists and is empty, calls the CreateNote sub, then calls the ReadNote sub.
Sub Initialize Dim tempDir As String, taskID As Integer Store the name of the current directory, then make the Windows Temp directory the current directory. startDir$ = CurDir$ tempDir$ = Environ("Temp") ChDir tempDir$ fileName$ = "_MYNOTE.TMP" Make sure the file exists and is empty before opening Notepad. fileNum% = FreeFile Open fileName$ For Output As fileNum% Write #fileNum% The file now contains only an empty line. Close fileNum% Open the file (guaranteed to exist) in Notepad. taskID% = Shell("notepad " & fileName$) CreateNote Create the note. See the CreateNote sub below. ReadNote Display the note. See the ReadNote sub below. End Sub
The CreateNote sub creates a header for the note, including the current date and time, displays a message, activates (shifts focus to) Notepad, and sends the header to Notepad. It then yields control to Windows for 10 seconds so the user can type into Notepad. If the 10-second While loop with the Yield were excluded, script execution would continue without any pause, giving the user no time to enter a note. After 10 seconds, an ActivateApp statement insures that Notepad has the focus (in case the user has shifted focus to another window), and a SendKeys statement sends keystrokes for the File Save menu command and the Control menu Minimize command. The keystrokes for File Save are ALT+FS and the keystrokes for Minimize are ALT+spacebar+N. ALT+spacebar+C opens the Control menu in the Notepad title bar. In a SendKeys statement, % represents the ALT key.
Sub CreateNote Dim header As String, finish As Single MessageBox "Write your note." header$ = Format(Now, LongDate) &"~~Note: " ActivateApp "notepad - " & fileName$ SendKeys "~" & header$, TRUE Send the note header
Chapter 11. Beyond Core LotusScript
183
to Notepad. finish! = Timer + 10 While Timer < finish! Yield Wend ActivateApp "notepad - " & fileName$ SendKeys "%fs% n",TRUE Save the file and minimize the window. End Sub
The ReadNote sub displays a message box, opens the file that was just saved, inputs the file contents into a String variable, and displays a message with the contents. The file name appears in the message box title bar.
Sub ReadNote MessageBox "Read your note." fileNum% = FreeFile Open fileName$ For Input As #fileNum% message$ = Input$(LOF(fileNum%), fileNum%) Close fileNum% MessageBox message$,, fileName$ End Sub
The Terminate sub executes. An ActivateApp statement shifts focus to Notepad, in case the user moved the focus to another window. A SendKeys statement sends ALT+F4 to Notepad, which closes Notepad. The sub then makes the current directory at startup the current directory again.
Sub Terminate ActivateApp "notepad - " & fileName$ SendKeys "%{f4}", TRUE ChDir startDir$ End Sub
OLE Automation
A Windows application that supports OLE Automation provides a set of product classes, each with a set of properties and methods. You can create and manipulate objects in such an application much as you do in the Lotus software application from which you are running LotusScript. For example, Microsoft Visio is a Windows drawing package that supports OLE automation. The following example builds an array of strings. Each string contains the name and job title of a manager on a Visio organizational chart. In the module declarations, declare a dynamic one-dimensional array of strings:
Dim manager() As String
The GetManagers sub uses the CreateObject function to create an instance of the Visio Application class, which runs a new instance of the Visio program (VISIO.EXE). To get an instance that is already running, use the GetObject function. A Visio Application object contains a collection of documents. Each document contains a collection of pages, and each page contains a collection of shapes. Visio provides a class for each of these: Application, Documents, Document, Pages, Page, Shapes, and Shape. GetManagers uses the Documents class Open method to open a drawing file, a Document object. The sub then cycles through the pages in the document and the shapes on each page. For each shape with Manager in its Name property, the sub places the Text property value in a new element of the array. The Text property for a Manager shape contains a managers name and job title.
Sub GetManagers Use Variant variables for objects Dim appVisioV As Variant, docObjV As Variant Dim shapesObjV As Variant, shapeObjV As Variant
184
Dim orgchart As String Dim iPage As Integer, iShape As Integer, _ iManager As Integer Set appVisioV = CreateObject("visio.application") orgchart$ = "c:\visio\drawings\orgchart.vsd" Set docObjV = appVisioV.Documents.Open(orgchart$) For iPage% = 1 To docObjV.Pages.Count Set shapesObjV = docObjV.Pages.Item(iPage%).Shapes For iShape% = 1 To shapesObjV.Count Set shapeObjV = shapesObjV.Item(iShape%) If Instr(shapeObjV.Name, "Manager") > 0 Then iManager% = iManager% + 1 ReDim Preserve manager$(1 To iManager%) manager$(iManager%) = shapeObjV.Text End If Next iShape% Next iPage% appVisioV.Quit End Sub
For information about Visio classes, including their properties and methods, see the Visio documentation.
185
If you are using a C++ compiler, the name of any function becomes corrupted. Use the extern C {. . .} construct to keep the exact name intact. If you are using Windows 95 or Windows NT, the name of an exported DLL function is case sensitive, although LotusScript automatically converts the name to uppercase in the Declare statement. To successfully call an exported DLL, use the Alias clause in the Declare statement to specify the function name with correct capitalization. LotusScript leaves the alias alone. Note: The _ is reserved for Notes-specific DLLs. This is a change effective as of Notes 4.5.1. If you attempt to load a DLL in Notes 4.51 or greater using LotusScript, and the name of the DLL is preceded by an underscore, you will receive the error Error in loading DLL.
Example
The following statements declare an exported DLL with an alias (preserving case sensitivity), and then call that function. Declare Function DirDLL Lib "C:\myxports.dll" _ Alias "_HelpOut" (I1 As Long, I2 As Long) DirDLL(5, 10)
Declaring C functions
To use C functions, first you must declare them in Declare statements. Declare statements appear at the module level, so enter these statements in the declarations section of the module where you want to call the C functions. In a Declare statement, you can declare a C function as either a function or a sub. The syntax is: Declare [Public | Private] {Function | Sub} LSname Lib libName [Alias aliasName ] ( [ argList ] ) [ As returnType ] If the C function does not return a value, or you are not interested in the return value, you can declare it as a Sub. In either case, the Declare statement identifies the library containing the function. All the C functions mentioned in this section come from the User32 library in the Windows API. GetActiveWindow takes no parameters and returns the handle (an integer) of the active window (the window with focus).
Declare Function GetActiveWindow Lib "User32" () As Long
SetWindowText returns nothing, so you can declare it as a sub. It has two input parameters: the window handle and a string. As long as they are valid LotusScript identifiers, you can use your own parameter names or copy the names used in the API documentation, as in the example below.
Declare Sub SetWindowText Lib "User32" Alias "SetWindowTextA" _ (ByVal hWnd As Long, ByVal lpString As String)
Note: Be aware that you are actually calling a C function which needs to be supplied by you. This may cause your script to be platform-dependent.
186
Note: Lists cannot be passed by reference. They also cannot be passed by value. Using a list as an argument produces a run-time error.
187
Keyword
How it is passed to a C function A 4-byte pointer to the characters is pushed on the call stack. The C function should not write to memory beyond the end of the string. If the call is made with a variable, changes to the string by the C function are reflected in the variable. This is not true for a string argument to a LotusScript function declared as ByVal.
A 16-byte structure, in the LotusScript format for Variants, is pushed on the call stack. A 4-byte product object handle is pushed on the call stack. The number of bytes of data in the argument is pushed on the call stack. For example, the argument contains a Long value, then the called function receives 4 bytes. The function may receive a different number of bytes at run time.
No other data types (arrays, lists, fixed-length strings, types, classes, or voids) can be passed by value. It is a run-time error to use these types as arguments. Any of the data types that can be passed by value can also be passed by reference. The argument ByVal 0& specifies a null pointer to a C function, when the argument is declared as Any.
Example
Declare Sub SemiCopy Lib "mylib.dll" _ (valPtr As Long, ByVal iVal As Long) Dim vTestA As Long, vTestB As Long vTestA = 1 vTestB = 2 SemiCopy vTestA, vTestB The C function named SemiCopy receives a 4-byte pointer to a 2-byte integer containing the value of vTestA, and a 2-byte integer containing the value of vTestB. Since vTestA is passed by reference, SemiCopy can dereference the 4-byte pointer and assign any 2-byte integer to that location. When control returns to LotusScript, vTestA contains the modified value. Since vTestB was passed by value, any changes made by the C function are not reflected in vTestB after the function call.
Passing strings
When you pass a string by reference, LotusScript passes a 4-byte pointer to a copy of the string in an internal buffer allocated in memory. The C function cannot safely modify the contents of this buffer unless the function is written specifically for LotusScript. When a string is passed by value, LotusScript passes a 4-byte pointer to a null-terminated string (which is what the C function expects) and passes a pointer to the string. The C function can modify this string, but cant lengthen it. Any changes to the string will be reflected in the script variable on return from the function. If you are passing a pointer to something other than a string, then pass the parameter by reference. You can specify the use of non-platform-native characters as arguments and return values using the LMBCS and Unicode keywords. v Unicode specifies a Unicode string of two-byte characters (words) using the platform-native byte order. v LMBCS specifies a LMBCS optimization group 1 string (multibyte characters).
188
String
Here is a sub that uses the Windows C functions GetActiveWindow and SetWindowText to set the title of the active window (the window with focus):
Sub Initialize Dim activeWin As Long, winTitle As String, _ winLength as Long winTitle = Stringe(255,0) activeWin = GetActiveWin winLength = GetWindowText(activeWin, winTitle, 255) winTitle = Left(winTitle, winlength) Messagebox winTitle, "Window title" End Sub
To get a window title at run time, use the GetWindowText function. GetWindowText has one input parameter (the window handle, of data type long) and two output parameters: a String variable and a buffer size (the maximum length of the string). The return value is the length of the string that the function places in the String variable.
Declare Function GetWindowText Lib "GetWindowTextA" _ (ByVal hWnd As ByVal lpString ByVal chMax As "User32" Alias _ Long, _ As Long _ Long) As Long
Note: You must be careful when working with a String variable that is given a value by a C function. If the C function assigns a value that is larger than the length already allocated for the string, it overwrites memory not allocated for the string. The results are unpredictable and may cause a crash. You can make sure that the String variable has space for the string in one of two ways: v Assign it a value that is at least as long as the string to be returned before you pass the variable to the C function. v Declare it as a sufficiently sized fixed-length String variable. For example, if the maximum length for the string is 255, then you can use the String function to put 255 NULL characters in a variable-length String variable:
winTitle$ = String(255, 0)
189
GetWindowText returns the actual length of the string. If you use a variable-length String variable, you can use the return value to get rid of the padding at the end of the string. For example:
Dim winTitle As String, winLength As Long winTitle = String(255, 0) activeWin% = GetActiveWindow() winTitleLength% = GetWindowText(activeWin%, winTitle$, 255) winTitle$ = Left(winTitle$, winTitleLength%)
Note: If you use a C function that does not return the length of a string, you can extract the left portion of the string up to the first NULL character as follows:
stringFromC$ = Left(stringFromC$, Instr(stringFromC$,_ Chr$(0)) -1)
In C:
long C_CALL_TYPE LSArrayArg(LSsValueArray *pLSArr) { long *pData=pLSArr->Data; //pData points to first array element return pData[0]+pData[1]; //Sum first 2 array elements }
Or:
long C_CALL_TYPE LSArrayArg(long **pLSArr) { long *pData=*pLSArr; //pData points to first array element return pData[0]+pData[1]; //Sum first 2 array elements
C_CALL_TYPE is the calling convention: Pascal, STDCALL, _System, or CDEL. Other C functions may require an array, such as the Windows function SetBitmapBits. You can still pass the array by passing the first array element by reference with the Any keyword, as shown in the following example. In LotusScript:
Declare Function FncArrayArg(A As Any) As Long Dim MyArr(0 to 5) As Long Print FncArrayArg(MyArr(0))
In C:
long C_CALL_TYPE FncArrayArg(long *pArr) { return pArr[0]+pArr[1]; //Sum first 2 array elements }
190
In the first example, all strings (fixed-length and variable-length) in type t1 and any of its nested types will be passed as Unicode strings. In the second example, all strings in type t1 (fixed- and variable-length) and any of its nested types will be passed as LMBCS strings. If Unicode or LMBCS is not specified in this way, the default is to pass all strings in a type argument in the platform-native character set. This is compatible with LotusScript Release 2. Strings contained in Variants in the type will not be affected. This change is incompatible with LotusScript Release 2, because translation to platform will be invoked by default on types containing strings (previously, these strings would have been passed as platform-native character set strings). If the type contains a fixed-length non-Unicode string, the entire structure must be copied and its size adjusted. The size of the structure will be smaller (each fixed-length string will contain half as many bytes when translated to platform or LMBCS, since the length of the string is fixed and must be preserved). This implies that the string may be truncated (lose information) because a Unicode string of length 20 may require more than 20 bytes to represent in platform (DBCS). The loss cannot occur with variable-length strings, since they are represented as pointers. LotusScript aligns type members to their natural boundaries for cross-platform transportability:
Data type Boolean Byte Integer Long Single Double Currency String (LMBCS) String (Unicode) String (Platform) Variant Alignment 2 bytes 1 byte 2 bytes 4 bytes 4 bytes 8 bytes 4 bytes 2 bytes 2 bytes 1 byte 8 bytes
The resulting alignment will not match the platform-specific alignment on Windows 3.1 and Windows 95. For example, LotusScript aligns the type member B on a 4-byte boundary, while the default alignment in Windows 3.1 will be on a 2-byte boundary.
191
Example 1
The following statements declare the C function SetBitmapBits.Its 3rd argument is an array argument. This is declared as type Any. In the function call, passing bitArray(0) passes the array by reference. Declare Sub SetBitmapBits Lib "_privDispSys" _ (ByVal hBM As Integer, ByVal cBytes As Long, pBits As Any) ... SetBitmapBits(hBitmap, cBytesInArray, bitArray(0))
Example 2
type mytype mName as string end type class myclass mName as string end class function VariantParam( v as Variant) as string dim tempstr as string tempstr = TypeName(v) VariantParam = tempstr end function sub initialize dim myinteger as integer dim mylong as long dim mystring as string dim myintlist list as integer dim myintarray() as integer dim mymytype as mytype dim mymyclass as myclass messagebox variantparam(myintlist) messagebox variantparam(myintarray) Error: Type mismatch on: MYMYTYPE messagebox variantparam(mymytype) messagebox variantparam(mymyclass) end sub
192
Type Rect left As Long top As Long right As Long bottom As Long End Type Declare Sub GetWindowRect Lib "User32" (Byval hWnd As Long, _ lpRect As Rect) Declare Sub MoveWindow Lib "User32" _ (Byval hWnd As Long, Byval x As Long, Byval y As Long, _ Byval nWidth As Long, nHeight As Long, Byval bRepaint As Long) Sub Initialize Dim activeWin As Long, winRect As Rect activeWin = GetActiveWindow Call GetWindowRect(activeWin, winRect) Call MoveWindow(activeWin, winRect.left, winRect.top, _ winRect.right/2, winRect.bottom/2, True) End Sub
Return values
The data type of a C function can be established by explicit data type declaration in the Declare statement, by a data type suffix on the function name in the Declare statement, or by an applicable Deftype statement. One of these must be in effect. If not, the data type of the return value defaults to Variant, which is illegal for a C function.
LotusScript data type Boolean Byte Integer Long Single Double Currency String Variant Product object User-defined object Type instance Any Array List Legal as C function return type? Yes Yes Yes Yes Yes Yes No Yes, except for fixed-length string No Yes (as a 4-byte object handle of type Long) Yes No No No No See LSX toolkit for details See LSX toolkit for details char * or char[] C data type bool byte int long float double
The following example uses five Windows 3.1 API functions. The user identifies a window in which to work. The script finds the window, resets the window text, and yields control as long as the user keeps the focus in the window. When the user moves focus out of the window, the script restores the original window text and displays a message. If the user asks for a window that does not exist or is not running, the script also displays an appropriate message.
Chapter 11. Beyond Core LotusScript
193
194
About LS2J
LS2J is the interface that allows data to transfer from the Java data type to the LotusScript data type and allows LotusScript to execute Java object methods. LS2J allows LotusScript to create Java objects as if they are native to the LotusScript environment. This set of LotusScript objects is implemented by way of a LotusScript Extension. You can use this LSX in any existing LotusScript implementation, standalone or embedded in another application, such as Enterprise System Builder (ESB), Lotus SmartSuite, or Lotus Notes.
Java security
LS2J enforces Java security as follows: v Only public methods and fields are available. v LS2J has the same access rights as a Java program which does not contain a package statement.
System requirements
LS2J is implemented on all Domino platforms. Your system must meet the following requirements: v The system must have enough memory to support both the Java Virtual Machine (JVM) and the LotusScript client applications. v To use LS2J from within Notes, remember that your LotusScript code must include:
Uselsx "*javacon"
Note: LS2J is implemented entirely as an LSX (in C++). There is no Java component to distribute.
Using LS2J
To use LS2J from within Notes, your LotusScript code must include this line:
Uselsx "*javacon"
This loads the LS2J Dynamic Link Library (DLL) on Win32 and registers all the Application Data Types (ADTs). LotusScript provides a JavaSession ADT to be used as an instance to connect with the JVM. This statement:
Set mySession = New JavaSession
creates a new Java session. If the JVM has not been started, one is created at this time. It is up to the LotusScript client to load the LSX. The environment determines how the Java Virtual Machine (JVM) is set up and the limits on how LotusScript can access the Java data. LotusScript locates the Java class files in two ways:
Chapter 11. Beyond Core LotusScript
195
1. In the Script Libraries that the user specified through the USE statement. 2. On the file system as specified in the Notes.ini variable JavaUserClasses. To tell Notes where the Java classes are, include the following line in your Notes.ini file:
JavaUserClasses = <classpath1>;<classpath2>; ... <classpathn>
For example, if the Java classes are in one directory, such as E:\LSI\test\java, the Notes.ini file would include the following line:
JavaUserClasses=E:\LSI\test\java
In the Notes environment, LotusScript locates Java classes and uses them as if they were LotusScript objects. For example, if you have a set of common classes that are written in Java, you may use those classes in LotusScript without modification.
Run the program. The answer is 50. Description of the USE statement: The syntax of the LotusScript USE statement is:
USE <script_library>
The Use statement examines the type of the Script Library. If the Script Library contains LotusScript, processing proceeds as before. If the Script Library contains Java classes, the contained Java classes are available to the LotusScript program by using LS2J.
196
Note: The restriction on using the LotusScript Use statement to incorporate a Script Library containing Java has been lifted.
The dot notation method is easier and more intuitive, but certain restrictions apply. The JavaMethod ADT method is significantly harder to use but is more appropriate for general use. Dot notation is ambiguous if any of the the conditions listed below occur. If they do, you can use the more general mechanism to resolve the ambiguity. v Case sensitivity LotusScript is case insensitive while Java is case sensitive. While theoretically you can have two Java methods differ only in case -- for example, MyMethod and mymethod -- they are distinctly different methods. There is no way for LotusScript to identify the correct method to invoke using the dot notation. The result is JVM-dependent if you try to access the function; that is, the results may differ depending on what operating system you are using. v Long method names LotusScript has an internal limitation of 40 characters for names. If you use the dot notation method, you wont be able to get to methods with names longer than 40 characters. v Method overloading LotusScript currently does not support method overloading. Because Java does, it is fairly common for a Java class to contain methods of the same name but with different signatures. If you use the dot notation, LotusScript uses trial-and-error to try and match the method. It is somewhat JVM-dependent, because the method that is matched depends on the order which the methods are presented to LotusScript by the JVM through JNI. The following algorithm is used to match the method: 1. Enumerate all methods with the specified name. 2. Retrieve the signature and check for the number of arguments. If they dont match, move on. 3. If the number of arguments matches, try to convert arguments in LotusScript to arguments in Java. Move to the next method if the number of arguments dont match. LS2J calls through to the Java method of the first successful match.
197
Most Java implementations enumerate methods in the order they were declared in the Java source file. However, that is not always the case: for example, the AIX JVM seems to enumerate the method in reverse order.
The user attempts to call the java.lang.Short Constructor. The correct call is the signature for a short parameter:
Set obj = cls.CreateObject("(S)V", 1)
Since X doesnt match any Java type, LotusScript raises an error before calling Java. The only error message is in the LotusScript error:
LS2J Error: Constructor failed to execute
If the LotusScript portion of LS2J cannot detect an error, it calls Java. Suppose the code reads:
Set obj = cls.CreateObject("(I)V", 1)
198
This signature could match a Constructor with an int parameter. LotusScript detects no error; attempts to call the Java Constructor, and fails because the java.lang.Short class has no Constructor with an int parameter. The LotusScript Error is still:
LS2J Error: Constructor failed to execute
The JavaError object, when retrieved from the JavaSession, contains the last error and the last StackTrace.
Example code using JavaError Sub Initialize Dim mySession As New JavaSession Dim myError As JavaError On Error GoTo ErrorHandling ... code here .... Exit Sub ErrorHandling: Set myError = mySession.getLastJavaError print Error print myError.ErrorMsg print myError.StackTrace End Sub
This code sample prints the LotusScript error, the Java error, and the Java StackTrace. Examples of LotusScript errors that might be misunderstood: Example 1: You try to instantiate an object, but you have the wrong signature or number of arguments.
LotusScript says: Java ErrorMsg says: LS2J: Null JavaObject java.lang.NoSuchMethodError: <init>
Example 2: You try to instantiate an object, but an error occurs in the Constructor.
LotusScript says: Java StackTrace says: LS2J: Null JavaObject java.lang.ArrayIndexOutOfBoundsException at myGraph.<init>(Compiled Code)
Example 3a: You try to execute a method, but use the wrong number of arguments.
LotusScript says: Java ErrorMsg says: LS2J: Parameter mismatch calling Method <Method Name here> LS2J error
Example 3b:
Chapter 11. Beyond Core LotusScript
199
Now, you execute the method with the right arguments but there is an error in the method.
LotusScript says: Java StackTrace says: LS2J: Parameter mismatch calling Method <Method Name here> java.lang.ArrayIndexOutOfBoundsException: 3 at myGraph.setOrientation(myGraph.java:262)
LS2J limitations
There are a few limitations with LS2J: v You may not delete a Variant containing a JavaClass object. v There are some data type limitations (see Data type mappings). v LotusScript property names are case insensitive, but Java property names are case sensitive. If two Java properties are the same except for their case, use the GetProperty and GetValue or SetValue methods to access the correct property. Similarly, LotusScript method names are case insensitive, and Java method names are case sensitive. Java methods may also be overloaded; that is, they may differ only by parameter type. If two Java methods are the same except for their case, or except for their parameter type, use the GetMethod and Invoke methods to access the correct method. See Invoking a method in a Java object. Java method calls are limited to twelve parameters. v LotusScript can access all Java values and classes; however, there is no mechanism for Java to access LotusScript objects directly.
LS2J classes
With LS2J, Lotus introduces the concept of a Java object reference. Similar to an OLE object reference, it is not a predefined class; rather, it represents a runtime instance of a Java object. Its properties and methods are determined at run time. The following table lists the LS2J interface classes.
LS2J class JavaClass JavaError JavaMethod JavaMethodCollection JavaObject JavaProperty JavaPropertyCollection JavaSession Description Represents a Java class. Allows LotusScript programmers to find an error raised from the Java program. Contains information about Java methods in a class. Is the enumerator for all the methods in a Java class. Represents a Java object instance. This is the key to connecting with a Java object. Contains information about a Java property in a class. Is the enumerator for all the properties in a Java class. Represents a connection instance of JVM with which LotusScript is interfacing.
JavaClass class
JavaClass is the reference to a Java class. You can create an instance of the object, or you can look at the static properties (fields) and invoke static methods of the class. Properties: ClassName property Methods: CreateObject method getClassMethods method
200
getClassProperties method GetMethod method GetProperty method Access: You can access a JavaClass object by getting: v A specific class using the getClass method of the JavaSession class v The JClass property of a JavaMethod object v The JClass property of a JavaProperty object Example: JavaClass class: This script gets the Java class Java.lang.Integer and creates an object of that class in LotusScript.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myObject As JavaObject Set mySession = New JavaSession () Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Create a "java.lang.Integer" object Set myObject = myClass.CreateObject("(I)V", 5)
ClassName property: This property is the name of the JavaClass object. The property is read only. Defined in: JavaClass Data type: String Syntax: To get: string = javaclass .ClassName Usage: This property is useful for retrieving a class name. For example, if the class has been passed to a function, this property allows you to find out the name of that class. Example: ClassName property: See Example: JClass property. CreateObject method: This method creates a JavaObject instance base of the JavaClass object. Defined in: JavaClass Syntax: Set javaobject = javaclass .CreateObject( Signature[, Argument1, ..., Argumentn]) Parameter: Signature String. This is a JNI signature representing the constructor to use to initialize the object.
JNI Signature B C D F I J Description byte char double float int long Examples (B)V (C)V (D)V (F)V (I)V (J)V Constructor requires A byte argument A char argument A double argument A float argument An int argument A long argument
201
(Ljava/lang/Integer;)V A java.lang.Integer argument An int array (Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)V 4 arguments: java.lang.String, java.lang.String, int, java.lang.String
Array of <sigtype> ([I)V fully-qualified class fully-qualified class int fully-qualified class
If the constructor has one or more parameters, call CreateObject with a signature parameter as follows:
<javaclass>.CreateObject("(...)V")
where ... represents the types of one the parameters in the table. Note that each signature for a fully-qualified-class must start with an L and end with a semicolon. Argumentn The arguments needed by the constructor, varying from 0 to 12. These arguments are optional. Usage: This method creates a JavaObject instance base of the JavaClass object, and returns a JavaObject reference. By default, the empty constructor is used. Otherwise, the user must specify which constructor by using the signature. Error thrown: LS2J error if there are any issues regarding the signature or the arguments. Example: CreateObject method: This script gets the Java class Java.lang.Integer and creates an object of that class in LotusScript.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myObject As JavaObject Set mySession = New JavaSession () Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Create a "java.lang.Integer" object Set myObject = myClass.CreateObject("(I)V", 5)
202
Defined in: JavaClass Syntax: Set Javamethodcollection = javaclass .getClassMethods() Usage: This method returns a list of all the public methods belonging to the class specified by javaclass. Example: getClassMethods method: See Example: JavaMethod class. getClassProperties method: This method returns a list of properties. Defined in: JavaClass Syntax: Set Javapropertycollection = javaclass .getClassProperties() Usage: This method returns a list of all the public properties belonging to the class specified by javaclass. Example: getClassProperties method: This script prints out all the available public properties belonging to the java.lang.Integer class.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Dim msg As String Set mySession = New JavaSession () Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() msg = "The properties belonging to java.lang.Integer are:" ForAll p in myPCollection msg = msg & { } & p.PropertyName End ForAll MessageBox msg
GetMethod method: This method returns a method from a JavaClass object. Defined in: JavaClass Syntax: Set Javamethod = javaclass .GetMethod( Methodname, Signature ) Parameters: Methodname String. Case sensitive. Name of the method you want a handle of. Signature String. JNI Signature representing the method needed.
JNI Signature B C D Description byte char double
203
Description float int long short void Boolean fully-qualified class Array of <sigtype>
Usage: This method returns the method matching the name given with the specified signature. Error thrown: NoSuchMethodException if the Java method does not exist with the signature given. Example: GetMethod method: This script gets the toString method from the java.lang.Integer class that requires an Integer argument, and returns a string.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim Count As Integer Set mySession = New JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get the toString method which takes an Integer and returns a string Set myMethod = _ myClass.GetMethod("toString","(I)Ljava/lang/String;") print {Data type of toString return value is a } _ & TypeName(myMethod.invoke(,5)) print {result of invoking the method with a value of 5 is } _ & myMethod.invoke(,5)
GetProperty method: This method returns a property. Defined in: JavaClass Syntax: Set Javaproperty = javaclass .getProperty( PropertyName ) Parameter: Propertyname String. Case sensitive. Name of the property you want a handle of. Usage: This method returns the property matching Propertyname. Error thrown: LS2J: No such Field Invalid if the property isnt static or does not exist. Example: GetProperty method: This script gets the MIN_VALUE static property from the java.lang.Integer class.
204
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Dim Count As Integer Set mySession = New JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get the toString method which takes an Integer and returns a string Set myProperty = myClass.GetProperty("MIN_VALUE") Print "Property data type is " _ & TypeName(myProperty.getValue()) Print "Value of property is " & myProperty.getValue()
JavaError class
JavaError is the main interface for LotusScript to get information about Java errors that occur. Besides the standard exceptions mentioned in each object, the Java program can raise an exception for many other reasons. All these errors are caught and re-raised as the LotusScript Error-JavaError. Users can put an on error condition to catch any Java exceptions. The JavaException is not cleared until the method ClearJavaException is called. In order to find out more, the LotusScript user uses the JavaError object. Properties: ErrorMsg property StackTrace property Example: JavaError class: This script will catch an error while trying to get a specific Java class. After the error is reported by the MessageBox, the JavaError is cleared using ClearJavaError.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myError As JavaError On Error GoTo Catch Set mySession = new JavaSession() Set myClass = mySession.GetClass("Invalid") done: exit sub Catch: Set myError = mySession.getLastJavaError() MessageBox myError.errormsg,, "Error" mySession.ClearJavaError Resume done
ErrorMsg property: This property contains the last Java error that occurred. The property is read only. Defined in: JavaError Data type: String Syntax: To get: String = javaError .ErrorMsg Example: ErrorMsg property: See Example: JavaError class. StackTrace property: This property contains the call stack of the error. The property is read only.
Chapter 11. Beyond Core LotusScript
205
Defined in: JavaError Data type: String Syntax: To get: String = javaError .StackTrace Example: StackTrace property: Using three Java Classes, this script demonstrates an error that would cause a stack trace. The result is printed under the section labeled LotusScript code. In ClassA.java
public class ClassA { ClassB CB = new ClassB(); public int FunctA(){ return CB.FunctB(); } }
In ClassB.java
public class ClassB { ClassC CC = new ClassC(); public int FunctB(){ return CC.FunctC(); } }
In ClassC.java
public class ClassC { int x = 10; int y = 0; public int FunctC(){ return x/y; } }
LotusScript code
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim myObject As JavaObject Dim myError As JavaError Set mySession = New JavaSession () Set myClass = mySession.GetClass("ClassA") Set myObject = myClass.CreateObject("()V") Set myMethod = myClass.getMethod("FunctA", "()I") On Error GoTo errhandler: print myMethod.invoke(o) done: exit sub errhandler: set myError = mySession.getLastJavaError()
206
MessageBox myError.StackTrace,, Error Resume done (Results) java.lang.ArithmeticException: / by zero at valid5.javaconn.java.ClassC.FunctC(ClassC.java:6) at valid5.javaconn.java.ClassB.FunctB(ClassB.java:5) at valid5.javaconn.java.ClassA.FunctA(ClassA.java:5)
JavaMethod class
The JavaMethod class describes a public method in a JavaClass object. This class is used when the dot reference method fails (as happens with case sensitivity, method overloading, or long names). Properties: JClass property MethodName property Modifier property Signature property Methods: Invoke method Example: JavaMethod class: This script prints out the number of toString methods belonging to the java.lang.Integer class.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMCollection As JavaMethodCollection Dim Count As Integer Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() Count = 0 ForAll m in myMCollection If m.MethodName = "toString" Then Count = Count + 1 End If End ForAll MessageBox "There are " & Count & " instances of the toString _ method in the method collection for java.lang.Integer"
JClass property: This property is a JavaClass object representing the JavaClass object in which the method belongs. The property is read only. Defined in: JavaMethod Data type: JavaClass Syntax: Set JavaClass = javamethod .JClass
207
Example: JClass property (JavaMethod class): This script displays a message box with the method name in the title and the class it belongs to in the message.
Sub Test (myMethod As JavaMethod) JClass property of JavaMethod is an instance of JavaClass MessageBox "Belongs to " & myMethod.JClass.ClassName _ & " Class",, "Method " & myMethod.MethodName End Sub
MethodName property: This property contains the name of the method. This property is read only. Defined in: JavaMethod Data type: String Syntax: To get: String = javamethod .MethodName Usage: This is the name of the method in javamethod. A method name might not be unique, because each method name could have a different signature. Example: MethodName property: This script prints out the position within the collection where there is a toString method.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim myMCollection As JavaMethodCollection Dim msg As String Set mySession = new JavaSession() msg = " " Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() set myMethod = myMCollection.getFirst() do if myMethod.MethodName = "toString" then msg = msg + { toString } & myMethod.Signature & _ { is located at element } & _ myMCollection.Current & _ { within the collection} End If set myMethod = myMCollection.getNext() loop while myMCollection.Current <> 1 Because getNext loops back to 1 when the end is reached MessageBox msg
Modifier property: This returns the modifier value(s) for a Java method. The property is read only. Defined in: JavaMethod Data type: Long
208
Syntax: To get: Long = javamethod .Modifier Usage: The Modifier property returns a combination of bits for the modifier(s) of the Java method (as specified by javamethod) as follows:
Modifier public static final synchronized native abstract Bit 1 8 16 32 256 1,024
For example, if a method is declared in Java as public static the value of Modifier would be 9: the value of 1 for public added to the value of 8 for static. Note: The keywords private and protected are not available (private and protected methods are not available with LS2J). Example: Modifier property (JavaMethod class):
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Set mySession = New JavaSession() Set myClass = mySession.GetClass("java/lang/Thread") Set myMethod = myClass.GetMethod("start", "()V") java.lang.Thread.start() modifiers: public native = 1 = 256 synchronized = 32
Signature property: This property is the JNI signature representing the method arguments and return value. The property is read only. Defined in: JavaMethod Data type: String Syntax: To get: String= javamethod .Signature Example: Signature property: See Example: MethodName property. Invoke method: This method executes a method. Defined in: JavaMethod Syntax: Set Variant = javamethod .Invoke( [JavaObject [,Argument1...[, Argument12]] ) Parameters: JavaObject
209
JavaObject. The instance of an object, if the method is not static. Optional if the method is static. Argumentn Variant. Optional. The arguments needed by the method. Maximum of 12 arguments. Return value: Variant. Result of the invoked method. Example: Invoke method: See Example: GetMethod method.
JavaMethodCollection class
The JavaMethodCollection class enumerates all the methods of a JavaClass object. This is a true enumerator class and you can use the ForAll statement on it. Properties: Count property Current property Methods: getFirst method getNext method getNth method Example: JavaMethodCollection class: See Example: JavaMethod class. Count property: This property contains the number of methods in the enumeration. The property is read only. Defined in: JavaMethodCollection Data type: Integer Syntax: To get: Integer = javamethodcollection .Count Usage: Use this to retrieve the number of methods in javamethodcollection. Overloaded methods are counted each as a separate method. Example: Count property (JavaMethodCollection class): This script prints out the number of toString methods belonging to the java.lang.Integer class.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim myMCollection As JavaMethodCollection Dim Count As Integer, i As Integer Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() For i = 1 to myMCollection.Count Set myMethod = myMCollection.getNth(i) If myMethod.MethodName = "toString" then
210
Count = Count + 1 End If Next Print "There are " & Count & " instances of toString" + _ "method in the Method collection for java.lang.Integer"
The last three methods are overloaded. Current property: This property contains the current position in the enumeration. This property is read only. Defined in: JavaMethodCollection Data type: Integer Syntax: To get: Integer = javamethodcollection .Current Usage: This returns your exact location within the collection.
211
Example: Current property (JavaMethodCollection class): This script prints out the position within the collection where there is a toString method.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim myMCollection As JavaMethodCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() Set myMethod = myMCollection.getFirst() Do If myMethod.MethodName = "toString" then Print "toString" & myMethod.Signature & _ " is located at the " & myMCollection.Current & _ " element within the collection" End If Set myMethod = myMCollection.getNext() Loop While myMCollection.Current <> 1 Because getNext loops back to 1 when the end is reached
getFirst method: This method returns the first JavaMethod object. Defined in: JavaMethodCollection Syntax: Set javamethod = javamethodcollection .getFirst() Return value: JavaMethod. The first JavaMethod object within the enumeration. Example: getFirst method (JavaMethodCollection class): This script prints out the position within the collection where there is a toString method.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim myMCollection As JavaMethodCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() Set myMethod = myMCollection.getFirst() Do If myMethod.MethodName = "toString" then Print "toString" & myMethod.Signature & _ " is located at the " & myMCollection.Current & _ " element within the collection" End If Set myMethod = myMCollection.getNext()
212
Loop While myMCollection.Current <> 1 Because getNext loops back to 1 when the end is reached
getNext method: This method returns the next JavaMethod object in the enumeration. Defined in: JavaMethodCollection Syntax: Set javamethod = javamethodcollection .getNext() Return value: JavaMethod. The next JavaMethod object within the enumeration. If you pass the last method within the enumeration, the first one will be returned. Example: getNext method (JavaMethodCollection class): This script prints out the position within the collection where there is a toString method.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod Dim myMCollection As JavaMethodCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() Set myMethod = myMCollection.getFirst() Do If myMethod.MethodName = "toString" then Print "toString" & myMethod.Signature & _ " is located at the " & myMCollection.Current & _ " element within the collection" End If Set myMethod = myMCollection.getNext() Loop While myMCollection.Current <> 1 Because getNext loops back to 1 when the end is reached
getNth method: This method returns the Java method in a specified position in the enumeration. Defined in: JavaMethodCollection Syntax: Set Javamethod = javamethodcollection .getNth( n ) Parameters: n Integer. The exact position within the enumeration to get the method from. Return value: JavaMethod. The method in the nth position in the enumeration. If there is no method at the specified position, it returns null. Example: getNth method (JavaMethodCollection class): This script prints out the number of toString methods belonging to the java.lang.Integer class.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myMethod As JavaMethod
213
Dim myMCollection As JavaMethodCollection Dim Count As Integer, i As Integer Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myMCollection = myClass.getClassMethods() For i = 1 to myMCollection.count Set myMethod = myMCollection.getNth(i) If myMethod.MethodName = "toString" then Count = Count + 1 End If Next Print "There are " & Count & " instances of the toString " + _ "method in the Method collection for java.lang.Integer"
JavaObject class
The JavaObject Reference is the key to connecting with a Java object. It is returned from the CreateObject method of the JavaClass class or the GetJavaObject function. It is similar to an OLE reference and represents a Java object instance. The properties and methods are adapted automatically. It can be assigned only to a Variant. Although Java Native Interface (JNI) allows us to look at properties (fields) and methods with different protected attributes, LotusScript adapts only the public ones. Properties: [adaptive -- all public fields (static, instance)] Methods: [adaptive -- all public methods (static, instance)] Usage: The JavaObject reference is not set if LotusScript has problems adapting the specified Java object. If the program tries to use the properties or methods, it raises an Object Variable Not Set error. Note: Due to LotusScript limitations, you cannot access the following properties and methods: v Properties and methods with names over 40 characters v Properties and methods with names that differ only in case (LotusScript is not case sensitive whereas Java is) v Methods with the same name and number of arguments, but with a different signature For these conditions, you must explicitly use JavaProperty class and JavaMethod class. Example: JavaObject class: This script prints the area of a 2 X 4 rectangle. Then, with the use of setValue, it resets the width and height and prints the new size.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Dim myObject As JavaObject Set mySession = new JavaSession() setProperty on custom class Set myClass = _ mySession.GetClass("valid5/javaconn/java/Rectangle;") Set myObject = myClass.CreateObject("(II)V", 2,4)
214
print "The area of our Rectangle (2 X 4) is " & _ myObject.getArea() Set myProperty = myClass.GetProperty("width") call myProperty.setValue(5,o) Set myProperty = myClass.GetProperty("height") call myProperty.setValue(10,o) Print "The area of our Rectangle (5 X 10) is " & _ myObject.getArea()
JavaProperty class
The JavaProperty class describes a public property in a JavaClass object. This class is used for instances when the dot reference method fails (because of case sensitivity or long names). Properties: JClass property PropertyName property Modifier property Type property Methods: getValue method setValue method Example: JavaProperty class: This script prints out all the properties belonging to a JavaClass object.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all Properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Print myPCollection.count & "Properties of the " & _ myClass.ClassNAme & " class are :" ForAll p in myPCollection Print p.PropertyName & _ " (" & myPCollection.current & ")" End ForAll
JClass property: This is a JavaClass object representing the Java class in which the JavaProperty belongs. The property is read only. Defined in: JavaProperty Data type: JavaClass Syntax: Set JavaClass = javaproperty .JClass Example: JClass property (JavaProperty class): This script displays a message box with the PropertyName in the title and the class it belongs to in the message.
Sub Test (myProperty As JavaProperty)
Chapter 11. Beyond Core LotusScript
215
JClass property of JavaProperty is an instance of JavaClass MessageBox "Belongs to " & myProperty.JClass.ClassName & _ " Class",, "Property " & myProperty.PropertyName End Sub
PropertyName property: This is the name of the JavaProperty. The property is read only. Defined in: JavaProperty Data type: String Syntax: To get: String = javaproperty .PropertyName Example: PropertyName property: This script displays a message box with the PropertyName in the title and the class it belongs to in the message.
Sub Test (myProperty As JavaProperty) JClass property of JavaProperty is an instance of JavaClass MessageBox "Belongs to " & myProperty.JClass.ClassName & _ " Class",, "Property " & myProperty.PropertyName End Sub
Modifier property: This returns the modifier value(s) for a Java property. The property is read only. Defined in: JavaProperty Data type: Long Syntax: To get: Long = javaproperty .Modifier Usage: The Modifier property returns a combination of bits for the modifier(s) of the Java property (as specified by javaproperty) as follows:
Modifier public static final volatile transient Bit 1 8 16 64 128
For example, if a property is declared in Java as public static final the value of Modifier would be 25: the value of 1 for public added to the value of 8 for static added to the value of 16 for final. Note: The keywords private and protected are not available (private and protected properties are not available with LS2J). Example: Modifier property (JavaProperty class):
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Set mySession = New JavaSession()
216
Set myClass = mySession.GetClass("java/lang/Short") Set myProperty = myClass.GetProperty("MIN_VALUE") java.lang.Short.MIN_VALUE has modifiers: public = 1 static = 8 final = 16 Modifier value is 25 Print "MIN_VALUE Modifier is " myProperty.Modifier
Type property: This is the LotusScript data type of the JavaProperty. The property is read only.
Java byte short int long float double boolean char java.lang.String other Objects LotusScript Byte Integer Long Double Single Double Boolean String String JavaObject LotusScript data type 17 2 3 5 4 5 11 8 8 32
Defined in: JavaProperty Data type: Long (no decimals) Syntax: To get: Long = javaproperty .Type Example: Type property: This script prints out all the properties and their data types.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all Properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Print myPCollection.count & "Properties of the " _ & myClass.ClassNAme & " class are :" ForAll p in myPCollection Print p.PropertyName & " (" & p.Type & ")" End ForAll
getValue method: This method returns the JavaProperty value. Defined in: JavaProperty
217
Syntax: Set Variant = javaProperty .getValue( [JavaObject] ) Parameter: JavaObject JavaObject. The instance of an object from which you want a property value, if the property is not static. Optional if the property is static. Return value: Variant Value of the JavaProperty. Usage: This method is used to get the value of either a public static property or a public object property. The object is necessary if the property is not static, and disregarded if the property is static. Example: getValue method: This script prints out the position of MAX_VALUE within the collection.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all Properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Print myPCollection.count & "Properties of the " _ & myClass.ClassNAme & " class are :" ForAll p in myPCollection If p.type <> 32 then If its not an object Print p.PropertyName & _ " (" & myPCollection.current _ & ") and value is " & p.getValue() Else Print p.PropertyName & _ " (" & myPCollection.current _ & ") and value is " & p.getValue().toString() End If End ForAll
setValue method: This method sets the JavaProperty value. Defined in: JavaProperty Syntax: Call javaproperty .setValue( NewValue [, JavaObject] ) Parameters: NewValue Variant. New Value for the JavaProperty. JavaObject JavaObject. Object to be set, if the property is not static. Optional if the property is static. Error thrown: IllegalAccessException. Thrown if the value is of the wrong type, or if the property is read only.
218
Example: setValue method: This script prints the area of a 2 X 4 rectangle then, with setValue, resets the width and height and prints the new size.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Dim myObject As JavaObject Set mySession = new JavaSession() setProperty on custom class Set myClass = _ mySession.GetClass("valid5/javaconn/java/Rectangle;") Set myObject = myClass.CreateObject("(II)V", 2,4) Print "The area of our Rectangle (2 X 4) is " & _ myObject.getArea() Set myProperty = myClass.GetProperty("width") Call myProperty.setValue(5,o) Set myProperty = myClass.GetProperty("height") Call myProperty.setValue(10,o) Print "The area of our Rectangle (5 X 10) is " & _ myObject.getArea()
JavaPropertyCollection class
The JavaPropertyCollection class enumerates all the properties of a JavaClass object. This is a true enumerator class and you can use the ForAll statement with it. Properties: Count property Current property Methods: getFirst method getNext method getNth method Example: JavaPropertyCollection class: This script prints out all the properties belonging to a JavaClass object.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all Properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Print myPCollection.count & "Properties of the " _ & myClass.ClassNAme & " class are :" ForAll p in myPCollection Print p.PropertyName & _ " (" & myPCollection.current & ")" End ForAll
219
Count property: This property contains the number of properties in the enumeration. The property is read only. Defined in: JavaPropertyCollection Data type: Integer Syntax: To get: Integer = javapropertycollection .Count Usage: Use this property to retrieve the number of properties in javapropertycollection. Example: Count property (JavaPropertyCollection class): This script prints out all the properties belonging to a JavaClass object.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all Properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Print myPCollection.count & "Properties of the " _ & myClass.ClassNAme & " class are :" ForAll p in myPCollection Print p.PropertyName & _ " (" & myPCollection.current & ")" End ForAll
Current property: This property contains the current position in the enumeration. The property is read only. Defined in: JavaPropertyCollection Data type: Integer Syntax: To get: Integer = javaPropertycollection .Current Usage: This property contains the exact location within the collection. Example: Current property (JavaPropertyCollection class): This script prints out the position of MAX_VALUE within the collection.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Set myProperty = myPCollection.getFirst()
220
Do If myProperty.PropertyName = "MAX_VALUE" then Print "MAX_VALUE is located at the " & _ myPCollection.current _ & " position within the collection" Exit Do End If Set myProperty = myPCollection.getNext() Loop While myPCollection.Current <> 1 Because getNext loops back to 1 when the end is reached
getFirst method: This method returns the first JavaProperty. Defined in: JavaPropertyCollection Syntax: Set javaProperty = javaPropertycollection .getFirst() Return value: JavaProperty. The first JavaProperty within the enumeration. Example: getFirst method (JavaPropertyCollection class): This script prints out the position of MAX_VALUE within the collection.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Set myProperty = myPCollection.getFirst() Do If myProperty.PropertyName = "MAX_VALUE" then Print "MAX_VALUE is located at the " & _ myPCollection.current _ & " position within the collection" Exit Do End If Set myProperty = myPCollection.getNext() Loop While myPCollection.Current <> 1 Because getNext loops back to 1 when the end is reached
getNext method: This method returns the next JavaProperty in the enumeration. Defined in: JavaPropertyCollection Syntax: Set javaProperty = javaPropertycollection .getNext() Return value: JavaProperty. The next JavaProperty within the enumeration. If you pass the last property within the enumeration, the first one is returned.
221
Example: getNext method (JavaPropertyCollection class): This script prints out the position of MAX_VALUE within the collection.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myProperty As JavaProperty Dim myPCollection As JavaPropertyCollection Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all methods belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Set myProperty = myPCollection.getFirst() Do If myProperty.PropertyName = "MAX_VALUE" then Print "MAX_VALUE is located at the " & _ myPCollection.current _ & " position within the collection" Exit Do End If Set myProperty = myPCollection.getNext() Loop While myPCollection.Current <> 1 Because getNext loops back to 1 when the end is reached
getNth method: This method returns the Java property in the specified position in the enumeration. Defined in: JavaPropertyCollection Syntax: Set javaProperty = javaPropertycollection .getNth( n ) Parameter: n Integer. The exact position within the enumeration to get the property from. Return value: JavaProperty. The property in the nth position in the enumeration. If there is no property at the specified position, the method returns null. Example: getNth method (JavaPropertyCollection class): This script prints out all the properties belonging to a JavaClass object.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myPCollection As JavaPropertyCollection Dim i As Integer Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Get a list of all Properties belonging to the java.lang.Integer class Set myPCollection = myClass.getClassProperties() Print myPCollection.count & "Properties of the " _ & myClass.ClassNAme & " class are :"
222
For i = 1 to myPCollection.count Set myProperty = myPCollection.getNth(i) Print myProperty.PropertyName & " (" & _ myPCollection.current & ")" next i
JavaSession class
JavaSession is the starting point for access to the Java objects. The session attaches to the existing JVM, if there is one. If a JVM has not been started, the LotusScript client tries to create the JVM and apply all the specified arguments. You can create as many JavaSessions as you want. All the resources created are associated with a particular session. Delete the session object to reclaim the resources. Properties: None Methods: ClearJavaError method GetClass method GetLastJavaError method Creation and access: To access the current JVM session. Syntax: Dim variableName As New JavaSession OR Set javaSession = New JavaSession Parameter: Arguments for this class are not documented because they are overwritten by Notes. These arguments are for internal use only. Example: JavaSession class: This script gets the Java class Java.lang.Integer and creates an object of that class in LotusScript.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myObject As JavaObject Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Create a "java.lang.Integer" object Set myObject = myClass.CreateObject("(I)V", 5)
ClearJavaError method: This method clears the last JavaError method that occurred. Defined in: JavaSession Syntax: Call javasession .ClearJavaError Usage: This method is used to clear the most recent JavaError. After you call javasession.ClearJavaError(), javaerror.errorMsg and javaerror.stackTrace return to their initial values: No Java Errors or Exceptions and No Java stack trace, respectively. Example: ClearJavaError method: This script catches an error while trying to get a specific Java class. After the error is reported by the message box, then all JavaErrors are cleared using ClearJavaError.
Dim myClass As JavaClass
Chapter 11. Beyond Core LotusScript
223
Dim myObject As JavaObject Dim myError As JavaError On Error GoTo Catch Set mySession = new JavaSession() Set myClass = mySession.GetClass("Invalid") exit Sub Catch: Set myError = mySession.getLastJavaError() MessageBox myError.errormsg,, "Error" mySession.ClearJavaError
getClass method: This method returns a reference to a Java class. Defined in: JavaSession Syntax: Set JavaClass = javasession .getClass( ClassName $ ) Parameters: ClassName$ String. The name of the class you would like to retrieve. For example, java/lang/Integer. Usage: This method will return a Java class reference with which a Java object can be created within LotusScript. Note: There are 2 ways you can represent a String class:
java.lang.String java/lang/String example: set MyClass = Session.getClass(java.lang.String) example: set MyClass = Session.getClass(java/lang/String)
When you use the dot . notation on the Macintosh, the Mac will return an error that the Class cannot be found. Instead, use the slash / notation. The slash / notation works on all platforms. Use the slash / notation in your applications for multi-platform support. Error thrown: JavaClassNotFound is thrown if the Java class cannot be located. Example: getClass method: This script gets the Java class Java.lang.Integer and creates an object of that class in LotusScript.
Dim mySession As JavaSession Dim myClass As JavaClass Dim myObject As JavaObject Set mySession = new JavaSession() Get Java "java.lang.Integer" class Set myClass = mySession.GetClass("java/lang/Integer") Create a "java.lang.Integer" object Set myObject = myClass.CreateObject("(I)V", 5)
getLastJavaError method: This method retrieves the last JavaError that occurred, and, in some cases, a call stack. Defined in: JavaSession Syntax: Set JavaError = javasession .getLastJavaError
224
Usage: This method is used to retrieve any possible JavaErrors that might have occurred. Example: getLastJavaError method: This script catches an error while trying to get a specific Java class. After the error is reported by the MessageBox, then the JavaError is cleared using ClearJavaError.
Dim myClass As JavaClass Dim myObject As JavaObject Dim myError As JavaError On Error GoTo Catch Set mySession = new JavaSession() Set myClass = mySession.GetClass("Invalid") exit Sub Catch: Set myError = mySession.getLastJavaError() MessageBox myError.errormsg,, "Error" mySession.ClearJavaError
A Variant should map to whatever data type it contains. Note: The Java byte type is signed (range -128 to +127), but the LotusScript Byte type is unsigned (range 0 to +255). Java byte values of -128 to -1 map to LotusScript Byte values of +128 to +255. Java byte values of 0 to +127 map to the same LotusScript values, 0 to +127.
Java byte value -128 -127 LotusScript Byte value +128 +129
Chapter 11. Beyond Core LotusScript
225
LotusScript Byte value +130 ... +254 +255 0 1 ... +126 +127
Note: You can use the LotusScript data type in place of the Java data type for Get/Set properties, arguments for Java methods, and return values.
LSStrings.lss:
Option Public Uselsx "*javacon" Dim mySession As JavaSession
226
Sub Initialize Dim myClass As JavaClass, myObject As JavaObject, s1 As String, _ s2 As String, s3 As String s1 = "A" s2 = "BC" s3 = "DE" Set mySession = New JavaSession ("\LSI\test\java;") Set myClass = mySession.GetClass("LSStrings;") Set myObject = myClass.CreateObject myObject.F1 = s1 myObject.F2 = s2 myObject.F3 = s3 MsgBox myObject.F1 & myObject.F2 & myObject.F3 & _ myObject.M1(s1) & myObject.M2(s2) & myObject.M3(s3) Displays "ABCDEABCDE" End Sub
LS2J dynamically adapts the Java/lang/String class then binds to the toCharArray method. The toCharArray method returns a char[], which is automatically translated into a LotusScript string.
Processing arguments
You can pass all primitive types and Java objects directly as arguments to JavaMethods. For reference types, LotusScript does not yet support the call-by-reference semantics. You can pass single dimension arrays into a Java method, but the results are not copied back into the LotusScript space. LotusScript also does not yet support passing in arrays of Java objects.
Limitations
Some important limitations include: v You cant bring a bitmap into LotusScript because the Java byte (signed 8-bit) data type is mapped to LotusScript integer. v You cant bring an integer greater than 32 bits into LotusScript without losing precision because the Java long (64 bit) data type is mapped to LotusScript Double. v You can use only single dimension arrays. v There is no call-by-reference semantics for arguments of reference type.
227
Mortgage Calculator
With this mortgage calculator you can get the value of a Java property and call several Java methods by using the names directly from LotusScript.
Mortgage.java
public class Mortgage { // Java property public static String F = "Mortgage Calculator"; // Java methods public double CalculateInterest(float rate, short yr, _ double principal) { // This bank doesnt bother with compound interest! return (rate / 100) * yr * principal; } public double CalculateTotal(double principal, _ double interest) { return principal + interest; } public double CalculateMonthlyPayment(float rate, _ short yr, double principal) { double interest = CalculateInterest(rate, yr, _ principal); double total = CalculateTotal(principal, interest); return total / (yr * 12); } }
Mortgage.lss
Uselsx "*javacon" Dim mySession As JavaSession Sub Initialize Dim myClass As JavaClass Dim myObject As JavaObject Dim header As String Dim rate As Single Dim yr As Integer Dim principal As Double, interest As Double Dim total As Double, monthly_payment As Double Set mySession = New JavaSession() Set LS values rate yr = 8.5 = 30
principal = 200000 Set mySession = New JavaSession() Get Java "Mortgage" class Set myClass = mySession.GetClass("Mortgage;")
228
Call Java "Mortgage" Constructor Set myObject = myClass.CreateObject Get Java property (can just use the name) header = myObject.F Call Java Methods (can just use the names) interest = myObject.CalculateInterest(rate, yr, _ principal) total = myObject.CalculateTotal(principal, interest) monthly_payment = _ myObject.CalculateMonthlyPayment(rate, yr, principal) MsgBox { } & header & { Interest rate: Years: Principal: Interest: Total: End Sub } & rate & {% } & 30 & { $} & principal & { $} & Round(interest, 2) & { $} & Round(total, 2) & {
Mortgage2.java
public class Mortgage2 { // Java properties with names that differ only by case public static String F = "Mortgage Calculator"; public static String f = "from your friendly neighborhood bank"; // Java methods // Two Java methods with names that differ only by case public double calculateinterest(float rate, _ short yr, double principal) { return rate * yr * principal; } public double CalculateInterest(float rate, _ short yr, double principal) { return calculateinterest(rate/100, yr, principal); } // Method with a long name public double CalculateTotal_with_a_method_name_over_40_characters_long (double principal, double interest)
229
{ return principal + interest; } // Two Java overloaded methods -- differ only by parameter types public double CalculateMonthlyPayment(double total, short yr) { return total / (yr * 12); } public double CalculateMonthlyPayment(float rate, short yr, _ double principal) { double interest = CalculateInterest(rate, yr, principal); double total = CalculateTotal_with_a_method_name_over_40_characters_long (principal, interest); return CalculateMonthlyPayment(total, yr); } }
Mortgage2.lss
Uselsx "*javacon" Dim mySession As JavaSession Sub Initialize Dim myClass As JavaClass Dim myObject As JavaObject Dim myProperty As JavaProperty Dim myMethod As JavaMethod Dim myError As JavaError Dim header1 As String, header2 As String Dim rate As Single Dim yr As Integer Dim principal As Double, interest As Double Dim total As Double, monthly_payment As Double Set mySession = New JavaSession() Set LS values rate yr = 8.5 = 30
principal = 200000 Set mySession = New JavaSession() Set myClass = mySession.GetClass("Mortgage2;") Call "Mortgage2" constructor Set myObject = myClass.CreateObject Use GetProperty()/GetValue() syntax when property names differ only by case Set myProperty = myClass.GetProperty("F") header1 = myProperty.GetValue() Set myProperty = myClass.GetProperty("f") header2 = myProperty.GetValue() Use GetMethod()/Invoke() syntax when method
230
names differ only by case Set myMethod = _ myClass.GetMethod("CalculateInterest", "(FSD)D") interest = myMethod.Invoke(myObject, rate, yr, _ principal) or when method name is over 40 characters long Set myMethod = myClass.GetMethod "(DD)D") total = myMethod.Invoke(myObject, principal, interest) or for overloaded Methods (differing only by parameter type) Set myMethod = _ myClass.GetMethod("CalculateMonthlyPayment", "(DS)D") monthly_payment = _ myObject.CalculateMonthlyPayment(total, yr) MsgBox { } & header1 & { } & header2 & { Interest rate: Years: Principal: Interest: Total: } & rate & {% } & 30 & { $} & principal & { $} & Round(interest, 2) & { $} & Round(total, 2) & { _ ("CalculateTotal_with_a_method_name_over_40_characters_long", _
Monthly payment: $} & Round(monthly_payment, 2) On Error GoTo errhandler Throws "java.lang.NoSuchMethodException" when user tries to get a method that doesnt exist Set myMethod = myClass.GetMethod("CalculateTax", _ "(D)D") done: Exit Sub errhandler: Set myError = mySession.GetLastJavaError() MsgBox "JavaError was " & myError.errorMsg Clear the Error mySession.ClearJavaError Resume done End Sub
231
232
Abs function
Returns the absolute value of a numeric expression.
Syntax
Abs ( numExpr )
Elements
numExpr Any numeric expression.
Return value
Abs returns the absolute value of numExpr. The data type of the return value is the same as the data type of numExpr, unless numExpris a Variant. In that case, the following rules apply: v If numExpr contains a string that LotusScript can convert to a number, the data type is Double. v If numExpr contains a value that LotusScript cannot convert to a number, the function raises a type-mismatch error. v If numExpr contains a NULL, the return value is NULL.
Usage
The absolute value of a number is its unsigned magnitude; for example, 3 and -3 both have an absolute value of 3.
Language cross-reference
@Abs function in formula language
Dim someV As Variant someV = "123" Print Abs(someV) someV = NULL Print Abs(someV)
ACos function
Returns the arccosine, in radians, of a number between -1 and 1, inclusive.
233
Syntax
ACos ( numExpr )
Elements
numExpr A numeric expression with a value between -1 and 1, inclusive.
Return value
ACos returns the arccosine, in radians, of the value of numExpr. The range of the return value is zero to pi, inclusive. The data type of the return value is Double. If the value of numExpris not in the range -1 to 1, inclusive, the function raises an error.
Usage
The arccosine of a number is the angle, in radians, whose cosine is equal to the value of that number.
Language cross-reference
@Acos function in formula language
ActivateApp statement
Makes a program window the active window.
Syntax
ActivateApp windowName AppActivate is acceptable in place of ActivateApp.
Elements
windowName A string expression designating the program window to activate.
Usage
windowName is not case sensitive. It must exactly match the leftmost characters of the program title that appears in the program window title bar. For example, if the program title of a running program window is Lotus Notes - Workspace, then a windowName value of Lotus Notes will activate that window. If more than one program title matches windowName, LotusScript will choose one of the program windows.
234
ActivateApp can activate a minimized window, but cannot restore or maximize it. Use SendKeys to restore or maximize a window. Use Shell to start a program.
ArrayAppend function
Appends one array to the end of another array and returns the result as a third array.
Syntax
ArrayAppend( sourceArray1, sourceArray2 )
Elements
sourceArray1 Any variant containing an array. sourceArray2 Any variant containing an array.
Return value
A variant containing an array.
Usage
During this operation sourceArray1 and sourceArray2 are not modified. If the two arrays are arrays of matching types, the returned array will be of that type. Otherwise, the returned array will be an array of Variants. The lower bound of the returned array is the same as the lower bound of sourceArray1, and the upper bound is the combined total of sourceArray1 and sourceArray2. For example: sourceArray1(1 to 5) = [1,2,3,4,5] sourceArray2(1 to 8) = [1,3,6,9,12,15,18,21) returned array (1 to 13) = [1,2,3,4,5,1,3,6,9,12,15,18,21)
Error handling
ArrayAppend throws a Type mismatch error if: v sourceArray1 is not an array v an array with more than one dimension is used ArrayAppend throws a Subscript out of range error if the array bounds of the constructed array are outside acceptable array limits. Extended examples: array and String functions
235
Sub Initialize arr1 will contain the following names arr1(1) = "Daniel" arr1(2) = "Nate" arr1(3) = "Joshua" arr1(4) = "Sam" arr1(5) = "Benjamin" arr1(6) = "Julie " arr1(7) = "Lauren " arr1(8) = "Scrubbles" arr2 will contain "Joe1", "Joe2", etc arr4 will contain integers, with all even entries being zero For i = 1 To 8 arr2(i) = "Joe" & i If (i Mod 2) = 0 Then arr4(i) = 0 Else arr4(i) = i End If Next Initialize the arrays tarray1 will contain (1,2,3,4,5,6,7,8,9,10) x = 1 For i =1 To 20 If i =< 10 Then tarray1(i) = i End If tarray2 will contain (2,4,6,8,10,12,14,16,18,20) If (i Mod 2) = 0 Then tarray2(x) = i x = x+1 End If Next
236
tarray3 will contain the following (8,6,4,2,25,0,0,0,0,0) tarray3(1) = 8 tarray3(2) = 6 tarray3(3) = 4 tarray3(4) = 2 tarray3(5) = 25 Run the examples ArrayExamples AtComputeStrings End Sub Sub Arrayexamples Arrayappend populates arr3 with all elements of arr1 and all elements of arr2, arr3 lower bound is 1 its upper bound is 16 Print "Arrayappend results:" arr3 = Arrayappend (arr1, arr2) Print " arr3 contains: ", arr3(1), arr3(2), "..." , _ arr3(15), arr3(16) Print " Up/Low bounds for arr3: " & Lbound(arr3) & _ " & " & Ubound(arr3) Arraygetindex example value = "Benjamin" Indexresult = Arraygetindex(arr1,value) Print "Arraygetindes results:" Print " Arraygetindex(arr1,value) returns ";_ Indexresult Indexresult = Arraygetindex(arr1,"Scrubbles") Print " Arraygetindex(arr1,""Scrubbles"") returns "; Indexresult Fulltrim of an array Print "Arraygetindex on fulltrimed array results:" localarray = Fulltrim(arr4) localarray = [1, 3, 5, 7] Indexresult = Arraygetindex(localarray, 3) Print " Arraygetindex(localarray, 3) returns "; Indexresult Fulltrim of a string Print "Fulltrim of string:" qbf_spaces = " The " jumped over the
Print " ", qbf_spaces qbf_trimed = Fulltrim(qbf_spaces) Print " ", qbf_trimed Arrayreplace example Print "Arrayreplace results:" Expected answer is "1 8 3 6 5 4 7 2 9 25" arresult = Arrayreplace( tarray1, tarray2, tarray3) Generate string that represent the contents of arresult msg1 = "" For i = 1 To 10 msg1 = msg1 & " " & arresult(i) Next Print " arresult = " & msg1 End Sub Sub AtComputeStrings() Dim s1 As String Dim s2 As String Dim v1 As Variant s1 = "The quick brown FOX jumps over the lazy dog." s2 = "he" Print " " Print "Results for Strleft, strright, strrightback," & _ " Strleftback"
Chapter 12. LotusScript Language Reference
237
Search left to right Strleft: expect v1 = "T" v1 = Strleft( s1, s2 ) Print " " + v1 Strright: expect v1 = " quick brown FOX jumps over the lazy dog." v1 = Strright( s1,s2 ) Print " " + v1 Search right to left Strleftback: expect v1 = "The quick brown FOX jumps over t" v1 = Strleftback( s1, s2 ) Print " " + v1 Strrightback: expect v1 = " lazy dog." v1 = Strrightback( s1, s2 ) Print " " + v1 With some optionals..... s1 = "The quick brown FOX jumps over the lazy dog." s2 = "o" the letter o CHANGED S2, pattern searched for HERE. A case INsensitive search, it finds the second occurrence of o and returns what is to the left of that. expect v1 = "The quick brown F " v1 = Strleft( s1,s2, 5, 2 ) Print " " + v1 A Case sensitive search, Finds the third occurrence of o and returns what is to the RIGHT of that. expect v1 = "ver the lazy dog." v1 = Strright( s1,s2, 0, 3 ) Print " " + v1 s2 = "O" A case sensitive search. Expect v1 = "The quick brown F" v1 = Strleftback( s1,s2,0 ) Print " " + v1 A case sensitive search, with a skip first occurrence, O in FOX is Skipped and no other occurrence exists, expect v1 = "" v1 = Strleft( s1,s2,0,2) Print " " + v1 End Sub
ArrayGetIndex results:
ArrayGetIndex(arr1,value) returns 5 Arraygetindex(arr1,"Scrubbles") returns 8
FullTrim of string: The quick brown fox jumped over the lazy dog.
The quick brown fox jumped over the lazy dog.
238
ArrayReplace results:
arresult = 1 8 3 6 5 4 7 2 9 25
ArrayGetIndex function
Searches an array of strings for the value given. If the value is found within the array, the array index of that value is returned.
Syntax
ArrayGetIndex( sourceArray, searchValue [, compMethod ] )
Elements
sourceArray An array or Variant containing an array. searchValue A value to search for within sourceArray. compMethod Optional integer specifying the type of comparison to use when searching for searchValue.
Number 0 1 4 5 Comparison Mode case sensitive, pitch sensitive case insensitive, pitch sensitive case sensitive, pitch insensitive case insensitive, pitch insensitive
Return value
A Variant of type long that provides the index into sourceArray where searchValue can be found. If no match is found, NULL is returned.
Usage
ArrayGetIndex converts all values passed to it into strings. For example, if you pass an array of integers, this function converts the values in the array to strings for this operation only. These string values are then used for comparing the array values to the searchValue. Option Compare can be used to specify whether case/pitch sensitivity should play a role in the comparisons. If compMethod is not specified, the default for the module is used. Items that cannot be converted are not compared.
Chapter 12. LotusScript Language Reference
239
ArrayReplace function
Performs a search and replace routine for multiple values within an array.
Syntax
ArrayReplace( sourceArray, compareArray, replaceArray )
Elements
sourceArray The source array from which a copy, with possible modifications, will be produced. compareArray An array containing the elements to be compared to the elements in sourceArray (can be a scalar which is treated as a single-element array). replaceArray An array containing the elements to be used to replace elements from sourceArray (can be a scalar which is treated as a single-element array).
Return value
A Variant containing an array which is constructed by these rules (the answer array).
Usage
Each element in sourceArray is prepared to be copied into the answer array. The resulting array is the same size as the array contained in parameter sourceArray. If the source and replace arrays are arrays of matching types, the answer array will be of that type. Otherwise, the answer array will be an array of Variants. Note: ArrayReplace works only with these LotusScript scalar data types: integer, long, single, double, currency, string, boolean, and byte. If any other data type is used in the sourceArray or thereplaceArray, the resulting array contains the exact same data elements as the sourceArray; that is, no replacement of array elements occurs. For each element in sourceArray, compareArray is scanned. If no elements match, the element from sourceArray is copied into the next available index in the answer array. However, if an element of compareArray matches an element from sourceArray, the index of the compareArray element is used to find a value in the array replaceArray. This value is then copied into the answer array instead of the value from sourceArray. For example: sourceArray = [1,2,3,4,5] compareArray = [2,4,6,8,10,12,14,16,18,20] replaceArray = [8,6,25,0,0,11,17] 1. Element 1 from sourceArray is compared to the elements in compareArray. Since no match is found, the first element from sourceArray is copied into the answer array in the first element.
240
answer array = [1,...] 2. Element 2 from sourceArray is compared to the elements in compareArray. The first element in compareArray matches the second element from sourceArray, so the index to the first element in compareArray, which is 1, is used to find a value in replaceArray, which is [8]. This value is then copied into the answer array. answer array = [1,8,...] 3. Element 3 from sourceArray is compared to the elements in compareArray. Since no match is found, the third element from sourceArray is copied into the answer array. answer array = [1,8,3,...] 4. Element 4 from sourceArray is compared to the elements in compareArray. The second element in compareArray matches the fourth element from sourceArray, so the index to the second element incompareArray, which is 2, is used to find a value in replaceArray, which is [6]. This value is then copied into the answer array. answer array = [1,8,3,6,...] 5. The last element from sourceArray is compared to the elements in compareArray. Since no match is found, the fifth element from sourceArray is copied into the answer array. answer array = [1,8,3,6,5] If the index from compareArray cannot be used as an index into replaceArray (that is, the index is out of bounds), a 0 or type equivalent is copied into the answer array for that element. Indices into the arrays are calculated from their base. Assume that compareArray is an array from (-10 to 0), and replaceArray is an array from (1 to 5). If the -10th element of compareArray, which is the first element in that array, is a match for a given element in sourceArray, then the first element of replaceArray is used as a replacement. For example: sourceArray(1 to 10) = [the,quick,sleek,cat,jumped,over,the,fat,sleeping,dog] compareArray(-10 to 0) = [sleek,cat,jumped,fat,sleeping,under,ball,purple,tree,slow,over] replaceArray(1 to 5) = [red,fox,hurdled,lazy,brown] 1. The first element in sourceArray is compared to the elements in compareArray. No match is found, so the first element from souceArray is copied to the answer array. answer array=[the,...] 2. The second element in sourceArray is compared to the elements in compareArray. No match is found, so the first element from souceArray is copied to the answer array. answer array=[the,quick,...] 3. The third element in sourceArray is compared to the elements in compareArray. A match is found at the first element of compareArray, but rather than trying to access the -10th index of replaceArray, which would be invalid, instead the equivalent index of the matching element of compareArray is calculated for replaceArray. As a result, the first element in replaceArray is then copied into the answer array.
Chapter 12. LotusScript Language Reference
241
answer array=[the,quick,red...] and so on. Note that the 0th element of compareArray is a match for an element in sourceArray. Since this translates to 11 for replaceArray, which is out of bounds, a null value is used for the replacement value instead. answer array=[the,quick,red,fox,hurdled,{null},...] In this way the quick sleek cat jumped over the fat sleeping dog becomes the quick red fox hurdled the lazy brown dog. Each element type must match for a conversion to take place. For example, if sourceArray contains the value 1 of data type integer, and compareArray contains the value 1 of data type long, then these elements would not match. Extended examples: array and String functions
ArrayUnique function
Removes duplicate elements from an Array. Note: This function is new with Domino Release 6.
Syntax
ArrayUnique( sourceArray [ ,compMethod ])
Elements
sourceArray Array of any type. compMethod Optional Integer specifying the type of comparison to use when searching for the delimiter, if the elements are strings.
Number 0 1 4 5 Comparison Mode case sensitive, pitch sensitive case insensitive, pitch sensitive case sensitive, pitch insensitive case insensitive, pitch insensitive
If you omit compMethod, the default comparison mode is the mode set by the Option Compare statement for this module. If there is no statement for the module, the default is case sensitive and pitch sensitive.
Return value
Returns an array with duplicates removed. For any elements of the array which compare equal, the first occurrence is copied into the result array.
242
Usage
Elements in a variant array will only compare equal if they are of the same type. The variant array cant contain classes or objects. Array elements that contain the null value will match other null values. Array elements that are empty will match with other elements that are empty. Error handling ArrayUnique throws a Run-time Type mismatch if: v the first parameter is not an array v v v v v v a list is passed instead of an array the array passed in has not been properly initialized the array is of classes the array is of NotesDocuments the array contains an array as an element the array contains nothing as an element
ArrayUnique throws a run-time Wrong Number of Dimensions error if the array is not one-dimensional.
Language cross-reference
@Unique function in formula language
Sub Initialize Dim resultArr as variant Dim count as integer use Comparison Method = 0 (case sensitive, pitch sensitive) resultArr = arrayunique(myTestArr,0) for count = lbound(resultArr) To ubound(resultArr) Print resultArr(count) next count End Sub Output: abc DEF Ghi ABC def gHi
Asc function
Returns the locale-sensitive ASCII character code for the first character in a string.
Syntax
Asc ( stringExpr )
243
Elements
stringExpr Any string expression.
Return value
Asc returns the locale-sensitive ASCII character code of the first character in stringExpr. If LotusScript is running on a native ASCII platform, the code represents the character value in the platforms native character set. If LotusScript is running on a native EBCDIC platform, the character is converted to its ASCII equivalent for the platforms current locale and that code is returned. The data type of the return value is Long. If the value of stringExpris NULL or the empty string (), the function raises an error.
Prints 65
97
ASin function
Returns the arcsine, in radians, of a number between -1 and 1, inclusive.
Syntax
ASin ( numExpr )
Elements
numExpr A numeric expression with a value between -1 and 1, inclusive.
Return value
ASin returns the angle, in radians, whose sine is equal to the value of numExpr. The range of the return value is -pi/2 to pi/2, inclusive. The data type of the return value is Double. If the value of numExpris not in the range -1 to 1, inclusive, the function raises an error.
Language cross-reference
@ASin function in formula language
244
Assign the value 90, the same angle in degrees. degrees# = rad# * (180 / pi) Print rad#, degrees# Prints 1.5707963267949 90
ATn function
Returns the arctangent, in radians, of a number.
Syntax
ATn ( numExpr )
Elements
numExpr Any numeric expression.
Return value
ATn returns the angle, in radians, whose tangent is equal to the value of numExpr. The range of the return value is -pi/2 (-90 degrees) to pi/2 (90 degrees), exclusive. The data type of the return value is Double.
Language cross-reference
@ATan function in formula language
ATn2 function
Returns the polar coordinate angle, in radians, of a point in the Cartesian plane.
Syntax
ATn2 ( numExprX , numExprY )
Elements
numExprX, numExprY Any numeric expressions. At least one of the two must be non-zero. numExprXand numExprY designate the coordinates of a point in the Cartesian plane.
Return value
ATn2 returns the angular portion of the polar coordinate representation of the point (numExprX, numExprY) in the Cartesian plane.
Chapter 12. LotusScript Language Reference
245
The range of the return value is -pi to pi, inclusively. If numExprX is 0, then ATn2 returns one of the following values: v -pi/2, if numExprY is negative v pi/2, if numExprY is positive If numExprX is positive, then ATn2(numExprX, numExprY) returns the same value as ATn(numExprY / numExprX).
Language cross-reference
@ATan2 function in formula language
Print the value each angle in degrees. Print quad1# * (180 / pi) Prints 45 Print quad2# * (180 / pi) Prints 135 Print quad3# * (180 / pi) Prints -135 Print quad4# * (180 / pi) Prints -45
Beep statement
Generates a tone on the computer.
Syntax
Beep
Usage
The tone that LotusScript produces depends on the sound-generating hardware in your computer.
246
Bin function
Returns the binary representation of a number as a string.
Syntax
Bin[$] ( numExpr )
Elements
numExpr Any numeric expression. If numExpr evaluates to a number with a fractional part, LotusScript rounds it to the nearest integer before deriving its binary representation.
Return value
Bin returns a Variant of DataType 8 (String), and Bin$ returns a String. Return values will only include the characters 0 and 1. The maximum length of the return value is 32 characters.
Usage
If the data type of numExpr is not Integer or Long, then LotusScript attempts to convert it to a Long. If it cannot be converted, a type mismatch error occurs.
Usage
A Boolean value is one that contains the value of True or False only. Boolean values are stored as 16-bit (2-byte) numbers. When Boolean values are converted to numeric data types, True becomes -1 and False becomes 0. When other numeric data types are converted to the Boolean data type, 0 becomes False and any other value becomes True. Boolean variables are initialized to False. There is no suffix character for the Boolean data type. When printed, a variable of Boolean data type displays as either True or False; when Write # is used, the variable is displayed as either #TRUE# or #FALSE#.
247
Bracket notation
For applications developed with some Lotus products, such as 1-2-3, you can use names in brackets rather than object reference variables to identify Lotus software objects. To determine whether your Lotus software supports this notation, see the product documentation.
Syntax
[ prodObjName ]
Elements
prodObjName The name understood by the product to identify an object (an instance of a product class).
Usage
In some cases, Lotus products assign names to objects, and in other cases you can use the product user interface to name the objects you create. In a spreadsheet, for example, A1 identifies a particular cell, and you could use the user interface to name a chart SalesTracking. Bracket notation lets you use these names without declaring an object variable and binding it to the object. For example, the product might allow you to use:
[A1].contents = Cstr(247000)
instead of:
Dim myCell as Range Set myCell = Bind("A1") mycell.contents = Cstr(247000)
In some cases, the product uses bracket notation when it records transcripts of user actions. This makes the transcripts easier to read and modify. For more information, see the product documentation.
248
The LotusScript compiler does not attempt to determine the class of objects that are identified with bracket notation, so any class syntax errors you make (such as the incorrect use of properties and other methods), will generate run-time errors, not compile-time errors. You can also use empty brackets to identify the currently selected product object. Empty brackets are equivalent to leading dot notation. For example, if the current selection is a range named Sales, then
[ ].CopyToClipboard
and
.CopyToClipboard
are equivalent to
[Sales].CopyToClipboard
All three statements copy the contents of the Sales range to the clipboard. To include square brackets as text within a string, double the brackets. For example, if the current selection is a range named Sales[East], use the following syntax:
[Sales[[East]]].CopyToClipboard
Usage
A Byte value is a positive integer in the range 0 to 255, inclusive, stored as a single, 8-bit (1-byte) unsigned number. Byte variables are initialized to 0. There is no suffix character for the Byte data type. A byte type can be used anywhere an integer type can be used. The baseline specification for the Byte data type is the same as the byte data type in Visual Basic. Byte is both a value and a data type. This means a byte value can be stored in either a variable declared as the Byte data type or a variable declared as a variant. Because a value retrieved from a variant may be significant, both cases must be tested for.
249
Example 2
Use Byte data type to retrieve single byte from a file Dim b As Byte Dim FF As Integer FF = Freefile Open "myfile.data" For Binary Access Read As ff While (Not Eof(ff)) Get #ff, ,b Wend Close #ff
Call statement
Calls a LotusScript sub or function.
Syntax 1
Call subOrFunction [ ( [ argList ] )]
Syntax 2
subOrFunction [ argList ]
Syntax 3
subOrFunction ( argPassedByVal )
Elements
subOrFunction The name of the sub or function being called. argList A list of arguments, separated by commas, for the sub or function being called. argPassedByVal A single argument to be passed by value to the sub or function being called. function The name of the function being called. returnVal The assignment variable containing the functions return value.
250
Usage
When you use the Call keyword, you must include parentheses around the argument list. If there are no arguments, the empty parentheses are optional. When you omit the Call keyword, the following parenthesis rules apply: v For a sub or a function, do not use parentheses around the argument list (Syntax 2) unless you are passing a single argument by value to the sub or function (Syntax 3). v For a function within an expression, enclose the argument list (if there is one) in parentheses (Syntax 4). Sub calls do not return a value. LotusScript uses a functions return value if the function call appears in an expression. The call can appear anywhere in an expression where the data type of the functions return value is legal. Function calls that use the Call keyword, however, do not return a value and cannot appear in an expression. LotusScript always uses the return value of a call to a built-in function. You must use its return value in an expression, and you cannot use the Call keyword.
Example 2
Define a sub and then invoke it in two ways. Sub PrintProduct (a As Integer, b As Integer) Print a% * b% End Sub
Chapter 12. LotusScript Language Reference
251
CBool function
Returns an expression converted to the Boolean data type. Note: This function is new with Domino Release 6.
Syntax
CBool ( expr )
Elements
expr Any numeric expression, or the string expressions True and False.
Return value
CBool returns an expression that has been converted to Boolean. CBool(EMPTY) returns False. If expr is a numeric expression, CBool returns True or False, depending on the value of the numeric expression: 0 becomes False, and any other value becomes True. If expr lies outside the acceptable range for the Boolean data type, the function raises an error.
Example 2
Convert and display Integer and String values converted to Boolean dim Int_1 as integer dim String_1 as string dim Bool_1, Bool_2 Int_1 = 0 print CBool(Int_1) Int_1 = 99 prints FALSE Bool_1 = CBool(Int_1)
252
String value must be "True" or "False" for successful conversion to type Boolean print DataType(Bool_1) print DataType(Bool_2) prints 11 (Boolean) prints 11 (Boolean)
CByte function
Returns an expression converted to the Byte data type. Note: This function is new with Domino Release 6.
Syntax
CByte ( expr )
Elements
expr Any numeric expression, or a string expression that LotusScript can convert to a number.
Return value
CByte returns an expression that has been converted to Byte. CByte(EMPTY) returns 0. If expr is a string expression, CByte returns the numeric representation of the string, rounded to the nearest integer. If LotusScript cannot convert the string to a number, the function raises an error. If expr lies outside the acceptable range for the Byte data type, the function raises an error.
253
Example 2
Convert an expression to a Byte Dim MyDouble, MyByte MyDouble = 125.5678 MyDouble is a Double MyByte = CByte(MyDouble) MyByte contains 126
CCur function
Returns a value converted to the Currency data type.
Syntax
CCur ( expr )
Elements
expr Any numeric expression, or a string expression that LotusScript can convert to a number.
Return value
CCur returns the numeric value of expr rounded to four decimal places, as a Currency value. CCur(EMPTY) returns 0. If expris a string expression, CCur returns the numeric representation of the string, rounded to four decimal places. If LotusScript cannot convert the string to a number, the function raises an error. If the value of expr is too large to fit in the Currency data type, the function raises an error.
Example 2
Dim Dim Dim Dim bulkPrice As Double labelPrice As String unitsSold As Integer paymentDue As Currency
bulkPrice# = 11.400556 unitsSold% = 57 paymentDue@ = CCur(bulkPrice# * unitsSold%) Print paymentDue@ Prints 649.8317
254
CDat function
Converts a numeric value or string value to a date/time value.
Syntax
CDat ( expr ) CVDate is acceptable in place of CDat.
Elements
expr Any of the following kinds of expression: v A numeric expression v A string expression that can be converted to a number v A string expression that can be converted to a date/time value
Return value
CDat returns a date/time value. The data type of the return value is a Variant of DataType 7 (Date/Time). If the integer part of expris not in the range -657434 to 2958465, the function raises an error. CDat(0) returns the date/time value December 30, 1899, 12:00:00 AM, formatted as 12:00:00 AM. CDat(EMPTY) returns the same value.
Usage
CDat converts expr to a date/time value in the LotusScript date/time format. CDat uses different conversion rules depending on the form of expr: v If expris a numeric expression, CDat converts the integer part of its value to a date and the fractional part to a time, and returns the corresponding date/time value. A date/time value stored in a Variant is an eight-byte floating-point value. The integer part represents a serial day counted from Jan 1, 100 AD. Valid dates are represented by integer numbers in the range -657434, representing Jan 1, 100 AD, to 2958465, representing Dec 31, 9999 AD. The fractional part represents the time as a fraction of a day, measured from time 00:00:00 (midnight on the previous day). In this representation of date/time values, day 1 is the date December 31, 1899. v If expris a string expression that can be converted to a number, CDat converts the string to a number and then converts the number to a date/time value and returns the result, as described in the previous bullet. v If expris a string expression in the form of a date, for example 8/20/98, CDat converts the value to a date/time in the internal date/time format. If LotusScript cannot convert the value to a date/time, the function raises an error.
255
Language cross-reference
@Time function in formula language @TextToTime function in formula language
Example 1
Dim dateV As Variant Convert a numeric value to a date/time value. dateV = CDat(34814.3289) Display the formatted date and time. Print Format$(dateV, "Medium Date"), _ Format$(dateV, "Medium Time") Prints 25-Apr-95 07:53 AM Convert the date back to a number. Print CDbl(dateV) Prints 34814.3289 Convert a date string to a date. Print CDat("April 25, 1995") Prints 4/25/95
Example 2
print CDat(-1_,cdate(0), cdate(1) Output is 12/29/1899 Output is 11:59:59 PM 12:00:00 AM 12:00:00 AM 12/31/1899 12:00:01 AM print CDat("23:59:59"), cdat("00:00:00"), cdat("00:00:01")
CDbl function
Returns a value converted to the Double data type.
Syntax
CDbl ( expr )
Elements
expr Any numeric expression, or a string expression that LotusScript can convert to a number.
Return value
CDbl returns the numeric value of expr as a Double value. CDbl(EMPTY) returns 0. If expr is a string expression, CDbl returns the numeric representation of the string, including any fractional part. If LotusScript cannot convert the string to a number, the function raises an error. If the value of expris too large to fit in the Double data type, the function raises an error.
Language cross-reference
@TextToNumber function in formula language
256
Example 2
Convert the sum of two Single values to Double. Dim x As Single Dim y As Single Dim result As Double x! = 11.06E23 y! = 6.02E23 result# = CDbl(x! + y!) Print result# Prints 1.70800003057064E+24
ChDir statement
Sets the current directory.
Syntax
ChDir path
Elements
path A string expression representing the path of an existing directory.
Usage
ChDir sets the current directory to path. The current directory is the directory that LotusScript uses when you specify a file name without a path. If the value of path does not begin with a drive letter, ChDir sets the current directory for the current drive. If the value of path includes a drive letter, ChDir sets the current directory for that drive, but does not reset the current drive. The path will not be used as the current directory until the current drive is reset. To change the current drive, use ChDrive. To return the current drive, use CurDrive. To return the current directory, use CurDir. The format and maximum length of path follow the conventions of the platform on which LotusScript is running.
257
ChDrive statement
Sets the current drive.
Syntax
ChDrive drive
Elements
drive A string expression representing an existing drive.
Usage
ChDrive sets the current drive to the value of drive.The current drive is the drive that LotusScript uses whenever you specify a file name or a path that does not include a drive. If the value of driveis the empty string (), ChDrive does not change the current drive. If the value of drive is a string of more than one character, ChDrive uses only the first character. ChDrive does not require a colon (:) after the drive letter. The drive must be in the range A to lastdrive, inclusive, where lastdrive is the maximum drive letter specified in CONFIG.SYS. To change the current directory, use ChDir. To return the current drive, use CurDrive. To return the current directory, use CurDir.
Chr function
Returns the character represented by a value interpreted as a locale-sensitive character code.
Syntax
Chr[$] ( numExpr )
Elements
numExpr
258
A numeric expression of data type Long in the range 0-255. If LotusScript is running on a native ASCII platform, the value is interpreted as a character code in the platform-native character set. If LotusScript is running on an EBCDIC platform, the value is interpreted as the character code for the ASCII equivalent in the platforms current locale. In either case, only single-byte ASCII values are valid.
Return value
Chr returns the character corresponding to the value of numExpr. Chr returns the ANSI platform-specific character corresponding to the value of numExpr. Chr returns a Variant of DataType 8 (String). Chr$ returns a String.
Usage
If the value of numExprcontains a fraction, LotusScript rounds the value before using it. The following table lists the ASCII characters. The head of each column is the value of the first character in the column in decimal.
000 NUL SOH STX ETX EOT ENQ ACK BEL BS TAB LF VT FF CR SO SI 016 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US 032 SPC ! " # $ % & ( ) * + , . / 048 0 1 2 3 4 5 6 7 8 9 : ; < = > ? 064 @ A B C D E F G H I J K L M N O 080 P Q R S T U V W X Y Z [ \ ] ^ _ 096 ` a b c d e f g h i j k l m n o 112 p q r s t u v w x y z { | } ~ DEL
CInt function
Returns a value converted to the Integer data type.
Syntax
CInt ( expr )
259
Elements
expr Any numeric expression, or a string expression that LotusScript can convert to a number.
Return value
CInt returns the value of exprrounded to the nearest integer, as an Integer value. CInt(EMPTY) returns 0. If expris a string expression, CInt returns the numeric representation of the string, rounded to the nearest integer. If LotusScript cannot convert the string to a number, the function returns an error. If the value of expr is too large to fit in the Integer data type, the function raises an error.
Language cross-reference
@Integer function in formula language @TextToNumber function in formula language
Example 2
Convert a Currency value to Integer. Dim x As Currency x@ = 13.43 Print CInt(x@) Prints 13
Class statement
Defines a class with its member variables and procedures.
Syntax
[ Public | Private ] Class className [ As baseClass ] classBody End Class
260
Elements
Public | Private Optional. Public specifies that the class is visible outside the module where the class is defined, as long as this module is loaded. Private specifies that the class is visible only in this module. A class is Private by default. className The name of the class. baseClass Optional. The name of another class from which this class is derived. classBody Declarations and definitions of class members. Class members can include member variables; member procedures (functions, subs, and properties); a constructor sub, named New; and a destructor sub, named Delete. Constants cannot be class members.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). Rules for defining classes: v Define a class only in module scope. Do not define a class within a procedure or within another class. v Do not use the word Object as a class name. Rules for declaring member variables: v Omit the Dim keyword from the variable declaration of member variables. v A separate declaration is required for each member variable. You cant declare two or more member variables in a single declaration using a comma-separated list. v You can use the Public or Private keywords for variable declarations. A member variable is private by default; it can be accessed only within the class. v Member variables cannot be declared Static. v A class can include an instance of itself as a member, but the variable declaration cannot include the New keyword. That is, the variable declaration cannot create an object of the class. v Do not use the following LotusScript keywords as member variable names: Public, Private, Static, Sub, Function, Property, Get, Set, New, Delete, and Rem. Rules for declaring member procedures: v You can use the keywords Public or Private for procedure declarations. A member procedure is Public by default; it can be accessed outside of the class. v Member procedures cannot be declared Static. v All LotusScript keywords are legal as member procedure names. Use the names New and Delete only to name the class constructor and destructor subs, respectively. Rules for referring to class members: v Refer to class members using the notation objName.memberName, where memberName identifies a class member defined in the class of the object reference variable objName.
Chapter 12. LotusScript Language Reference
261
v You can use the keyword Me to refer to the object itself when you are inside a member procedure. In the example, Me.textColor refers to the value currently assigned to the textColor member of this instance of the class. v If you name a class member with a LotusScript keyword, you must refer to the member within member subprograms using the Me keyword. v Derived class methods can override methods of the base class. The signature of the overriding member must match the signature of the overridden member. Within the procedure of a derived class, you refer to a base class member of the same name using the notation baseClassName..memberName. v Use the With statement to work with members of a specific class using the notation .memberName. Rules for working with objects (class instances): v To create an object, use the New keyword in a Dim or Set statement for an object reference variable. v LotusScript sets the initial value of an object reference variable to NOTHING. Use the Is operator to test an object reference variable for the NOTHING value. v Any Variant variable can take an object reference as its value. Use the IsObject function to test whether the contents of a Variant variable are an object reference. v Use the Delete statement to delete an object. LotusScript sets the value of variables that refer to the object to NOTHING. A class definition can include a definition for the constructor sub, named New. If the definition exists, LotusScript calls this sub each time it creates an object of that class. A class definition can include a definition for the destructor sub, named Delete. If the definition exists, LotusScript calls this sub whenever it deletes an object of that class.
262
CLng function
Returns a value converted to the Long data type.
Syntax
CLng ( expr )
Elements
expr Any numeric expression, or a string expression that LotusScript can convert to a number.
Return value
CLng returns the value of exprrounded to the nearest integer, as a Long value. CLng(EMPTY) returns 0. If expris a string expression, CLng returns the numeric representation of the string, rounded to the nearest integer. If LotusScript cannot convert the string to a number, the function raises an error. If the value of expr is too large to fit in the Long data type, the function raises an error.
Language cross-reference
@Integer function in formula language @TextToNumber function in formula language
Example 2
Convert Double and String values to Long, rounding up or down as indicated. Dim x As Double, y as String x# = 13.400556 Print CLng(x#) Prints 13
263
x# = 13.67 Print CLng(x#) Prints 14 y="1.345" Print CLng(y) y="1.678" Print CLng(y) y="string" Print CLng(y) returns a type mismatch error Prints 2 Prints 1
Close statement
Closes one or more open files, after writing all internally buffered data to the files.
Syntax
Close [ [ # ] fileNumber [ , [ # ] fileNumber ] ... ]
Elements
fileNumber Optional. The number that LotusScript assigned to the file when it was opened. If you omit fileNumber, Close closes all open files.
Usage
The pound sign (#) preceding fileNumber is optional and has no effect on the statement. Before closing the open files, Close writes all internally buffered data to the files. If LotusScript encounters a run-time error that is not handled by an On Error statement, LotusScript closes all open files; otherwise, the files remain open. If the value of fileNumber is contains a fraction, LotusScript rounds the value before using it.
CodeLock function
Acquires the lock specified by ID.
Syntax
CodeLock ( lockID )
Elements
lockID ID of lock to be locked (assigned by LotusScript through CreateLock)
Return values
CodeLock will return TRUE, if the lock is acquired.
264
Usage
Acquires the lock specified by ID. If the lock is already held by another agent, the thread stalls until the lock becomes available. Bear in mind that CodeLock and CodeUnLock should always be done in pairs; failure to adhere to this practice will lead to unexpected results. Extended examples: lock functions
The second example demonstrates how CodeLock can avoid the problem presented in Example 1. You create and make sure you have a secure lock before you read and make changes to the count, and when you are done, you release the lock. Example 2:
Sub Initialize Dim Sess As New NotesSession Dim Doc As NotesDocument Dim Count As NotesItem Dim Status As Integer Dim LockID As Integer Dim others As Integer Creating a Lock ID or getting the Lock ID For the event of "WebSiteHits" Infinite loop that can only be exited when this agent has a successfull lock. An unsuccessfull lock means that this agent is presently being run by someone else. If Codelock(LockID) Then Exit Do We finally have a lock, exiting Loop
Chapter 12. LotusScript Language Reference
LockID = Createlock("WebSiteHits")
Do While True
265
End If Loop Set Doc = Sess.SavedData Set count = Doc.GetFirstItem("WebHits") If count Is Nothing Then Set count = New NotesItem(Doc, "WebHits", 0) End If count.Values = count.Values(0) + 1 Call Doc.Save(True,False) Once completed, release and destroy this lock so another run of this agent can continue.
CodeLockCheck function
Returns the number of agents waiting for the the specified lock, plus 1.
Syntax
CodeLockCheck ( lockID )
Elements
lockID ID of lock to be checked (assigned by LotusScript through CreateLock)
Return values
A Long value indicating the sum of the agents that have the lock and are waiting for the lock.
Usage
A sample return value of 4 would mean that one agent has the specified lock and three other agents are waiting for it. Zero indicates the lock is not locked.
CodeUnlock function
Releases the lock, making it available for the next agent requesting it.
Syntax
CodeUnlock ( lockID )
Elements
lockID ID of lock to be unlocked (assigned by LotusScript through CreateLock)
Return values
CodeUnLock returns TRUE if the lock was successfully released.
266
Usage
Releases the lock specified by ID. Bear in mind that CodeLock and CodeUnLock should always be done in pairs; failure to adhere to this practice will lead to unexpected results. Extended examples: lock functions
Command function
Returns the command-line arguments used to start the Lotus software application that started LotusScript.
Syntax
Command[$]
Return value
The return value does not include the program name. Command returns a Variant of DataType 8 (String). Command$ returns a String. If the command that started the product specified no arguments, the function returns the empty string ().
Usage
You can call the Command function as either Command or Command(). You can call the Command$ function as either Command$ or Command$(). To run a Lotus software application macro in a script, use Evaluate. To start a program from a script, use Shell. In Lotus Notes, the Command function always returns an empty string. In OS/2, macros in some products must be converted before they are OS/2 ready.
Const statement
Defines a constant.
Syntax
[ Public | Private ] Const constName = expr [ , constName = expr ]...
Elements
Public | Private Optional. Public specifies that the constant is visible outside the module where the constant is defined, as long as that module is loaded. Private specifies that the constant is visible only within the module where the constant is defined.
Chapter 12. LotusScript Language Reference
267
A constant is Private by default. If you declare a constant within a procedure, you cannot use Public or Private. constName The name of the constant. expr An expression. The value of the expression is the value of the constant. The expression can contain any of the following. v v v v Literal values (numbers and strings) Other constants Arithmetic and logical operators Built-in functions, if their arguments are constant and if LotusScript can evaluate them at compile time. The following functions are evaluated at compile time if their arguments are expressions including only literals and constants.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). A constant is a named variable whose value cannot be changed. You can declare a constant in a module or a procedure, but you cannot declare a constant in a type or class definition.
268
You can specify the data type of a constant by appending a data type suffix character to constName. Alternatively, if the constant is numeric and expr is a numeric literal, you can specify the data type by appending a data type suffix character to expr. If you do not append a data type suffix character to constName or expr, LotusScript determines the data type of the constant by the value assigned to it. v For a floating-point value, the data type is Double. v For an integer value, the data type is Integer or Long, depending on the magnitude of the value. These rules are illustrated in the examples following. Whether you specify a suffix character in the Const statement or LotusScript determines the data type based on the constants value, you can use the constant in a script with or without a data type suffix character. If you use the constant with a suffix character, the suffix character must match the data type of the constant. The data type of a constant is not affected by Deftype statements.
Example 2
Define a String constant, firstName. Const firstName$ = "Andrea" Define a Single constant, appInterest. Const appInterest! = 0.125 Define a Currency constant, appLoan. Const appLoan@
= 4350.20 Display a message about the amount of interest owed. MessageBox firstName$ & owes _ & Format(appLoan@ * appInterest!, Currency)
Cos function
Returns the cosine of an angle.
Syntax
Cos ( angle )
Elements
angle A numeric expression, specifying an angle expressed in radians.
Return value
Cos returns the cosine of angle, a value between -1 and 1, inclusive. The data type of the return value is Double.
269
Language cross-reference
@Cos function in formula language
CreateLock function
Finds the lock ID associated with Name. If none exists, the Lock ID is created.
Syntax
CreateLock( lockName )
Elements
lockName String identifier for this particular lock.
Return values
CreateLock will return the lock ID as a simple integer. It will return an error if the platform does not support locks or if there is insufficient shared memory.
Usage
Note that the variable the lock ID is stored in is simply an integer. If the variable goes out of scope the ID will be lost. It can be recovered by calling CreateLock again with the same name. Locks are unique across the current shared memory name space. Locks are freed automatically when the thread exits or may be freed by DestroyLock. Note: When a lock ID is lost DestroyLock cannot be used on the lock and system resources are taken up by the lock until the ID is recovered and the lock destroyed or the agent or thread is exited. Extended examples: lock functions
CreateObject function
Creates an OLE Automation object of the specified class. Note: CreateObject is not supported under OS/2 or UNIX. It is supported on the Macintosh as long as OLE support is installed.
Syntax
CreateObject ( className )
Elements
className
270
A string of the form appName.appClass, designating the kind of object to create (for example, WordPro.Application). The appName is an application that supports OLE Automation. The appClass is the class of the object to create. Products that support OLE Automation provide one or more classes. See the product documentation for details.
Return value
CreateObject returns a reference to an OLE Automation object.
Usage
Use the Set statement to assign the object reference returned by CreateObject to a Variant variable. If the application is not already running, CreateObject starts it before creating the OLE Automation object. References to the object remain valid only while the application is running. If the application terminates while you are using the object reference, LotusScript raises a run-time error. LotusScript supports the OLE vartypes listed in the table below. Only an OLE method or property can return a vartype designated as OLE only.
OLE vartype VT_EMPTY VT_NULL VT_I2 VT_I4 VT_R4 VT_R8 VT_CY VT_DATE VT_BSTR VT_DISPATCH VT_ERROR VT_BOOL VT_DECIMAL VT_VARIANT VT_UNKNOWN VT_ARRAY Description (No data) (No data) 2-byte signed integer 4-byte signed integer 4-byte real 8-byte real Currency Date String IDispatch, OLE only Error, OLE only Boolean Decimal, converted to Double (A reference to data of any other type) IUnknown, OLE only (An array of data of any other type)
LotusScript supports iterating over OLE collections with a ForAll statement. LotusScript supports passing arguments to OLE properties. For example:
Set v.prop to 4; v.prop takes two arguments. v.prop(arg1, arg2) = 4
LotusScript does not support identifying arguments for OLE methods or properties by name rather than by the order in which they appear, nor does LotusScript support using an OLE name by itself (without an explicit property) to identify a default property.
271
Results are unspecified for arguments to OLE methods and properties of type boolean, byte, and date that are passed by reference. LotusScript does not support these data types. The word CreateObject is not a LotusScript keyword.
The following script works on the Mac with Microsoft Word installed
Sub Initialize Set MyApp = CreateObject ( "Word.Application") MyApp.Visible = True End Sub
CSng function
Returns a value converted to the Single data type.
Syntax
CSng ( expr )
Elements
expr Any numeric expression, or a string expression that LotusScript can convert to a number.
Return value
CSng returns the numeric value of expr as a Single value. CSng(EMPTY) returns 0. If expris a string expression, CSng returns the numeric representation of the string, including any fractional part. If LotusScript cannot convert the string to a number, the function raises an error. If the value of expris too large to fit in the Single data type, the function raises an error.
Language cross-reference
@TextToNumber function in formula language
272
nvar = Csng(nstr) Messagebox nvar,, Typename(nvar) Else Messagebox nstr,, "Not a number" End Sub
Example 2
Convert a Double value by rounding to nearest Single. Dim x As Double x# = 1.70800003057064E+24 Print CSng(x#) Prints 1.708E+24
CStr function
Returns a value converted to the String data type.
Syntax
CStr ( expr ) expr Any numeric expression, date, or string expression that LotusScript can convert to a string.
Return value
CStr returns the value of expras a String value. CStr(EMPTY) returns the empty string ().
Language cross-reference
@Text function in formula language
CurDir function
Returns the current directory on a specified drive.
Syntax
CurDir[$] [ ( drive ) ]
Elements
drive Optional. A string expression specifying an existing drive. If you omit drive, CurDir uses the current drive.
Chapter 12. LotusScript Language Reference
273
Return value
CurDir returns the current directory on drive. CurDir returns a Variant of DataType 8 (String). CurDir$ returns a String.
Usage
If the value of drive is a string of more than one character, CurDir uses only the first character. CurDir does not require a colon after the drive letter. To set the current directory on a specified drive, use ChDir. To set the current drive, use ChDrive. To return the current drive, use CurDrive. You can call this function with no arguments as either CurDir or CurDir( ).
Language cross-reference
@FileDir function in formula language
CurDrive function
Returns a string identifying the current drive.
Syntax
CurDrive[$]
Return value
CurDrive returns the current drive letter followed by a colon. CurDrive returns a Variant of DataType 8 (String). CurDrive$ return a String. To set the current directory on a specified drive, use ChDir. To set the current drive, use ChDrive. To return the current directory on a drive, use CurDir. You can call the CurDrive function as either CurDrive or CurDrive(). You can call the CurDrive$ function as either CurDrive$ or CurDrive$().
274
Usage
The Currency suffix character for implicit type declaration is @. Use the Currency data type for calculations with money. Currency variables are initialized to 0. The range of Currency values is -922,337,203,685,477.5807 to 922,337,203,685,477.5807, inclusive. On Unix platforms, the values must fall within the range -922,337,203,685,477.5666 to 922,337,203,685,477.5666, inclusive. Use the Currency data type for fixed point calculations in which four-decimal-place accuracy is meaningful. LotusScript aligns Currency data on a 4-byte boundary. In user-defined types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space.
CVar function
Returns a value converted to the Variant data type.
Syntax
CVar ( expr )
Elements
expr Any expression.
Return value
CVar returns the value of expr. The data type of the return value is Variant.
275
DataType function
Returns the data type of the value of an expression.
Syntax
DataType ( expr ) VarType is acceptable in place of DataType.
Elements
expr Any expression.
Return value
DataType returns a number representing the data type of expr. The following table describes the possible return values. The first column is the return value. The last column is Yes if the return value applies to variants only.
Return 0 1 2 3 4 5 6 7 8 9 10 11 12 13 17 34 35 2,048 8,192 8,704 Value type EMPTY NULL Integer Long Single Double Currency Date/Time String OLE object or NOTHING OLE error Boolean Variant list or array IUNKNOWN (OLE value) Byte User-defined object Product object List Fixed array Dynamic array Constant V_EMPTY V_NULL V_INTEGER V_LONG V_SINGLE V_DOUBLE V_CURRENCY V_DATE V_STRING V_DISPATCH V_ERROR V_BOOLEAN V_VARIANT V_IUNKNOWN V_BYTE V_LSOBJ V_PRODOBJ Yes Yes Yes Yes Variants only Yes Yes
Usage
The file lsconst.lss defines the constants described in the preceding table. If you want to refer to the return values as symbolic constants instead of numbers, use the %Include directive to include this file in your script.
276
If the argument to DataType is a list or an array, the return value is the sum of the value that represents a list or an array plus the value that represents the data type of elements of the list or array. For example, a fixed array of Integers is 8194 (that is, 8192 + 2); a list of Variants is 2060 (that is, 2048 + 12). The return value 13 signifies an unknown value type, corresponding to the OLE value IUNKNOWN. To test for this value, use the IsUnknown function.
Language cross-reference
@IsNumber function in formula language @IsTime function in formula language @IsText function in formula language
itemWeight! = 2.7182 itemName$ = "Jute twine" item(1) = itemWeight! item(2) = itemName$ Print DataType(item(1)) Prints 4 Print DataType(item(2)) Prints 8 Print DataType(item(3)) Prints 0 (initalized to EMPTY) Dim cells As Range Suppose Range is a product-defined class. Print DataType(cells) Prints 35 Set cells2 = cells Print DataType(cells2) Prints 35 Dim areas(3) As Range An array of Range product objects Print DataType(areas) Prints 8227 (8192 + 35) Set cal = CreateObject("dispcalc.ccalc") Print DataType(cal) Prints 9 Dim stats(3) As Integer An array of Integers Print DataType(stats%) Prints 8194 (8192 + 2) Dim misc List As Variant A list of Variants Print DataType(misc) Prints 2060 (2048 + 12)
277
Suffix $
Value range (String length ranges from 0 to 32K characters) Initial value: (empty string)
Size (2 bytes/character)
Besides these scalar data types, LotusScript supports the following additional data types and data structures:
Data type or structure Array Description An aggregate set of elements having the same data type. An array can comprise up to 8 dimensions whose subscript bounds can range from -32768 to 32767. Initial value: Each element in a fixed array has an initial value appropriate to its data type. List Variant A one-dimensional aggregate set whose elements have the same data type and are referred to by name rather than by subscript. A special data type that can contain any scalar value, array, list, or object reference. Initial value: EMPTY User-defined data type An aggregate set of elements of possibly disparate data types. Comparable to a record in Pascal or a struct in C. Initial value: Member variables have initial values appropriate to their data types. Class An aggregate set of elements of possibly disparate data types together with procedures that operate on them. Initial value: When you create an instance of a class, LotusScript initializes its member variables to values appropriate to their data types, and generates an object reference to it. Object reference A pointer to an OLE Automation object or an instance of a product class or user-defined class. Initial value: NOTHING. 4 bytes Up to 64K bytes Up to 64K bytes 16 bytes Size Up to 64K bytes
In each of the preceding tables, the specified storage size is platform independent.
Date function
Returns the current system date as a date/time value.
Syntax
Date[$]
Return value
Date returns the integer part of the value returned by the Now function. Date returns that value as a Variant of DataType 7 (Date/Time). Date$ returns that value as a String.
Usage
The Date function is equivalent to the Today function.
278
You can call the Date function as either Date or Date( ). You can call the Date$ function as either Date$ or Date$().
Date statement
Sets the system date.
Syntax
Date[$] = dateExpr
Elements
dateExpr Any expression whose value is a valid date/time value: either a String in a valid date/time format, or else a Variant containing either a date/time value or a string value in date/time format. If dateExpris a string in which the date part contains only numbers and valid date separators, the operating systems international Short Date format determines the order in which the numbers are interpreted as month, day, and year values. The date part of the string must have one of the following forms: mm-dd-yy or dd-mm-yy mm-dd-yyyy or dd-mm-yyyy mm/dd/yy or dd/mm/yy mm/dd/yyyy or dd/mm/yyyy
Usage
If you specify a 2-digit year designation (yy) in Notes or Domino, LotusScript interprets 50 through 99 as the years 1950 through 1999 and 00 through 49 as the years 2000 through 2049. For example, 88 and 1988 are equivalent year designations and 12 and 2012 are equivalent year designations. If you specify a 2-digit year designation in SmartSuite, LotusScript interprets the years differently. For information on how each SmartSuite product interprets 2-digit year designations, see the online Help entry entitled Year 2000. This entry appears on the Help menu of each SmartSuite product.
DateNumber function
Returns a date value for a given set of year, month, and day numbers.
Syntax
DateNumber ( year , month , day ) DateSerial is acceptable in place of DateNumber.
279
Elements
year A numeric expression designating a year. If you specify a 2-digit year designation (yy) in Notes or Domino, LotusScript interprets 50 through 99 as the years 1950 through 1999 and 00 through 49 as the years 2000 through 2049. For example, 88 and 1988 are equivalent year designations and 12 and 2012 are equivalent year designations. If you specify a 2-digit year designation in SmartSuite, LotusScript interprets the years differently. For information on how each SmartSuite product interprets 2-digit year designations, see the online Help entry entitled Year 2000. This entry appears on the Help menu of each SmartSuite product. month A numeric expression designating a month of the year (a value from 1 through 12). If you assign montha negative value, DateNumber calculates a prior date by measuring backward from December of the preceding year. (For example, 1995, -2, 10 is evaluated as October 10, 1994.) day A numeric expression designating a day of the month (a value from 1 through 31). If you assign day a negative value, then DateNumber calculates a prior date by measuring backward from the last day of the month immediately preceding the specified month. (For example, 1995, 5, -3 is evaluated as April 27, 1995, by subtracting 3 from 30, the last day of April, the month before the 5th month.)
Return value
DateNumber returns the date value for the given year, month, and day. The data type of the return value is a Variant of DateType 7 (Date/Time).
Language cross-reference
@Date function in formula language @Time function in formula language
DateValue function
Returns the date value represented by a string expression.
Syntax
DateValue ( stringExpr )
280
Elements
stringExpr A string expression representing a date/time. stringExpr must be a String in a valid date/time format or else a Variant containing either a date/time value or a string value in date/time format. If you omit the year in stringExpr, DateValue uses the year in the current system date. If stringExpr is a string whose date part contains only numbers and valid date separators, the operating systems international Short Date format determines the order in which the numbers are interpreted as month, day, and year values. If you specify a 2-digit year designation (yy) in Notes or Domino, LotusScript interprets 50 through 99 as the years 1950 through 1999 and 00 through 49 as the years 2000 through 2049. For example, 88 and 1988 are equivalent year designations and 12 and 2012 are equivalent year designations. If you specify a 2-digit year designation in SmartSuite, LotusScript interprets the years differently. For information on how each SmartSuite product interprets 2-digit year designations, see the online help entry entitled Year 2000. This entry appears on the Help menu of each SmartSuite product.
Return value
DateValue returns the date value represented by stringExpr. The data type of the return value is a Variant of DataType 7 (Date/Time).
Usage
If the stringExpr argument specifies a time of day, DateValue validates the time, but omits it from the return value.
Language cross-reference
@TextToTime function in formula language
Day function
Returns the day of the month (an integer from 1 to 31) for a date/time argument.
Syntax
Day ( dateExpr )
Elements
dateExpr Any of the following kinds of expression: v A valid date/time string of String or Variant data type.
Chapter 12. LotusScript Language Reference
281
In a 2-digit year designation (yy) in Notes or Domino, LotusScript interprets 50 through 99 as the years 1950 through 1999 and 00 through 49 as the years 2000 through 2049. For example, 88 and 1988 are equivalent year designations and 12 and 2012 are equivalent year designations. In a 2-digit year designation in SmartSuite, LotusScript interprets the years differently. For information on how each SmartSuite product interprets 2-digit year designations, see the online Help entry entitled Year 2000. This entry appears on the Help menu of each SmartSuite product. v A numeric expression whose value is a Variant of DataType 7 (Date/Time) v A number within the valid date range: the range -657434 (representing Jan 1, 100 AD) to 2958465 (Dec 31, 9999 AD) v NULL
Return value
Day returns an integer between 1 and 31. The data type of the return value is a Variant of DataType 2 (Integer). Day(NULL) returns NULL.
Language cross-reference
@Day function in formula language
Syntax
Declare [ Public | Private ] { Function | Sub } LSname Lib libName [ Alias aliasName ] ( [ argList ] ) [ As returnType ]
Elements
Public | Private Optional. Public indicates that the declared C function is visible outside this module, for as long as the module is loaded. Private indicates that the declared C function is visible only within this module. A declared C function is Private by default. Function | Sub Specifies that the C function is to be called as either a function or a sub. LSname
282
The function or sub name used within LotusScript. If you omit the Alias clause, this name must match the name declared in the shared library. If the statement is declaring a Function (using the keyword Function), then you can append a data type suffix character to LSname, to declare the type of the functions return value. libName A literal string, or a string constant, specifying the shared library file name. The file name extension is optional. You can optionally include a complete path specification. LotusScript automatically converts libName to uppercase. If you need to preserve case sensitivity, use the aliasName described below. aliasName Optional. A literal string containing one of the following: v A case-sensitive C function name as declared in the shared library v A pound sign (#) followed by an ordinal number representing the position of the function in the library; for example, #1 This argument is useful when the C function name is not a valid LotusScript name, or when you need to preserve case sensitivity (for example, when calling an exported library function in a 32-bit version of Windows). argList Optional. An argument list for the external function. Parentheses enclosing the list are required, even if the C function takes no arguments. argList has the form: argument [, argument] ... where argument is: [ ByVal ] name As[ LMBCS| Unicode ] [ dataType | Any ] The optional LMBCS and Unicode keywords may be used with the String data type only, to specify the character set. See the usage information and examples that follow. Use the keyword Any to pass an argument to a C function without specifying a data type, suppressing type checking. returnType The data type of the functions return value. The clause As returnType is not allowed for a sub, since a sub doesnt return a value. For a function, either specify As returnType, or append a data type suffix character to LSname, to declare the data type of the functions return value. Do not specify both a returnType and a data type suffix character. You cant use Any as a returnType. You cant use Variant, Currency, or fixed-length String as a returnType.
283
If you omit As returnType and the function name has no data type suffix character appended, the function returns a value of the data type specified by a Deftype statement that applies to the function name. A C function cant return a Variant; so a DefVar statement cant apply to the function name. returnType has the form: [ LMBCS | Unicode ] dataType The dataType must match the C function return type exactly; no conversion is performed on the return value. The optional LMBCS and Unicode keywords may be used with the String data type only, to specify the character set. See the usage information and examples that follow.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). You can only declare external functions at the module level. If a function is not typed with a return type or a data type suffix character, LotusScript generates an error. The _ is reserved for Notes specific DLLs. This is a change put in as of Notes 4.5.1. If you attempt to load a DLL in Notes 4.51 or greater using LotusScript and the name of the DLL is preceded by an underscore you will receive the error Error in loading DLL.
Passing arguments
By default, LotusScript passes arguments to external functions by reference. Arguments can be passed by value using the ByVal keyword, but only if LotusScript can convert the value passed to the data type of the corresponding C function argument. Arrays, type variables, and user-defined objects must be passed by reference. You cant pass lists as arguments to C functions. You cant use a fixed-length String as an argument. Product objects can be passed by reference (passing a reference to the instance handle) or by value (passing the instance handle itself). They can be passed by value only by using the keyword ByVal. Parentheses cant be used on the actual argument. An argument can be typed as Any to avoid data type restrictions. Arguments of type Any are always passed by reference, regardless of the type of data they contain. You can pass a Variant containing an array or list to a C function argument declared as Any.
284
Example 2
Declare an exported library function (SendDLL) with an alias to preserve case sensitivity. Declare Function SendDLL Lib "C:\myxports.dll" _ Alias "_SendExportedRoutine" (i1 As Long, i2 As Long) Call SendDLL SendDLL(5, 10)
Example 3
Pass the string argument amIStr to the function StrFun as a Unicode string. The functions return value is also a Unicode string. Declare Function StrFun Lib "lib.dll" _ (amIStr As Unicode String) As Unicode String
Example 4
Pass the string argument amLStr to the function StrFun as a LMBCS string. The functions return value is a LotusScript platform-native string. Declare Function StrFun Lib "lib.dll" _ (amLStr As LMBCS String) As String
Syntax
Declare [ Static ] [ Public | Private ] procType procName [ ([ argList ] ) ] [ As returnType ]
Elements
Static Optional. Specifies that the values of the procedures local variables are saved between calls to the procedure. If this keyword is present, it must also be present in the definition of the procedure. Public | Private
285
Optional. Public indicates that the declared procedure is visible outside this module, for as long as the module is loaded. If this keyword is present, it must also be present in the definition of the procedure. Private indicates that the declared procedure is visible only within this module. If this keyword is present, it must also be present in the definition of the procedure. procType One of the following four keyword phrases, to identify the kind of procedure: Function Sub Property Get Property Set procName The name of a function, sub, or property. If procType is Function (a function is being declared), then procName can have a data type suffix character appended to declare the type of the functions return value. argList A comma-separated list of argument declarations for the procedure. The procedure must be a function or a sub (procType must be Function or Sub). The argument declarations must match the argument declarations in the function or sub definition exactly. The syntax for each argument declaration is: [ ByVal ] argument [ ( ) | List ] [ As type ] ByVal means that argument is passed by value: that is, the value assigned to argument is a local copy of a value in memory, rather than a pointer to that value. argument () is an array variable. argument List identifies argument as a list variable. Otherwise, argument can be a variable of any of the other data types that LotusScript supports. As dataType specifies the variables data type. You can omit this clause and use a data type suffix character to declare the variable as one of the scalar data types. If you omit this clause and argument doesnt end in a data type suffix character (and isnt covered by an existing Deftype statement), its data type is Variant. Enclose the entire list of argument declarations in parentheses. returnType The data type of the functions return value. This is optional for a function, and not allowed for a sub or a property, because they dont return values. returnType must match the return type specified in the function definition; no conversion is performed on the return value. If you omit As returnType, the function names data type suffix character appended to procName (the function name) determines the return values type. Do not specify both a returnType and a data type suffix character. If you omit As returnType and procName has no data type suffix character appended, the function returns a value either of data type Variant or of the data type specified by a Deftype statement.
286
Usage
The IDE implicitly generates forward declarations of procedures; directly entering them in the IDE is unnecessary and causes syntax errors. You can %Include a file containing forward declarations of procedures contained in the file. You can directly enter in the IDE forward declarations of class properties and methods. The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). You can make a forward declaration only at the module level or within a class. The procedure, if it exists, must be defined in the same scope as the forward declaration. LotusScript does not generate an error if a procedure has a forward declaration but is not defined. (An error will be generated if you try to call a procedure that has been declared but not defined.) A procedure declared within a class definition cannot be declared as Static. The use of Static, Public, and Private keywords in a Property Get forward declaration must match their use in the corresponding Property Set forward declaration, if one exists.
Deftypestatements
Set the default data type for variables, functions, and properties whose names begin with one of a specified group of letters. Note: DefBool and DefByte are new with Domino Release 6.
Syntax
DefBool range [, range] ... DefByte range [, range] ... DefCur range [ , range ] ... DefDbl range [ , range ] ... DefInt range [ , range ] ...
Chapter 12. LotusScript Language Reference
287
DefLng range [ , range ] ... DefSng range [ , range ] ... DefStr range [ , range ] ... DefVar range [ , range ] ...
Elements
range A single letter, or two letters separated by a hyphen. Spaces or tabs around the hyphen are ignored. A two-letter range specifies the group of letters including the given letters and any letters between. These must be letters with ASCII codes less than 128. Letters in range are case insensitive. For example, the group of letters J, j, K, k, L, and l can be designated by any one of these range specifications: J-L, L-J, j-L, L-j, J-l, l-J, j-l, or l-j.
Usage
The following table lists the Deftype statements, the data type that each one refers to, and the data type suffix character for that data type.
Statement DefBool DefByte DefCur DefDbl DefInt DefLng DefSng DefStr DefVar Data type Boolean Byte Currency Double Integer Long Single String Variant Suffix character (none) (none) @ # % & ! $ (none)
Deftype statements can only appear at the module level, but they affect all declarations contained within the module at module level and within its procedures. They do not affect the declarations of data members of types and classes. They do affect declarations of function members and property members of classes. All Deftype statements in a module must appear before any declaration, explicit or implicit, in the module. Exception: the declaration of a constant (by the Const statement) is not affected by Deftype statements. No range in any Deftype statement can overlap any other range in the same Deftype statement or in any other Deftype statement in the same module. The range A-Z is special. It includes all international characters, not only the letters with ASCII codes less than 128. It is the only range specification that includes international characters. For example, to change the default data type of all variables, functions, and properties to Single (the standard data type for several versions of BASIC), specify DefSng A-Z.
288
Declarations that are explicit as to data type (such as Dim X As Integer, Dim Y$, or Define MyFunction As Double) take precedence over Deftype declarations.
Delete statement
Executes an objects Delete sub, if the sub exists, and then deletes the object.
Syntax
Delete objRef
Elements
objRef An object reference variable or Variant containing an object reference.
Usage
The Delete statement calls the Delete sub in the objects class definition (if one exists), and then sets all references to the object to NOTHING. If the objects class is a derived class, LotusScript executes the base classs Delete sub (if one exists) after executing the classs Delete sub. For product objects, the interpretation of a Delete statement is up to the product. In some cases, for example, the Delete statement deletes the object reference, but not the object itself. A product may provide its own script mechanism for deleting the object. In Lotus Notes Release 4, for example, you can use the Delete statement to delete an object reference to a Notes database, but you use the NotesDatabase class Remove method to delete the database itself (an .nsf file).
289
Define a constructor sub for the class. Sub New (Na As String, Addr As String, Bal As Currency) Me.Name$ = Na$ Me.Address$ = Addr$ Me.Balance@ = Bal@ End Sub Define a destructor sub for the class. Sub Delete Print "Deleting customer record for: "; Me.Name$ End Sub End Class Create an object of the Customer class. Dim X As New Customer ("Acme Corporation", _ "55 Smith Avenue, Cambridge, MA", 14.92) Print X.Balance@ Output: 14.92 Delete the object, first running the destructor sub. Delete X Output: Deleting customer record for: Acme Corporation Then the object is deleted.
DestroyLock function
Removes the current link to the lock specified. If the number of links is zero, the lock is destroyed.
Syntax
DestroyLock ( lockID As Integer)
Elements
lockID ID of lock to be destroyed (assigned by LotusScript through CreateLock)
Return values
DestroyLock returns TRUE if the lock was successfully destroyed.
Usage
Any agent that uses locks should be sure to use the DestroyLock function when they are done using a lock. If the lock is not destroyed, it will continue to use system resources as no one can use that lock again until the agent exits. Extended examples: lock functions
Dim statement
Declares variables.
Syntax
{ Dim | Static | Public | Private } variableDeclaration [ , variableDeclaration ]...
290
Elements
Dim | Static | Public | Private Variable declarations begin with one of the words Dim, Static, Private, or Public. Dim indicates that a variable is nonstatic and private by default. v Static indicates that the variables value is saved between calls to the procedure where the variable is declared. v Public indicates that the variable is visible outside the scope (module or class) where the variable is defined, for as long as this module remains loaded. v Private indicates that the variable is visible only within the current scope. You can use the Static keyword in procedure scope, but not in module or class scope. You can use the Public and Private keywords in module or class scope, but not in procedure scope. variableDeclaration The declaration has one of the following forms, depending on the kind of variable being declared: v Scalar variable: variableName[dtSuffix] [ As type ] v Object reference variable: variableName As[ New ] type [ argList ] v List variable: variableName[dtSuffix] List [ As type] v Array variable: variableName[dtSuffix] ( [ bounds] ) [ As type] You can declare any number of variables in a single statement, separated by commas. variableName The name of the variable being declared. dtSuffix Optional. A character that specifies the data type of variableName. The data type suffix characters and the data types that they represent are: @ for Currency, # for Double, % for Integer, & for Long, ! for Single, and $ for String. type Optional for scalar variables, lists, and arrays. A valid LotusScript data type, user-defined data type, user-defined class, or product class. This specifies the type of variableName. If type is the name of a class, variableName is an object reference for that type: its value can only be a reference to an instance of that class or to an instance of a derived class of that class, or the value NOTHING. New Optional. Valid only if type is the name of a user-defined or product class. New creates a new object of the class named by type, and assigns a reference to that object in variableName. Note that in some cases, Lotus products provide other mechanisms for creating product objects in scripts, such as product functions or product object methods. See your Lotus software documentation for details. argList
Chapter 12. LotusScript Language Reference
291
Optional. This is valid only if the New keyword is specified. For user-defined classes, argList is the comma-separated list of arguments required by the class constructor sub New, defined in the class named by type. For product classes, consult the product documentation. bounds Optional. boundsis a comma-separated list of bounds for the dimensions of a fixed array. Each bound is specified in the form [ lowerBound To ] upperBound where lowerBound is a number designating the minimum subscript allowed for the dimension, and upperBoundis a number designating the maximum. If no lowerBound is specified, the lower bound for the array dimension defaults to zero (0), unless the default lower bound has been changed to 1 using the Option Base statement. For example, with a default lower bound of 0, the following statement allocates storage for 4 strings instead of the assumed 3 strings:
Dim strArray(3) as String
If you dont define any bounds, the array is defined to be a dynamic array.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals).
Declaring arrays
For a fixed array, Dim specifies the type of the array, the number of dimensions of the array, and the subscript bounds for each dimension. Dim allocates storage for the array elements and initializes the array elements to the appropriate value for that data type (see Initializing variables, later in this section). For a dynamic array, Dim only specifies the type of the array. The number of dimensions of the array and the subscript bounds for each dimension are not defined; and no storage is allocated for the array elements. The declaration of a dynamic array must be completed by a later ReDim statement. Arrays can have up to 8 dimensions. Array subscript bounds must fall in the range -32,768 to 32,767, inclusive.
292
Declaring lists
A list is initially empty when it is declared: it has no elements, and no storage is allocated for it. An element is added to a list when the list name with a particular list tag first appears on the left-hand side of an assignment statement (a Let statement or a Set statement). If the character set is single byte, Option Compare determines whether list names are case sensitive. For example, if Option Compare Case is in effect, the names ListA and Lista are different; if Option Compare NoCase is in effect, these names are the same. If the character set is double byte, list names are always case and pitch sensitive.
Initializing variables
Declaring a variable also initializes it to a default value. v Scalar variables are initialized according to their data type: Numeric data types (Boolean, Byte, Integer, Long, Single, Double, Currency): Zero (0) Variants: EMPTY Fixed-length strings: A string filled with the NULL character Chr(0) Variable-length strings: The empty string () v Object reference variables are initialized to NOTHING, unless New is specified in the variable declaration. v Each member of a user-defined data type variable is initialized according to its own data type. v Each element of an array variable is initialized according to the arrays data type. v A list variable has no elements when it is declared, so there is nothing to initialize.
Visibility of declarations
The default visibility for a declaration at the module level is Private, unless Option Public has been specified. The default visibility for a variable declaration within a class is Private. Public and Private can only be used to declare variables in module or class scope. Variables declared within a procedure are automatically Private; members of user-defined data types are automatically Public. Once created, these cannot be changed.
293
Example 2
Dim xB As New Button("Merge", 60, 125)
xB is declared as an object reference variable to hold references to objects of the class named Button. A new Button object is created. For this example, suppose that the constructor sub for the class Button takes three arguments: a name for a button, and x- and y-position coordinates for the location of the button. The new button created is named Merge, and positioned at (60, 125). A reference to this button is assigned to xB.
Example 3
Declare iVer and kVer as Integer variables. Note that the phrase As Integer must be repeated to declare both variables as Integer. Dim iVer As Integer, kVer As Integer Declare nVer as an Integer variable. The declared type of mVer is Variant, the default data type, because no data type is declared for mVer: there is no As type phrase for mVer, and no data type suffix attached to mVer. Dim mVer, nVer As Integer Print TypeName(mVer), TypeName(nVer%) Prints EMPTY INTEGER
Example 4
Declare marCell and perDue as Integer variables. The phrase As Integer declares marCell as an Integer variable. The data type suffix % declares perDue as an Integer variable. Dim marCell As Integer, perDue% Print TypeName(marCell), TypeName(perDue%) Prints INTEGER INTEGER
Example 5
Dim marCell% As Integer Error, because the Dim statement attempts to declare the Integer variable marCell using both the data type suffix character for Integer, and the data type name Integer. The declaration should include one or the other, but not both.
Example 6
A data type suffix character is optional in references to a declared variable. Declare marCell as an Integer variable. Dim marCell As Integer Use the data type suffix character in a reference to marCell. marCell% = 1 Refer to marCell without using the suffix character. Print marCell Prints 1
294
Example 7
Declare marCell as an Integer variable. Dim marCell As Integer Assign integer value to marCell. marCell% = 1 Print marCell$ Error, because the Print statement refers to marCell using the data type suffix character $ for a String variable, but marCell was declared as an Integer.
Example 8
Dim db As New NotesDatabase ("Server003", "discuss.nsf")
This Dim objRefAs New prodClass(argList) statement declares an object reference to, and creates an instance of, the Notes/Domino NotesDatabase class. The Dim statement for creating a NotesDomino object requires two string arguments: a server name and a database path name.
Dir function
Returns file or directory names from a specified directory, or returns a drive volume label.
Syntax
Dir[$] [ ( fileSpec [ , attributeMask ] ) ]
Elements
fileSpec A string expression that specifies a path and the file names you want returned. The argument is required only for the first call to Dir$ for any path. Standard wildcard characters can be used in fileSpec to designate all files satisfying the wildcard criterion. Asterisk ( * ) for either the file name or the extension designates all files with any characters in that position. Question mark ( ? ) in any character position in either part of the name designates any single character in that position. attributeMask An integer expression whose value specifies what names should be returned. If this argument is omitted, the names of normal files that match fileSpecare returned. If you supply an attributeMask argument, you must supply a fileSpec argument. Dir$ always returns the names of normal files. To include other files in the returned list of file names, specify the sum of those values in the following table that correspond to the desired kinds of files:
Mask 0 2 4 8 16 File attribute Normal file Hidden file System file Volume label Directory Constant ATTR_NORMAL ATTR_HIDDEN ATTR_SYSTEM ATTR_VOLUME. If any other attribute is specified, ATTR_VOLUME is ignored. ATTR_DIRECTORY
295
Return value
Dir returns a Variant of DataType 8 (String), and Dir$ returns a String. Note: On any platform except Windows (16, 9x, NT, 2000) if you ask for just the volume label you will get an empty string.
Usage
The constants in the table are defined in the file lsconst.lss. Including this file in your script allows you to use constant names instead of their numeric values. To determine whether a particular file exists, use an exact file name for the file_spec argument to Dir or Dir$. The return value is either the file name or, if the file does not exist, the empty string (). The first call to Dir or Dir$ returns the name of the first file in the specified directory that fits the file name specifications in the fileSpec argument. Then: v Subsequent calls to Dir or Dir$ without an argument retrieve additional file names that match fileSpec. You can call the Dir function with no arguments as either Dir or Dir( ). You can call the Dir$ function with no arguments as either Dir$ or Dir$(). v If there are no more file names in the specified directory that match the specification, Dir returns a Variant of DataType 8 (String); Dir$ returns the empty string (). If Dir or Dir$ is called without an argument after the empty string has been returned, LotusScript generates an error. The Dir or Dir$ function may not be called recursively.
Do statement
Executes a block of statements repeatedly while a given condition is true, or until it becomes true.
Syntax 1
Do [ While | Until condition ] [ statements ] Loop
Syntax 2
Do [ statements ] Loop [ While | Until condition ]
296
Elements
condition Any numeric expression. 0 is interpreted as FALSE, and any other value is interpreted as TRUE.
Usage
In Syntax 1, condition is tested before entry into the loop, and before each subsequent repetition. The loop repeats as long as condition evaluates to TRUE (if you specify While), or until condition evaluates to TRUE (if you specify Until). In Syntax 2, condition is tested after the body of the loop executes once, and after each subsequent repetition. The loop repeats as long as condition evaluates to TRUE (if you specify While), or until condition evaluates to TRUE (if you specify Until).
Language cross-reference
@DoWhile function in formula language @While function in formula language
Examples: Do statement
Each loop below executes four times, exiting when the loop variable reaches 5. Dim i As Integer, j As Integer i% = 1 j% = 1 Do While i% < 5 Test is value before executing loop. i% = i% + 1 Print i% ; Loop Output: 2 3 4 5 Do j% = j% + 1 Print j% ; Loop Until j% >= 5 Test js value after executing loop. Output: 2 3 4 5
Dot notation
Use dot notation to refer to members of user-defined types, user-defined classes, and product classes.
Syntax 1
typeVarName . memberName
297
Syntax 2
objRefName . memberName[ ( argList ) ]
Elements
typeVarName A variable of a user-defined data type. memberName A member of a user-defined type, a user-defined class, or a product class. Class members may include methods, properties, and variables. objRefName An object reference variable. argList Optional. A list of one or more arguments; some class methods and properties require an argument list.
Usage
Use dot notation to refer to the members of user-defined data types, user-defined classes, and product classes. When referring to the currently selected product object, you may omit objRefName. In some cases, you can use bracket notation, substituting [ prodObjName ] for objRefName. For more information, see your Lotus software documentation. Note that dot notation is interpreted differently when it appears within a With statement. See that topic for details.
Usage
The Double suffix character for implicit type declaration is #. Double variables are initialized to 0. The range of Double values is -1.7976931348623158E+308 to 1.7976931348623158E+308, inclusive. On UNIX platforms, the range is -1.7976931348623156E+308 to 1.797693134862315E+308, inclusive. The smallest non-zero Double value (disregarding sign) is 2.2250738585072014E-308.
298
LotusScript aligns Double data on an 8-byte boundary. In user-defined types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space.
End statement
Terminates execution of the currently executing script.
Syntax
End [ returnCode ]
Elements
returnCode Optional. An integer expression. The script returns the value of this expression to the Lotus software application that executed the script.
Usage
Some Lotus products do not expect a return value when an End statement executes. See the products documentation. If the product does not expect a return value, you do not need to use returnCode. The product will ignore it if you do.
Language cross-reference
@Return function in formula language
Environ function
Returns information about an environment variable from the operating system.
Syntax 1
Environ[$] ( { environName | n } )
299
Elements
environName A string of uppercase characters indicating the name of an environment variable. n A numeric value from 1 to 255, inclusive, indicating the position of an environment variable in the environment string table.
Return value
Environ returns a Variant, and Environ$ returns a String. If you specify the environment variable by name with environName, LotusScript returns the value of the specified environment variable. If that environment variable is not found, LotusScript returns the empty string (). If environName is the empty string or evaluates to NULL or EMPTY, LotusScript generates an error. If you specify the environment variable by position with n, LotusScript returns the entire environment string, including the name of the environment variable. If n is larger than the number of strings in the environment string table, LotusScript returns the empty string (). If n is less than 1, greater than 255, an EMPTY Variant, or NULL, LotusScript generates an error.
Language cross-reference
@Environment function in formula language ENVIRONMENT keyword in formula language
EOF function
Returns an integer value that indicates whether the end of a file has been reached.
Syntax
EOF ( fileNumber ) fileNumber The ID number assigned to the file when it was opened.
300
Return value
The return value depends on the type of file that you are using. The following table shows the EOF return values for binary, random, and sequential file types.
File type Binary Random Sequential EOF returns TRUE if: EOF returns FALSE if:
The last executed Get statement cannot read the It successfully reads the amount of data amount of data (the number of bytes) requested. requested. The last executed Get statement cannot read an entire record. The end of the file has been reached. It successfully reads an entire record. The end of the file has not been reached.
Usage
The end of file is determined by the operating system (from the file length stored in the file system). A Ctrl+Z character (ASCII 26) is not considered an end-of-file marker for any type of file: sequential, random, or binary.
Erase statement
Deletes an array, list, or list element.
Syntax
Erase { arrayName | listName | listName ( tag ) } [,{ arrayName|listName | listName ( tag ) } ]...
Elements
arrayName An array or a Variant variable containing an array. arrayName can end with empty parentheses. listName A list or a Variant variable containing a list. listNamecan end with empty parentheses. tag The list tag of a list element to be erased from the specified list.
301
Usage
The following table shows how the Erase statement affects arrays and lists.
Item Fixed array Dynamic array Effect of Erase statement Its elements are reinitialized. LotusScript removes all elements from storage and recovers the storage. The array retains its type, but has no elements. You must use ReDim to redeclare the array before referring to its elements again. If you used ReDim before it was erased, the array maintains the same number of dimensions. List List element LotusScript removes all elements from storage and recovers the storage. The list retains its type, but has no elements. The element no longer exists in the list.
Erl function
Returns the line number in the current script procedure where the current error occurred.
Syntax
Erl
Return value
Erl returns an Integer. It returns FALSE (0) if there is no current error, which signifies that the most recent error has been handled.
Usage
You can call the function as either Erl or Erl(). The line number returned by Erl is for the procedure handling the error. If a calling procedure contains an On Error statement and the called procedure does not, an error in the called procedure is reported at the line number of the Call statement or function reference in the calling procedure.
302
Error ( ERRTYPEMISMATCH ) exit sub ErrHandler: Print "Got error " & Error$ & " on line " & cstr(Erl) resume next End Sub
Err function
Returns the current error number.
Syntax
Err
Return value
Err returns an Integer. If there is no current error, Err returns FALSE (0).
Usage
The error number is set when an error occurs, or by the Err statement. Generally, the function Err is used within an error-handling routine. You can call the function as either Err or Err().
Language cross-reference
@IsError function in formula language
303
Err statement
Sets the current error number.
Syntax
Err = errNumber
Elements
errNumber A numeric expression whose value is an error number.
Usage
The Err statement sets the current error number to an error number you specify. This may be any number in the range 0 to 32767 inclusive.
Error function
Returns an error message for either a specified error number or the current error.
Syntax
Error[$] [ ( errNumber ) ]
Elements
errNumber
304
A numeric expression whose value is an error number. If no errNumber is specified, LotusScript returns the message for the current (most recent) error.
Return value
Error returns a Variant, and Error$ returns a String. If no errNumber is specified, and there is no current error, the function returns the empty string (). You can call the Error function with no arguments as either Error or Error( ). You can call the Error$ function with no arguments as either Error$ or Error$( ).
Language cross-reference
@Error function in formula language @IsError function in formula language
Error statement
Signals an error number and its corresponding message.
Syntax
Error errNumber [ , msgExpr ]
Elements
errNumber A numeric expression whose value is a LotusScript-defined error number or a user-defined error number.
305
msgExpr Optional. A string expression containing an error message. This string replaces any existing message associated with the error number.
Usage
If errNumber is a LotusScript-defined error number, this Error statement simulates a LotusScript error. If it is not, this statement creates a user-defined error. When the Error statement is executed, LotusScript behaves as if a run-time error has occurred. If no error handling is in effect (set up by an On Error statement) for the specified error, execution ends and an error message is generated. The error message generated is msgExpr if it is specified. If msgExpr is omitted, the error message is the LotusScript error message for the specified error number, if that number designates a LotusScript error. Otherwise the message User-defined error is generated. User-defined errors must be in the range of 1000-1999. See LSERR.LSS for a list of LotusScript errors.
Syntax
Evaluate ( macro [ , object ] )
306
Elements
macro A string expression specifying the text of a Lotus software application macro, in the syntax that the product recognizes. Refer to the Lotus software documentation for the correct syntax of the macro. If the macro text is in a constant or string literal, the Lotus software application needs to do only initial processing of the macro once, at compile time, while variable strings incur that processing each time the macro is evaluated. object Optional. The name of a product object. Refer to the product documentation to determine if the macro requires an object, and what the object is.
Return value
If the Lotus software application macro being executed returns a value, the Evaluate function returns a Variant containing that value. Otherwise, the function does not return a value.
Sub Click(Source As Button) The macro text must be known at compile time. Const NotesMacro$ = "@Sum(NumberList) / @Elements(NumberList)" Dim result As Variant, j As Integer Dim db As New NotesDatabase("", "MYSALES.NSF") Dim dc As NotesDocumentCollection Dim doc As NotesDocument Set dc = db.AllDocuments For j% = 1 To dc.Count Set doc = dc.GetNthDocument(j%) result = Evaluate(NotesMacro$, doc) MessageBox("Average is " & result(0)) Next End Sub
Statement Syntax
Execute text
Function Syntax
Execute ( text )
Elements
text A string expression specifying the text to be compiled and executed.
Chapter 12. LotusScript Language Reference
307
Return value
The Execute function returns one of the following values: v The return code of an End statement, if one was executed. v Zero (0), if no End statement was executed, or if the executed End statement had no return value.
Usage
LotusScript considers text a separate script, compiling and executing it as a temporary module thats unloaded as soon as execution finishes. Variables declared in the calling script (where the Execute statement appears) are only accessible in the temporary module if they are declared Public. Both these Public variables, and variables declared Public in external modules used by the calling script, will be accessible automatically. To reference a local variable in the temporary module, use the CStr function to convert its value to a string, and then include the result in text. Variables declared in the temporary module are not accessible outside of that script. To delimit text that spans several lines or includes double-quote characters, use vertical bars (| |) or braces ({ }). Any compilation error in the temporary module will be reported as a run-time error in the scope containing the Execute statement. Any run-time error in the temporary module will be reported as a run-time error within the scope of that module, not the scope containing the Execute statement. To handle run-time errors within the temporary module, use the On Error statement. The Execute statement is not legal at the module level; you can use it only in procedures. Note: In Lotus Notes, if you modify a global variable in an Execute statement, the variable must be defined in the (Declarations) event for (Global), not the (Declarations) event for the object containing the script.
Sub DoCalc To handle any compilation error in the Execute statement On Error GoTo BadCalc Execute |Option Declare Dim x x is a Variant to accept any calculation. x = | & InputBox ("Enter your calculation") & | MessageBox "The result is " & x| Exit Sub Report an error and exit. BadCalc: MessageBox "Not a valid calculation" Exit Sub End Sub DoCalc Call the sub.
308
Sub ComputeInterest Dim script As String, calc As String, retcode As Integer calc$ = InputBox("Compute loan interest (charge/loan)") script$ = _ |Option Declare Sub Initialize Dim pct As Single pct! = | & calc$ & | If pct! < 0 Then End -2 -2 is a status code. ElseIf pct! > 1 Then End -3 -3 is a status code. End If MessageBox("Interest is " & Format(pct!,"percent")) End Sub| retcode% = Execute (script$) If retcode% = -2 Then MessageBox("You computed a negative interest rate!") ElseIf retcode% = -3 Then MessageBox("You computed an excessive interest rate!") End If End Sub ComputeInterest Call the sub.
Exit statement
Terminates execution of the current block statement.
Syntax
Exit blockType
Elements
blockType A keyword designating the type of the block statement for which execution is to be terminated. It must be one of the following keywords: Do For ForAll Function Sub Property
Usage
When LotusScript encounters this statement, it returns control to the scope containing the block statement for which execution is to be terminated. An Exit statement of a particular type is legal only within an enclosing block statement. LotusScript returns control from the innermost block statement or procedure of that type. However, the innermost block statement containing the Exit statement need not be of that type. For example, a function definition can include a For...Next block statement, and an Exit Function statement can appear within this statement. If LotusScript encounters the Exit Function statement during execution, control is returned immediately from the function, in which case the For...Next block statement is not executed to completion.
Chapter 12. LotusScript Language Reference
309
The following table shows the rules for transfer of control after the Exit statement.
Exit block type Exit Do Exit For Exit ForAll Exit Function Exit Sub Exit Property Execution continues At the first statement following the end of the Do block statement. At the first statement following the end of the For block statement. At the first statement following the end of the ForAll block statement. In the calling script, as it would from a normal return from the procedure. In the calling script, as it would from a normal return from the procedure. In the calling script, as it would from a normal return from the procedure.
If you exit a function or a Property Get without assigning a value to the function or property variable, that function or property returns the initialized value of the variable. Depending on the data type of the function or propertys return value, this value can be either 0, EMPTY, or the empty string ().
Language cross-reference
@Return function in formula language
Function AssignCode As String Dim code As String code$ = InputBox("Enter a 5-character code") If Len(code$) <> 5 Then Exit Function AssignCode = code$ It is a valid code. End Function If AssignCode() <> "" Then MessageBox "You entered a valid code." Else MessageBox "The code you entered is not valid." End If
Exp function
Returns the exponential(base e) of a number.
Syntax
Exp ( numExpr )
Elements
numExpr Any numeric expression, designating the power to which you wish to raise the value e. If the value of numExpr exceeds 709.78, LotusScript returns an overflow error.
Return value
Exp returns the exponential (base e) of numExpr. The data type of the return value is Double.
310
Usage
The value of e is approximately 2.71828182845905. Exp is the inverse function of Log.
Language cross-reference
@Exp function in formula language
FileAttr function
Returns the access type, or the operating system file handle, for an open file.
Syntax
FileAttr ( fileNumber , attribute )
Elements
fileNumber The number associated with the file when you opened it. attribute A number (either 1 or 2) specifying the type of information you want. Instead of 1 or 2, you can specify the constant ATTR_MODE or ATTR_HANDLE, respectively. These constants are defined in the file lsconst.lss. Including this file in your script allows you to use constants instead of their numeric values.
Return value
If attribute is ATTR_HANDLE, then FileAttr returns the operating system file handle for the file. If attribute is ATTR_MODE, then FileAttr returns an integer representing the access for the file, as shown in the following table.
Return value 1 2 4 8 32 Access Input Output Random Append Binary Constant ATTR_INPUT ATTR_OUTPUT ATTR_RANDOM ATTR_APPEND ATTR_BINARY
311
Open "data.txt" For Append As fileNum% hdl% = FileAttr(fileNum%, ATTR_HANDLE) Select Case FileAttr(fileNum%, ATTR_MODE) Case 1 : mode$ = "Input" Case 2 : mode$ = "Output" Case 4 : mode$ = "Random" Case 8 : mode$ = "Append" Case 32 : mode$ = "Binary" End Select Close fileNum% Print "DOS File Handle = "; hdl%; "Mode = "; mode$
FileCopy statement
Makes a copy of a file.
Syntax
FileCopy source , destination
Elements
source A string expression containing the name of the file you want to copy. The expression can optionally include a path. destination A string expression containing the name to be given to the copy. The expression can optionally include a path.
Usage
The file being copied must not be open. The source and destination strings cannot include wildcard characters. If destination names a file that already exists, the copy replaces the existing file with that name. To prevent this, you can use the Dir function to determine whether a file with the name destination already exists. Or, use the SetFileAttr statement to set the read-only attribute for the file.
FileDateTime function
Returns a string showing the date and time that a file was created or last modified.
Syntax
FileDateTime ( fileName )
312
Elements
fileName A string expression; you can include a path. fileName cannot include wildcard characters.
Return value
The returned date and time appear in the default format based on the operating systems international settings. If the file doesnt exist, FileDateTime returns an error.
FileLen function
Returns the length of a file in bytes.
Syntax
FileLen ( fileName )
Elements
fileName A string expression; you can optionally include a path. The fileName cannot contain wildcard characters.
Return value
FileLen returns a Long value.
Fix function
Returns the integer part of a number.
Syntax
Fix ( numExpr )
313
Elements
numExpr Any numeric expression.
Return value
Fix returns the value of its argument with the fractional part removed. The data type of the return value is determined by the data type of numExpr. The following table shows special cases.
numExpr NULL Variant containing a string interpretable as a number Variant containing a date/time value Return value NULL Double The date part of the value
Usage
The Fix function rounds toward 0: v For a positive argument, Fix returns the nearest integer less than or equal to the argument (if the argument is between 0 and 1, Fix returns 0). v For a negative argument, Fix returns the nearest integer larger than or equal to the argument (if the argument is between 0 and -1, Fix returns 0). The Fix function and the Int function behave differently. The return value from Int is always less than or equal to its argument. Tip: It is always true that Fix(numExpr) + fraction(numExpr) = numExpr.
For statement
Executes a block of statements a specified number of times.
314
Syntax
For countVar = first To last [ Step increment ] [ statements ] Next [ countVar ]
Elements
countVar A variable used to count repetitions of the block of statements. The data type of countVar should be numeric. first A numeric expression. Its value is the initial value of countVar. last A numeric expression. Its value is the final value of countVar. increment The value (a numeric expression) by which the countVar is incremented after each execution of the statement block. The default value of increment is 1. Note that increment can be negative.
Usage
After exit from a loop, the countVar for the loop has its most recent value.
315
Dim x As Integer Dim y As Integer For x% = 1 To 3 For y% = 1 To 2 Print x% ; Next Next y Next Next x Output: 1 1 2 2 3 3
If you dont include countVar as part of a For loop terminator (Next), LotusScript matches For loop delimiters from the most deeply nested to the outermost. LotusScript lets you combine For loop terminators when they are contiguous, as in the following example:
Dim x As Integer Dim y As Integer For x% = 1 To 3 For y% = 1 To 2 Print x% ; Next y%, x% Terminate the inner loop and then the outer loop. Output: 1 1 2 2 3 3
Language cross-reference
@For function in formula language
ForAll statement
Executes a block of statements repeatedly for each element of an array, a list, or a collection. A collection is an instance of a product collection class or an OLE collection class. Note: ForAll works on Product collections; it does not support Notes collections.
Syntax
ForAll refVar In container [ statements ] End ForAll
Elements
refVar A reference variable for the array, list, or collection element. In the body of the ForAll loop, you use refVar to refer to each element of the array, list, or collection named by container. refVar cant have a data type suffix character appended.
316
container The array, list, or collection whose elements you wish to process.
Usage
On entry to the loop, refVar refers to the first element of the array, list, or collection. On each successive iteration, refVar refers to the next element of the array, list, or collection. Upon completion of the loop, execution continues with the first statement following the loops End ForAll statement. Note: If youre using ForAll on an array of arrays, do not ReDim the iterator (this generates the Illegal ReDim error).
Using refVar
Since refVar is an alias for the actual array, list, or collection element, you can change the value of the element to which it refers by assigning a new value to refVar. For example:
ForAll x In y x = x + 1 End ForAll
This adds 1 to the value of each element in the array, list, or collection named y. If container is a list, you can pass refVar to the ListTag function to get the name (the list tag) of the list element that refVarcurrently refers to. For example:
Print ListTag(refVar)
Because refVar is implicitly defined by the ForAll statement, you should not include it in your variable declarations. The scope of refVar is the loop, so you cant refer to it from outside of the loop. If container is an array or list, refVar has the data type of the array or list being processed. If this data type cannot be determined by LotusScript at compile time or if container is a collection, refVar is a Variant. In that case, the data type of the array or list cannot be a user-defined data type, because Variants cannot be assigned values of a user-defined data type. You can reuse a refVarin a subsequent ForAll loop, provided that the data type of the container matches that of the container in the ForAll loop where refVar was first defined. You cant use the ReDim statement on the reference variable. For example, suppose that zArr is an array of arrays, and a ForAll statement begins:
ForAll inzArr In zArr
Language cross-reference
@Transform function in formula language
317
Example 2
Dim minima(5) As Integer minima%(0) = 5 minima%(1) = 10 minima%(2) = 15 Set all elements of array minima to 0. ForAll x In minima% x = 0 End ForAll
Example 3
In Freelance Graphics, an Application object contains a DocumentCollection object. The DocumentCollection object contains a collection of Document objects. Each Document object contains a PageCollection object. Each PageCollection object contains a number of Page objects. Each Page object contains an ObjectCollection object. ObjectCollection is a heterogenous collection that may include TextBox objects. In addition to For loops, you can use ForAll loops or indexing to access individual members of a collection class. This example uses three nested ForAll loops to iterate through the collections. Within individual TextBlock objects, the script uses indexing to set list entries at levels 2 through 5 in each TextBox object to Italic.
Dim level As Integer ForAll doc In [Freelance].Documents ForAll pg In Doc.Pages ForAll obj In Pg.Objects If the object is a TextBlock, set the font to Garamond, and set list entries at levels 2 through 5 to Italic. If obj.IsText Then obj.Font.FontName = "Garamond" For level% = 2 To 5 obj.TextProperties(level%).Font.Italic = TRUE Next level% End If End ForAll End ForAll End ForAll
The Application class Documents property returns an instance of the DocumentCollection class. Each element in the collection is a document, an instance of the Document class. The Document class Pages property returns an instance of the PageCollection class. Each element in the collection is a page, an instance of the Page class. The Page Objects property returns an instance of the ObjectCollection class. Some of the elements in this collection may be text blocks, instances of the TextBox class.
318
Format function
Formats a number, a date/time, or a string according to a supplied format.
Syntax
Format[$] ( expr [ , fmt ] )
Elements
expr Any expression. The expression is evaluated as a numeric expression if fmt is a numeric format, as a date/time if fmt is a date/time format, and as a string if fmtis a string format. fmt Optional. A format string: either a string consisting of the name of a format pre-defined in LotusScript, or else a string of format characters. If this format string is not supplied, Format[$] behaves like Str[$], omitting the leading space character for positive numbers.
Return value
Format returns a Variant containing a string, and Format$ returns a String. If expr is a string and fmt is a numeric format string, LotusScript attempts to convert the string to a number. If successful, LotusScript then formats the result. If the string cant be converted to a number, LotusScript attempts to interpret it as a date/time, and attempts to convert it to a numeric value. If successful, LotusScript then formats the result. If expr cant be converted to the data type of the format string, Format returns expr without formatting it.
319
Display of the value of expr is ... In standard scientific notation: with one digit to the left of the decimal separator and two digits to the right of the decimal separator, followed by the letter E or e and a number representing the exponent. No if the number is 0, and Yes otherwise. False if the number is 0, and True otherwise. Off if the number is 0, and On otherwise.
% (percent sign)
, (comma)
- + ( ) space
320
Meaning Literal character prefix. The character following the backslash is displayed as is; for example, \# displays #. To display a backslash itself, precede it with another backslash; that is, \\ displays \. Literal string enclosed in double quotation marks. To specify the double quotation mark character in the fmt argument, you must use Chr(34). The characters enclosed in quotation marks are displayed as they appear in the format string.
ABC
; (semicolon)
Format section separator. Separates the positive, negative, zero, and NULL sections in fmt. If you omit the negative or zero format sections, but include the semicolons representing them, they are formatted like the positive section.
A custom format string for numeric values can have from one to four sections, separated by semicolons. In a format string with more than one section, each section applies to different values of expr. The number of sections determines the values to which each individual section applies. The following table describes how each section of a one-part or multi-part format string is used.
Number of sections One Two Three Four Description The format applies to all numbers. The first section formats positive numbers and 0. The second section formats negative numbers. The first section formats positive numbers. The second section formats negative numbers. The third section formats 0. The first section formats positive numbers. The second section formats negative numbers. The third section formats 0. The fourth section formats NULL.
Date/time formats
Since date/time values are stored as floating point numbers, date/time values can be formatted with numeric formats. They can also be formatted with date/time formats. You can either use one of the named date/time formats shown in the following section, or create a custom date/time format using the date/time formatting codes shown in the subsequent section.
Long Date Medium Date Short Date Long Time Medium Time Short Time
321
/ (slash)
dddddd
w ww m mm mmm mmmm q yy
yyyy h hh n nn s ss ttttt
322
Meaning Uses hour values from 1 to 12, displaying AM or am for hours before noon, and PM or pm for hours after noon. Uses hour values from 1 to 12, displaying A or a for hours before noon, and P or p for hours after noon. Uses hour values from 1 to 12. Displays the contents of the 1159 string (s1159) in WIN.INI for hours before noon, and the contents of the 2359 string (s2359) for hours after noon. AMPM is case-insensitive, but the case of the string displayed matches the string as it exists in the operating systems international settings. The default format is AM/PM.
The following table shows some custom date/time formats applied to one date and time: 6:43:04 in the evening of April 12, 1995.
fmt m/d/yy d-mmm-yy d-mmmm mmmm-yy y hh:mm AM/PM h:mm:ss a/p h:mm h:mm:ss m/d/yy h:mm Display 4/12/95 12-Apr-95 12-April April-95 102.00 06:43 PM 6:43:04 p 18:43 18:43:04 4/12/95 18:43
323
This table shows the formatting codes for Peoples Republic of China.
Formatting code aaaa O o A a E e EE ee Meaning Weekday in full format (three double-byte characters) Month (double-byte) Month (single-byte) Day (double-byte) Day (single-byte) Short year (double-byte) Short year (single-byte) Long year (double-byte) Year (single-byte)
This table shows the formatting codes for the Taiwan region.
Formatting code aaaa O o Meaning Weekday in full format (three double-byte characters) Month (double-byte) Month (single-byte)
324
Meaning Day (double-byte) Day (single-byte) Year in era (double-byte) Year in era (single-byte) Year in era with era abbreviation (double-byte) Year in era with era abbreviation (single-byte) Year in era with era name (double-byte) Year in era with era name (single-byte) Christian year with Christian era name (double-byte) Christian year with Christian era name (single-byte)
Dim rev As Currency, expense As Currency, bal As Currency rev@ = CCur(InputBox("How much did we make this month?")) expense@ = CCur(InputBox("How much did we spend?")) bal@ = rev@ - expense@ MessageBox "Our balance this month is " _ & Format(bal@, "Currency") Percent Dim total As Integer, attend As Integer, percent As Double total% = CInt(InputBox("How many people registered?")) attend% = CInt(InputBox("How many people actually attended?")) percent# = attend% / total% MessageBox "The attendance was " _ & Format(percent#, "Percent") MessageBox "The attendance was " _ & Format(percent#, "0%") Use custom format codes can carry % to any number of places: Use "Percent" format
Example of custom formatting using sections Dim x As Integer x = 1 Print Format(x, "0.0;0%") Output: 1.0 x = -1 Print Format(x, "0.0;0%") Output: 100%
Chapter 12. LotusScript Language Reference
325
x = 0 Print Format(x, "0.0;0%;zippo") Output: zippo Print chr$(34) & Format(x, "zippo") & chr$(34) Output: "zippo" Yes/No, True/False, & On/Off Dim value As Integer value = 0 Print Format$(value, "Yes/No") Print Format$(value, "On/Off") value = 2 Print Format$(value, "Yes/No") Print Format$(value, "On/Off") Date and Time formats x = 36525 Print Format(x, "General Date") Print Format(x, "Long Date") Print Format(x, "Medium Date") Print Format(x, "Short Date") y = 123.45 Print Format(y, "Long Time") Print Format(y, "Medium Time") Print Format(y, "Short Time") Custom String formats Dim x As String, y As String, z As String Format directory string x = "dtemp" Print Format(x, "!copy to directory @:\\@") Output: copy to directory d:\temp Use sections and NULL data Print Format(y, "!copy to directory @:\\@;dont copy - no valid data") Output: dont copy - no valid data Manipulate character positions dim x as string, y as string, z as string x = "hello world" y = "hello" z = "world" Print Format(x, "!@") Output: hello world print format(y, "&&&&&&&&&&" & z) Output: "helloworld" (& ignores non-characters) print format(y, "!&&&&&&&&&&" & z) Output: "helloworld" (! matters not with &) print format(y, "@@@@@@@@@@" & z) Output: " Format all characters to lower then upper case z = "Hello World" Print Format(z, "<") Print Format(z, ">") Output: hello world Output: HELLO WORLD helloworld" world" print format(y, "!@@@@@@@@@@" & z) Output: "hello Output: 10:48:00 AM Output: 10:48 AM Output: 10:48 Output: 12/31/1999 Output: 31-Dec-99 Output: 12/31/99 Output: Friday, December 31, 1999 Output "Yes" Output "On" Output "No" Output "Off"
326
Fraction function
Returns the fractional part of a number.
Syntax
Fraction ( numExpr )
Elements
numExpr Any numeric expression.
Return value
The data type of the return value is the same as the data type of numExpr.
Usage
The following table shows special cases of the return value:
numExpr A date/time value An integer NULL Return value The time portion 0 NULL
FreeFile function
Returns an unused file number.
Syntax
FreeFile
Return value
FreeFile returns an Integer value.
327
Usage
Use FreeFile when you need a file number (to open a file), but you dont know what file numbers are currently available. If no more file numbers are available, an error is generated. LotusScript limits the number of open files to 255. Depending on your operating system environment and the Lotus software you are running, the actual number of files that you can open may be 15 or less. See your product documentation for details. You can call the function as either FreeFile or FreeFile().
FullTrim function
Given an array, eliminates empty entries and eliminates duplicate, trailing and leading whitespace within entries; and given a string, eliminates duplicate, trailing and leading whitespace in the string.
Syntax
FullTrim( v )
Element
v Any array, string, or variant containing a string.
Return value
A variant containing an array or string. If you pass in a string, you get back a string. If you pass in an array, you get back an array.
Usage
Empty for strings is the Empty string. Empty for numbers is the value 0. Empty for variants containing the above are the same, as well as NULL and Empty. The FullTrim trims strings by eliminating any duplicate whitespaces (SPACE, TAB, NEWLINE) from the center of the string and all whitespace at the beginning and end of the strings. The number of elements in the returned array may vary as empty elements are removed. If all the elements are removed, an array with one empty element is returned.
328
Function statement
Defines a function.
Syntax
[ Static ] [ Public | Private ] Function functionName [ ( [ paramList ] ) ] [ As returnType ] [ statements ] End Function
Elements
Static Optional. Specifies that the values of the functions local variables are saved between calls to the function. Public | Private Optional. Public specifies that the function is visible outside the scope (module or class) where the function is defined, as long as that remains loaded. Private specifies that the function is visible only within the current scope. A function in module scope is Private by default; a function in class scope is Public by default. functionName The name of the function. This name can have a data type suffix character appended, to declare the type of the functions return value. paramList Optional. A comma-separated list of declarations indicating the parameters to be passed to this function in function calls. The syntax for each parameter declaration is: [ ByVal ] parameter [ ( ) | List ] [ As type ] ByVal means that parameter is passed by value: that is, the value assigned to parameter is a local copy of a value in memory, rather than a pointer to that value. parameter () is an array variable. parameter List identifies parameter as a list variable. Otherwise, parameter can be a variable of any of the other data types that LotusScript supports. As dataType specifies the variables data type. You can omit this clause and append a data type suffix character to parameter to declare the variable as one of the scalar data types. If you omit this clause and parameter has no data type suffix character appended (and isnt covered by an existing Deftype statement), its data type is Variant. Enclose the entire list of parameter declarations in parentheses. returnType
329
Optional. The data type of the value returned by the function. returnType can be any of the scalar data types, or Variant, or a class name. If As returnType is not specified, the function names data type suffix character determines the return values type. Do not specify both a returnType and a data type suffix character; LotusScript treats that as an error. If you omit returnType and the function name has no data type suffix character appended, the function returns a value either of data type Variant or of the data type specified by a Deftype statement.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). Arrays, lists, type instances, and objects cant be passed by value as arguments. They must be passed by reference. To return a value from a function, assign a value to functionName within the body of the function definition (see the example). If you assign an array to functionName, you cannot refer to an element of functionName within the body of the function; such a reference will be taken as a recursive call of the function. To refer to an element of functionName, assign functionName to a variant variable and index the element there. A function returns a value; a sub does not. To use the value returned by a function, put the function call anywhere in an expression where a value of the data type returned by the function is legal. You dont have to use the value returned by a function defined by the Function statement. (The value returned by a built-in function must be used.) To call a function without using the return value, use the Call statement. A function definition cannot contain another function or sub definition, or a property definition. A function member of a class cannot be declared Static. You can exit a function using an Exit Function statement. Note: If youre using a 32-bit version of Windows, an integer has four bytes; use the short integer (two bytes) to correspond to the LotusScript Integer when passing data to LotusScript. This note applies to Windows platforms only.
330
Dim price As Single, message As String Function Payment (princpl As Single, _ ByVal intrst As Single, _ ByVal term As Integer) As Single intrst! = intrst! / 12 term% = term% * 12 If any of the arguments are invalid, exit the function (payment will return the value 0). If princpl! <= 0 Or intrst! <= 0 Or term% < 1 Then _ Exit Function The standard formula for computing the amount of the periodic payment of a loan: Payment = princpl! * intrst! / (1 - (intrst! + 1) ^ _ (-term%)) End Function Sub ComputeMortgageCosts (price As Single) Dim totalCost As Single, downpmt As Single Dim mortgage As Single, intrst As Single Dim monthlypmt As Single, years As Integer EnterInfo: downpmt! = CSng(InputBox ("How much is the down payment?")) The downpayment must be at least 10% of the price. If downpmt! < (0.1 * price!) Then MessageBox "Your down payment must be at least " _ & Format(price! * .1, "Currency") GoTo EnterInfo Else mortgage! = price! - downpmt! End If intrst! = CSng(InputBox("What is the interest rate?")) years% = CInt(InputBox("How many years?")) Call the Payment function, which returns the monthly payment. monthlypmt! = Payment(mortgage!, intrst!, years%) totalCost! = downpmt! + (monthlypmt! * years% * 12) If monthlypmt! > 0 Then Create a multiline message. message$ = _ |Price | & Format(price!, "Currency") & | Down Payment: | & Format(downpmt!, "Currency") & | Mortgage: | & Format(mortgage!, "Currency") & | Interest: | & Format(intrst!, "Percent") & | Term: | & Str(years%) & | years Monthly Payment: | & Format(monthlypmt!, _ "Currency") & | Total Cost: | & Format(monthlypmt! * years% * 12, _ "Currency") Else message$ = "You did not enter valid input." End If End Sub Start here. price! = CSng(InputBox("How much does the house cost?")) Call the Compute MortgageCosts sub. ComputeMortgageCosts (price!) Display the message. MessageBox message$
Get statement
Reads data from a binary file or a random file into a variable.
331
Syntax
Get # fileNumber , [ recordNumber ] , variableName
Elements
fileNumber The number assigned to the file when it was opened with the Open statement. Note that the pound sign (#), fileNumber, and variableName are all required. recordNumber Optional. The file position (the byte position in a binary file, or the record number in a random file) where data retrieval begins. If you omit recordNumber, LotusScript retrieves data beginning from the current file position. variableName The variable to be used for storing the retrieved data. variableName cannot be an array. However, a fixed-length array defined within a data type is allowed (this array could also contain other arrays as elements).
Usage
The first byte or record in a file is always file position 1. After each read operation, the file position is advanced: v For a binary file, by the size of the variable v For a random file, by the size of a record The Get statement reads data into variableName depending on the variables data type. The following table shows how the Get statement behaves for different data types.
variableName data type Variant Get statements behavior The Get statement interprets the first two bytes as the DataType of the data to be read. If the DataType is EMPTY or NULL, the Get statement stops reading data and sets variableName to EMPTY or NULL. If the DataType is numeric, the Get statement reads the appropriate number of bytes used to store data of that Data Type: Byte: 1 byte Boolean: 2 bytes Integer: 2 bytes Long: 4 bytes Single: 4 bytes Double: 8 bytes Currency: 8 bytes Date/time: 8 bytes Fixed-length string The Get statement reads the specified number of characters. For example, if a variable is declared as String*10, the Get statement reads exactly 10 characters.
332
Get statements behavior The Get statement behaves differently, depending on the type of file youre using. Random file: The first two bytes read indicate the strings length. The Get statement reads exactly that number of characters. If variableName is larger than a random file record, data is read from the file until variableName is filled. After variableName is filled, the file position is advanced to the next record. Binary file: The number of bytes read from the file is equal to the length of the string currently assigned to variableName. If variableName has not been initialized, no data is read from the file.
The number of bytes required to read the data is the sum of the number of bytes required to read all members of the used-defined data type, which cannot contain a dynamic array, a list, or an object.
Note: Even though strings in LotusScript 4 can be longer than 64K, there are still restrictions with the length of the string you can read or write using the GET and PUT statements. The only combination of filetypes that will work with long strings is with a binary file and a variable-length string. Fixed length strings, strings in variants, and random files will not work with strings greater than 64K in length because they have a two-byte header which contains the length of the string. Two bytes cannot represent more than 64K.
333
Prints three records: 123 John Smith 456 Jane Doe 789 Jack Jones
GetFileAttr function
Retrieves file-system attributes of a file or directory.
Syntax
GetFileAttr ( fileName ) GetAttr is acceptable in place of GetFileAttr.
Elements
fileName The name of a file or directory. File and directory names can optionally include paths.
Return value
The return value is the sum of the Integer values in the following list for those attributes that apply to fileName:
Value 0 1 2 4 16 32 Attribute Normal file Read-only file Hidden file System file Directory File that has changed since it was last backed up (archived) Constant ATTR_NORMAL ATTR_READONLY ATTR_HIDDEN ATTR_SYSTEM ATTR_DIRECTORY ATTR_ARCHIVE
Usage
The constants in the preceding list are defined in the file lsconst.lss. Including this file in your script allows you to use constant names instead of their numeric values.
334
If (attr% And ATTR_HIDDEN) Then msg$ = msg$ & " Hidden " If (attr% And ATTR_SYSTEM) Then msg$ = msg$ & " System " If (attr% And ATTR_DIRECTORY) Then msg$ = msg$ & " Directory " Print msg$ SetFileAttr fileName$, ATTR_NORMAL Kill fileName$ Reset to normal.
GetObject function
Opens an OLE Automation object contained in an application file, or returns the currently active OLE Automation object of the specified class. Note: GetObject is not supported under OS/2 or UNIX. It is supported on the Macintosh as long as OLE support is installed.
Syntax
GetObject ( [pathName] [ , className])
Elements
pathName Either a string containing the full path and file name of an application file or an empty string. The application must support OLE Automation. If pathName is the empty string () or is missing, you must specify a className. className A string of the form appName.appClass that identifies the application in which the class is defined and the class of the object to retrieve (for example, WordPro.Application). appName is the name of an application that supports OLE Automation. appClass is the name of the class of which you want to retrieve an instance.
Return value
GetObject returns an OLE Automation object reference.
Usage
Use the Set statement to assign the object reference returned by GetObject to a Variant variable. If the application specified by appName is not already running, GetObject starts it before retrieving the OLE Automation object. References to the object remain valid only while the application is running. If the application terminates while you are using the object reference, LotusScript generates a run-time error. If pathName is the empty string () or is missing, GetObject retrieves the currently active object of the specified class. If no object of that class is active, an error occurs. If className is omitted, GetObject determines the application to run and the object to retrieve based on the pathName. This form of GetObject is useful only when the application file contains a single object. Each product that supports OLE Automation provides one or more classes. See the products documentation for details. LotusScript supports the following return types for OLE properties and methods. Only an OLE method or property can return a type designated as OLE only.
Chapter 12. LotusScript Language Reference
335
OLE return type VT_EMPTY VT_NULL VT_I2 VT_I4 VT_R4 VT_R8 VT_CY VT_DATE VT_BSTR VT_DISPATCH VT_ERROR VT_BOOL VT_DECIMAL VT_VARIANT VT_UNKNOWN VT_ARRAY
Description (No data) (No data) 2-byte signed integer 4-byte signed integer 4-byte real 8-byte real Currency Date String IDispatch, OLE only Error, OLE only Boolean Decimal, converted to Double (A reference to data of any other type) IUnknown, OLE only (An array of data of any other type)
Note: If the application specified by appName is registered as a single-instance object, call CreateObject to get that object as GetObject will cause an error. This is different from Visual Basic; in Visual Basic, if GetObject is called with an empty string as first parameter, it behaves the same as CreateObject. You can use a ForAll loop to iterate over the members of OLE collections. LotusScript supports passing arguments to OLE properties. For example:
Set v.prop to 4; v.prop takes two arguments. v.prop(arg1, arg2) = 4
LotusScript does not support identifying arguments for OLE methods or properties by name rather than by the order in which they appear, nor does LotusScript support using an OLE name by itself (without an explicit property) to identify a default property. Results are unspecified for arguments to OLE methods and properties of type boolean, byte, and date that are passed by reference. LotusScript does not support these data types. The word GetObject is not a LotusScript keyword.
The following script works on the Mac with Microsoft Word installed.
Sub Initialize Dim myDoc As Variant Dim filename As String
336
filename = "MKashG4HD:MSTestDoc" Get the Word.Document object from a file. Set myDoc = GetObject(filename,"Word.Document") Make the object visible myDoc.Application.Visible = True End Sub
GetThreadInfo function
Returns system information about the thread.
Syntax
GetThreadInfo (Dim InfoID as Integer)
Elements
InfoID Information to be returned
Return values
Data A variant containing the information to be returned.
Usage
Pass any of the LSI_ constants from the table below to GetThreadInfo to have it return the current value of that constant.
Code LSI_THREAD_LINE LSI_THREAD_PROC LSI_THREAD_MODULE LSI_THREAD_VERSION LSI_THREAD_LANGUAGE LSI_THREAD_COUNTRY LSI_THREAD_TICKS LSI_THREAD_TICKS_PER_SEC LSI_THREAD_PROCESS_ID LSI_THREAD_TASK_ID LSI_THREAD_CALLPROC LSI_THREAD_CALLMODULE Meaning Current Line Number Name of current procedure Name of current module LotusScript version number (Human) language setting Country or region setting Get current clock ticks Get clock ticks per second (supported only on platforms that support parallel processing primitives) Get current process ID (supported only on platforms that support parallel processing primitives) Get current task ID (supported only on platforms that support parallel processing primitives) Get the name of the calling procedure Get the name of the calling module
The values of the constants are defined in LSPRVAL.LSS, which is automatically included through LSCONST.LSS.
337
GoSub statement
Transfers control in a procedure to a labeled statement, with an optional return of control.
Syntax
GoSub label
Elements
label The label of a statement to which you want to transfer control.
Usage
You cant use the GoSub statement at the module level; you can only use it in a procedure. The GoSub statement, its label, and the Return statement must all reside in the same procedure. When LotusScript encounters a GoSub statement, execution branches to the specified labeled statement and continues until either of two things happen: v LotusScript encounters a Return statement, at which point execution continues from the statement immediately following the GoSub statement. v LotusScript encounters a statement such as Exit or GoTo, which passes control to some other part of the script.
Sub GetName Dim yourName As String, Message As String yourName$ = InputBox$("What is your name?") If yourName$ = "" Then The user enters nothing. GoSub EmptyString Do a case-insensitive comparison. ElseIf LCase(yourName$) = "john doe" Then GoSub JohnDoe Else Message$ = "Thanks, " & yourName$ _ & ", for letting us know who you are." End If The Return statements return control to the next line. MessageBox Message$ Exit Sub
338
EmptyString: yourName$ = "John Doe" Message$ = "Okay! As far as were concerned, " _ & "your name is " & yourName$ & _ ", and youre on the run!" Return JohnDoe: Message$ = "Were on your trail, " & yourName$ _ & ". We know you are wanted dead or alive!" Return End Sub GetName Call the GetName sub.
GoTo statement
Transfers control within a procedure to a labeled statement.
Syntax
GoTo label
Elements
label A label of a statement to which you want to transfer control.
Usage
You cant use the GoTo statement at the module level; you can only use it in a procedure. You cant use GoTo to transfer control into or out of a procedure or a With...End With block. Use the GoTo statement to transfer control to any labeled statement that does not violate either of the preceding rules.
339
MessageBox "You entered 1." Exit Sub label2: MessageBox "You entered 2." Exit Sub label3: MessageBox "You entered 3." Exit Sub An error condition has occurred. OutOfRange: MessageBox "The value you entered is negative, " _ & "greater than 255, or is not a number. Try again!" GoTo EnterNum End Sub OneTwoThree Call the OneTwoThree sub.
Hex function
Return the hexadecimal representation of a number as a string.
Syntax
Hex[$] ( numExpr )
Elements
numExpr Any numeric expression. If numExpr evaluates to a number with a fractional part, LotusScript rounds it to the nearest integer before deriving its hexadecimal representation.
Return value
Hex returns a Variant of DataType 8 (String), and Hex$ returns a String. Return values will only include the characters 0 - 9 and A - F, inclusive. The maximum length of the return value is eight characters.
Usage
If the data type of numExpr is not Integer or Long, LotusScript attempts to convert it to a Long. If it cannot be converted, an error occurs.
Hour function
Returns the hour of the day for a date/time argument as an integer from 0 to 23.
Syntax
Hour ( dateExpr )
340
Elements
dateExpr Any of the following: v A valid date/time string of String or Variant data type. For Notes or Domino, LotusScript interprets a 2-digit year designation in a date/time string so that 50 through 99 represent the years 1950 through 1999 and 00 through 49 represent the years 2000 through 2049. For SmartSuite, LotusScript interprets the years differently. For more information, see the SmartSuite online Help entry entitled Year 2000. v A number within the valid date range: the range -657434 (Jan 1, 100 AD) to 2958465 (Dec 31, 9999 AD), inclusive. v NULL
Return value
Hour returns a Variant containing a value of DataType 2 (Integer). If the dateExpr is a Variant containing the value NULL, then Hour returns NULL.
Language cross-reference
@Hour function in formula language
If...GoTo statement
Conditionally executes one or more statements or transfers control to a labeled statement, depending on the value of an expression.
Syntax
If condition GoTo label [ Else [ statements ] ]
Elements
condition Any numeric expression. A value of 0 is interpreted as FALSE, and any other value is interpreted as TRUE.
341
Usage
An If...GoTo statement must occupy a single line of code. Line continuation with the underscore character ( _ ) is allowed. If condition is TRUE, LotusScript executes the GoTo statement, transferring control to the statement following the label label. If condition is FALSE, LotusScript executes the block of statements in the Else clause. If there is no Else clause, execution continues with the next statement. You cant use an If...GoTo statement to transfer control into or out of a procedure, and you cant use it at the module level.
Language cross-reference
@If function in formula language @V2If function in formula language @Failure function in formula language
If...Then...Else statement
Conditionally executes one or more statements, depending on the value of an expression.
342
Syntax
If condition Then [ statements ] [ Else [ statements ] ]
Elements
condition Any numeric expression. A value of 0 is interpreted as FALSE, and any other value is interpreted as TRUE. statements A series of statements, separated by colons.
Usage
An If...Then...Else statement must occupy a single line of code. Line continuation with the underscore character (_) is allowed. If condition is TRUE, the statements following Then, if any, are executed. If condition is FALSE, the statements following Else are executed. If no statements follow Then, and there is no Else clause, Then must be followed by a colon (:). Otherwise LotusScript assumes that the statement is the first line of an If...Then...Else...End If statement.
Language cross-reference
@If function in formula language @V2If function in formula language
If...Then...ElseIf statement
Conditionally executes a block of statements, depending on the value of one or more expressions.
Syntax
If condition Then statements [ ElseIf condition Then statements ] ... [ Else
343
statements ] End If
Elements
condition Any numeric expression. A value of 0 is interpreted as FALSE, and any other value is interpreted as TRUE. statements Statements that are executed if condition is TRUE.
Usage
LotusScript executes the statements following the Then keyword for the first condition whose value is TRUE. It evaluates an ElseIf condition if the preceding condition is FALSE. If none of the conditions is TRUE, LotusScript executes the statements following the Else keyword. Execution continues with the first statement following the End If statement. You can include any number of ElseIf expressions in the block. You can include an If statement within an If statement. Each If block must be terminated by an End If.
Language cross-reference
@If function in formula language @V2If function in formula language
%If directive
Conditionally compiles a block of statements, depending on the value of one or more product constants.
Syntax
%If productConst statements
344
Elements
productConst A constant defined by a Lotus software application, or one of the platform-identification constants described below. Refer to the products documentation for a list of product-defined constants. statements Statements that are compiled if productConst evaluates to TRUE.
Usage
You cannot enter %If, %ElseIf, %Else, and %End If directly in the IDE. You must enter these directives in a file and insert the file in the IDE with the %Include directive. productConst must appear on the same line as %If or %ElseIf. Nothing except a comment can appear on the same line following %If productConst or %ElseIf productConst, or on the same line with %Else or %End If. None of these lines can be continued with the underscore character (_). To test each %If condition or %ElseIf condition in this statement, the LotusScript compiler calls the Lotus software application to evaluate the constant productConst. The product returns either TRUE (-1) or FALSE (0). A condition is evaluated only if the product returns FALSE for the preceding condition. LotusScript compiles the statements for the first %If condition or %ElseIf condition that the product evaluates as TRUE. Once this happens, no further conditions are evaluated, and no further statements are compiled. If neither the %If condition nor any %ElseIf condition evaluates to TRUE, the %Else statements (if any) are compiled. You can include any number of %ElseIf directives in the block. You cant include an %If block within an %If block. LotusScript implements the constants in the following table as product #defines. When one of these is used as productConst, the LotusScript compiler does not call the product to evaluate productConst. LotusScript itself evaluates the constant as TRUE or FALSE. The value of each constant depends on the platform LotusScript is running on.
Constant WIN16 WIN32 WINNT Platform or functionality Windows with 16-bit API (Windows 3.1) Windows with 32-bit API (Windows NT or Windows 95) Windows NT
Chapter 12. LotusScript Language Reference
345
Constant WIN95 WIN40 WIN98 WIN2K WINDOWS HPUX SOLARIS UNIX OS2 LINUX MAC OLE MAC68K MACPPC OS400 OS390 ZOS
Platform or functionality Windows 95 Windows 95 or Windows NT 4.0 Windows 98 Windows 2000 Any Windows platform type (any of the above WINxxconstants) HP/UNIX 9.X or greater Sun/OS 5.0 or greater Any UNIX type (HP_UX or Solaris) OS/2, version 2.0 or greater Linux Macintosh System 7 OLE-2 is available Macintosh Motorola 68000 version (running on either a 68xxx Macintosh or the PowerPC) Macintosh PowerPC version IBM AS400 IBM S/390 User System Services IBM z/OS (OS390 is also TRUE)
For example, here are several platforms and the constants that identify them: Windows 3.1 WIN16, WINDOWS Windows 95 WIN32, WIN95, WIN40, WINDOWS HP/UNIX 9.X HPUX, UNIX OS/2 2.0 or greater OS2
346
Declare Function GetActiveWindow% Lib "User" () Declare Function GetWindowText% Lib "User" _ (ByVal hWnd%, ByVal lpstr$, ByVal i%) %ElseIf WIN32 32-bit Windows Dim activeWin As Long Window handles are Long. Declare Function GetActiveWindow& Lib "User32" () Declare Function GetWindowText% Lib "User32" _ Alias "GetWindowTextA" _ (ByVal hWnd&, ByVal lpstr$, ByVal i&) %End If Print the name of the currently active window. activeWin = GetActiveWindow() Returns an Integer or a Long. Call GetWindowText(ActiveWin, winTitle$, 80) Print winTitle$
IMESetMode function
Changes the current input mode (IME) into the mode user specified at its parameter. IMESetMode is supported for Windows DBCS system only.
Syntax
IMESetMode ( IMEMode )
Elements
IMEMode Integer value for the desired IME mode user prefer to set. You can specify the values listed in the following table for the IMEMode parameter.
Country or Region All Constant IME_ON IME_OFF Japan IME_HIRAGANA IME_KATAKANA_DBCS IME_KATAKANA_SBCS IME_ALPHA_DBCS IME_ALPHA_SBCS Taiwan IME_NATIVE_MODE IME_ALPHA_DBCS IME_ALPHA_SBCS Korea IME_HANGEUL IME_HANJACONVERT IME_ALPHA_DBCS IME_ALPHA_SBCS PRC IME_NATIVE_MODE IME_ALPHA_DBCS IME_ALPHA_SBCS Value 1 2 4 5 6 7 8 4 7 8 4 5 7 8 4 7 8 Description Set IME on Set IME off Double-byte Hiragana Double-byte Katakana Single-byte Katakana Double-byte alphanumeric Single-byte alphanumeric Taiwan native mode Double-byte alphanumeric Single-byte alphanumeric Hangeul DBC Hanja conversion Double-byte alphanumeric Single-byte alphanumeric PRC native mode Double-byte alphanumeric Single-byte alphanumeric
347
Return values
TRUE IME mode has been set successfully. FALSE Unable to set IME correctly, or unable to find IME on the system.
Usage
IMESetMode is available on interactive execution of LotusScript. The IMESetMode function is related with the IMEStatus function and generally used with it. The IMESetMode function is expected to be used upon the Entering event of a Notes field.
Examples: IMESetMode
In this example when the user moves the cursor into a field, IME is automatically invoked into HIRAGANA input mode. When the user moves from the field, IME resets to its original status.
Public InitIMEMode As Integer Sub Entering ( Source As Field ) InitIMEMode = IMEStatus If InitIMEMode <> IME_HIRAGANA Then Call IMESetMode ( IME_HIRAGANA ) End If End Sub Sub Exiting ( Source As Field ) If InitIMEMode <> IMEStatus Then Call IMESetMode ( InitIMEMode ) End If End Sub
IMEStatus function
Returns an integer indicating the current input mode (IME) for extended character sets. Note that IMEStatus is supported for Windows DBCS only. The codes for PRC and the Taiwan region are supported on Win95 only.
Syntax
IMEStatus
Return value
The function returns a status code indicating the current input mode (IME).
Usage
IMEStatus provides support for languages that use extended character sets. The code returned depends on the country for which the Lotus software application is built. The following table describes the return values. For countries not listed in the table, the return value is 0.
Country or Region All Constant IME_NOT_INSTALLED IME_ON Value 0 1 Description IME is not installed IME is on
348
Country or Region
Constant IME_OFF
Value 2 4 5 6 7 8 4 7 8 4 5 7 8 4 7 8
Description IME is off Double-byte Hiragana Double-byte Katakana Single-byte Katakana Double-byte alphanumeric Single-byte alphanumeric Taiwan native mode Double-byte alphanumeric Single-byte alphanumeric Hangeul DBC Hanja conversion Double-byte alphanumeric Single-byte alphanumeric PRC native mode Double-byte alphanumeric Single-byte alphanumeric
Japan
Taiwan
Korea
PRC
Example
See IMESetMode.
Implode function
Concatenates all members of an Array of Strings and returns a string. Elements of the Array are separated by a delimiter, if provided, or the space character ( ). Note: This function is new with Domino Release 6.
Syntax
Implode( sourceArray , [delimiter])
Elements
sourceArray One-dimensional Array containing the substrings to be concatenated. sourceArray can be an array of Strings, or an array of Variants. If sourceArray is an array of Variants, Implode will attempt to convert any non-string elements to Strings. delimiter Optional String containing separation character(s) for the concatenated Strings
Return value
Implode returns a String containing the elements of sourceArray with delimiter between elements, or with the space character as a separator if delimiter is not specified.
349
Usage
Implode creates a String that will hold the concatenation of sourceArray. Implode then iterates through sourceArray, With each iteration, Implode converts the next element of sourceArray to a String, if necessary, and appends it to the concatenation String. If more elements remain in sourceArray, a delimeter (either or the specified value) is appended to the concatenation String and Implode continues to iterate. After all elements of sourceArray have been concatenated, Implode returns the concatenation String.
Error handling
Implode will throw a Run-time Type mismatch if: v an element in a variant array cannot be coerced to a string. v the delimiter is set to nothing. v the array passed in is not of either type string or variant. v a list is passed instead of an array. v the array passed in contains an element set to nothing. v the array passed in has not been properly initialized. Implode will throw a run-time Wrong Number of Dimensions error if the array is not one-dimensional. Implode will throw a run-time Invalid Use of Null error if the array passed in contains an element set to null or if the delimiter is set to null. Note: Implode is an alias of Join and is identical in every way.
%Include directive
At compile time, inserts the contents of a text file into the module where the directive appears.
Syntax
%Include fileName
Elements
fileName A string literal whose value is a file name; you can optionally include a path.
350
If you omit the file name extension, LotusScript assumes .lss. To include a file that has no extension, include a period at the end of the file name. For example:
%Include "orfile."
This prevents LotusScript from adding the .lss extension to the file name.
Usage
The %Include directive must be the only item on a line, except for an optional trailing comment. It must be followed by white space (a space character, a tab character, or a newline character).
%Include statement %Include myfile.lss %Include include\myfile.lss %Include c:\include\myfile.lss Path type relative path, no directory relative path, with directory absolute path LotusScript looks for this file: <program dir>\myfile.lss <program dir>\include\myfile.lss c:\include\myfile.lss
An included file can itself contain %Include directives. You can nest up to 16 files. At compile time, LotusScript replaces the %Include directive with the entire contents of the named file. They are then compiled as part of the current script. If a run-time or compile-time error occurs in a statement in an included file, the line number reported is that of the %Include directive. The file you include must be a text file containing only LotusScript statements. If anything in the included file cannot be compiled, LotusScript generates a compiler error. If the file is not found, LotusScript generates an error. Note: EBCDIC platforms may exhibit backwards incompatibility starting with LotusScript Release 5 (Notes/Domino Release 6). Earlier releases interpret an included file as LMBCS (which is the same as ASCII in the single-byte range). Ongoing releases interpret an included file using the platform-native character set. On EBCDIC platforms, included text must be EBCDIC. In particular, if you have shipped ASCII-encoded LotusScript source files without text translation (binary FTP, for example), the files must be translated on EBCDIC platforms prior to inclusion.
Input # statement
Reads data from a sequential file and assigns that data to variables.
Syntax
Input # fileNumber , variableList
Elements
fileNumber The number assigned to the file when you opened it. A pound sign (#) sign must precede the file number.
Chapter 12. LotusScript Language Reference
351
variableList A list of variables, separated by commas. The data read from the file is assigned to these variables. File data and its data types must match these variables and their data types. variableList cannot include arrays, lists, variables of a user-defined data type, or object reference variables. It can include individual array elements, list elements, and members of a user-defined data type or user-defined class.
Usage
The following table shows how the Input # statement reads characters for various data types.
variableList data type Numeric variable How Input # reads characters The next non-space character in the file is assumed to begin a number. The next space, comma, or end-of-line character in the file ends the number. Blank lines and non-numeric values are translated to the number 0. The next non-space character in the file is assumed to begin a string. Note these special conditions: If that character is a double quotation mark (), it is ignored; however, all characters following it (including commas, spaces, and newline characters) up to the next double quotation mark are read into the string variable. If the first character is not a double quotation mark, the next space, comma, or end-of-line character ends the string. Blank lines are translated to the empty string (). Note that tab is a non-space character. Fixed-length string variable Variant variable LotusScript reads this according to its length. For example, LotusScript reads a variable declared as String *10 as 10 bytes. The next non-space character in the file is assumed to begin the data. If the data is: Empty (a delimiting comma or blank line), LotusScript assigns the variable the EMPTY value. The literal #NULL#, LotusScript assigns the variable the NULL value. A date/time literal, LotusScript assigns the variable the DataType 7 (Date/Time). A whole number, LotusScript assigns the variable the Data Type 2 (integer) if the number is in the legal range for integer; the DataType 3 (Long) if the number is in the legal range for Long but not within the range for integer; and otherwise the DataType 5 (Double). A number with a fractional part, LotusScript assigns the variable the DataType 5 (Double). If none of the above applies, LotusScript assigns the variable the String type.
String variable
If LotusScript encounters an EOF (end-of-file), input terminates and an error is generated. LotusScript inserts chr(10) to represent the newline character in any multi-line string (for example, a string that you type in using vertical bars or braces). If you Print the string to a file, this newline character will be translated into the platform-specific newline character(s). If you Write the string to a file, no translation is done. Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform.
352
Note: When reading a multiline string from a sequential file written by the Write # statement, use Input, not Line Input. When reading record-oriented data, using a random file with the Get statement is easier and more efficient than using Input #. Use Get for reading record-oriented data (a random file); use Input # for reading text data (a sequential file).
Close fileNum%
Input function
Reads a sequence of characters from a sequential or binary file into a string variable, without interpreting the input.
Syntax
Input[$] ( count , [#]fileNumber )
353
Elements
count The number of characters to read. fileNumber The number assigned to the file when you opened it.
Return value
The Input function returns a Variant, and Input$ returns a String. LotusScript returns the specified number of characters, beginning at the current position in the file. If you request more characters than are available, LotusScript generates an error. If count is 0, LotusScript returns the empty string ().
Usage
The input data is not filtered or translated in any way. All characters are returned, including newline characters, quotation marks, and spaces. If you want to work with bytes instead of characters, use the InputB or InputB$ function. You cannot use the Input, Input$, InputB, or InputB$ functions to read a file opened in Output, Append, or Random mode.
InputB function
Reads a sequence of bytes from a sequential or binary file into a string variable without interpreting the input.
Syntax
InputB[$] ( count , [#]fileNumber ) count
354
The number of bytes to read. fileNumber The number assigned to the file when it was opened.
Return value
The InputB function returns a Variant, and InputB$ returns a String. LotusScript returns the specified number of bytes, beginning at the current position within the file. If you request more bytes than are available, LotusScript generates an error. The length of the returned string (measured in characters, as computed by the Len function) is (# bytes returned) / 2 if an even number of bytes is returned, and otherwise (# bytes returned + 1) / 2, if an odd number of bytes is returned. If an odd number of bytes is returned, then the last character in the returned string is padded with a 0 byte. If count is 0, LotusScript returns the empty string ().
Usage
The input data is not filtered or translated in any way. All bytes are returned, including the bytes representing newline, quotation marks, and space. If you want to work with characters instead of bytes, use the Input or Input$ function. You cannot use the Input, Input$, InputB, or InputB$ function to read a file opened in Output, Append, or Random mode.
InputBox function
Displays a dialog box containing a prompt for user entry, and returns input from the user as a string.
Syntax
InputBox[$] ( prompt [ , [ title ] [ , [ default ] [ , xpos , ypos ] ] ] )
Elements
prompt A string expression. This is the message displayed in the dialog box. prompt can be any length. LotusScript defines, but does not enforce, a minimum supported length of 128. The specific product being used (that is, Notes, ESB, and so on) may impose other limits. title Optional. A string expression. This is displayed in the title bar of the dialog box. titlecan be any length. LotusScript defines, but does not enforce, a minimum supported length of 128. The specific product being used (that is, Notes, ESB, and so on) may impose other limits. If you omit title, nothing is displayed in the title bar. If you omit title and specify either default or xpos and ypos, include a comma in place of title.
Chapter 12. LotusScript Language Reference
355
default Optional. A string expression. This is displayed in the text entry field in the dialog box as the default user response. default can be any length. LotusScript defines, but does not enforce, a minimum supported length of 512. The specific product being used (that is, Notes, ESB, and so on) may impose other limits. If you omit default, the text input box is empty. If you omit default and specify xpos and ypos, include a comma in place of default. xpos Optional. A numeric expression that specifies the horizontal distance, in units of 1 pixel, between the left edge of the dialog box and the left edge of the display screen. If you omit xpos, the distance is 0. If you specify xpos, you have to specify ypos as well. ypos Optional. A numeric expression that specifies the vertical distance, in units of 1 pixel, between the top edge of the dialog box and the top edge of the screen. If you omit ypos, the distance is 0. If you specify ypos, you have to specify xpos as well.
Return value
The InputBox function returns a Variant containing a string. InputBox$ returns a String. Returned string can be any length. LotusScript defines, but does not enforce, a minimum supported length of 512. The specific product being used (that is, Notes, ESB, and so on) may impose other limits.
Usage
InputBox displays a dialog box with OK and Cancel buttons and a text entry field, interrupting execution of the script until the user confirms the text entry by clicking OK or Cancel. Then InputBox returns that entry. If the user clicks Cancel, InputBox returns the empty string (). When the user clicks OK or Cancel, execution resumes. The Lotus software where you are running LotusScript may allow longer strings than described above for prompt, title, default, and the text entered into the text entry field. LotusScript will support longer strings for these items if the Lotus software does, up to the maximum string size. If you are using LotusScript from within Lotus Notes, note that the InputBox function writes to: v A dialog box when executing on a Notes client. The user clicks OK, Cancel, Abort, Retry, Yes, or No to continue. v NOTES.LOG when executing on a Domino server.
Language cross-reference
@Prompt function in formula language
InputBP function
Reads a sequence of bytes (in the platform-native character set) from a sequential or binary file into a string variable without interpreting the input.
356
Syntax
InputBP[$] ( count , [#]fileNumber ) count The number of bytes to read. fileNumber The number assigned to the file when it was opened.
Return value
The InputBP function returns a Variant, and InputBP$ returns a String. LotusScript returns the specified number of bytes, beginning at the current position within the file. If you request more bytes than are available, LotusScript generates an error. The length of the returned string (measured in characters, as computed by the Len function) is the number of Unicode characters that the bytes translate into. For example, 10 bytes of ASCII characters translate into 10 Unicode characters; 10 bytes of DBCS characters translate into 5 Unicode characters. If the last requested byte read is the lead byte of a DBCS character, the byte is dropped and the file pointer is positioned one byte before the last requested byte. If count is 0, LotusScript returns the empty string ().
Usage
The input data is translated into Unicode. If you want to work with characters instead of platform bytes, use the Input or Input$ function. If you want to work with untranslated bytes, use the InputB or InputB$ function. You cannot use the Input, Input$, InputB, InputB$, InputBP, or InputBP$ function to read a file opened in Output, Append, or Random mode.
InStr function
Returns the position of the character that begins the first occurrence of one string within another string.
Syntax
InStr ( [ begin , ] string1 , string2 ) or InStr ( [ begin , ] string1 , string2 [, compMethod ] )
Elements
begin
357
Optional. A numeric expression with a positive integer value. begin specifies the character position in string1 where InStr should begin searching for string2. If you omit begin, it defaults to 1. If you specify compMethod, you must specifybegin as well. string1 The string that InStr searches for the occurrence of string2. string2 The string for which InStr searches to see if it occurs in string1. compMethod A number designating the comparison method:
Number 0 1 4 5 Comparison method case-sensitive, pitch-sensitive case-insensitive, pitch-sensitive case-sensitive, pitch-insensitive case-insensitive, pitch-insensitive
If you specify compMethod, you must specifybegin as well. If you omit compMethod, the default comparison mode is the mode set by the Option Compare statement for this module. If there is no statement for the module, the default is case-sensitive and pitch-sensitive.
Return value
InStr returns the character position of the first occurrence of string2 within string1. The following table shows how the function responds to various conditions.
Condition string1 is the empty string () string2 is not found after begin in string1 begin is larger than the length of string1 string2 is the empty string () string1 is NULL string2 is NULL begin or compMethod is NULL Return value 0 0 0 The value of begin.If you omit begin, InStr returns the value 1. NULL NULL Error
Usage
If you want to work with bytes, use the InStrB function.
Language cross-reference
@Middle function in formula language
358
InStrB function
Returns the position of the byte beginning the first occurrence of one string within another string.
Syntax
InStrB ( [ begin , ] string1 , string2 )
Elements
begin Optional. A numeric expression with a positive integer value, begin specifies the character position in string1 where InstrB should begin searching for string2. If you omit begin, it defaults to 1. string1 The string to be searched. string2 The string for which InStrB searches.
Return value
InStrB returns the byte position of the first occurrence of string2 in string1. The following table shows how the function responds to various conditions.
Condition string1 is (the empty string) string2 is not found after begin in string1 Return value 0 0
359
Condition begin is larger than the length of string1 string2 is (the empty string) string1 is NULL string2 is NULL begin is NULL
Return value 0 The value of begin.(If you omit begin, InStrB returns the value 1.) NULL NULL Error
Usage
If you want to work with characters, use the InStr function. Note: The byte position returned by InStrB is independent of the platform-specific byte order.
InStrBP function
Returns the position of the byte (in the platform-native character set) beginning the first occurrence of one string within another string.
Syntax
InStrBP ( [ begin , ] string1 , string2 )
Elements
begin Optional. A numeric expression with a positive integer value, begin specifies the character position in string1 where InStrBP should begin searching for string2. If you omit begin, it defaults to 1. string1 The string to be searched. string2 The string for which InStrBP searches.
Return value
InStrBP returns the byte position in the platform-specific character set of the first occurrence of string2 in string1. The following table shows how the function responds to various conditions.
360
Condition string1 is (the empty string) string2 is not found after begin in string1 begin is larger than the length of string1 string2 is (the empty string) string1 is NULL string2 is NULL begin is NULL
Return value 0 0 0 The value of begin.(If you omit begin, InStrB returns the value 1.) NULL NULL Error
Usage
If you want to work with characters, use the InStr function.
Dim bigStr As String, littleStr As String Dim positionOfByte As Long bigStr$ = "abcdefghi" littleStr$ = "efg" positionOfByte& = InStrBP(1, bigStr$, littleStr$) Print positionOfByte& Output: 5
InStrC function
Returns the position of the column that begins the first occurrence of one string within another string for column-based writing systems, such as Thai.
Syntax
InStrc(off, string1, string2)
Elements
off The number of the offset string1 A string containing Thai-based columns string2 A second string containing columns
Return value
The position of the column that begins the first occurrence of one string within another.
Usage
If off is greater than the length in bytes of string1 or string2, the function returns an empty string.
Chapter 12. LotusScript Language Reference
361
Int function
Returns the nearest integer value that is less than or equal to a number.
Syntax
Int ( numExpr )
Elements
numExpr Any numeric expression.
Return value
The data type of numExpr determines the data type of the value returned by the Int function. The following table shows special cases.
numExpr NULL Variant containing a string interpretable as a number Return value NULL Double
Usage
The value returned by the Int function is always less than or equal to its argument. The Fix function and the Int function behave differently. Fix removes the fractional part of its argument, truncating toward 0.
Usage
An Integer value is a whole number in the range -32768 to 32767, inclusive. Integer variables are initialized to 0. The Integer suffix character for implicit type declaration is %. LotusScript aligns Integer data on a 2-byte boundary. In user-defined data types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space.
362
IsArray function
Tests the value of an expression to determine whether it is an array.
Syntax
IsArray ( expr )
Elements
expr Any expression.
Return value
IsArray returns TRUE (-1) if expr is an array; otherwise IsArray returns FALSE (0).
IsDate function
Tests the value of an expression to determine whether it is a date/time value.
Syntax
IsDate ( expr )
Elements
expr Any expression.
Return value
IsDate returns TRUE (-1) if expr is any of the following: v A Variant value of DataType 7 (Date/Time) v A Variant value of type String, where the string represents a valid date/time value v A String value representing a valid date/time value Otherwise IsDate returns FALSE (0).
Chapter 12. LotusScript Language Reference
363
Usage
A date/time value stored in a Variant is an 8-byte floating-point value. The integer part represents a serial day counted from Jan 1, 100 AD. Valid dates are represented by integers between -657434 (representing Jan 1, 100 AD) and 2958465 (representing Dec 31, 9999 AD). The fractional part represents the time as a fraction of a day, measured from time 00:00:00 (midnight on the previous day). In this representation of date/time values, day 1 is the date December 31, 1899.
IsDefined function
Tests a string expression to determine whether it is the name of a product or platform constant at run time.
Syntax
IsDefined ( stringExpr )
Elements
stringExpr Any string expression.
Return value
IsDefined returns TRUE (-1) if stringExpr is the name of a product or platform constant at run time. Otherwise IsDefined returns FALSE (0).
Usage
The IsDefined function is used as a run-time parallel to the %If directive. It is commonly used to test the run-time value of a platform-identification or product constant that may be used to govern conditional compilation. Note: IsDefined is not a LotusScript keyword. LotusScript implements the platform constants in the following table as product #defines. When one of these is used as productConst, the LotusScript compiler does not call the product to evaluate productConst. LotusScript itself evaluates the constant as TRUE or FALSE. The value of each constant depends on the platform LotusScript is running on.
Constant WIN16 WIN32 WINNT WIN95 Platform or functionality Windows with 16-bit API (Windows 3.1) Windows with 32-bit API (Windows NT or Windows 95) Windows NT Windows 95
364
Constant WIN40 WIN98 WIN2K WINDOWS HPUX SOLARIS UNIX LINUX OS2 MAC OLE MAC68K MACPPC
Platform or functionality Windows 95 or Windows NT 4.0 Windows 98 Windows 2000 Any Windows platform type (any of the above WINxxconstants) HP/UNIX 9.X or greater Sun/OS 5.0 or greater Any UNIX type (HP_UX or Solaris) Linux OS/2, version 2.0 or greater Macintosh System 7 OLE-2 is available Macintosh Motorola 68000 version (running on either a 68xxx Macintosh or the PowerPC) Macintosh PowerPC version
The constants can define platforms at different levels and are not mutually exclusive. For example, on WinNT, the platform returned can be WIN32_X86, WINNT, WIN32, or WINDOWS. Product constants are defined by, and are specific to, the host product, for example Notes, 1-2-3, ESB, and so on. Refer to the products documentation for a list of product-defined constants.
IsElement function
Tests a string to determine whether it is a list tag for a given list.
Syntax
IsElement ( listName ( stringExpr ) )
Elements
listName The name of a defined list. expr Any expression.
Chapter 12. LotusScript Language Reference
365
Return value
The IsElement function returns TRUE (-1) if stringExpr is the list tag for any element of listName. Otherwise IsElement returns FALSE (0).
Usage
If listName is not the name of a defined list, LotusScript generates an error. If expr is a numeric expression, LotusScript first converts its value to a string. If the character set is single byte, Option Compare determines whether list names are case sensitive. For example, if Option Compare Case is in effect, the names ListA and Lista are different; if Option Compare NoCase is in effect, these names are the same. If the character set is double byte, list names are always case and pitch sensitive.
366
of the ForAll loop. Exit ForAll End If End ForAll If found = FALSE Then MessageBox "Not a valid employee Id." End If Else MessageBox "We have no such employee." End If
IsEmpty function
Tests the value of an expression to determine whether it is EMPTY.
Syntax
IsEmpty ( expr )
Elements
expr Any expression.
Return value
The IsEmpty function returns TRUE (-1) if expr has the value EMPTY. This occurs only if expr is a Variant and has not been assigned a value. Otherwise IsEmpty returns FALSE (0).
IsList function
Tests the value of an expression to determine whether it is a list.
Syntax
IsList ( expr )
Elements
expr Any expression.
Return value
The IsList function returns TRUE (-1) if expr is a list; otherwise IsList returns FALSE (0).
367
IsNull function
Tests the value of an expression to determine whether it is NULL.
Syntax
IsNull ( expr )
Elements
expr Any expression except an object reference or a Variant that contains an object reference.
Return value
The IsNull function returns TRUE (-1) if expr is NULL; otherwise it returns FALSE (0).
Usage
The IsNull function checks whether a Variant contains NULL. For example:
If IsNull(LoVar) Then Print "LoVar is NULL" Else Print LoVar
Do not use the IsNull function with an object reference variable argument; to test whether an object reference variable has been initialized, use (objref Is Nothing).
Language cross-reference
Built-in constants in LotusScript language Testing object references in LotusScript language
IsNumeric function
Tests the value of an expression to determine whether it is numeric, or can be converted to a numeric value.
Syntax
IsNumeric ( expr )
368
Elements
expr Any expression.
Return value
The IsNumeric function returns TRUE (-1) if the value of expris a numeric value or can be converted to a numeric value. The following values are numeric: v Integer v Long v Single v v v v v v v Double Currency Date/Time EMPTY String (if interpretable as number) OLE error Boolean (TRUE, FALSE)
If expr is not a numeric value and cannot be converted to a numeric value, IsNumeric returns FALSE (0). The following values are not numeric: v NULL v Array v v v v List Object (OLE Automation object, product object, or user-defined object) String (if it cannot be interpreted as number) NOTHING
Usage
A common use of IsNumeric is to determine whether a Variant expression has a numeric value.
Language cross-reference
@IsNumber
A string that is not interpretable as a number v = "Twelve" Print IsNumeric(v) Output: False A string that is interpretable as a number v = "12" Print IsNumeric(v) Output: True
369
IsObject function
Tests the value of an expression to determine whether it is a user-defined object, a product object, or an OLE Automation object. Note: The ability to use IsObject on OLE Automation objects is limited to Windows.
Syntax
IsObject ( expr )
Elements
expr Any expression.
Return value
The IsObject function returns TRUE (-1) if the value of expr is an object (user-defined object, product object, or OLE Automation object) or NOTHING. Otherwise IsObject returns FALSE (0).
IsScalar function
Tests an expression to determine if it evaluates to a single value.
Syntax
IsScalar ( expr )
Elements
expr Any expression.
Return value
The IsScalar function returns TRUE (-1) if expr evaluates to one of the following: v EMPTY v v v v Byte Integer Long Single
LotusScript Language Guide
370
v v v v v v
Otherwise (if expr is an array, list, object, NOTHING, or NULL), IsScalar returns FALSE (0).
Class SenClass ... class definition End Class Set var = New SenClass Print IsScalar(var) Output: Dim senArray(1 To 5) var = senArray Print IsScalar(var) Dim senList List var = senList Print IsScalar(var)
False
Output:
False
Output:
False
IsUnknown function
Tests the value of an expression to determine whether it has the OLE value V_IUNKNOWN.
Syntax
IsUnknown ( expr )
Elements
expr Any expression.
Return value
The IsUnknown function returns True (-1) if expr is a Variant and the value of expr is V_IUNKNOWN. This value may be returned by a call to a property or method of an OLE Automation object. Otherwise IsUnknown returns False (0).
371
Join function
Concatenates all members of an Array of Strings and returns a string. Elements of the Array are separated by a delimiter, if provided, or the space character ( ). Note: This function is new with Domino Release 6.
Syntax
Join( sourceArray , [delimiter])
Elements
sourceArray One-dimensional Array containing the substrings to be concatenated. sourceArray can be an array of Strings, or an array of Variants. If sourceArray is an array of Variants, Join will attempt to convert any non-string elements to Strings. delimiter Optional String containing separation character(s) for the concatenated Strings
Return value
Join returns a String containing the elements of sourceArray with delimiter between elements, or with the space character as a separator if delimiter is not specified.
Usage
Join creates a String that will hold the concatenation of sourceArray. Join then iterates through sourceArray, With each iteration, Join converts the next element of sourceArray to a String, if necessary, and appends it to the concatenation String. If more elements remain in sourceArray, a delimeter (either or the specified value) is appended to the concatenation String and Join continues to iterate. After all elements of sourceArray have been concatenated, Join returns the concatenation String.
Error handling
Join will throw a Run-time Type mismatch if: v an element in a variant array cannot be coerced to a string. v the delimiter is set to nothing. v the array passed in is not of either type string or variant. v a list is passed instead of an array. v the array passed in contains an element set to nothing. v the array passed in has not been properly initialized. Join will throw a run-time Wrong Number of Dimensions error if the array is not one-dimensional. Join will throw a run-time Invalid Use of Null error if the array passed in contains an element set to null or if the delimiter is set to null. Note: Join is an alias of Implode and is identical in every way.
Language cross-reference
@Implode function in formula language
372
Kill statement
Deletes a file.
Syntax
Kill fileName
Elements
fileName A string expression whose value is a file name; wildcards are not allowed. fileNamecan contain a drive indicator and path information.
Usage
Use Kill with care. If you delete a file with the Kill statement, you cant restore it with LotusScript statements or operating system commands. Make sure the file is closed before you attempt to delete it. Kill deletes files, not directories. To remove directories, use the RmDir statement.
LBound function
Returns the lower bound for one dimension of an array.
Syntax
LBound ( arrayName [ , dimension ] )
Elements
arrayName The name of an array dimension Optional. An integer argument that specifies the array dimension; the default is 1.
Return value
The LBound function returns an Integer.
Usage
The default value for dimension is 1.
Chapter 12. LotusScript Language Reference
373
LotusScript sets the lower bound for each array dimension when you declare a fixed array or define the dimensions of a dynamic array with a ReDim statement. The default lower bound for an array dimension is 0 or 1, depending on the Option Base setting.
LCase function
Returns the lowercase representation of a string.
Syntax
LCase[$] ( expr )
Elements
expr Any numeric or String expression for LCase; and any Variant or String expression for LCase$.
Return value
LCase returns a Variant of DataType 8 (a String), and LCase$ returns a String.
Usage
LCase ignores non-alphabetic characters. LCase(NULL) returns NULL. LCase$(NULL) returns an error.
Left function
Extracts a specified number of the leftmost characters in a string.
Syntax
Left[$] ( expr , n )
Elements
expr Any numeric or String expression for Left; and any Variant or String expression for Left$. If expr is numeric, LotusScript converts it to a string before performing the extraction. n The number of characters to be returned.
Return value
Left returns a Variant of DataType 8 (a String), and Left$ returns a String.
374
If n is 0, the function returns the empty string (). If n is greater than the length (in characters) of expr, the function returns the entire string. Left(NULL) returns NULL. Left$(NULL) is an error.
LeftB function
Lotus does not recommend using the LeftB function in LotusScript Release 3 and after because Release 3 and after use Unicode, a character set encoding scheme that represents each character as two bytes. Because a two-byte character can be accompanied by leading or trailing zeroes, extracting characters by byte position no longer yields reliable results. Use the Left function for left character set extractions instead.
LeftBP function
Extracts a specified number of the leftmost bytes in a string using the platform-specified character set.
Syntax
LeftBP[$] ( expr , n )
Elements
expr Any numeric or String expression for LeftBP; and any Variant or String expression for LeftBP$. If expr is numeric, LotusScript converts it to a string before performing the extraction. n The number of bytes to be returned using the platform-specified character set.
Return value
LeftBP returns a Variant of DataType 8 (a String), and LeftBP$ returns a String. If n is 0, the function returns the empty string (). If n is greater than the length (in bytes) of expr, the function returns the entire string. LeftBP(NULL) returns NULL. LeftBP$(NULL) is an error. If a double-byte character is divided, the character is not included.
375
LeftC function
Extracts the leftmost n columns from a string for column-based writing systems, such as Thai and Vietnamese.
Syntax
LeftC( StringExpr, n )
Elements
StringExpr A String expression containing character columns n The number of columns to be returned using the platform-specified character set.
Return value
LeftC returns a Variant containing the columns specified by n.
Usage
If n is 0, the function returns the empty string (). If n is greater than the length (in columns) of StringExpr, the function returns the entire string. LeftC supports the Thai and Vietnamese languages.
Len function
Returns the number of characters in a string, or the number of bytes used to hold a numeric value.
Syntax
Len ( { stringExpr | variantExpr | numericExpr | typeName } )
Elements
stringExpr Any string expression. variantExpr Any Variant expression that includes a variable name. numericExpr The name of a variable, an element of an array, an element of a list, or a member variable of a user-defined data type or class. The data type of numericExpris numeric. typeName
376
An instance of a user-defined data type. It can be a simple variable of that data type, or an element of an array variable or a list variable of that data type.
Return value
For stringExpr, Len returns the number of characters in the string expression. For variantExpr, Len returns the number of characters required to hold the value of variantExpr converted to a String. For numericExpr, Len returns the number of bytes required to hold the contents of numericExpr. For typeName, Len returns the number of bytes required to hold the contents of all the member variables, unless the user-defined data type includes Variant or variable-length String members. In that case, the length of the variable of the user-defined data type may not be the same as the sum of the lengths of its member variables.
Usage
In LotusScript Release 3 and after, Len(NULL) generates an error. In previous releases of LotusScript, Len(NULL) returned NULL. Len(v), where v is EMPTY, returns 0. To determine the length of a string in bytes rather than in characters, use the LenB function. To determine the length of a string in bytes in the platform-native character set, use the LenBP function.
Example 2
User-defined data type with variable-length String member Type OrderInfo ordID As String * 6 custName As String End Type An instance of the user-defined data type Dim ord As OrderInfo ord.ordID$ = "OR1234" ord.custName$ = "John R. Smith" Total length of the ords members is 19. Print Len(ord.ordID$) + Len(ord.custName) Length of ord is 16. Print Len(ord)
LenB function
Returns the length of a string in bytes, or the number of bytes used to hold a variable.
377
Syntax
LenB ( { stringExpr | variantExpr | numericExpr | typeName } )
Elements
stringExpr Any string expression. variantExpr Any Variant expression that includes a variable name. numericExpr The name of a variable, an element of an array, an element of a list, or a member variable of a user-defined data type or class. The data type of numericExpris numeric. typeName An instance of a user-defined data type. It can be a simple variable of that data type, or an element of an array variable or a list variable of that data type.
Return value
For stringExpr, LenB returns the number of bytes in the string expression. For variantExpr, LenB returns the number of bytes required to hold the value of variantExpr converted to a String. For numericExpr, LenB returns the number of bytes required to hold the contents of numericExpr. For typeName, LenB returns the number of bytes required to hold the contents of all the member variables, unless the user-defined data type includes Variant or variable-length String members. In that case, the length of the variable of the user-defined data type may not be the same as the sum of the lengths of its member variables.
Usage
In LotusScript Release 3 and after, LenB(NULL) generates an error. In previous releases of LotusScript, LenB(NULL) returned NULL. LenB(v), where v is EMPTY, returns 0. To determine the length of a string in characters, use the Len function. To determine the length of a string in bytes in the platform-native character set, use the LenBP function.
378
LenBP function
Returns the length of a string in bytes, or the number of bytes used to hold a variable, in the platform-native character set.
Syntax
LenBP ( { stringExpr | variantExpr | numericExpr | typeName } )
Elements
stringExpr Any string expression. variantExpr Any Variant expression that includes a variable name. numericExpr The name of a variable, an element of an array, an element of a list, or a member variable of a user-defined data type or class. The data type of numericExpr is numeric. typeName An instance of a user-defined data type. It can be a simple variable of that data type, or an element of an array variable or a list variable of that data type.
Return value
For stringExpr, LenBP returns the number of bytes in the string expression. For variantExpr, LenBP returns the number of bytes required to hold the value of variantExpr converted to a String. For numericExpr, LenBP returns the number of bytes required to hold the contents of numericExpr. For typeName, LenBP returns the number of bytes required to hold the contents of all the member variables, unless the user-defined data type includes Variant or variable-length String members. In that case, the length of the variable of the user-defined data type may not be the same as the sum of the lengths of its member variables.
Usage
LenBP(NULL) generates an error. LenBP(v), where v is EMPTY, returns 0. To determine the length of a string in characters, use the Len function. To determine the length of a string in bytes in the LotusScript internal character set, use the LenB function. To determine the length of a string in columns (for column-based languages) use the LenC function.
LenC function
Returns the length of a string in number of character columns. The LenC function is used for column based writing systems, such as Thai.
379
Syntax
LenC( stringExpr )
Elements
stringExpr A string expression using character columns
Return value
An Integer indicating the number of columns in the string expression.
Usage
LenC(NULL) generates an error. LenC(v), where v is EMPTY, returns 0. To determine the length of a string in characters, use the Len function. To determine the length of a string in bytes in the LotusScript internal character set, use the LenB function. To determine the length of a string in columns (for column-based languages) use the LenC function.
Let statement
Assigns a value to a variable.
Syntax
[ Let ] variableID = expr
Elements
Let Optional. The Let statement is chiefly useful as a means of documenting an assignment statement. The absence of the Let keyword has no effect on the assignment. variableID A variable or variable element to which the value of expris assigned. variableID can be of any data type that LotusScript recognizes, other than an object reference, an array, or a list. variableIDcan take any of these forms: v variableName A non-array, non-list variable. The variable may not be an array or list variable, but it may be a Variant containing an array or list. v arrayName ( subscripts ) An array element. arrayName is an array variable or a Variant containing an array. v listName ( listTag ) A list element. listName is a list variable or a Variant containing a list. v typeVar . memberVar A member variable of a user-defined data type. typeVar is an instance of a user-defined data type. typeVar can be an element of an array or list. memberVar is a member variable of that user-defined data type. memberVar can be a scalar data type, a fixed array, or a Variant containing a scalar data type, an array, a list, or an object reference. v object . memberVar object .. memberVar Me. memberVar
380
A member variable or property of a class. object is an expression whose value is an object reference. memberVar is a member variable or property of that class, or an element of an array member variable, or an element of a list member variable. Use Me only within a procedure defined within the class. expr Any expression except one whose value is an object reference. The expr must be of the same data type as variableID, or else must be convertible to the data type of variableID. The rules for data type conversion determine how (if at all) LotusScript converts the value of expr before assigning it to variableID.
Usage
LotusScript assigns the value of expr to the variable or variable element named by variableID. Do not use the Let statement to assign an object reference to a variable. Use the Set statement to do that.
Assign the value of b to an array element. Dim devArray(3) Let devArray(1) = b% Print devArray(1) Output: 2 Assign the value of c to a list element. Dim devList List Let devList("one") = c% Print devList("one") Output:
For an instance of a user-defined data type, assign the value of c - a to a member variable. Type DevType num As Integer End Type Dim inst As DevType Let inst.num% = c% - a% Print inst.num% Output: 1 For an instance of a user-defined class, assign the value of a + b to a member variable. Class DevClass Public num% As Integer End Class Set devObj = New DevClass Let devObj.num% = a% + b% Print devObj.num% Output: 4
Syntax
Line Input # fileNumber , varName
381
Elements
# fileNumber The number assigned to the file when you opened it. A # sign must precede the file number. varName A String or Variant variable to hold the contents of one line of the file.
Usage
Line Input # reads characters from a sequential file until it encounters a newline character. Line Input # does not read the newline character into the variable. When reading a multiline string from a sequential file, use the Input # statement, not the Line Input # statement.
ListTag function
Returns the name of the list element currently being processed by a ForAll statement.
Syntax
ListTag ( refVar )
Elements
refVar The reference variable in a ForAll list iteration loop.
Return value
ListTag returns a String that is the name of the list element currently referred to by refVar. ListTag generates an error if refVar is not the reference variable specified in the ForAll statement. If Option Compare NoCase is in effect and the character set is single byte, names are returned as all uppercase. Option Compare has no effect if the character set is double byte.
Usage
The ListTag function is valid only inside a ForAll block whose target is a list.
382
LOC function
Returns the current position of the file pointer in a file.
Syntax
LOC ( fileNumber )
Elements
fileNumber The number assigned to the file when you opened it.
Return value
The following table presents the LOC return values for random, sequential, and binary files.
File type Random Sequential Binary Return value The number of the last record read from or written to the file. This is the file pointer position, minus 1. The byte position in the file, divided by 128 and truncated to an integer. The position of the last byte read from or written to the file. This is the file pointer position, minus 1.
383
Write at record 2. rec2.empNumber% = 456 rec2.empName$ = "Jane Doe" Put #fileNum%, 2, rec2 Print LOC(fileNum%) Output: Read from record 1. Get #fileNum%, 1, rec2 Print LOC(fileNum%) Close fileNum%
Output:
Syntax
Lock [#]fileNumber [ , recordNumber | { [ start] To end } ] Unlock[#]fileNumber [ , recordNumber | { [ start] To end } ]
Elements
fileNumber The number assigned to the file when you opened it. recordNumber In a random file, the number of the record that you want to lock or unlock. In a binary file, the byte that you want to lock or unlock. The first record in a random file is record number 1; the first byte in a binary file is byte number 1. LotusScript locks or unlocks only the specified record or byte. In a sequential file, LotusScript locks or unlocks the whole file, regardless of value you specify for recordNumber. start To end In a random file, the range of record numbers you want to lock or unlock. In a binary file, the range of bytes that you want to lock or unlock. If you omit start, LotusScript locks records or bytes from the beginning of the file to the specified end position. In a sequential file, LotusScript locks or unlocks the whole file, regardless of the start and end values.
Usage
In Windows 3.1, you must run SHARE.EXE to enable the locking feature if you are using MS-DOS version 3.1 or later. Earlier versions of MS-DOS do not support Lock and Unlock. Always use Lock and Unlock statements in pairs whose elements (fileNumber, recordNumber, start, and end) match exactly. If you do not remove all locks, or if the elements do not match exactly, unpredictable results can occur.
384
Dim rec1 As PersonRecord, rec2 As PersonRecord Dim fileNum As Integer, recNum As Integer Dim fileName As String recNum% = 1 fileNum% = FreeFile() fileName$ = "data.txt" Create a record. Open fileName$ For Random As fileNum% rec1.empNumber% = 123 rec1.empName$ = "John Smith" Put #fileNum, recNum%, rec1 Print rec1.empName$ ; rec1.empNumber% Output: John Smith 123 Lock and update the record. Lock #fileNum%, recNum% Get #fileNum%, recNum%, rec2 Print rec2.empName$ ; rec2.empNumber% Output: John Smith 123 rec2.empName$ = "John Doe" Put #fileNum%, recNum%, rec2 Print rec2.empName$ ; rec2.empNumber% Output: John Doe 123 Release the lock. Unlock #fileNum%, recNum% Close fileNum%
LOF function
Returns the length of an open file in bytes.
Syntax
LOF ( fileNumber )
Elements
fileNumber The number assigned to the file when you opened it.
Return value
The LOF function returns a value of type Long.
Usage
LOF works only on an open file. To find the length of a file that isnt open, use the FileLen function.
385
Log function
Returns the natural (base e) logarithm of a number.
Syntax
Log ( numExpr )
Elements
numExpr Any numeric expression greater than zero.
Return value
The Log function returns a value of type Double.
Usage
The base for natural logarithms (e) is approximately 2.71828.
Example 2
Compute the base 10 logarithm of a number. Function Log10 (inVal As Single) As Single Log10 = Log(inVal!) / Log(10) End Function Print Print Print Print Log10(10) Log10(100) Log10(1 / 100) Log10(1) Output: Output: Output: Output: 1 2 -2 0
Usage
The Long suffix character is &. Long variables are initialized to 0. A Long value is a whole number in the range -2,147,483,648 to 2,147,483,647 inclusive. LotusScript aligns Long data on a 4-byte boundary. In user-defined types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space.
386
2094070921
2094070921
LSet statement
Assigns a specified string to a string variable and left-aligns the string in the variable.
Syntax
LSet stringVar = stringExpr
Elements
stringVar The name of a string variable. It may be a fixed-length String variable, a variable-length String variable, or a Variant variable. stringExpr The string to be assigned to the variable and left-aligned.
Usage
If the length of stringVar is greater than the length of stringExpr, LotusScript left-aligns stringExpr in stringVarand sets the remaining characters in stringExpr to spaces. If the length of stringVar is less than the length of stringExpr, LotusScript copies only that many of the leftmost characters from stringExpr to stringVar. If stringVar contains a numeric value, LotusScript converts it to a string to determine the length of the result. If stringVar is a Variant, it cant contain NULL. You cant use LSet to assign values from an instance of one user-defined data type to another.
LTrim function
Removes leading spaces from a string and returns the result.
Syntax
LTrim ( stringExpr )
387
Elements
stringExpr Any string expression.
Return value
LTrim returns the trimmed version of stringExpr without modifying the contents of stringExpr itself. LTrim returns a Variant of DataType 8 (a String), and LTrim$ returns a String.
Function Syntax
MessageBox ( message [ , [ buttons + icon + default + mode ] [ , boxTitle ] ] )
Statement Syntax
MessageBox message [ , [ buttons + icon + default + mode ] [ , boxTitle ] ] The MessageBox function and statement are identical, except that only the function has a return value. MsgBox is acceptable in place of MessageBox.
Elements
message The message to be displayed in the message box (a string). The length of message is dependent on the operating system. buttons Defines the number and type of buttons to be displayed in the message box:
Constant name MB_OK MB_OKCANCEL MB_ABORTRETRYIGNORE MB_YESNOCANCEL MB_YESNO MB_RETRYCANCEL Value 0 1 2 3 4 5 Buttons displayed OK OK and Cancel Abort, Retry, and Ignore Yes, No, and Cancel Yes and No Retry and Cancel
388
default Defines the default button in the message box. Pressing ENTER has the same effect as clicking the default button:
Constant name MB_DEFBUTTON1 MB_DEFBUTTON2 MB_DEFBUTTON3 Value 0 256 512 Default button First button Second button Third button
boxTitle The string to appear in the title bar of the message box. boxTitle can be up to 128 characters in length.
Return value
The MessageBox function return value is an integer in the range of 1 to 7, inclusive. This value indicates which button the user pressed in the message box, as shown in the following table.
Return value 1 2 3 4 5 6 7 Button OK Cancel Abort Retry Ignore Yes No Constant IDOK IDCANCEL IDABORT IDRETRY IDIGNORE IDYES IDNO
389
Usage
The valid values for the buttons, icon, default, and mode elements listed in the preceding tables are defined as constants in the file LSCONST.LSS. If you want to use the constants instead of numbers, include this file in your script. The Lotus software where you are running LotusScript may allow longer strings than described above for message and boxTitle. LotusScript will support longer strings for these items if the Lotus software does. Note: The length of message is dependent on the operating system. If you are launching applications in a mixed environment (for example, PC and Mac), keep your message length equal to or shorter than the smallest limit of the operating systems to be used. Use the newline character to force line breaks in the message element. Or use vertical bars or braces to specify a multiline string. If you dont force line breaks, the text wraps automatically in the message box. Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. If newlines are desired in the output, it is the programmers responsibility to ensure that the string contains the correct newline for the platform. If you are using LotusScript from within Lotus Notes, note that the MessageBox function writes to: v A dialog box when executing in the foreground on a Notes client. The user clicks OK, Cancel, Abort, Retry, Yes, or No to continue. v NOTES.LOG when executing on a Domino server without pausing or as a scheduled agent in the Notes client. Note: Whenever a MessageBox function is executed in the back end, it will return zero, regardless of the defaults or modes. Only the prompt is displayed. The display goes to the server console, Notes log, and anywhere that debugging output is redirected (DEBUG_OUTFILE) if on a server, or to the debug console if on the client. This does not appy to the MessageBox statement.
Example 2
Use the MessageBox statement to display a multiline message in a message box labeled "Demo" and containing an OK button. %Include "lsconst.lss" Dim twoLiner As String twoLiner = |This message is on two lines| MessageBox twoLiner, MB_OK, "Demo"
390
Mid function
Extracts a string from within another string, beginning with the character at a specified position.
Syntax
Mid[$] ( expr , start [ , length ] )
Elements
expr Any numeric or string expression. LotusScript converts a numeric to a string before performing the extraction. start The position of the first character to extract from the string, counting from 1 for the leftmost character. length The number of characters to extract from the string.
Return value
Mid returns a Variant of DataType 8 (a string), and Mid$ returns a String. If there are fewer than length characters in the string beginning at the start position, or if you omit the length argument, the function returns a string consisting of the characters from start to the end of expr. If start is greater than the length of expr, the function returns the empty string ().
Language cross-reference
@Middle function in formula language
Mid statement
Replaces part or all of one string with characters from another string.
Syntax
Mid[$] ( stringVar , start [ , length ] ) = stringExpr
Elements
stringVar A String variable, or a Variant variable containing a string value. The stringVar cannot be a literal string. start The position of the first character in stringVar that you want to replace.
Chapter 12. LotusScript Language Reference
391
length Optional. The number of characters you want to use from stringExpr. stringExpr A string expression. Characters from stringExpr replace characters in stringVar.
Usage
Mid can alter the size of stringVar in bytes if you are working with multibyte characters. For example, if you are replacing a single-byte character with a double-byte character, the size of the string in bytes increases. Otherwise, Mid does not alter the length of stringVar. That is, Mid does not append characters to stringVar. Mid uses as many characters of stringExpr as will fit in stringVar beginning at start and ending at start+length - 1. To direct Mid to use all of stringExpr, either omit length, or specify a length greater than the length of the value in stringExpr. If start is greater than the length of stringVar, LotusScript generates an error.
Language cross-reference
@ReplaceSubstring function in formula language
The three-character string BCD, beginning at the second character of string1, is replaced with the first three characters contained in string2, 123.
MidB function
Lotus does not recommend using MidB in LotusScript Release 3 or later. Because these releases use Unicode, extracting characters by byte position no longer yields reliable results. Instead, use the Mid function for character set extractions.
MidB statement
Lotus does not recommend using MidB statements in LotusScript Release 3 or later. Because these releases use Unicode, replacing characters by byte position no longer yields reliable results. Instead, use the Mid statement for character set replacement.
MidBP function
Extracts a number of bytes (using the platform-specified character set) from within another string, beginning at a specified position.
392
Syntax
MidBP[$] ( expr , start [, length] )
Elements
expr Any numeric or String expression for MidBP; and any Variant or String expression for MidBP$. If expr is numeric, LotusScript converts it to a string before performing the extraction. start The position of the first byte in expr that you want to return. length Optional. The number of characters you want to use from expr.
Return value
MidBP returns a Variant of DataType 8 (a String), and LeftBP$ returns a String. If there are fewer than length bytes in the string beginning at the start position, or if you omit the length argument, the function returns a string consisting of the characters from start to to the end of expr. If start is greater than the length in bytes of expr, the function returns an empty string. If a double-byte character is divided, the character is not included.
MidC function
Extracts a number of character columns from a string starting at a character column offset, searching left to right. The MidC function is used for column-based writing systems, such as Thai.
Syntax
Midc( string, off, n )
Elements
string A string containing character-based columns off The number of the offset where you want to begin extraction n The number of columns to be extracted
393
Return value
MidC returns a string of length n.
Usage
If there are fewer than n columns in the string beginning at the off position, or if you omit the n argument, the function returns a string consisting of the characters from off to the end of string. If off is greater than the length in bytes of string, the function returns an empty string.
Minute function
Returns the minute of the hour (an integer from 0 to 59) for a date/time argument.
Syntax
Minute ( dateExpr )
Elements
dateExpr Any of the following kinds of expression: v A valid date/time string of type String or Variant. For Notes or Domino, LotusScript interprets a 2-digit designation of a year in a date/time string so that: v 50 through 99 represent the years 1950 through 1999. v 00 through 49 represent the years 2000 through 2049. For SmartSuite, LotusScript interprets the years differently. For more information, see the Year 2000 item on the Help menu of each SmartSuite product. v A numeric expression whose value is a Variant of DataType 7 (Date/Time). v A number within the valid date range: the range -657434 (representing Jan 1, 100 AD) to 2958465 (Dec 31, 9999 AD), inclusive. v NULL.
Return value
Minute returns an integer between 0 and 59. The data type of the return value is a Variant of DataType 2 (Integer). Minute(NULL) returns NULL.
Language cross-reference
@Minute function in formula language
394
secondsFrag$ = Str(60 - Second(Time)) crlf$ = Chr(13) & Chr(10) Carriage return/line feed message$ = "Current time: " & timeFrag$ & ". " & crlf$ _ & "Time remaining in the day: " _ & hoursFrag$ & " hours, " _ & minutesFrag$ & " minutes, and " _ & secondsFrag$ & " seconds." MessageBox(message$)
MkDir statement
Creates a directory.
Syntax
MkDir path
Elements
path A string expression whose value is the name of the directory you want to create.
Usage
A drive letter in path is optional. If it is not included, the current drive is used. Relative pathnames may also be used. Use the path syntax for the platform on which you are running LotusScript. The maximum allowable length of the path string varies with the platform. LotusScript generates an error if the directory cannot be created.
Month function
Returns the month of the year (an integer from 1 to 12) for a date/time argument.
Syntax
Month ( dateExpr )
Elements
dateExpr Any of the following kinds of expression: v A valid date/time string of String or Variant data type. For Notes or Domino, LotusScript interprets a 2-digit designation of a year in a date/time string so that: v 50 through 99 represent the years 1950 through 1999. v 00 through 49 represent the years 2000 through 2049. For SmartSuite, LotusScript interprets the years differently. For more information, see the Year 2000 item on the Help menu of each SmartSuite product. v A numeric expression whose value is a Variant of DataType 7 (Date/Time).
Chapter 12. LotusScript Language Reference
395
v A number within the valid date range: the range -657434 (representing Jan 1, 100 AD) to 2958465 (Dec 31, 9999 AD), inclusive. v NULL.
Return value
Month returns an integer between 1 and 12. The data type of the return value is a Variant of DataType 2 (Integer). Month(NULL) returns NULL.
Language cross-reference
@Month function in formula language
Name statement
Renames a file or directory.
Syntax
Name oldName As newName
Elements
oldName A string expression whose value is the name of an existing file or directory, optionally including a path. newName A string expression whose value is the name to be given to the file or directory, optionally including a path. The newName cannot be another file or directory that already exists.
Usage
To move a file, specify complete paths in both oldName and newName. Use the same file name for both arguments if you dont want to rename it. You cant move a file from one drive to another except under Windows NT and Windows 95. You cant rename a file or directory to itself except under Windows NT and Windows 95. You can rename a directory, but you cant move it except under UNIX. You cant rename the current directory.
396
Now function
Returns the current system date and time as a date/time value.
Syntax
Now
Return value
Now returns the current system date and time as a Variant of DataType 7 (Date/Time).
Usage
A date/time value is an eight-byte floating-point value. The integer part represents a serial day counted from the date January 1, 100 AD. The fractional part represents the time as a fraction of a day, measured from midnight on the preceding day. You can call the function as either Now or Now().
Language cross-reference
@Now function in formula language @Today function in formula language
Oct function
Returns the octal representation of a number as a string.
Syntax
Oct[$] ( numExpr )
Elements
numExpr Any numeric expression. If numExpr evaluates to a number with a fractional part, LotusScript rounds it to the nearest integer before deriving its octal representation.
Return value
Oct returns a Variant of DataType 8 (String), and Oct$ returns a String.
Chapter 12. LotusScript Language Reference
397
Return values will only include the numerals 0 to 7, inclusive. The maximum length of the return value is 11 characters.
Usage
If the data type of numExpr is not Integer or Long, then LotusScript attempts to convert it to a Long. If it cannot be converted, a type mismatch error occurs.
Rounds Double argument, then converts to Long. Print Oct$(17.3) Prints "21" Computes product 16.587, rounds to 17.0, then converts to Long. Print Oct$(17.1 * .97) Prints "21"
On Error statement
Determines how an error will be handled in the current procedure.
Syntax
On Error [ errNumber ] { GoTo label | Resume Next | GoTo 0 }
Elements
errNumber Optional. An expression whose value is an Integer error number. If this is omitted, this statement refers to all errors in the current procedure. This value can be any error number that is defined in LotusScript at the time the On Error statement is encountered. GoTo label Specifies that when the error occurs, execution continues with an error-handling routine that begins at label. The error is considered handled. Resume Next Specifies that when the error occurs, execution continues with the statement following the statement which caused the error. No error-handling routine is executed. The values of the Err, Erl, and Error functions are not reset. (Note that a Resume statement does reset these values.) The error is considered handled. GoTo 0 If errNumber is specified, when the error occurs, the error should be handled by the most recent general On Error statement that specifies no error number. If errNumber is omitted, no errors are handled in the current procedure.
Usage
The On Error statement is an executable statement. It allows the procedure containing it to change the way LotusScript responds to particular errors. If no On Error statement is used, an error ordinarily causes execution to end. On Error allows a procedure to handle the error and continue execution appropriately.
398
If you reverse the statements, however, all errors go to the General label:
On Error 11 Goto DivBy0 On Error Goto General
Language cross-reference
@Error function in formula language @IfError function in formula language @Failure function in formula language
399
The Call statement generates a division-by-zero error at the attempted division of y by z. Execution resumes at the next statement, the If statement. The current error number is the value of the constant ErrDivisionByZero, which was defined in the file lserr.lss previously included in the script by the %Include statement. Therefore the Print statement is executed. Then the Exit Function statement terminates execution within Best(), without executing further statements within the procedure; and control returns to the caller.
%Include "lserr.lss" Function Best() Dim x As Integer, y As Integer, z As Integer After any error-generating statement, resume execution with the next statement. On Error Resume Next ... y% = 3 z% = 0 ... x% = y% / z% Generates division-by-zero error. If Err = ErrDivisionByZero Then Print "Attempt to divide by 0. Returning to caller." Exit Function End If ... End Function Call Best()
On Event statement
Binds an event-handling sub or function to an event associated with a Lotus software object, or breaks an existing binding. Note: The Lotus software application may provide an empty sub or function for each object event, in which case you do not need to use On Event statements. You can enter a script in the appropriate sub or function, and the script automatically executes when the event occurs. For details, see the product documentation.
Syntax
On Event eventName From prodObject{Call handlerName | Remove[ handlerName ] }
Elements
eventName The name of an event specified in the product class definition. prodObject An expression whose value is a reference to a product object. (Events cannot be specified in user-defined class definitions.) Call Binds the handlerName sub or function to the specified eventName from the specified prodObject. handlerName The name of an event-handling sub or function for the specified eventName and prodObject. Whenever the specified event happens on the specified object, handlerName is called.
400
Remove Detaches the handlerName sub or function from the object-event pair. If no handlerName is specified, this statement detaches all event-handling subs from the object-event pair.
Usage
An event-handling sub or function is defined like any other sub or function, with the restriction that its first parameter must be a reference to the product object that can raise the event. The remaining parameters are defined by the event in the product class, and are used in the handler call. You can specify multiple event-handling subs or functions for the same event from the same object, using multiple On Event statements. The order of execution of event-handling subs or functions bound to the same event is undefined. A function is necessary only if the event requires a return value from the handler. Note: Of the three types of objects LotusScript understands (OLE/COM objects, LotusScript product objects, and LotusScript Native objects), only LotusScript product objects can register events.
On...GoSub statement
Transfers control to one of a list of labels, processes statements until a Return statement is reached, and returns control to the statement immediately following the On...GoSub statement.
Syntax
On numExpr GoSub label [ , label, ... ]
Elements
numExpr
401
A numeric expression whose value determines which of the labels is the target of the transfer of control. The value of numExpr must not exceed 255. label A label that specifies the location of a series of statements to execute. The last statement in this series is a Return statement.
Usage
The On...GoSub statement, its labels, and the Return statement must all reside in the same procedure. LotusScript transfers control to the first label if numExpr is 1, to the second label if numExpr is 2, and so on. Execution continues from the appropriate label until a Return statement executes. Then control returns to the statement immediately following the On...GoSub statement. If LotusScript encounters a statement (such as Exit or GoTo) that forces an early exit from the procedure before reaching a Return statement, the Return statement is not executed. LotusScript rounds numExpr to the nearest integer before using it to determine the target label. If numExpr is 0, or is larger than the number of labels in the list, the On...GoSub statement is ignored and execution continues at the statement that immediately follows it. LotusScript generates an error if numExpr evaluates to a number less than 0 or greater than 255.
On...GoTo statement
Transfers control to one of a list of labels.
Syntax
On numExpr GoTo label [ , label ]...
Elements
numExpr A numeric expression whose value determines which of the labels is the target of the transfer of control. The value of numExprmust not exceed 255.
402
Usage
On...GoTo cant be used at the module level or to transfer control into or out of a procedure. LotusScript transfers control to the first label if numExpr is 1, to the second label if numExpr is 2, and so on. LotusScript rounds numExpr to the nearest integer before using it to determine the target label. If numExpr is 0, or is larger than the number of labels in the list, the On...GoTo statement is ignored and execution continues at the statement following it. LotusScript generates an error if numExpr evaluates to a number greater than 255.
Open statement
Opens a file, enabling access to it for reading or writing data.
Chapter 12. LotusScript Language Reference
403
Syntax
Open fileName [ For { Random| Input| Output | Append| Binary } ] [ Access{ Read| Read Write | Write } ] [ { Shared | Lock Read | Lock Read Write | Lock Write}] As[#]fileNumber [ Len = recLen ] [Charset= MIMECharsetName] This statement must appear on one line, unless you use an underscore ( _ ) for line continuation.
Elements
fileName A string expression indicating the file to open. fileName may include a complete path. If you do not specify a drive and a directory, LotusScript looks for the file in the default directory on the default drive. If you specify a drive but no directory, LotusScript looks for the file in the default directory of the specified drive. On platforms without drive letters, the default directory is used. If you specify a fileNamethat does not exist, LotusScript generates an error if the mode is Input; for all other modes, LotusScript creates the file and opens it. For mode Optional. Specifies the files mode; the default is Random. v Random Default mode. Designates random access mode; that is, the file is accessible by record number. Use the Get and Put statements to read and write the file. If you omit the Access clause, LotusScript makes three attempts to open the file, using Read Write access, then Write access, and finally Read access. If all three attempts fail, an error is generated. v Input Designates sequential input mode. Use the Input and Input # statements to read the file. If the mode conflicts with the Access type, LotusScript generates an error. For example, you cant open a file in Input mode with Write access. v Output Designates sequential output mode. Use the Write # and Print # statements to write to the file. If the mode conflicts with the Access type, LotusScript generates an error. For example, you cant open a file in Output mode with Read access. v Append Designates sequential output mode, beginning at the current end-of-file. If the mode conflicts with the Access type, LotusScript generates an error. For example, you cant open a file in Append mode with Read access. Unless you use the Seek statement to move to a file position other than the end of the file, the Print # and Write # statements append text to the end of the file. v Binary Designates binary file mode. Use the Get and Put statements to read and write the file. If you omit the Access clause, LotusScript makes three attempts to open the file, using Read Write access, thenWrite access, and finally Read access. If all three attempts fail, an error is generated.
404
Access operations Optional. Specifies what operations can be performed on the file. An error is generated if the access type conflicts with the file mode specified in the For clause. v Read Default access type for Input mode. Only read operations are permitted. v Read Write Default access type for Random mode. Both read and write operations are permitted. v Write Default access type for Output, Append, and Binary modes. Only write operations are permitted. Lock type Optional. The default is Shared.Determines how the open file can be shared when accessed over a network by other processes, including processes owned by other users. Under Windows 3.1, you must run SHARE.EXE to enable the locking feature if you are using MS-DOS version 3.1 or later. Lock is not supported for earlier versions of MS-DOS. v Shared Default locking type. No file locking is performed. Any process on any machine on the network can read from or write to the file. v Lock Read Prevents other processes from reading the file, although they can write to it. The lock is applied only if read access has not already been granted to another process. v Lock Read Write Prevents other processes from reading and writing to the file. The lock is applied only if read or write access has not already been granted to another process. If a lock is already in place, it must be released before opening a file with Lock Read Write. v Lock Write Prevents other processes from writing to the file, although they can read from it. The lock is applied only if write access has not already been granted to another process. fileNumber An integer expression with a value between 1 and 255, inclusive. This number is associated with the file when you open the file. Other file-manipulation commands use this number to refer to the file. recLen Optional. Designates the record length; use an integer expression with a value between 1 and 32767, inclusive. For a Random file, recLen is the record length for the file (all records in a single file must have the same length). The default record length is 128 bytes. For a sequential (Input, Output, or Append) file, recLen is the number of characters to be read from the file into an internal buffer, or assigned to an internal buffer before it is written to the file. This need not correspond to a record size, because the records in a sequential file can vary in size. A larger buffer uses more memory but provides faster file I/O. The default buffer size is 512 bytes. For a Binary file, recLenis ignored.
405
MIMECharsetName Note: This element is new with Domino Release 6. Optional. Designates the character set to use for sequential file I/O. If no character set is provided, file I/O is done in the platform code page with the following exceptions: v If a UTF-16 or UTF-8 byte order mark (BOM) is detected at the beginning of the file, the file I/O is done in the code page specified by the BOM. v For existing OS/400 (iSeries) files, if no UTF-16 or UTF-8 BOM is detected, the files CCSID (character set) attribute determines the code page. See MIME charset names for a list of valid MIME charset values.
Usage
If a file is already open in Binary, Random, or Input mode, you can open a copy of the file using a different file number, without closing the open file. If a file is already open in Append or Output mode, you must close it before opening it with a different file number. LotusScript limits the number of open files to 255. Depending on your operating system environment and the Lotus software you are running, the actual number of files that you can open may be 15 or less. See your product documentation for details.
Type RecType empId As Double employee As String End Type Dim arrayOfRecs() As RecType A dynamic array that will get sized to the number of lines in c:\123w\work\thenames.txt Dim txt As String Dim fileNum As Integer Dim counter As Integer Dim countRec As Integer Get an unused file number so LotusScript can open a file. fileNum% = FreeFile() counter% = 0 Open "c:\123w\work\thenames.txt" For Input As fileNum% Do While Not EOF(fileNum%) Read each line of the file. Line Input #fileNum%, txt$ Increment the line count. counter% = counter% + 1 Loop Return the file pointer to the beginning of the file. Seek fileNum%, 1 The file has counter number of lines in it, so arrayOfRecs() is defined with that number of elements. ReDim arrayOfRecs(1 To counter%) Read the contents of the file into arrayOfRecs. For countRec% = 1 To counter%
406
Input #fileNum%, arrayOfRecs(countRec%).employee$, _ arrayOfRecs(countRec%).empId# Next Close fileNum% Print arrayOfRecs(2).employee$ & " " arrayOfRecs(2).empId# Output: Roman Minsky 23456 Examples using MIMEcharsetname Open "EBCDIC.TXT" for output as ff CHARSET="ebcdic-us" access write _
Open "UNICODE.TXT" for output access write _ as ff CHARSET="utf-16" Open "ASCII.TXT" for output Access write _ as ff CHARSET="ascii"
Syntax
Option Base base
Elements
base The default lower bound (either 0 or 1) for all dimensions of all arrays in the module in which the Option Base statement occurs.
Usage
Option Base can be specified only once in a module, and only at the module level. If you use Option Base, it must precede all array declarations and all ReDim statements in the module. The value set by Option Base applies to all arrays in the module that are either declared by Dim statements or redefined by ReDim statements. If the module does not include an Option Base statement, the default lower bound for all dimensions of all arrays is 0. For example, a one-dimensional array of 10 elements would use subscripts 0-9.
Syntax
Option Compare option1 [, option2 ]
407
Elements
Option can be any of the following: Binary Comparison is bit-wise. If Binary is specified, no other option can be specified. Case or NoCase Comparison is case sensitive (default) or case insensitive. Only one of these options can be specified. The keyword Text is acceptable in place of NoCase. Pitch or NoPitch Comparison is pitch sensitive (default) or pitch insensitive. Only one of these options can be specified. These options apply to Asian (double byte) characters.
Usage
The Case, NoCase, Pitch, and NoPitch keywords specify string comparison using the character collation sequence determined by the Lotus software that you are using. The Binary keyword specifies string comparison in the platforms collation sequence: the effect is platform sort-order, case-sensitive, pitch-sensitive comparison. Option Compare can be specified more than once per module, but the options cannot conflict. Option Compare can appear anywhere at module level. Option Compare applies to all string comparisons in the module. If you omit the Option Compare statement, the default method of string comparison is the same as Option Compare Case and Option Compare Pitch. In certain functions such as InStr and StrCompare, the case and pitch sensitivity established by Option Compare or by default can be overridden by case-sensitivity and pitch-sensitivity arguments.
Example 2
In this example, no Option Compare statement appears in the module, so the list tags a and A are different tags, because case-sensitive comparison in the country/language collation order is the default.
408
Thus, the assignments to Loft(a) and Loft(A) refer to two different list elements. Within the ForAll statement, the ListTag function retrieves a list tag; and the Print statement prints it on a separate line.
Dim loft List As Integer loft%("a") = 2 loft%("A") = 17 ForAll i In loft% Print ListTag(i) Output: "a" and "A" End ForAll
Example 3
In this example, the Option Compare NoCase statement specifies case-insensitive comparison in the country or region/language collation order as the default method for string comparison, so the list tags a and A are the same tag. Thus, the assignments to loft(a) and loft(A) refer to the same list element. There is only one list tag for the ListTag function to retrieve and print.
Option Compare NoCase Dim loft List As Integer loft%("a") = 2 loft%("A") = 17 ForAll i In loft% Print ListTag(i) Output: "A" End ForAll
Example 4
In this example, the Option Compare Binary statement specifies bit-wise (platform sort-order, case-sensitive) comparison as the default method for string comparison, so the list tags a and A are different tags. Thus, the assignments to loft(a) and loft(A) refer to different list elements.
Option Compare Binary Dim loft List As Integer loft%("a") = 2 loft%("A") = 17 ForAll i In loft% Print ListTag(i) Output: "a" and "A" End ForAll
Syntax
Option Declare Explicit is acceptable in place of Declare.
Usage
Option Declare can be specified only once in a module, and only at the module level. If the Option Declare statement appears in a module, then undeclared variables will generate syntax errors. When Option Declare is in effect, you must use the Dim statement to declare variables, except for arrays. You can still define an array implicitly using the ReDim statement. Option Declare must be used before any variables are implicitly declared.
409
Syntax
Option Public
Usage
Option Public can be specified only once in a module, and only at the module level. It must appear before any declarations in the module. Option Public applies to module-level declarations for any variable, constant, procedure, user-defined data type, user-defined class, or external C function. It does not apply to label definitions, ForAll reference variables, or any implicitly declared variables. The IDE automatically puts an Option Public statement in (Globals) (Options), so all (Globals) declarations are public by default. If you delete the Option Public statement, you must explicitly specify the Public keyword to make (Globals) declarations public. If a variable of a user-defined data type or an object reference variable is Public, the data type or the class to which it refers cannot be Private. Use the Private keyword in a declaration to override Option Public for that declaration.
Print statement
Prints data to the screen. Syntax Print [ exprList ]
Elements
exprList A list of expressions separated by semicolons, spaces, or commas.
410
Usage
If exprList is omitted, Print prints a blank line. Use the Spc and Tab functions to insert spaces and tabs between data items. The Print statement adds a newline character to the end of exprList (to force a carriage return), unless exprList ends with a semicolon or a comma. LotusScript inserts chr(10) to represent the newline character in any multiline string (for example, a string that you type in using vertical bars or braces). If you use Print to print the string, this newline character will be translated into the platform-specific newline character(s). Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. The following table shows how the Print statement handles data items specified in exprList.
Data item variable string date/time value Print statement behavior Prints the value of the variable. Prints the string. Prints the date as a string in the operating system Short Date and Time format. If either the date part or the time part is missing from the value, only the supplied part is printed. Prints an empty string (). Prints the string #NULL#.
Variant with the value EMPTY Variant with the value Null
The following table shows the effect of semicolons and commas in the Print statement.
Punctuation character Semicolon or space in exprList Semicolon at end ofexprList Comma in exprList Comma at end of exprList Print statement behavior The next data item is printed with no spaces between it and the previous data item. The next Print statement continues printing on the same line, with no spaces or carriage returns inserted. The next data item is printed beginning at the next tab stop. (Tab stops are at every 14 characters.) The next Print statement continues printing on the same line, beginning at the next tab stop. (Tab stops are at every 14 characters.)
If v v v
you are in Lotus Notes, note that the Print statement writes to the following: The status bar when executing on a Notes client in non-debug mode. The status bar and output window when executing on a Notes client in debug mode. NOTES.LOG when executing on a Domino server.
If the request is from the Web, Print will be re-directed to the source. Print can be used to dynamically generate a Web page via QueryOnEvent.
411
c% = 15 Print a%, b%, c% Prints 5 10 15 LotusScript prints the values of a, b, and c, separating them with tabs and ending the line with a newline character.
Print # statement
Prints data to a sequential text file.
Syntax
Print # fileNumber , [ exprList ]
Elements
fileNumber The file number assigned to the file when it was opened. Note that the pound sign (#), the file number, and the comma are all required. exprList Optional. A list of string and/or numeric expressions separated by semicolons, spaces, or commas. If you omit exprList, Print # prints a blank line.
Usage
Use Print # only on files opened in Output or Append mode. Unlike the Write # statement, the Print # statement does not separate the printed data items with formatting characters such as commas and quotation marks. Use the Spc and Tab functions to insert spaces and tabs between data items. If you set a width for the file using the Width statement, then the following occurs: v A comma moves the next print position to the next tab stop. If this moves the print position past the defined width, the next data item is printed at the beginning of the next line. v If the current print position is not at the beginning of a line and printing the next item would print beyond the defined width, the data item is printed at the beginning of the next line. v If the item is larger than the defined width, its printed anyway because Print # never truncates items. However, the line is terminated with a newline character to ensure that the next data item is printed on a new line. Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. The preceding statements about the effect of the Width statement apply for a width of 0, as well as any positive width. The following table shows how the Print # statement handles data items specified in exprList.
Data item variable string Print # statement behavior Prints the value of the variable. Prints the string.
412
Print # statement behavior Prints the date as a string in the operating system Short Date and Time format. If either the date part or the time part is missing from the value, only the supplied part is printed. Prints nothing to the file for the data item. Prints the string NULL to the file.
Variant with the value EMPTY Variant with the value Null
The following table shows the effect of semicolons and commas in the Print # statement.
Punctuation character Semicolon or space in exprList Comma in exprList Print statement behavior The next data item is printed with no spaces between it and the previous data item. The next data item is printed beginning at the next tab stop. (Tab stops are at every 14 characters.)
Syntax
[ Static ] [ Public | Private ] Property { Get | Set } propertyName [ ( [ paramList] ) ] [ As type ] [ statements ] End Property
413
Elements
Static Optional. Specifies that the values of a Static propertys variables are saved between calls to the property. Public | Private Optional. Public specifies that the property is visible outside the scope (module or class) where the property is defined, as long as this module is loaded. Private specifies that the property is visible only within the current scope. A property in module scope is Private by default. A property in class scope is Public by default. The Property Get and Property Set definitions for a property must use the same Public or Private setting. Get | Set Specifies which operation the procedure performs. A Property Get procedure retrieves the value of the property. A Property Set procedure assigns a value to the property. propertyName The name of the property. This name can have a data type suffix character appended to declare the data type of the value passed to and returned by the property. paramList Optional. A comma-separated list of declarations indicating the parameters to be passed to this property in Get and Set operations. The Get and Set operations must have the same number of arguments. The syntax for each parameter declaration is: [ ByVal ] parameter [ ( ) | List ] [ As type ] ByVal means that parameter is passed by value: that is, the value assigned to parameter is a local copy of a value in memory, rather than a pointer to that value. parameter () is an array variable. parameter List identifies parameter as a list variable. Otherwise, parameter can be a variable of any of the other data types that LotusScript supports. As dataType specifies the variables data type. You can omit this clause and append a data type suffix character to parameter to declare the variable as one of the scalar data types. If you omit this clause and parameter has no data type suffix character appended (and isnt covered by an existing Deftype statement), its data type is Variant. Enclose the entire list of parameter declarations in parentheses. type Optional. The data type of values passed to and returned by the property. type can be any of the scalar data types, a Variant, or a class name. If As Type is not specified, the property names data type suffix character determines the values type. Do not specify both a type and a data type suffix character, as LotusScript treats that as an error.
414
If no type is specified and the property name has no data type suffix character appended, the propertys value is either of data type Variant or of the data type specified by a Deftype statement. The types in the Property Get and Property Set definitions must be the same. statements Statements to retrieve or assign a property value.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). A property usually consists of two procedures with the same name: a Property Get and a Property Set. However, you are not required to provide both. A property member of a class cannot be declared Static. That is, a Property Get or Property Set statement within a class definition cannot begin with Static.
Or:
These statements assign the value of saveInt plus increment to x Dim saveInt As Integer Property Get pInt (increment As Integer) As Integer pInt% = saveInt% + increment% End Property x = pInt%(1%)
Or:
These statements assign the value of x + increment to SaveInt Dim SaveInt As Integer
415
Property Set pInt (increment As Integer) As Integer saveInt% = pInt% + increment% End Property pInt%(1%) = x
A variable to store values between uses of the property Dim count As Integer Property Get counter As Integer count% = count% + 1 Add 1 to the previous value. counter% = count% Return the value. End Property Property Set counter As Integer count% = counter% Assign the value to count. End Property counter% = 100 Each time the property is used, it increments count by 1 and returns counts value, so this prints 101. Print counter% Prints 102 Print counter%
Put statement
Writes data from a variable to a binary file or a random file.
416
Syntax
Put [#] fileNumber , [ recordNumber ] , variableName
Elements
fileNumber The file number assigned to the file when it was opened with the Open statement. Note that the pound sign (#), fileNumber, and variableName are all required. recordNumber Optional. The file position (the byte position in a binary file, or the record number in a random file) where data is written. If you omit the recordNumber, data is written starting at the current file position. variableName The variable holding the data to be written. variableName cannot be an array; however, a fixed-length array defined within a data type is allowed (this array could even contain other arrays as elements).
Usage
The first byte or record in a file is always file position 1. After each write operation, the file position is advanced: v For a binary file, by the size of the variable v For a random file, by the size of a record If variableName is shorter than the length of a record in the file, Put does not overwrite or delete any data that may already be stored in the remainder of that record. The following table shows how the Put statement behaves for different data types.
variableName data type Variant Put statements behavior The Put statement writes the DataType as the first two bytes before the value itself. If the DataType is EMPTY or NULL, the Put statement writes no more data. If the DataType is numeric, the Put statement writes the number of bytes of data appropriate for that DataType: Byte: 1 byte Boolean: 2 bytes Integer: 2 bytes Long: 4 bytes Single: 4 bytes Double: 8 bytes Currency: 8 bytes Date/time: 8 bytes Fixed-length String The Put statement writes the specified number of characters. For example, if a variable is declared as String * 10, then exactly 10 characters are written.
417
Put statements behavior The Put statement behaves differently, depending on the type of file youre using. Random files: The first two bytes written indicate the length of the string. Then the Put statement writes the number of characters specified by that length. If variableName is not initialized, the Put statement writes a string of length 0. If variableName is longer than a record, LotusScript generates the Bad record length error. If variableName is shorter than a record, the remainder of the record is not cleared. Binary files: The number of bytes written to the file is equal to the length of the string currently stored in variableName. If variableName is not initialized, no data is written to the file. Note that in binary files, data is written without regard to record length.
The Put statement writes the sum of the bytes required to write all members of the used-defined data type, which cannot contain a dynamic array, a list, or an object.
Note: Even though strings in LotusScript 4 can be longer than 64K, there are still restrictions with the length of the string you can read or write using the GET and PUT statements. The only combination of filetypes that will work with long strings is with a binary file and a variable-length string. Fixed length strings, strings in variants, and random files will not work with strings greater than 64K in length because they have a two-byte header which contains the length of the string. Two bytes cannot represent more than 64K.
Seek fileNum%, 1 Rewind file to beginning. Do While Not EOF(fileNum%) Get a record, print it out. Get advances the file position to the next record automatically. Get #fileNum%, , rec Print rec.empNumber%, rec.empName$ Loop Output:
418
123 John Smith 456 Jane Doe 789 Jack Jones Close fileNum%
Randomize statement
Seeds (initializes) the random number generator.
Syntax
Randomize [ numExpr ]
Elements
numExpr Any numeric expression. If you omit numExpr, Randomize uses the return value from Timer.
Usage
Use Randomize to seed the random number generator before calling Rnd to generate a number. If you use Randomize with numExpr and then repeatedly call Rnd with no arguments, LotusScript returns the same sequence of random numbers every time you run the script. To generate a different sequence of random numbers each time you run the script, do one of the following: v Use a variable numExpr to make sure that Randomize receives a different seed value every time the script is executed. v Use Randomize with no numExpr. This seeds the random number generator with the return value from Timer. The particular sequence of random numbers generated from a given seed depends on the platform where you are running LotusScript.
Example 2
Randomize Dont provide any seed. Print Rnd(); Rnd(); Rnd(); Rnd(); Rnd() Prints a series of random numbers. If you rerun this script, LotusScript produces a different sequence of random numbers, because Randomize is called with no argument.
ReDim statement
Declares a dynamic array and allocates storage for it, or resizes an existing dynamic array.
419
Syntax
ReDim [ Preserve ] arrayName ( bounds ) [ As type] [ , arrayName ( bounds ) [ As type ] ] ...
Elements
Preserve Optional. If youve already declared arrayName, LotusScript preserves the values currently assigned to it. If you omit Preserve, LotusScript initializes all elements of the array, depending on the data type of the array variable.
Data type of array variable Boolean, Byte, Integer, Long, Single, Double, or Currency Fixed-length String Variable-length String Variant Class User-defined data type Initial value of array element 0 A string of the specified length, filled with the Null character (Chr(0)) The empty string () EMPTY NOTHING The initial value of each elements own data type
arrayName The name of an array to be declared or resized. The arrayName must designate an array; it cannot be a Variant variable containing an array. bounds A comma-separated list of dimension bounds for arrayName. Each set of dimension bounds has the following form: [ lowerBound To ] upperBound The lowerBound is the minimum subscript allowed for the dimension, and upperBound is the maximum. If you dont specify a lowerBound, the lower bound for the array dimension defaults to 0, unless the default lower bound has been changed to 1 using the Option Base statement. Array bounds must fall in the range -32768 to 32767, inclusive. type Optional. A valid LotusScript data type, user-defined type, or class that specifies the data type of arrayName. You cannot change the data type of an existing array. If arrayName was declared and type is specified in the current ReDim statement, type must match the original data type of arrayName.
Usage
A ReDim statement allocates storage for a dynamic array. You can resize the array with additional ReDim statements as often as you want. Each time you resize the array, LotusScript reallocates the storage for it.
420
Unlike a Dim statement, ReDim cannot specify an array as Private, Public, or Static. To specify a dynamic array with one of these characteristics, declare it first in a Dim statement. If you declare a dynamic array with a Dim statement, LotusScript doesnt allocate storage for the array elements. You cant actually use the array in your script until you allocate storage with ReDim. Arrays can have up to 8 dimensions. The first ReDim statement for an array sets the number of dimensions for the array. Subsequent ReDim statements for the array can change the upper and lower bounds for each dimension, but not the number of dimensions. If Preserve is specified, you can change only the upper bound of the last array dimension. Attempting to change any other bound results in an error. Do not use ReDim on a fixed array (an array already declared and allocated by a Dim statement). If youre using ForAll on a container variable that is an array of arrays, do not ReDim the reference variable (this generates the Illegal ReDim error).
Example 2
Option Base 1 Declare a two-dimensional dynamic array, of Variant type. ReDim markMar(2, 2) Assign a markMar(1, markMar(2, markMar(1, markMar(2, value to each element. 1) = 1 1) = 2 2) = 3 2) = 4
Change the upper bound of the last dimension of markMar from 2 to 3, preserving the values already stored in existing elements of markMar. ReDim Preserve markMar(2,3) Assign values to the additional elements of markMar. markMar(1, 3) = 5 markMar(2, 3) = 6
Rem statement
Indicates a one-line comment in a script.
Syntax
Rem text
421
Elements
text A one-line comment that LotusScript ignores.
Usage
The Rem statement indicates a comment or remark in the script. The Rem statement need not be the first statement on a line, but it is the last: the LotusScript compiler ignores all text from the Rem keyword to the end of the current line. A line continuation character (an underscore) does not continue a Rem statement. The apostophe ( ) has the same effect as the Rem keyword and can appear anywhere on a line without needing a colon ( : ) to separate the statements. As with Rem, LotusScript ignores everything after the apostrophe.
Language cross-reference
REM keyword in formula language
Example 2
x = 5 : Rem The colon is required to separate statements. x = 5 No colon is required before a single quote.
%Rem directive
Indicates one or more comment lines in a script.
Syntax
%Rem text %End Rem
Elements
text One or more lines of text that LotusScript ignores.
Usage
The compiler ignores all text between %Rem and %End Rem, including text on the same line. %Rem and %End Rem must each be the first text on a line (they may be preceded on the line by spaces or tabs). Each must be followed by one or more spaces, tabs, or newline characters before any more text appears. %Rem...%End Rem blocks cannot be nested.
422
Note: For compatibility with older versions of the language, LotusScript Release 3 accepts the directive %EndRem (with no space) in place of %End Rem.
Language cross-reference
REM keyword in formula language
Example 2
%Rem blocks cannot be nested, so the second %Rem directive is illegal in the following. %Rem Comment line 1 Comment line 2 ... %Rem Error Comment line ... %End Rem %End Rem
Replace function
Replaces specific words or phrases in a string with new words or phrases that you specify. Note: This function is new with Domino Release 6.
Syntax
Replace( sourceArray , findArray , replacementArray [, start [, count [, compMethod]]])
Elements
sourceArray Array of type String containing the strings to be modified findArray Array of type String containing the words or phrases to be replaced replacementArray Array of type String containing the replacement words or phrases start optional Integer specifying the character position to start at in each String
Chapter 12. LotusScript Language Reference
423
count optional Integer specifying the maximum number of replacements to make. compMethod Optional Integer specifying the type of comparison to use when searching for the delimiter, if the elements are strings.
Number 0 1 4 5 Comparison Mode case sensitive, pitch sensitive case insensitive, pitch sensitive case sensitive, pitch insensitive case insensitive, pitch insensitive
If you omit compMethod, the default comparison mode is the mode set by the Option Compare statement for this module. If there is no statement for the module, the default is case sensitive and pitch sensitive.
Return value
Replace returns an Array of type String that contains sourceArray, where any values in replaceArray have been replaced by the corresponding values in replacementArray.
Usage
Replace searches the String in sourceArray for the String in replaceArray. If a match is found, the substring is replaced with a corresponding substring from replacementArray. Each String in replaceArray is scanned against each String in sourceArray as modified by prior substitutions. Replace is case sensitive. If no matches are found, then a copy of sourceArray is returned. If more strings are specified in replaceArray than in replacementArray, the extra strings in replaceArray are replaced with the last string in replacementArray. Extra strings in replacementArray are ignored. For example:
sourceArray = ["first second third"] replaceArray = ["first"]["second"]["1"]["third"]["2"]["3"] replacementArray = ["1"]["2"]["a"]["3"]["b"]["c"]
would return: [a b c] First, Replace substitutes 1 for first (the first String in replacementArray replaces the first string in replaceArray):
["1 second third"]
424
b for 2:
["a b 3"]
If sourceArray, replaceArray, or replacementArray is not either a String, or an Array of type String, then a run-time type mismatch error is thrown.
Language cross-reference
@Replace function in formula language EditFind @command in formula language
array1(0) = "original0" array1(1) = "ThisShouldNotBeReplaced1" array1(2) = "original2" array2(0) = "original" array2(1) = "ShouldNotFindThis" array2(2) = "once" array3(0) = "replaced--once--" array3(1) = "this should be skipped" array3(2) = "twice" ret = replace(array1, array2, array3) for x = 0 to 2 Print ret(x) Next End Sub OUTPUT replaced--twice--0 ThisShouldNotBeReplaced1 replaced--twice--2
Reset statement
Closes all open files, copying the data from each file to disk.
Syntax
Reset
Usage
Before closing the open files, Reset writes all internally buffered data to the files.
425
Resume statement
Directs LotusScript to resume script execution at a particular statement in a script, after an error has occurred.
Syntax
Resume [ 0 | Next | label ]
Elements
0 Resumes execution at the statement that caused the current error. Next Resumes execution at the statement following the statement that caused the current error. label Resumes execution at the specified label.
Usage
Use the Resume statement only in error-handling routines; once LotusScript executes the Resume statement, the error is considered handled. Resume continues execution within the procedure where it resides. If the error occurred in a procedure called by the current procedure, and the called procedure didnt handle the error, then Resume assumes that the statement calling that procedure caused the error: v Resume [0] directs LotusScript to execute again the procedure-calling statement that produced the error. Note that this may result in an infinite loop, where in every iteration, the procedure generates the error and then is called again. v Resume Next directs LotusScript to resume execution at the statement following the procedure call. The Resume statement resets the values of the Err, Erl, and Error functions.
426
Return statement
Transfers control to the statement following a GoSub or On...GoSub statement.
Syntax
Return
Usage
The GoSub and On...GoSub statements transfer control to a labeled statement within a procedure. Execution continues from this statement until a Return statement is encountered. LotusScript then transfers control to the first statement following the GoSub or On...GoSub statement. While executing the procedure, LotusScript can encounter a statement, such as Exit or GoTo, that forces an early exit from the procedure; in this case, the Return is not executed. The GoSub or On...GoSub statement, its labels, and the Return statement must reside in the same procedure.
Right function
Extracts a specified number of the rightmost characters in a string.
Syntax
Right[$] ( expr , n )
427
Elements
expr Any numeric or String expression for Right; and any Variant or String expression for Right$. If the expression is numeric, it is first converted to a string. n The number of characters to be returned.
Return value
Right returns a Variant of DataType 8 (String), and Right$ returns a String. If n is 0, Right returns the empty string (); if n is greater than the number of characters in expr, Right returns the entire string. Right(NULL,1) returns NULL. Right$(NULL,1) returns an error.
Usage
LotusScript Release 3 and later represent characters with two bytes instead of one, so Lotus no longer recommends using the RightB function to work with bytes.
Language cross-reference
@Right function in formula language
RightB function
LotusScript Release 3 and later use Unicode, a character set encoding scheme that represents each character as bytes. This means that a character can be accompanied by leading or trailing zeroes, so Lotus no longer recommends using RightB to work with bytes. Instead, use the Right function for right character set extractions.
RightBP function
Extracts a specified number of the rightmost bytes in a string using the platform-specified character set.
Syntax
RightBP[$] ( expr , n )
Elements
expr Any numeric or String expression for RightBP; and any Variant or String expression for RightBP$. If expr is numeric, LotusScript converts it to a string before performing the extraction. n
428
Return value
RightBP returns a Variant of DataType 8 (a String), and RightBP$ returns a String. If n is 0, the function returns the empty string (). If n is greater than the length (in bytes) of expr, the function returns the entire string. RightBP(NULL) returns NULL. RightBP$(NULL) is an error. If a double-byte character is divided, the character is not included.
Language cross-reference
@Right function in formula language
RightC function
Extracts the rightmostn columns from a string for column-based writing systems, such as Thai and Vietnamese.
Syntax
RightC[$] ( StringExpr, n )
Elements
StringExpr A String expression containing character columns. n The number of columns to be returned using the platform-specified character set.
Return value
RightC returns a Variant containing the columns specified by n. RightC$ returns a String.
Usage
If n is 0, the function returns the empty string (). If n is greater than the length (in columns) of StringExpr, the function returns the entire string. RightC supports the Thai and Vietnamese languages.
429
RmDir statement
Removes a directory from the file system.
Syntax
RmDir path
Elements
path A String expression specifying the path of the directory you want to remove.
Usage
The maximum length of path depends on the platform you are using. If the directory named by path is not empty, RmDir generates an error.
Rnd function
Generates a random number greater than 0 and less than 1.
Syntax
Rnd [ ( numExpr ) ]
Elements
numExpr Any numeric expression.
Return value
The return value is a number of data type Single. The following table shows how Rnd behaves, depending on the sign of numExpr.
Sign of numExpr Positive Zero ( 0 ) Negative Rnd behavior Returns the next random number in the sequence of random numbers generated from the value that most recently seeded the random number generator. Returns the random number most recently generated. The random number generator is seeded again with numExpr. Rnd returns the first number in the sequence generated from that seed value.
Usage
Use Randomize to seed the random number generator before calling Rnd to generate the number.
430
If you use Randomize with an argument and then repeatedly call Rnd (with no arguments), LotusScript returns the same sequence of random numbers every time you execute the script. The particular sequence of random numbers generated from a given seed depends on the platform where you are running LotusScript. If you use Randomize without an argument, LotusScript generates a different sequence of numbers each time you execute the script. You can call the function with no arguments as either Rnd or Rnd( ).
Language cross-reference
@Random function in formula language
.3883555
.3883555
Round function
Rounds a number to a specified number of decimal places.
Syntax
Round ( numExpr , places )
Elements
numExpr Any numeric expression. The number to be rounded. places Any numeric expression representing the desired number of decimal places. If placesis not an integer, it is converted to one.
Return value
Round returns aDouble. If the first non-significant digit is 5, and all subsequent digits are 0, the last significant digit is rounded to the nearest even digit. See the example that follows.
431
If placesis negative, the number is rounded to places digits to the left of the decimal point. See the example that follows.
Language cross-reference
@Round function in formula language
RSet statement
Assigns a specified string to a string variable and right-aligns the string in the variable.
Syntax
RSet stringVar = stringExpr
Elements
stringVar The name of a fixed-length String variable, a variable-length String variable, or a Variant variable. stringExpr The string to be assigned to the variable and right-aligned.
Usage
If the length of stringVar is greater than the length of stringExpr, LotusScript right-aligns stringExpr within stringVar and sets the remaining characters in stringVar to spaces. If the length of stringVar is less than the length of stringExpr, LotusScript copies only as many leftmost characters from stringExpr as will fit within stringVar. If stringVar contains a numeric value, LotusScript converts it to String to determine the length of the result. If stringVar is a Variant, it cant contain NULL. You cannot use RSet to assign variables of one user-defined data type to variables of another user-defined data type.
432
Example 2
Dim x As Variant x = "q" RSet x = "ab" Print x Prints "a" The string "q" is assigned to the Variant variable x, giving it a length of 1. The single leftmost character "a" of the two-character string expression "ab" is assigned to x.
RTrim function
Remove trailing spaces from a string and return the resulting string.
Syntax
RTrim[$] ( stringExpr )
Elements
stringExpr Any String expression.
Return value
RTrim returns a Variant of DataType 8 (String), and RTrim$ returns a String. RTrim returns the trimmed version of stringExpr, but does not modify the contents of stringExpr itself.
Run statement
LotusScript Release 3 and after no longer support the Run statement. To execute a Lotus software application macro, use the Evaluate function or statement.
Second function
Returns the second of the minute (an integer from 0 to 59) for a date/time argument.
Syntax
Second ( dateExpr )
Elements
dateExpr Any of the following kinds of expression: v A valid date/time string of String or Variant data type.
433
For Notes and Domino, a 2-digit designation of a year is interpreted so that 50 through 99 represent the years 1950 through 1999 and 00 through 49 represent the years 2000 through 2049. For SmartSuite, LotusScript interprets the years differently. For more information, see the Year 2000 item on the Help menu of each SmartSuite product. v A numeric expression whose value is a Variant of DataType 7 (Date/Time). v A number within the valid date range: the range -657434 (representing Jan 1, 100 AD) to 2958465 (Dec 31, 9999 AD). v NULL.
Return value
Second returns an integer between 0 and 59. The data type of Seconds return value is a Variant of DataType 2 (Integer). Second(NULL) returns NULL.
Language cross-reference
@Second function in formula language
Seek function
Returns the file position (the byte position in a binary file or the record number in a random file) in an open file.
Syntax
Seek ( fileNumber )
Elements
fileNumber The number assigned to the file when it was opened with the Open statement.
Return value
Seek returns a Long value between 1 and 2.0E31 - 1, inclusive, unless the file position is very large. For a file position larger than 2.0E30, the return value is negative.
434
For a binary or sequential file, Seek returns the current byte position within the file. For a random file, Seek returns the number of the next record within the file.
Usage
The first byte or record in a file is always file position 1.
Seek statement
Sets the file position (the byte position in a binary file or the record number in a random file) in an open file.
Syntax
Seek [#]fileNumber , position
Elements
fileNumber The number assigned to the file when it was opened with the Open statement. position The desired file position for the next read or write operation. In a binary or sequential file, this is a non-zero byte location; in a random file, this is a record number (in a random file). In a binary or sequential file, the first byte is byte number 1; in a random file, the first record is record number 1. If position is zero or is omitted, Seek returns an error.
435
Usage
The record number in a Get statement or a Put statement overrides a file position set by a Seek statement. Writing to a file after moving the file position beyond the end of the file appends data to the end of the file.
Syntax
Select Case selectExpr [ Case condList [ statements ] ] [ Case condList [ statements ] ] ... [ Case Else [ statements ] ] End Select
436
Elements
selectExpr An expression whose value is compared with values in the subsequent condList conditions. This expression is evaluated once, and its value is used repeatedly for comparison. condList Each condList is a list of conditions, one of which must be met for the subsequent group of statements to execute. Each condition takes one of the forms listed below, where expr is any expression: v expr Returns TRUE if selectExpr matches expr exactly. v expr To expr Returns TRUE if the selectExpr falls inclusively within this range. The range must be specified in ascending order. For example, if you specify 25 To 50, the corresponding group of statements is executed when selectExpr is any value between 25 and 50, inclusive. If you specify -4 to -1, the corresponding group of statements is executed when selectExpr is any value between -4 and -1, inclusive v Is comparisonOp expr Returns TRUE when the comparison operation for selectExpr and expr is true. The comparison operator must be one of the following: = > < <> >< <= =< >= =>. For example, if you specify Is < 37, then the corresponding group of statements is executed when selectExpr is less than 37. statements Statements to be executed if one of the governing conditions in the associated condList is the first condition to be satisfied.
Usage
The selectExpr is compared against each condition, within each condList in succession. The first time that a condition in some condList is satisfied, the group of statements associated with that condList is executed and the selection operation ends. Either a single group of statements is executed, or no statements are executed. If you include a Case Else group of statements, its executed only if selectExpr fails all conditions in all condList arguments.
Dim segSelect As Double ... For segSelect# = -1 to 7 Select Case segSelect# Case 0 : Print Case 1, 2 : Print Case 3 To 5 : Print Case Is >= 6 : Print Case Else : Print End Select Next Output:
437
SendKeys statement
Enters keystrokes in the active window as if they were entered from the keyboard. SendKeys is not supported on Macintosh and UNIX platforms and is not supported in Lotus Domino and Notes.
Syntax
SendKeys string[ , processNow ] string Any string expression, specifying a sequence of keystrokes to be sent to the active window. To repeat a keystroke in string, use the code {key count}, where key is the keystroke to repeat, and count is the number of times to repeat it. For example, {RIGHT 3} represents pressing the Right Arrow key three times. Include a space between key and count; otherwise {key count} may be interpreted as a function key specification. For example, {F 4} represents pressing the letter F four times, but {F4} represents pressing the function key F4. processNow Optional. Any numeric value. A nonzero value is interpreted as TRUE; a zero (0) is interpreted as FALSE. v If processNow is TRUE, script execution does not continue until after all characters in string have been processed by the active window. v If processNow is FALSE, script execution continues immediately, whether or not string has been fully processed. The default value of processNow is FALSE. You will usually want to specify TRUE for processNow.
Usage
The SendKeys statement is not legal at the module level. To send an ordinary keyboard key or sequence of keys, such as A or 8 or DIR, simply include the character(s) in string. To send non-printing keyboard keys, such as Tab or Backspace, or keys that perform actions in the active window, such as Page Up, use the key code from the following table in string.
Key Backspace Break Caps Lock Code {BS} or {BKSP} or {BACKSPACE} {BREAK} {CAPSLOCK}
438
Key Clear Del Down arrow End Enter Esc Help Home Ins Left arrow Num Lock Pg Dn Pg Up Right arrow Scroll Lock Tab Up arrow Function keys
Code {CLEAR} {DEL} or {DELETE} {DOWN} {END} ~ or {ENTER} {ESC} or {ESCAPE} {HELP} {HOME} {INSERT} {LEFT} {NUMLOCK} {PGDN} {PGUP} {RIGHT} {SCROLLLOCK} {TAB} {UP} {F1} to {F16}
To include a character from the following table in string, enclose it in braces as shown.
Character Brace Bracket Caret Parenthesis Percent sign Plus sign Tilde Code {{} or {}} {[} or {]} {^} {(} or {)} {%} {+} {~}
The following table shows how to designate keys pressed in combination with Alt, Ctrl, or Shift.
Combination key Alt Ctrl Shift Code % ^ + Example %{F4} represents Alt+F4 ^{F4} represents Ctrl+F4 +{F4} represents Shift+F4
To apply a combination key to a sequence of keys, enclose the sequence in parentheses. For example, +(xy) holds down the Shift key for both x and y. It is equivalent to +x+y.
439
SendKeys cannot send keystrokes to a window that is not a Windows or an OS/2 Presentation Manager program, and cannot send the Print Scrn key to any program. Also, SendKeys cannot send keystrokes to an OS/2 Presentation Manager window if that window is in the same process as the program calling SendKeys. SendKeys generates an Illegal function call error if string contains any of the following elements: v An unmatched parenthesis v An illegal key code v An illegal repeat count v Too many characters Note that SendKeys is often useful after Shell, to send keystrokes to the program that Shell started. Remember that Shell does not guarantee that the program is loaded before executing the statements that follow it.
Set statement
Assigns an object reference to a variable, or associates an object with a variable. Use one of the following three syntaxes:
Elements
var A Variant variable, an object of the class class, an object of a class derived from class, or any variable element that accepts an object reference, such as an element of an array, list, or user-defined data type. class The name of the user-defined or product class of the object to be created. argList For user-defined classes, argList is the comma-separated list of arguments required by the class constructor sub New, defined in the class named by type. For product classes, consult the product documentation.
440
Elements
var1 A Variant variable, an object of the same class as var2, an object of a class derived from var2s class, or any variable element that accepts an object reference, such as an element of an array, list, or user-defined data type. var2 An expression whose value is NOTHING, an object reference of the same class as var1, an object reference of a class derived from var1s class, or an object reference of a class from which var1 is derived. In the latter case, var2 must contain an instance of var1s class or a class derived from var1.
Elements
var A Variant variable, an object of prodClass, or any variable element that accepts an object reference, such as an element of an array, list, or user-defined data type. Bind The Bind keyword associates objectName with var. The association is made by name, and is valid until any of the following conditions is true: v var is out of scope. v objectName no longer exists. v var is set to another value. Note that you should not use Bind to associate a Lotus Notes object with a variable. Notes implicitly binds its supporting objects. prodClass Optional. The product class of the object objectName. If prodClassis not specified, LotusScript assumes that objectName is of the same class as var. If varis a Variant, you must include prodClass. objectName A string specifying the name and, optionally, the path of the product object of class prodClass. The form of this string is product-specific. For example, the product object name might have the form ApplicationWindowName\ObjectName. Refer to your Lotus software documentation for information about specifying product object names.
Usage
The Set statement is the object reference assignment statement. It is parallel to the Let statement, the general assignment statement for variables of all types except object reference variables.
441
When you use the user interface, rather than a script, to create a product object, some Lotus products implicitly declare the name you (or the product) have assigned the object as an object reference variable and bind it to the object. This allows you to use the object name in scripts without explicitly declaring a variable and binding it to the object. To test an object reference variable for the NOTHING value, use the Is operator.
Language cross-reference
@Set function in formula language
Example 2 (Syntax 2)
The classes Worker and Carpenter must already be defined, with Carpenter as a derived class of Worker. The first Dim statement declares x as an object reference variable of Worker. The second Dim statement declares y as an object reference variable of Carpenter. This statement also creates a new object of Carpenter, named "Terry"; and assigns its reference to the variable y. The Set statement assigns the reference in y to variable x. (A reference to a Carpenter can be assigned to a variable of Worker because Worker is the base class of Carpenter.) Dim x As Worker Dim y As New Carpenter("Terry") Set x = y
Example 3 (Syntax 3)
The Dim statement declares icCheckBox as an object reference variable of the pre-defined product class Check. The Set statement binds the object reference variable icCheckBox to the product object Checkbox1. Dim icCheckBox As Check Set icCheckBox = Bind("Checkbox1")
SetFileAttr statement
Sets the system attributes of a file.
Syntax
SetFileAttr fileName , attributes SetAttr is acceptable in place of SetFileAttr.
Elements
fileName A string expression; you can optionally include a path. attributes
442
The attributes to apply to the file, expressed as the sum of any of the following Integer values:
Value 0 1 2 4 32 Description Normal file Read-only Hidden System Changed since last back-up Constant ATTR_NORMAL ATTR_READONLY ATTR_HIDDEN ATTR_SYSTEM ATTR_ARCHIVE
The constants are defined in the file lsconst.lss. Including this file in your script allows you to use constant names instead of the corresponding numeric values.
Usage
Do not use SetFileAttr on an open file, unless the file has been opened as read-only.
Reset to normal
Sgn function
Identifies the sign (positive or negative) of a number.
Syntax
Sgn ( numExpr )
Elements
numExpr Any numeric expression.
443
Return value
The following table shows the values that the Sgn function returns.
Sign of numExpr Negative Zero Positive Value -1 0 1
Language cross-reference
@Sign function in formula language
Shell function
Starts another program.
Syntax
Shell ( program [ , windowStyle ])
Elements
program A string expression whose value is the name of the program to run, including arguments. program can be the name of an executable file that uses a file name extension of BAT, COM, PIF, or EXE. You can omit the file name extension, and you can optionally include a complete path specification. Using an internal DOS command name generates an error. windowStyle Optional. A number designating a valid window style, as specified in the following table.
Style 1, 5, or 9 2 3 4 or 8 6 or 7 Description Normal with focus Minimized with focus (default) Maximized with focus Normal without focus Minimized without focus Constant SHELL_NORMAL_FOCUS SHELL_MIN_FOCUS SHELL_MAX_FOCUS SHELL_NORMAL_NO_FOCUS SHELL_MIN_NO_FOCUS
The constants are defined in the file lsconst.lss. Including this file in your script allows you to use constant names instead of the numeric values assigned to them.
444
Return value
If LotusScript successfully starts program, Shell returns the number 33. Note: To get the programs task ID, use the Shellid function instead. If LotusScript cannot start program, Shell returns an error.
Usage
Shell must be called from within an expression or an assignment statement, so that its return value is used. In a UNIX or AIX environment, LotusScript will resume execution of the script only after the program has completed. In other environments, after Shell starts a program, LotusScript continues to execute the script without waiting to make sure the program has completed. You cannot be sure that a program started by Shell has finished running before the rest of your script is executed.
Language cross-reference
@LaunchApp function in formula language AttachmentLaunch @command in formula language Execute @command in formula language
Shellid function
Starts another program and returns its task ID.
Syntax
Shellid ( program [ , windowStyle ] )
Elements
program A string expression whose value is the name of the program to run, including arguments. program can be the name of an executable file that uses a file name extension of BAT, COM, PIF, or EXE. You can omit the file name extension, and you can optionally include a complete path specification. Using an internal DOS command name generates an error. windowStyle
445
Optional. A number designating a valid window style, as specified in the following table.
Style 1, 5, or 9 2 3 4 or 8 6 or 7 Description Normal with focus Minimized with focus (default) Maximized with focus Normal without focus Minimized without focus Constant SHELL_NORMAL_FOCUS SHELL_MIN_FOCUS SHELL_MAX_FOCUS SHELL_NORMAL_NO_FOCUS SHELL_MIN_NO_FOCUS
The constants are defined in the file lsconst.lss. Including this file in your script allows you to use constant names instead of the numeric values assigned to them.
Return value
If the operating system is Windows or Macintosh, and LotusScript successfully starts program, Shellid returns the programs task ID, a number that uniquely identifies the program. With other operating systems, if LotusScript successfully starts program, Shellid returns the number 33. If LotusScript cannot start program, Shellid returns an error.
Usage
Shellid must be called from within an expression or an assignment statement, so that its return value is used. After Shellid starts a program, LotusScript continues to execute the script without waiting to make sure the program has completed. You cannot be sure that a program started by Shellid has finished running before the rest of your script is executed. ShellID is a restricted operation - make sure you have set runtime security level 2 or higher Allow restricted operations. This feature will spawn processes which may outlive the spawning process. The ID returned from the function is so that you can terminate the program at a later time. If you dont want this behavior, use Shell.
Sin function
Returns the sine, in radians, of an angle.
Syntax
Sin ( angle )
446
Elements
angle Any numeric expression. It is interpreted as an angle expressed in radians.
Return value
Sin returns the sine of angle,a Double between -1 and 1, inclusive.
Language cross-reference
@Sin function in formula language
Usage
The Single suffix character for implicit data type declaration is the exclamation point (!). Single variables are initialized to zero (0). The range of Single values is -3.402823E+38 to 3.402823E+38, inclusive. The smallest nonzero Single value, disregarding sign, is 1.175494351E-38. LotusScript aligns Single data on a 4-byte boundary. In user-defined data types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space.
Sleep statement
Causes a script to pause for at least the number of seconds specified. The script may pause longer.
Syntax
Sleep ( numExpr )
Elements
numExpr Any numeric expression.
Chapter 12. LotusScript Language Reference
447
Usage
This function provides a way for a script to wait without consuming the system resources of a spin loop. Implementation depends on the platform, but on all platforms except the legacy platforms, this function causes the LotusScript code to give up its time slice. Accuracy is limited to the accuracy of the platform being used. If the most accurate timing is limited to milliseconds, the time specified is rounded up to the nearest millisecond.
Space function
Returns a specified number of spaces as a string.
Syntax
Space[$] ( numExpr )
Elements
numExpr Any numeric expression. If numExpr includes a fractional part, LotusScript rounds it to the nearest integer.
Return value
The return value contains numExpr space characters. Space returns a Variant of DataType 8 (String), and Space$ returns a String.
Spc function
Inserts a specified number of spaces in the output from a Print or Print # statement, beginning at the current character position.
Syntax
Spc ( numExpr )
Elements
numExpr Any numeric expression whose value is between 0 and 32000, inclusive. numExpr designates the number of spaces to insert in the Print output.
448
Usage
If you specify a width for the file, numExpr interacts with that width as follows: v If numExpr is smaller than the width, LotusScript prints numExpr spaces. v If numExpr is larger than the width, LotusScript prints as many spaces as fit on one line, with the remainder appearing on the next line, until numExpr spaces have been printed. You can set the width only for printed files. If you dont specify a width for the file, LotusScript prints exactly numExpr spaces.
Split function
Returns an Array of Strings that are the substrings of the specified String. Note: This function is new with Domino Release 6.
Syntax
Split ( expression [, delimiter [, count [, compMethod ]]])
Elements
expression The scalar String to be split into its substrings delimiter An optional scalar String containing the characters to separate substrings. If delimiter is not specified, then the space character is used count
449
An Integer specifying the number of substrings to return. The default value of -1 indicates that all substrings are returned. compMethod An Integer specifying the type of comparison to use when searching for the delimiter.
Number 0 1 4 5 Comparison method Case Sensitive, Pitch sensitive Case Insensitive, Pitch sensitive Case Sensitive, Pitch insensitive Case Insensitive, Pitch insensitive
Use 2 to specify string comparison in the platforms collation sequence. If 2 is specified, strings are compared bit-wise. If you omit compMethod, the default comparison mode is the mode set by the Option Compare statement for this module. If there is no statement for the module, the default is case-sensitive and pitch-sensitive.
Return value
Split returns an Array of Strings. Each element of this array contains a substring found in expression.
Usage
Split parses expression into substrings consisting of text delimited by the separator character (or the beginning or end of the String), and not containing the separator character. These substrings are placed into an Array in order, and the Array is returned. Whitespace is not trimmed. Carriage returns are not trimmed and do not cause separations. If the number of results specified is greater than the number of actual results, the returned Array will equal the number of actual results If the number of results specified is less than the number of actual results, the last element of the array returned will contain the remainder of the string. For example,
split("this is a test", " ", 2)
would return an array with element 0 = this, 1 = is a test If count is < -1, a RunTime Arg Out of Range error is thrown. If count is 0, Split returns an array of size 0 with lbound 0 and ubound -1.
Error Handling:
Split will throw a Runtime Type Mismatch if either the expression or the delimiter is not scalar. Split will throw a Runtime Argument Out of Range error if count is < -1 or optcompare is an invalid value.
Language cross-reference
@Explode function in formula language
450
Sqr function
Returns the square root of a number.
Syntax
Sqr ( numExpr )
Elements
numExpr Any numeric expression greater than or equal to zero.
Return value
Sqr returns a Double. If numExpr is negative, Sqr returns an error.
Language cross-reference
@Sqrt function in formula language
Stop statement
Simulates the occurrence of a breakpoint.
Syntax
Stop
Usage
The Stop statement operates as follows when run on the server: v If the remote debugger is not running or is running but not enabled, Stop is ignored. Performance of the agent is not affected.
451
v If the remote debugger is running and enabled, STOP waits according to the time-out value specified in the server record. (Stop uses the Agent wait at start time value in the Remote Debug Manager tab of the Server Tasks tab.) If the debugger does not attach to that agent within the specified time-out value, execution continues. So the STOP statement does not stop the agent completely, but waits to allow the user to attach the remote debugger to it. v If the remote debugger is attached, the agent stops at the Stop statement as if a breakpoint was set. The Stop statement operates as follows when in debug mode (File->Tools->Debug LotusScript) on the client: v If the agent is running as a scheduled agent in the background, Stop is ignored. v If the agent is run from the Agents or Actions menu, the Stop statement suspends execution of the script and transfers control to the LotusScript debugger as though a breakpoint is set at the Stop statement. v When not in debug mode, the Stop statement is ignored. The Stop statement is legal within a procedure or class. It is not legal at the module level.
Str function
Returns the String representation of a number.
Syntax
Str[$] ( numExpr )
Elements
numExpr Any numeric expression.
Return value
Str returns a Variant of DataType 8 (a string), and Str$ returns a String.
Usage
When LotusScript represents a positive number as a String, it inserts a leading space.
Language cross-reference
@TextToNumber function in formula language
StrCompare function
Compares two strings and returns the result.
452
Syntax
StrCompare ( string1 , string2 [ , compMethod ]) StrComp is acceptable in place of StrCompare.
Elements
string1 Any String expression. string2 Any String expression. compMethod A number designating the comparison method.
Number 0 1 4 5 Comparison method Case Sensitive, Pitch sensitive Case Insensitive, Pitch sensitive Case Sensitive, Pitch insensitive Case Insensitive, Pitch insensitive
Use 2 to specify string comparison in the platforms collation sequence. If 2 is specified, strings are compared bit-wise. If you omit compMethod, the default comparison mode is the mode set by the Option Compare statement for this module. If there is no statement for the module, the default is case-sensitive and pitch-sensitive.
Return value
The following table shows what StrCompare returns, depending on the relationship between the strings being compared.
Strings being compared Either string is NULL string1 is less than string2 string1 equals string2 string1 is greater than string2 StrCompare result NULL -1 0 1
Language cross-reference
@Compare function in formula language
453
StrConv function
Converts a string to a different case or character set.
Syntax
StrConv ( expr , conversionType )
Elements
expr A string or numeric expression. A numeric expression is converted to a string. conversionType An integer that defines the type of conversion:
Constant name SC_UpperCase SC_LowerCase SC_ProperCase SC_Wide SC_Narrow SC_Katakana SC_Hiragana SC_NativeDigit SC_ArabicDigit Value 1 2 3 4 8 16 32 256 512 Type of conversion Uppercase Lowercase Proper case Single byte to double byte Double byte to single byte Hiragana to Katakana Katakana to Hiragana Convert 0-9 to native digits Convert native digits to 0-9
Return value
The return value is a variant containing the result of the conversion.
454
Usage
The valid values for the conversionType elements listed in the preceding table are defined as constants in the file lsconst.lss. If you want to use the constants instead of numbers, include this file in your script. ConversionType values can be combined (ored) as follows: v Any combination of SC_UpperCase, SC_LowerCase, and SC_ProperCase causes SC_ProperCase. v Combining SC_Wide and SC_Narrow is illegal. v Combining SC_Katakana and SC_Hiragana is illegal. v If combined, the following operations occur in the following order: case operation, SC_Wide, SC_Katakana. Case operations are applied to double-byte alphanumeric characters. If expr is the null string, the result is the null string. If expr is Null, the result is Null. For proper case, the following numeric character codes are treated as word separators in a string literal: 0 (null), 9 (horizontal tab), 12 (form feed), 32 (space), 0x3000 (double-byte space). The following are treated as separators in a multi-line string: 10 (line feed), 13 (carriage return).
Language cross-reference
@ProperCase function in formula language @LowerCase function in formula language @UpperCase function in formula language @Narrow function in formula language @Wide function in formula language
StrLeft function
Searches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern.
Syntax
StrLeft ( expression , pattern [, compMethod [, occurrences ]] )
Elements
expression A String to search for the specified pattern. pattern The String pattern to search for. compMethod
455
occurrences Long. Number of occurrences to match before returning the substring. Default = 1 or return on first occurrence found. Extended example: array and String functions
Language cross-reference
@Left function in formula language
StrLeftBack function
Searches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern.
Syntax
StrLeftBack ( expression , pattern [, compMethod [, occurrences ]])
Elements
expression A String to search for the specified pattern. pattern The String pattern to search for. compMethod An Integer specifying which comparison to use.
Flag 0 1 4 5 Type of Comparison Case Sensitive, Pitch Sensitive Case Insensitive, Pitch Sensitive Case Sensitive, Pitch Insensitive Case Insensitive, Pitch Insensitive
occurrences Long. Number of occurrences to match before returning the substring. Default = 1 or return on first occurrence found.
456
Language cross-reference
@LeftBack function in formula language
StrRight function
Searches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern.
Syntax
StrRight ( expression , pattern [, compMethod [, occurrences ]] )
Elements
expression A String to search for the specified pattern. pattern The String pattern to search for. compMethod An Integer specifying which comparison to use.
Flag 0 1 4 5 Type of Comparison Case Sensitive, Pitch Sensitive Case Insensitive, Pitch Sensitive Case Sensitive, Pitch Insensitive Case Insensitive, Pitch Insensitive
occurrences Long. Number of occurrences to match before returning the substring. Default = 1 or return on first occurrence found. Extended example: array and String functions
Language cross-reference
@Right function in formula language
StrRightBack function
Searches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern.
Syntax
StrRightBack( expression , pattern [, compMethod [, occurrences ]])
457
Elements
expression A String to search for the specified pattern. pattern The String pattern to search for. compMethod An Integer specifying which comparison to use.
Flag 0 1 4 5 Type of Comparison Case Sensitive, Pitch Sensitive Case Insensitive, Pitch Sensitive Case Sensitive, Pitch Insensitive Case Insensitive, Pitch Insensitive
occurrences Long. Number of occurrences to match before returning the substring. Default = 1 or return on first occurrence found. Extended example: array and String functions
Language cross-reference
@RightBack function in formula language
StrToken function
Returns a specified word from a text string. Note: This function is new with Domino Release 6.
Syntax
StrToken ( expression , delimiter , wordNumber [, compMethod])
Elements
expression String containing the string to be scanned. delimiter String containing the character(s) that will delimit a word in expression. wordNumber Long indicating which word from expression should be returned. compMethod
458
Optional Integer specifying the type of comparison to use when searching for the delimiter.
Number 0 1 4 5 Comparison Mode case sensitive, pitch sensitive case insensitive, pitch sensitive case sensitive, pitch insensitive case insensitive, pitch insensitive
If you omit compMethod, the default comparison mode is the mode set by the Option Compare statement for this module. If there is no statement for the module, the default is case sensitive and pitch sensitive.
Return value
Returns a String. The String returned is the specified word from expression.
Usage
StrToken returns the specified word from a text string. A word is defined as the part of a string that is delimited by the defined separator character. For example, if you specify a space ( ) as the separator, a word is any series of characters preceded by and followed by a space (or by the quotation marks that indicate the beginning or end of the string). e.g. hello there has four words - , hello , there, Note: The first word, , is considered a word because it is delimited by the beginning of the string on the left and by the delimiter character on the right. Expression is broken up into words and the word in the position specified by wordNumber is returned. If the absolute value of wordNumber is greater than the number of words, the specified word is assumed to be the empty string . If wordNumber = 0, the word specified is taken to be the 1st word of the String (i.e. wordNumber=0 is equivalent to wordNumber=1) If wordNumber < 0, the word specfied is found by counting backwards from the last word of the String.
Error Handling
StrToken will throw a Runtime Type Mismatch if the expression or delimiter is not scalar, or if wordNumber is not a long (cannot be coerced to a long by the compiler) StrToken will throw a Runtime Argument Out of Range Error if the optionCompare value is invalid.
Language cross-reference
@Word function in formula language
459
OUTPUT Computers
Usage
The String suffix character for implicit data type declaration is the dollar sign ($). The declaration of a string variable uses this syntax: Dim varName As String [* num] The optional num argument specifies that varName is a fixed-length string variable of numcharacters. A fixed-length string variable is initialized to a string of null characters (the character Chr(0)). When you assign a string to a fixed-length string variable, LotusScript truncates a longer string to fit into the declared length. It pads a shorter string to the declared length with trailing spaces. Fixed-length strings are often used in declaring data structures for use in file I/O or C access. An implicitly declared String variable is always a variable-length string variable. Variable-length strings are initialized to the empty string (). LotusScript aligns variable-length String data on a 4-byte boundary. In user-defined data types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space. Fixed-length strings are not aligned on any boundary.
Explicitly declare a variable-length String variable. Dim firstName As String firstName$ = "Mark" Explicitly declare a fixed-length String variable. Dim homeState As String * 4 homeState$ = " MA" Implicitly declare a variable-length String variable. adStreet$ = "123 Maple St." Print firstName$ Prints "Mark" Print adStreet$; homeState$ Prints "123 Maple St. MA"
String function
Returns a string consisting of a particular character repeated a number of times. The character is specified as a string, or a value interpreted as a locale-sensitive ASCII character code.
Syntax
String[$] ( stringLen , { charCode | stringExpr } )
460
Elements
stringLen A numeric expression whose value is the number of characters to put in the returned string. LotusScript rounds stringLen to the nearest integer. charCode A numeric expression of data type Long. If LotusScript is running on a native ASCII platform, the value is interpreted as a code in the platform-native character set. If LotusScript is running on a native EBCDIC platform, the value is interpreted as the ASCII equivalent for the platforms current locale. Both single-byte and double-byte characters are acceptable. stringExpr Any string expression. The first character in this string is the character to be used in the returned string.
Return value
String returns a Variant of DataType 8 (String), and String$ returns a String.
********
Sub statement
Defines a sub.
Syntax
[ Static ] [ Public | Private ] Sub subName [ ( [ argList ] ) ] [statements ] End Sub
Elements
Static Optional. Directs LotusScript to save the values of the subs local variables between calls to the sub. Public | Private Optional. Public specifies that the sub is visible outside the scope (module or class) where the sub is defined, as long as this module is loaded. Private specifies that the sub is visible only within the current scope. A sub in module scope is Private by default; a sub in class scope is Public by default. subName The sub name. The names Delete, Initialize, New, and Terminated are specialized. Use these names only as described in the topics Sub Delete, Sub Initialize, Sub New, and Sub Terminate.
Chapter 12. LotusScript Language Reference
461
argList Optional. A comma-separated list of declarations for arguments to be passed to this sub when it is called. The syntax for each argument declaration is: ByVal argument [ ( ) | List ] [ As dataType ] ByVal specifies that argument is passed by value: that is, the value assigned to argument is a copy of the value specified in the sub call, rather than a reference to the original value. argument () is an array variable. argument List identifies argument as a list variable. Otherwise, argument can be a variable of any of the other data types that LotusScript supports. As dataType specifies the variables data type. You can omit this clause and use a data type suffix character to declare the variable as one of the scalar data types. If you omit this clause and argument doesnt end in a data type suffix character (and isnt covered by an existing Deftype statement), LotusScript assigns it the Variant data type. Enclose the entire list of argument declarations in parentheses.
Usage
The Public keyword cannot be used in a product object script or %Include file in a product object script, except to declare class members. You must put such Public declarations in (Globals). Arrays, lists, type instances, and objects cant be passed by value as arguments. They must be passed by reference. A sub does not return a value. A sub can be called in either of these two forms: subName arg1, arg2, ... Call subName(arg1, arg2, ...) A sub definition cant contain the definition of another procedure (a function, sub, or property). A sub member of a class cannot be declared Static. You can exit a sub using an Exit Sub statement. Your Lotus software application can provide special named subs for use in your scripts; see the product documentation for more information.
462
v If the user enters positive values, Payment returns the monthly payment. Otherwise, it returns 0. ComputeMortgageCosts then constructs an appropriate message.
Dim price As Single, message As String Function Payment (princpl As Single, _ ByVal intrst As Single, _ ByVal term As Integer) As Single intrst! = intrst!/12 term% = term% * 12 If any of the parameters is invalid, exit the function (Payment will return the value 0). If princpl! <= 0 Or intrst! <= 0 Or term% < 1 Then Exit Function The standard formula for computing the amount of the periodic payment of a loan: Payment = princpl! * intrst! /(1 - (intrst! + 1) ^ (-term%)) End Function Sub ComputeMortgageCosts (price As Single) Dim totalCost As Single, downpmt As Single Dim mortgage As Single, intrst As Single Dim monthlypmt As Single, years As Integer EnterInfo: downpmt! = CSng(InputBox(How much is the down payment?")) The downpayment must be at least 10% of the price. If downpmt! < (0.1 * price!) Then MessageBox "Your down payment must be at least " _ & Format(price! * .1, "Currency") GoTo EnterInfo: End If mortgage! = price! - downpmt! intrst! = CSng(InputBox("What is the interest rate?")) years% = CInt(InputBox("How many years?")) Call the Payment function to return the monthly payment. monthlypmt! = Payment(mortgage!, intrst!, years%) totalCost! = downpmt! + (monthlypmt! * years% * 12) If monthlypmt! > 0 Then Create a multiline message. message$ = _ |Price | & Format(price!, "Currency") & | Down Payment: | & Format(downpmt!, "Currency") & | Mortgage: | & Format(mortgage!, "Currency") & | Interest: | & Format(intrst!, "Percent") & | Term: | & Str(years%) & | years Monthly Payment: | & Format(monthlypmt!, "Currency") & | Total Cost: | & Format(monthlypmt! * years% * 12, "Currency") Else message$ = "You did not enter valid input." End If End Sub Start here. price! = CSng(InputBox("How much does the house cost?")) Call the Compute MortgageCosts sub. ComputeMortgageCosts (price!) Display the message. MessageBox message$
Sub Delete
A user-defined sub that LotusScript executes when you delete an object belonging to the class for which the Delete sub is defined.
463
Syntax
Sub Delete [ statements ] End Sub
Usage
In the definition for a user-defined class, you can define a destructor named Delete. This sub is automatically executed whenever you delete an object belonging to the class for which you defined the Delete sub. The Delete sub is always Public: you cant declare it as Private. The Delete sub cant take any arguments. The Delete sub cant be called directly; its invoked only when the object is deleted. The name Delete can only be used as the name of a destructor; for example, it cant be used to name any other procedure or a variable.
Sub Initialize
A user-defined sub that LotusScript executes when the module containing the Initialize sub is loaded.
464
Syntax
Sub Initialize [ statements ] End Sub
Usage
Include in the Initialize sub any statements that you want executed when LotusScript loads the containing module. The Initialize sub is always Private. The Initialize sub cannot take any arguments.
Sub New
A user-defined sub that LotusScript executes when you create an object of the class for which the New sub is defined.
Syntax
Sub New [ ( [ argList ] ) ] [ , baseClass ( [ baseArgList ] ) ] [ statements ] End Sub
Elements
argList Optional. A comma-separated list of parameter declarations for the New sub, enclosed in parentheses. Use the following syntax for each parameter declaration: [ ByVal ] paramName [ ( ) | List ] [ As dataType ] ByVal means that paramName is passed by value: that is, the value assigned to paramName is a copy of the value specified in the sub call, rather than a reference to the original value.
Chapter 12. LotusScript Language Reference
465
paramName() is an array variable; List identifies paramName as a list variable; otherwise, paramName can be a variable of any of the other data types that LotusScript supports. As dataType specifies the variable data type. You can omit this clause and use a data type suffix character to declare the variable as one of the scalar data types. If you omit this clause, and paramName doesnt end in a data type suffix character (and isnt covered by an existing Deftype statement), its data type is Variant. If the New sub for the derived class has no arguments, and the New sub for the base class has no arguments, omit (argList) and baseClass (baseArgList). baseClass ( [ baseArgList ] ) Optional. The baseClassis the name of the class from which the derived class is derived. This name must match the baseClass name in the Class statement for the derived class. The baseArgListis a comma-separated list of arguments for the sub New of the base class. Note that these are actual arguments, not parameter declarations. This syntax enables a call of the New sub for the derived class to furnish actual arguments to the call of the New sub for the base class. Include this syntax in the New sub only if all of these conditions are true: v The class being defined is a derived class. v The New sub for the base class of this derived class requires arguments. Note that these arguments must be furnished to the New sub for the base class through the call of the New sub for the derived class. v The argument list for the sub New of the base class does not match the argument list for the sub New of the derived class in number and data type of arguments; or you want to pass different arguments to the base class sub New than those passed to the derived class sub New. When the class being defined is a derived class, each call of the New sub for the derived class generates a call of the New sub for the base class. If that base class is itself a derived class of another base class, another call is generated, and so on.
Usage
In the definition for a user-defined class, you can include a definition for the constructor sub, named New. If the definition exists, LotusScript calls this sub whenever it creates an object from that class. LotusScript calls the sub immediately after creating the object.
466
Define destructor sub. Sub Delete Print "Deleting text object." End Sub Define a sub to invert background and text colors. Sub InvertColors Dim x As Integer, y As Integer x% = backGroundColor% y% = textColor% Me.backGroundColor% = y% Me.textColor% = x% End Sub End Class Create a new object of class textObject. Dim zz As New textObject(0, 255, "This is my text") Output: Creating new instance of text object ... Text object state: Background color: 0 Text color: 255 Invert the objects background and text colors. zz.InvertColors Delete the object, first running the destructor sub. Delete zz Output: Deleting text object.
Sub Terminate
A user-defined sub that LotusScript executes when the module containing the Terminate sub is unloaded.
Syntax
Sub Terminate [statements ] End Sub
Usage
Include in the Terminate sub any statements that you want executed when LotusScript unloads the containing module. The Terminate sub is always Private. The Terminate sub cannot take any arguments.
467
loaded. Sub Terminate Return to the startup directory. ChDir startDir$ End Sub
Tab function
Moves the print position to a specified character position within a line, when called from within a Print or Print # statement.
Syntax
Tab ( column )
Elements
column Any integer expression between 1 and 32000, inclusive, specifying a character position in the printed output. If column is less than 1, the Tab position defaults to 1 (the leftmost print position).
Usage
If you havent specified a width for the file, Tab checks column against the current print position, and acts as follows: v If youve already printed past the position specified by column, Tab prints a newline character, and then prints the next character in the column position on the next line. Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. v If column is at the current position, or after the current position, Tab prints enough spaces to move to the position specified by column and prints the next character in the column position on the current line. If you print to a file whose width was set with the Width # statement, Tab interacts with that width as described in the following table.
Column > width <1 < current print position > current print position Tab moves to: column Mod width column 1 (column - current position) on the next line (column - current position) on the same line
Language cross-reference
@Char function in formula language
LotusScript prints the contents of firstN and lastN, using Tab() to separate them as follows:
468
The semicolons in the Print statement are optional; they have no effect on the output, because the print position is determined by Tab.
Tan function
Returns the tangent, in radians, of an angle.
Syntax
Tan ( angle )
Elements
angle Any numeric expression. It is interpreted as an angle expressed in radians.
Return value
Tan returns a Double.
Language cross-reference
@Tan function in formula language
Time function
Returns the system time as a time value.
Syntax
Time[$]
Return value
Time returns a time value representing the system time. The return value is the fractional part of the value returned by the Now function. Time returns that value as a Variant of DataType 7 (Date/Time). Time$ returns that value as a String. Both forms return the time rounded to the nearest second.
Usage
You can call the Time function as either Time or Time( ). You can call the Time$ function as either Time$ or Time$( ).
469
Time statement
Sets the system time to a specified time. This statement is not valid on UNIX operating systems, for which you need to have root user privileges to change the system time. Note: TSyntax Time[$] = timeExpr
Elements
timeExpr Any expression whose value is a valid date/time value: either a String in a valid date/time format, or else a Variant containing either a date/time value or a string value in date/time format.
TimeNumber function
Returns a time value for a specified hour, minute, and second.
Syntax
TimeNumber ( hour , minute , second ) TimeSerial is acceptable in place of TimeNumber.
Elements
hour A numeric expression representing an hour (0 to 23, inclusive). minute A numeric expression representing a minute (0 to 59, inclusive). second A numeric expression representing a second (0 to 59, inclusive).
Return value
TimeNumber returns a Variant of DataType 7 (Date/Time). Its value represents time of day as a fraction of 24 hours, measured from midnight.
Usage
You can use expressions for hour, minute, and second to compute a time relative to another time. For example:
470
TimeNumber(3, 5, 5 - 10)
computes the time 10 seconds before 3:05:05 AM (the result is 3:04:55 AM).
Timer function
Returns the time elapsed since midnight, in seconds.
Syntax
Timer
Return value
Timer returns the number of seconds elapsed since midnight as a Single value.
Usage
LotusScript rounds the number of seconds to the nearest hundredth. The Randomize Statement uses the return value from Timer as its default seed value. You can call the function as either Timer or Timer( ).
TimeValue function
Returns the time value represented by a string expression.
Syntax
TimeValue ( stringExpr )
Elements
stringExpr A string expression that represents a valid date/time, or a Variant of DataType 7 (Date/Time). It can use either 12-hour or 24-hour format; for example, both 14:35 and 2:35PM are valid. If you omit the seconds value in the stringExpr argument, it defaults to zero (0).
Return value
TimeValue returns a Variant of DataType 7 that contains a fractional date/time value.
Chapter 12. LotusScript Language Reference
471
Usage
If stringExpr specifies a date, TimeValue validates the date, but omits it from the return value.
Language cross-reference
@TextToTime function in formula language
Today function
Returns the system date as a date value.
Syntax
Today
Return value
Today returns the system date as a Variant of DataType 7 (Date/Time). The return value is the integer part of the value returned by the Now function.
Usage
The Today function is equivalent to the Date function. You can call the function as either Today or Today( ).
Language cross-reference
@Today function in formula language
Trim function
Removes leading and trailing spaces from a string and returns the resulting string.
Syntax
Trim[$] ( stringExpr )
472
Elements
stringExpr Any string expression.
Return value
Trim returns the trimmed version of stringExpr, but does not modify the contents of stringExpr itself. Trim returns a Variant of DataType 8 (String), and Trim$ returns a String.
Language cross-reference
@Trim function in formula language
Type statement
Defines a user-defined data type consisting of one or more members.
Syntax
[ Public| Private ] Type typeName member declarations End Type
Elements
Public | Private Optional. Public specifies that the user-defined data type is visible outside the module where it is defined, as long as that module is loaded. Private specifies that the user-defined data type is visible only within the module where it is declared. A type is Private by default. typeName The name of the type. member declarations Declarations for the members of the type. There must be at least one declaration in the type; the declarations cannot include Const statements.
473
474
Print "Call " & x.name$ & " at " & Str$(x.areaCode%) & "-" & _ Call Rory at 999-555-9320"
x.phone% Output:
Example 2
Create an array to hold five instances of phoneRec. Dim multiX(5) As phoneRec multiX(2).name$ = "Maria" Assign values. multiX(2).areaCode% = 212 multiX(2).phone$ = "693-5500" Retrieve data from a type member. Dim phoneLocalHold As String * 8 phoneLocalHold$ = multiX(2).phone$ Print phoneLocalHold$ Output: 693-5500
Example 3
To maintain a file that contains a phone list, read all of the data from the file into LotusScript. The data fills a list in which each element is an instance of the defined type.
Create a list to hold records from the file. Dim phoneList List As phoneRec Declare a phoneRec variable to hold each record from the file in turn. Open the file. Dim tempRec As phoneRec Open "c:\phones.txt" For Random Access Read Write _ As #1 Len = Len(tempRec) Read the file and store the records in the list. Dim recNum As Integer recNum% = 1 While EOF(1) = FALSE Get #1, recNum%, tempRec phoneList(tempRec.Name$) = tempRec recNum% = recNum% + 1 Wend Close #1 Note that the Get statement automatically fills each member of the tempRec variable. Since tempRec and the elements of phoneList are both of data type phoneRec, tempRec can be assigned to any element of phoneList without reference to its members, which LotusScript copies automatically.
TypeName function
Returns a string identifying the data type of the value of an expression.
Chapter 12. LotusScript Language Reference
475
Syntax
TypeName ( expr )
Elements
expr Any expression.
Return value
Value of expr EMPTY NULL Boolean Byte Integer Long Single Double Currency Date String NOTHING OLE object OLE error Return value EMPTY NULL BOOLEAN BYTE INTEGER LONG SINGLE DOUBLE CURRENCY DATE STRING OBJECT OBJECT ERROR The name of the object class, as an uppercase string. For example, for an object of the Employee class, LotusScript returns EMPLOYEE. The name of the list data type, plus the word LIST, all as an uppercase string. For example, for a list of type String, LotusScript returns STRING LIST. Array The name of the array data type as an uppercase string, followed by parentheses enclosing one space. For example, for an integer array, LotusScript returns INTEGER( ). In Variant only In Variant only In Variant only In Variant only Storage of variable In Variant only In Variant only
List
Language cross-reference
@IsNumber function in formula language @IsTime function in formula language @IsText function in formula language
476
Arrays Dim arrayl(1 To 4) As Long Print TypeName(arrayl&) Prints "LONG( )" Dim arrayV(1 To 4) Print TypeName(arrayV) Prints "VARIANT( )" Dim y As Variant y = arrayl Print TypeName(y) Prints "LONG( )" Lists Dim listStr List As String Print TypeName(listStr$) Prints "STRING LIST" Dim listVar List Print TypeName(listVar) Prints "VARIANT LIST" Dim p As Variant p = listStr$ Print TypeName(p) Prints "STRING LIST" Class instances Class Employee ... class definition End Class Dim temp As Employee Print TypeName(temp) Prints "EMPLOYEE" Set hire = New Employee Print TypeName(hire) Prints "EMPLOYEE" Dim emps(3) As Employee Print TypeName(emps()) Prints "EMPLOYEE( )" OLE class instances Set cal = CreateObject("dispcalc.ccalc") Print TypeName(cal) Prints "OBJECT"
UBound function
Returns the upper bound for one dimension of an array.
Syntax
UBound ( arrayName [ , dimension])
Elements
arrayName The name of an array. dimension Optional. An integer argument that specifies the array dimension for which you want to retrieve the upper bound.
Return value
UBound returns an Integer.
Chapter 12. LotusScript Language Reference
477
Usage
The default value for dimension is 1. LotusScript sets the upper bound for each array dimension when you declare a fixed array, or when you use ReDim to define the array dimensions of a dynamic array.
UCase function
Converts all alphabetic characters in a string to uppercase, and returns the resulting string.
Syntax
UCase[$] ( expr )
Elements
expr For UCase, any numeric or string expression. For UCase$, any Variant or string expression.
Return value
UCase returns a Variant of DataType 8 (String). UCase$ returns a String. UCase(NULL) returns NULL. UCase$(NULL) returns an error.
Usage
The function has no effect on non-alphabetic characters.
Language cross-reference
@UpperCase function in formula language
UChr function
Returns the character represented by a Unicode numeric character code.
478
Syntax
UChr[$] ( longExpr )
Elements
longExpr Any expression with a numeric value between 0 and 65535, inclusive.
Return value
UChr and UChr$ return the Unicode character corresponding to the value of longExpr. UChr returns a Variant of DataType 8 (String). UChr$ returns a String.
Uni function
Returns the Unicode numeric character code for the first character in a string.
Syntax
Uni ( stringExpr )
Elements
stringExpr Any string expression.
Return value
Uni returns a Long.
Usage
If stringExpris NULL or the empty string (), the function returns an error.
Unlock statement
See Lock and Unlock Statements.
479
Use statement
Loads a module containing Public definitions needed by the module being compiled.
Syntax
Use useScript
Elements
useScript A String literal, or a constant containing a String value, specifying the module to load. The Lotus software application that youre using determines whether useScriptmust be compiled before use. Consult the product documentation for more information.
Usage
The Use statement can appear only at module level, before all implicit declarations within the module. Note that the Use statement is supported in Lotus Notes.
UseLSX statement
Loads a LotusScript extensions (lsx) file containing Public definitions needed by the module being compiled.
Syntax
UseLSX lsxLibraryName
480
Elements
lsxLibraryName A string literal specifying the lsx file to load, either a name prepended with an asterisk or the full path name of the file. If you specify a name prepended with an asterisk (for example, *LSXODBC), the file is determined by searching the registry, initialization file, or preferences file, depending on the client platform. The Windows 95 registry, for example, might contain an entry for HKEY_LOCAL_MACHINE, SOFTWARE, Lotus, Components, LotusScriptExtensions, 2.0, LSXODBC, whose value is c:\notes95\nlsxodbc.dll. lsxLibraryName can contain ?, an optional flag that signals the lsx file is not necessary during run time. The question mark is part of the String, * and % flags follow the ? if desired. e.g. ?*NAME_OF_LIBRARY. For example:
const lsxLibraryName = "?NAME_OF_LIBRARY" UseLSX lsxLibraryName
Usage
LotusScript registers the Public classes defined in the lsx file for use in the module containing the UseLSX statement. Other modules that use this containing module can also access these Public classes. Note that Lotus Notes supports the UseLSX statement. The UseLSX statement loads a .LSX file containing Public definitions. These definitions then become available to the current script. Once the .LSX file has been downloaded, its classes are browsable in the Notes class browser. The Notes platform has a registry of LSXes. If the file-specification string in the UseLSX statement begins with an asterisk (*), then Notes looks in the registry for the name consisting of the rest of the string. The registry entry for that name specifies the file location in the platform file system. The _ is reserved for Notes specific dlls. This is a change put in as of Notes 4.5.1. If you attempt to load a dll in Notes 4.51 or greater using LotusScript and the name of the dll is preceded by an underscore you will receive the error Error in loading DLL. A library name prefixed with a ? is considered to be optional at run time. The library must be present at compile time in order to compile the script, however, if the LSX cannot be loaded at run time, the script will still execute as long as classes defined by the LSX are not referenced or functions/procedures defined by the LSX are not called from the script. If the LSX is not loaded and a line of script references an LSX class or procedure, the following errors would be thrown. ERR = 230 ERROR = Unknown class instance ERR = 48 ERROR = Error in loading DLL
481
UString function
Returns a string of identical characters. You can specify the repeating character either by its Unicode numeric code, or as the first character in a string argument.
Syntax
UString[$] ( stringLen , { charCode | stringExpr } )
Elements
stringLen A numeric expression whose value is the number of characters to put in the returned string. LotusScript rounds stringLen to the nearest integer. charCode A numeric expression whose value specifies the Unicode numeric character code for the repeating character. LotusScript rounds charCodeto the nearest integer. Unicode codes range from 0 through 65535 inclusive. The Uni function returns the Unicode code for a given character. stringExpr Any string expression. The first character in this string is the character to be used for the repeating character.
Return value
UString returns a Variant of DataType 8 (String). UString$ returns a String.
Usage
If the value of charCode is less than 0 or greater than 65535, the function returns an error.
Language cross-reference
@Repeat function in formula language
********
Val function
Returns the numeric value represented by a string.
Syntax
Val ( stringExpr )
Elements
stringExpr
482
Any string expression that LotusScript can interpret as a numeric value. It can contain any of the following kinds of characters. v Digits (0 1 2 3 4 5 6 7 8 9) v Other characters in hexadecimal integers (a b c d e f A B C D E F) v Sign characters (+ -) v Decimal point (.) v Exponent characters (E e D d) v Prefix characters in binary, octal, and hexadecimal integers (& B O H) v Suffix type characters (% & ! # @)
Return value
Val returns the converted part of stringExpr as a Double.
Usage
Val strips out spaces, tabs, carriage returns, and newlines from stringExpr. It starts converting from the beginning of the string and stops when it encounters a character other than those listed for stringExpr in the preceding list. Note: If the string being evaluated is a hexidecimal number between 8000 and FFFF, both the prefix (&H) and suffix (&) must be used. Hexidecimal numbers between 0 and 7FFF may use just the prefix (&H) or both the prefix (&H) and suffix (&).
Language cross-reference
@TextToNumber function in formula language
Usage
A variable that is declared without a data type or a suffix character is of type Variant. Variant values are initialized to EMPTY. A Variant variable can contain values of any scalar data type, or any of the following special values.
Chapter 12. LotusScript Language Reference
483
v Array: A declared array may be assigned to a Variant variable. The reverse is not true; for example, a Variant variable containing an array may not be assigned to a declared array variable. v List: A list may be assigned to a Variant variable. The reverse is not true; for example, a Variant variable containing a list may not be assigned to a declared list variable. v Object reference: A reference to any instance of a user-defined class or product class, or to an OLE Automation object, may be assigned to a Variant variable. v Date/time value: An 8-byte floating-point value representing a date/time may be assigned to a Variant variable. The integer part represents a serial day counted from Jan 1, 100 A.D. Valid dates are represented by integer numbers in the range -657434 (representing Jan 1, 100 A.D.) to 2958465 (representing Dec 31, 9999 A.D.). The fractional part represents the time as a fraction of a day, measured from time 00:00:00 (midnight on the previous day). In this representation of date/time values, day 1 is the date December 31, 1899. v NULL: A Variant can take the value NULL either by explicit assignment, or by the evaluation of an expression containing NULL as an operand. (For most expressions, if one or both operands are NULL, the expression evaluates to NULL.) v EMPTY: In expressions, EMPTY is converted to 0 for numeric operations, and to the empty string () for string operations. Variants take the value EMPTY only upon initialization, or upon assignment from another Variant whose value is EMPTY. A Variant cannot contain an instance of a user-defined type. To determine the data type of the value in a Variant variable, use the DataType or TypeName function. LotusScript aligns Variant data on an 8-byte boundary. In user-defined data types, declaring variables in order from highest to lowest alignment boundaries makes the most efficient use of data storage space.
484
Weekday function
Returns the day of the week, an integer from 1 to 7, for a date/time argument.
Syntax
Weekday ( dateExpr )
Elements
dateExpr Any of the following kinds of expression: v A valid date/time string of String or Variant data type. For Notes or Domino, LotusScript interprets a 2-digit designation of a year in a date/time string so that 50 through 99 represent the years 1950 through 1999 and 00 through 49 represent the years 2000 through 2049. For SmartSuite, LotusScript interprets the years differently. For more information, see the Year 2000 item on the Help menu of each SmartSuite product. v A numeric expression whose value is a Variant of DataType 7 (Date/Time). v A number within the valid date range: -657434, representing Jan 1, 100 A.D., to 2958465, representing Dec 31, 9999 A.D. v NULL.
Return value
Weekday returns an integer between 1 and 7. The data type of the return value is a Variant of DataType 2 (Integer). Weekday(NULL) returns NULL.
Usage
Sunday is day 1 of the week.
Language cross-reference
@Weekday function in formula language
While statement
Executes a block of statements repeatedly while a given condition is true.
Syntax
While condition [ statements ]
Chapter 12. LotusScript Language Reference
485
Wend
Elements
condition Any numeric expression. LotusScript interprets a value of 0 as FALSE, and interprets any other value as TRUE.
Usage
LotusScript tests condition before entering the loop and before each subsequent repetition. The loop repeats while condition is TRUE. When conditionis FALSE, execution continues with the first statement following the Wend statement.
Language cross-reference
@While function in formula language @For function in formula language
Width # statement
Assigns an output width to a sequential text file.
Syntax
Width # fileNumber , width
Elements
# fileNumber The file number that LotusScript assigned to the file when it was opened. The file must be open. You must include both the pound sign (#) and the file number. width
486
An integer expression in the range 0 to 255, inclusive, that designates the number of characters LotusScript writes to a line before starting a new line. A width of 0, the default, specifies an unlimited line length.
Usage
If data to be written would cause the width of the current line to exceed the Width # setting, that data is written at the beginning of the next line instead. The Print # statement is the only output statement affected by the Width # statement. Write # ignores the width set by Width #.
With statement
Provides a shorthand notation for referring to members of an object.
Syntax
With objectRef [ statements ] End With
Elements
objectRef An expression whose value refers to a user-defined object, a product object, or an OLE object.
487
Usage
The With statement lets you refer to the members of an object using a dot to represent the object name. You can also use a dot outside of a With statement to represent the currently selected product object. You cannot use a dot to refer to the selected product object in a With statement. LotusScript assumes that any member preceded by a dot is a member of objectRef. You can nest With statements up to 16 levels. LotusScript does not support entering a With statement using GoTo. Reassigning the objectRefvariable inside the With statement does not change the object referred to by the dot. However, any other operation reassigns the object. See the following example.
Write # statement
Writes data to a sequential text file with delimiting characters.
Syntax
Write # fileNumber [ , exprList ]
Elements
# fileNumber The file number that LotusScript assigned to the file when it was opened. You must include both the pound sign (#) and the file number. exprList Optional. The list of String or numeric expressions to be written to the file, separated with commas.
488
If you omit exprList, Write # writes a blank line to the file. The exprList cant include arrays, lists, type variables, or objects. The exprList can include individual array elements, list elements, or type members.
Usage
Use Write # only with files opened for either Output or Append. Use the Input # statement to read data written by Write #. Write # ignores the file width set by the Width # statement. Data items are separated with commas, and a newline character is inserted after all data has been written to the file. LotusScript inserts chr(10) to represent the newline character in any multi-line string (for example, a string that you type in using vertical bars or braces). If you Print the string to a file, this newline character will be translated into the platform-specific newline character(s). If you Write the string to a file, no translation is done. Note: Newline does not mean either chr(10) or chr(13) on all platforms. Newline is the character or sequence of characters that is used to mark the end of a line. This may be chr(10), or chr(13), but it may also be something else, because the actual value of newline depends on the platform. Note: When reading a multiline string from a sequential file written by the Write # statement, use Input, not Line Input. The following table shows how the Write # statement behaves with various data types specified in exprList.
Data type Numeric String Variant of DataType 7 (Date/Time) Write # statement behavior Omits leading and trailing spaces. Encloses all strings in double quotation marks. Pads fixed-length strings with spaces as needed. Uses one of the following date formats: #yyyy-mm-dd hh:mm:ss# #yyyy-mm-dd# #hh:mm:ss# If either the date part or the time part is missing from the value, LotusScript writes only the part provided to the file. Variant with the value EMPTY Variant with the value NULL Writes a comma without data to the file. If that variable is the last item on the line, the comma is omitted. Writes the string NULL to the file.
489
Open fileName$ For Output As fileNum% Write #fileNum%, "Joe Smith", 123, "1 Rogers Street", _ 25000.99 Write #fileNum%, "Jane Doe", 456, "Two Cambridge Center", _ 98525.66 Write #fileNum%, "Jack Jones", 789, "Fourth Floor", 0 Close fileNum% Read it all back and print it. Open fileName$ For Input As fileNum% For I% = 1 To 3 Input #fileNum%, empName$, empNumber%, empLocation, _ empSalary@ Print empName$, empNumber%, empLocation, empSalary@ Next I% Close fileNum% Output: LotusScript prints out the contents of the file C:\data.txt in groups of four values each. Each group consists of a String, an Integer, a Variant, and a Currency value, in that order.
Year function
Returns the year, as a 4-digit integer, for a date/time argument.
Syntax
Year ( dateExpr )
Elements
dateExpr Any of the following kinds of expressions: v A valid date/time string of String or Variant data type. For Notes or Domino, LotusScript interprets a 2-digit designation of a year in a date/time string so that 50 through 99 represent the years 1950 through 1999 and 00 through 49 represent the years 2000 through 2049. For SmartSuite, LotusScript interprets the years differently. For more information, see the Year 2000 item on the Help menu of each SmartSuite product. v A numeric expression whose value is a Variant of DataType 7 (Date/Time). v A number within the valid date range: -657434, representing Jan 1, 100 AD, to 2958465, representing Dec 31, 9999 AD. v NULL.
Return value
Year returns an integer between 100 and 9999. The data type of the return value is a Variant of DataType 2 (Integer). Year(NULL) returns NULL.
Language cross-reference
@Year function in formula language
490
Syntax
Yield DoEvents is acceptable in place of Yield.
Return value
The Yield function returns 0 as an Integer value.
Usage
The Yield function and statement transfer control to the operating system, so that it can process the events in its queue. In Windows, the operating system does not return control until it has processed all outstanding events, including those generated by a SendKeys statement. The Yield function and statement are legal within a procedure or a class. They are not legal at the module level. You can call the function as either Yield or Yield().
491
Yield Loop When the user closes the calculator, continue. MessageBox "Calculations done" End Sub DoCalc Call the DoCalc sub.
492
The legal range of values of binary, octal, or hexadecimal integers is the range for Long integers (see the preceding table). The following table lists the maximum number of characters needed to represent integers in binary, octal, and hexadecimal notation. This is also the maximum number of characters that the Bin, Oct, or Hex function returns.
Integer type Binary Octal Hexadecimal Maximum number of characters needed to represent a value 32 11 8
493
Item Total string storage Length of a string literal Length of a string value Total string literal storage in a module
Maximum Limited by available memory. 16,267 characters (32,000 bytes). 2G bytes 2G bytes
Note: Even though strings in LotusScript 4 can be longer than 64K, there are still restrictions with the length of the string you can read or write using the GET and PUT statements. The only combination of filetypes that will work with long strings is with a binary file and a variable-length string. Fixed-length strings, strings in variants, and random files will not work with strings greater than 64K in length because they have a two-byte header which contains the length of the string. Two bytes cannot represent more than 64K.
494
Maximum 255
495
496
Other differences
OLE functions are not supported. This limitation affects CreateObject and GetObject. OS/2 users can invoke REXX applications from LotusScript.
497
Declare
Generates a run-time error if a drive letter is included in the argument. Does not return the following attributes: ATTR_HIDDEN, ATTR_ARCHIVE, ATTR_VOLUME, ATTR_SYSTEM.
GetObject Input #, Input, Input$, InputB, InputB$, Line Input, Print, Write # IsObject, IsUnknown Open, Lock, Unlock
Not supported. Generates a run-time error. Compiled scripts using these constructs may be platform-specific, since file data is stored in a platform-specific manner. UNIX character set, byte order, line terminator, and numeric precision specifics may affect the portability of scripts using these functions.
See Other differences, below. No explicit or implicit file locking is supported on UNIX. This implies the following: v LotusScript for UNIX allows the user to copy, open, etc., a file that is already opened for reading. Thus, the Name statement works differently on UNIX. v The Open statement may specify only Shared as its lock status. Lock Read, Lock Write, and Lock Read Write will cause a run-time error. v The Lock and Unlock statements will cause a run-time error.
SendKeys
498
Usage in UNIX Ignores the attributes ATTR_HIDDEN, ATTR_ARCHIVE, and ATTR_VOLUME. Window styles are ignored. For reasons of security and system integrity, only asuperuser can change the time on a UNIX system. Attempting to change the time under any other username will generate a run-time error. Attempting to change the time while logged in as superuser will change the time system-wide.
Other differences
Function aliasing with ordinal numbers (using the Alias clause in the Declare statement) is not possible on UNIX, because UNIX has no notion of numbering the routines in a shared library. Where wildcards are permitted in file path strings, LotusScript supports the use of UNIX regular expressions in addition to the * and ? characters. However, using regular expressions in file path strings makes the script platform-dependent. The Like operator does not use use the same regular expression syntax as the UNIX shell. It uses LotusScript regular expressions. OLE is not supported on LotusScript Release 3.0 for UNIX platforms. This difference affects CreateObject, GetObject, IsObject, and IsUnknown. The CreateObject and GetObject functions will raise run-time errors when executed on UNIX platforms. The IsObject function tells if a variable refers to a native or product
Chapter 14. Appendix B Platform Differences
499
object, but not an OLE object, since OLE objects dont exist on the UNIX platform. The IsUnknown function always returns FALSE on UNIX, since there is no way for a Variant expression to receive the V_UNKNOWN value.
Environ FileLen GetFileAttr Len, LenB Lock Open SendKeys SetFileAttr Unlock
500
The Macintosh does not store a default directory for each drive. It maintains only one current directory, not one per drive as in DOS. Drive names can be up to 27 characters in length. This limitation affects ChDir, ChDrive, and CurDir. The Macintosh does not recognize the directory specifications . and ... This limitation affects the Dir function. The Macintosh does not use the file system attributes Volume, Archive, and System. This limitation affects Dir, GetFileAttr, and SetFileAttr. Macintosh uses the carriage return (ASCII 13) character as the line terminator. Other platforms use other characters. This difference means that files and strings manipulated with the same LotusScript code but executed on different platforms may have different sizes. For instance, the UNIX platform uses a single character (linefeed) as the line terminator, so text files written on that platform have equal length to those written on Macintosh. Since the Windows platform uses a two-character sequence, text files written there are larger than text files written on Macintosh, given identical source code. This difference affects FileLen, Len, LenB, and LenBP. Macintosh permits files that are open for reading to be manipulated (copied, opened, etc.) by another application. A file opened for output by LotusScript is locked; other applications cannot open or copy the file, but can move or rename it. Lock and Unlock work only on shared volumes; the file being locked must be on a server or file sharing must be turned on for a local volume (Sharing Setup on the control panel). This difference affects Open, Lock, and Unlock.
Other differences
Function aliasing with ordinal numbers (using the Alias clause in the Declare statement) is not possible on the Macintosh PC. There are no system environment variables on the Macintosh. This limitation affects Environ.
Dir, Dir$
501
Usage in OS/400 Strings containing line terminators are smaller than on DOS/Windows platforms. The line terminator is one character (line feed), not two. Therefore, the return value of these functions will be smaller for strings on OS/400 than on Windows. Generates a run-time error if a drive letter is included in the argument. Does not return the following attributes: ATTR_HIDDEN, ATTR_ARCHIVE, ATTR_VOLUME, ATTR_SYSTEM. Not supported. Generates a run-time error. Compiled scripts using these constructs may be platform specific, because file data is stored in a platform-specific manner. OS/400 character set, byte order, line terminator, and numeric precision specifics may affect the portability of scripts using these functions. See Other differences. Explicit or implicit file locking is not supported. This implies the following: v LotusScript for OS/400 allows the user to do operations (Such as copy or open) on a file that is already opened for reading. Thus, the Name statement works differently with OS/400. v The Open statement can specify only Shared as its lock status. Lock Read, Lock Write, and Lock Read Write will cause a run-time error. v The Lock and Unlock statements will cause a run-time error.
GetObject Input #, Input, Input$, InputB, InputB$, Line Input, Print, Write # IsObject, IsUnknown Open, Lock, Unlock
Not supported. Generates a run-time error. Ignores the attributes ATTR_HIDDEN, ATTR_ARCHIVE, and ATTR_VOLUME. Window styles are ignored. Changing the time on OS/400 through LotusScript is not supported. Generates a run-time error.
Other differences
Function aliasing with ordinal numbers (using the Alias classes in the Declare statement) is not possible with OS/400. Where wild cards are permitted in file path strings, LotusScript supports the use of UNIX regular expressions in addition to the * and ? characters. However, using regular expressions in file path strings makes the script platform dependent. OLE is not supported on LotusScript Release 3.1 for OS/400. This difference affects the CreateObject, GetObject, IsObject, and IsUnknown functions. The CreateObject and IsObject functions will raise
502
run-time errors when executed on OS/400 platforms. The IsObject function can determine if a variable refers to a native or product object, but not an OLE object, because OLE objects do not exist on the OS/400 platform. The IsUnknown function always returns FALSE on OS/400, because there is no way for a Variant expression to receive the V_UNKNOWN value. When passing pointer arguments to C functions, be aware that the pointer size on OS/400 is 16 bytes, not 4 bytes.
503
504
505
506
507
508
509
Note: With Release 6, ISO-8859-10, the ISO character set for Nordic languages is not supported. EBCDIC charset names
Charset Name IBM037 EBCDIC-US IBM273 IBM277 IBM278 IBM280 IBM284 IBM285 IBM297 IBM420 IBM424 IBM500 IBM838 IBM870 IBM871 IBM875 IBM1025 IBM1026 IBM1047 IBM1112 IBM1122 IBM930 IBM933 IBM935 IBM937 IBM939 IBM1388 Description US and Canadian English, Dutch, Protuguese Alias for IBM037 German Danish, Norwegian Finnish, Swedish Italian Spanish International English French Arabic Hebrew Intl. Eglish, Latin-1, Albanian, Belgian English, French Thai Latin-2, Croatian, Czech, Hungarian, Polish Icelandic Greek Bulgarian, Russian, Serbian Cyrillic Turkish Latin-1 Open Systems Latvian, Lithuanian Estonian Japanese Katakana Korean Simplified Chinese Traditional Chinese Japanese Latin Simplified Chinese
510
511
Do one of the following: v In the derived classs Sub New declaration, specify which arguments to pass to the base classs Sub New, for example as follows:
Class Derivedclass As Baseclass Sub New (X As Long, Y As Long), Baseclass (X) End Sub End Class
v Redefine the derived classs Sub New so that its parameters match those of the base classs Sub New. For example:
Class Derivedclass As Baseclass Sub New (X As Long) End Sub End Class
512
For example, a module-scope variable may have the same name as a class defined in that module, because variable names and class names are in different namespaces and therefore dont conflict. However, a module-scope variable may not have the same name as a function defined in that module. The name space where a name resides doesnt depend on whether the name is declared Public, Private, or external (declared by the external Declarestatement). All of these share the same name space. Remove the duplicate declaration.
513
Remove Public from the declaration, or change the Public name so that it does not conflict with the name in the already loaded module.
Suffix characters are not valid on these names. Remove suffix characters from any names on which they are invalid.
514
A class constructor sub must be a part of the definition of a class, and must be named New. If the sub is not intended to be a class constructor, remove the constructor clause (that is, the comma, the name of the class, and the argument list). Otherwise, rename the sub to New.
Parent SUB NEW has arguments, SUB NEW is required for: <class name>
You defined a derived class that has no Sub New. If the corresponding base classs Sub New requires arguments, the derived class must have a Sub New that provides those arguments. For example:
Class BaseClass Sub New (X As Integer) End Sub End Class Class DerivedClass As BaseClass End Class Dim ObjRefVar As New DerivedClass
Define a Sub New for the derived class whose signature includes the arguments required by the base classs Sub New. For example:
Class BaseClass Sub New (X As Integer) End Sub End Class Class DerivedClass As BaseClass Sub New (X As Integer) End Sub End Class Dim ObjRefVar As New DerivedClass(5)
Legal
515
Class BaseClass X As Integer Sub Y ... End Sub End Class Class DerivedClass As BaseClass X As Integer Y As Integer ... End Class
Illegal Illegal
Member of PUBLIC class or type is instance of a PRIVATE class or type: <member name>
Within the definition of a Public class or user-defined data type, you declared as PublicLSAZ_DIM_Statement a member variable that refers to a Private class or user-defined data type, or you included a Public method that returns an instance of a Private class or user-defined type. For example, in the following code, the definition of the variable B produces this error condition:
Private Type MyType A As Integer End Type Public Class MyClass Public B As MyType End Class
Change the Public class or user-defined data type to Private, or the Private class or user-defined data type to Public.
516
Illegal. Target is an array or list element. OK. Target is an entire array or list.
517
Wrong data type for argument <argument name> in event handler <event handler name>
You specified a procedure as the handler in an On Event statement. The declareddata type of a parameter in the definition of that procedure does not match the data type of the corresponding parameter specified when the event was registered with LotusScript. Refer to the documentation of the product in which you are running LotusScript for information about the arguments that the event handler requires. Change the declared data type of the parameter in the subprogram definition to match the registered data type of the corresponding parameter.
518
Object reference variables, list variables, and dynamic array variables are not valid members of a user-defined data type. Remove the invalid member declaration.
Out of memory
You must free enough memory to perform the operation that caused this error message. To free memory in your computer, do one of the following: v If you have other programs in memory, end one or more of those programs. v Reduce the amount or size of Public data.
Chapter 18. Appendix F Compile-time Error Messages
519
520
Derived class may not be PUBLIC when parent is PRIVATE: <class name>
You defined a Public class whose base class is Private. The base class from which a Public class is derived cannot be Private. Change the definition of the base class to Public, or change the derived class to Private.
521
Change the declaration or its corresponding definition so that both are either functions, subs, or properties.
Storage class or visibility does not match forward declaration: <subprogram name>
You declared a function, sub, or property with a Declare statement and then defined the procedure with a Function, Sub, Property Set, or Property Get statement. The definition differs from the declaration in one or another of the following respects: v The declaration contains the keyword Static but the definition doesnt, or vice versa. (The keyword Static specifies that the storage class of the procedures variables will be static by default.) v The procedure is declared as Public but defined as Private, or vice versa. Change the declaration or the corresponding definition of the procedure so that they match.
Change the data type of the return value in the declaration or in the corresponding definition so that they match.
522
Make the parameters in the declaration and definition match each other. v The procedure that you forward declared is a parameterized constructor sub (Sub New) inside a Class statement and you have not defined a Sub New for that class. Either remove the Declare statement or define a corresponding Sub New.
Change the data type of the indicated parameter in the declaration or the definition of the procedure so that they match. v The data type of the indicated parameter matches the data type of the corresponding parameter in the procedure declaration, but the parameters represent different kinds of data structure. For example:
Declare Function MyFunction(X() As Integer) As Integer ... Function MyFunction(X As Integer) As Integer Illegal because X is a ... End Function scalar variable but X() is an array
Change the parameter specification in the declaration or the definition of the procedure so that the two match.
523
Change the base class procedure or the corresponding derived class procedure so that both are either subs, functions, or properties.
PROPERTY GET and SET must have same storage class and visibility
One of the following occurred: v You declared a propertys variables to be Static by default in either the Property Get statement or the Property Set statement, but not in both. The declarations must agree: either both or neither must specify Static. Change either statement to agree with the other. v You declared a propertys scope in a Property Get statement differently from the propertys scope in the corresponding Property Set statement. The property must have a single scope: either Public or Private. Make them both Public or Private.
524
Change the base classs procedure or the corresponding procedure in the derived class so that both are either subs, functions, or properties
Change the data type of the derived classs property or the corresponding property in the base class so that they match.
525
Remove ByVal from the declaration. v You tried to pass an array, list, object reference, or instance of a user-defined data type by value in a call to a LotusScript procedure. For example:
Type MyType A As Integer End Type Sub MySub(X As MyType) ... End Sub Dim Z As MyType MySub(Z) Illegal: this tries to pass by value. MySub Z Legal: this passes by reference.
or
Dim anArray(1 to 3) As String Sub MySub2(Z As Variant) ... End Sub MySub2(anArray()) Illegal: this tries to pass by value. MySub2 anArray() Legal: this passes by reference.
Pass the argument by reference. Remove the parentheses around the argument in the calling statement.
526
Illegal
or:
Set X = New MyType Illegal
You use the keyword New to declare or assign a value to an object reference variable, that is, an instance of a class. Remove New from the declaration or assignment statement.
Class ClassName As ClassName is also illegal even if ClassName exists because a class may not be derived from itself. v A Set statement, as in:
Set X = New ClassName
Declare the class or user-defined data type before you refer to it.
527
If Deftype a-z has been specified in a module, no other Deftype range may be specified in that module. Redefine your Deftype ranges so that no letter is included in more than one range.
528
v v v v v
On...GoSub statement Resume statement Return statement SendKeys statement Yield statement
Revise the script to remove any of these statements at the module level.
The class name used in a Set...Bind... statement must be a product class name, not a user-defined class name. Change the class name following the Bind keyword to a product class name, or remove the statement.
Either replace the name in the ReDim statement with the name of a dynamic array, or remove the statement.
Chapter 18. Appendix F Compile-time Error Messages
529
Change the count variable in one of the For loops so that they are different from each other.
Use a different variable: either an existing ForAll reference variable of the correct type, or a new variable.
530
Define the member within the class or data type definition, or remove the reference.
Illegal single-line IF
A physical end-of-line (with no line-continuation character) appeared before the end of the Then or Else clause in an If...Then...Else statement. For example:
If X = Y Then Do : X = X + 1 Loop Illegal. Loop must appear on same line as Do.
A single-line If...Then...Else statement must be completely contained on one line, including any continuation lines designated by line-continuation characters. Do one of the following: v Write the Then clause and the Else clause on the same line as the If.
Chapter 18. Appendix F Compile-time Error Messages
531
v Use a line-continuation character. v Use an If...Then...Else...End If block statement in place of the single-line If...Then...Else statement.
Remove the dotdot syntax and use an object reference variable in its place.
532
v A ReDim statement In each of these statements, the name must be the name of a variable, a property, or a ForAllreference variable.
Chapter 18. Appendix F Compile-time Error Messages
533
Replace the name with a valid name, or remove the invalid statement.
Replace the name with an appropriate name, or remove the invalid statement.
Remove this use of the name, or replace it with a name that has a value (for example, a function name instead of a sub name).
Numeric overflow
In defining a constant with the Const statement, you specified a numeric value that is too large for the specified or default data type: v The value is too large for the data type specified by the values suffix character. v If no suffix character is specified, the value is too large for a Double. For example:
Const X = 100000% Const Y = 100000! Illegal because the value is too large for Legal
Change the suffix character to match the magnitude of the value, or specify a smaller value.
534
Numeric underflow
In defining a constant with the Const statement, you specified a numeric value that is too small for the specified or default data type: v The value is too small for the data type specified by the values suffix character. v If no suffix character is specified, the value is too small for a Double. For example:
Const X = .1E-300! Const X = .1E-300# Illegal because the value is too small for the data type Single Legal
Change the suffix character to match the magnitude of the value, or specify a larger value.
Declaration may not contain type suffix and data type: <name>
You specified a declaration that contains both a data type suffix character and an AsdataType clause . A declaration may not contain both, even if they match. For example:
Dim myInt% As Integer Illegal
Remove either the suffix character or the As dataType clause from the declaration.
535
536
Legal because string is properly quoted Legal because string is properly quoted and preceded by line-continuation character Output: Hi, Martin.
Terminate the string with double quotation marks on the same line where it starts.
Illegal because there is no matching vertical bar Illegal because the delimiters dont match.
Check for any unpaired or improperly paired multiline string delimiters and enclose the string appropriately.
537
Class MyClass ... End Class Dim MyObj As New MyClass Dim varV As Variant varV = MyObj Illegal syntax
For more information, refer to the list of expected language elements following the unexpected language element in the error message.
538
Unknown statement
The compiler could not parse the statement on the line specified in the error message. If a statement was intended, check the legal syntax for the statement. If a comment was intended, designate the line as a comment line. Otherwise, remove the incorrect text.
Define a Property Set procedure for the property to which you want to assign a value.
Define a Property Get procedure for the property whose value you want to retrieve.
Duplicate option
You used the Option Base, Option Declare, or Option Public statements more than once in a module. These statements can only appear once each per module. Remove any repeated instances of the Option Base, Option Declare, or Option Public statements within the module. To override the lower bound setting specified by the Option Base statement, use explicit lower bounds in a Dim or ReDim statement.
539
Supply the missing argument in the function call. v A comma was not followed by an argument. For example:
Function MyFunction(A As Integer, B As Integer) As Integer ... End Function anInt% = MyFunction(,3) Illegal
Replace the invalid argument in the ListTag function call with the ForAll reference variable where ListTag appears.
540
v You tried to pass an array, a list, or an object reference to a function or sub, but the corresponding parameter is not defined as one of these or as a Variant. Pass an argument of the correct kind. v You tried to pass a scalar value to a function or sub, but the corresponding parameter is defined as an array, a list, or an object reference variable. Pass an argument of the correct kind. v You tried to assign an instance of a user-defined data type to a Variant. For example:
Type myType A As Integer End Type Dim typeInst As myType Dim varV As Variant varV = typeInst Illegal
This is not allowed. Remove the assignment statement. v You used a Set statement to try to assign a value other than an object reference to an object reference variable (or a Variant holding an object reference). For example:
Class MyClass ... End Class Dim X As New MyClass Dim N As Integer N% = 5 Set X = N%
Illegal
This is not allowed. Remove the assignment statement. v You used a Set statement to try to assign an object reference to something other than an object reference variable or a Variant. For example:
Class MyClass ... End Class Dim X As New MyClass Dim N As Integer Set N% = X Illegal
This is not allowed. Remove the assignment statement. v You used a Set statement to try to assign an object reference variable of one class to an object reference variable of another class. You can only do this when the variables designate instances of the same class or when the target variable designates a base class and the variable whose value is being assigned designates a derived class from that base. For example:
Class MyClass ... End Class Class BaseClass ... End Class Class DerivedClass As BaseClass ... End Class Dim A As New MyClass Dim B As New BaseClass Dim D As New DerivedClass Set B = A Illegal Set D = B Illegal Set B = D Legal
Remove or revise the assignment. v You used a Set or Set...New statement to try to create an object (class instance) and assign a reference to it to a variable that is not an object reference variable or a Variant.
541
Class MyClass ... End Class Dim X As New MyClass Dim N As Integer Set N% = New MyClass
Illegal
Remove or revise the assignment. v You used a Set or Set...Bind statement in which the target variable is not an object reference variable or a Variant holding an object reference. v You used a With statement whose target is not an object reference variable or a Variant containing an object reference. The With statement can only be used to operate on objects. v A ReDim statement contains a data type that does not match the data type in the declaration of the array, or the data type in a previous ReDim statement whose target was that array. Change the data type in the ReDim statement so that it matches the data type of the declaration or previous ReDim statement whose target was that array, or remove the data type from the ReDim statement. Once you specify a data type for a dynamic array, it is not necessary to specify the data type again in subsequent ReDim statements. v You used a variable declared as a non-numeric data type as the count variable in a For statement. Replace the count variable with a variable of the appropriate numeric type.
Illegal BYVAL
One of the following conditions could have caused this error: v You specified the ByVal keyword on a subscript in referring to an array element. Remove the ByVal keyword. v You specified the ByVal keyword in an array bounds expression in a ReDim statement. Remove the ByVal keyword.
542
Define the label named in the error message only once. Define other labels to replace the other instances of this label.
If the Exit statement is unintended, remove it. If the Exitstatement has the right type but is misplaced, relocate it to within the intended block of that type. If the Exitstatement is in the intended place within a block but has the wrong type, change its type to the type of that block.
543
You may have inadvertently put parentheses around an argument in a sub or function call. Use parentheses on arguments in sub and function calls only if you are using the Call keyword. The following arguments cannot be passed by value: v Arrays v Lists v Variables of a user-defined data type v Object reference variables In addition, only arguments of type String or Variant can be passed by value to the LotusScript Len function. Arguments of other data types cannot be passed by value. Remove the parentheses or the ByVal keyword.
Illegal because MyClasss Sub New takes only two arguments Legal
v A Set statement of the form: Set X = New ClassName v A declaration of a derived class when the arguments that the derived classs constructor requires are different from the ones that the base classs constructor requires. In this case, constructor arguments for the base class must be specified after the BaseClassName clause in the Sub New declaration, as in the following example:
Class BaseClass Sub New(X As Integer) ... End Sub End Class Class DerivedClass As BaseClass Sub New(Y As String, X As Integer), BaseClass(X%, Y) Illegal Sub New(Y As String, X As Integer), BaseClass(X) Legal ... End Sub End Class
544
v As though it were an object reference variable or a variable of a user-defined data type and you were referring to one of its members, as in X.Y Remove the illegal use of the array or list.
545
v The sub or function has a single parameter that the caller is passing by value. For example:
MySub("ABC") MyFunction(anInt%) X% = MyFunction(123, "XXX") Legal Legal Legal
Remove the parentheses from around the argument list or call the sub or function with the Call statement.
546
Insert the name of the product class after the Bind keyword.
Illegal Directive
Any of the following could have caused this error: v You used an unrecognized directive. For example:
%Else If %ElseIf Illegal Legal
v You nested a %Rem...%End Rem block inside another %Rem...%End Rem block. v You used an %End Rem without a preceding %Rem. v You used a %Else, %ElseIf, or %End If directive outside a %If...%End If block. v You nested a %If...%End If block inside another %If...%End If block.
Insert the comment character if a comment is intended, or remove the superfluous characters.
547
To refer to an element in a nested array, list, or collection, assign the inner array, list, or collection to a variable of type Variant:
Dim varV As Variant varV = anArray(1) Print varV(1)
Legal
v Use v UseLSX You can only use these statements at the module level. Move the statement to the module level.
548
Illegal because the preceding assignment statement referred to the X declared in outer scope
549
Move the declaration of the variable in the inner scope so that it precedes the assignment statement, or remove the declaration of the variable in the inner scope. Moving the declaration of the variable in the inner scope creates a local variable that shadows the one in the outer scope, while removing the declaration lets you refer to the variable in the outer scope from within the inner scope.
v You included empty parentheses in a reference to a class member function that returns an array, list, or collection. You can either remove the empty parentheses or insert the appropriate subscript or subscripts.
or:
550
Class MyClass Sub New(aString As String, anInt As Integer) ... End Sub End Class Dim X As MyClass Set X = New MyClass("ABC") Illegal. MyClasss Sub New expects two arguments: a string and then an integer.
Include all of the required arguments in the appropriate order in the Dim or Set statement.
Illegal Legal
551
Move the Function, Property Get, Property Set, or Sub statement to outside the block.
552
Remove the Dim, Public, Private, or Static keyword. v You used the Dim keyword when defining a member variable in a Class statement. For example:
Class MyClass Dim X As Integer End Class Illegal: Dim keyword is not allowed here.
Conflicting option
You specified conflicting options in an Option Compare statement or statements. You cannot specify any other options if you specify Binary. You cannot specify both Case and NoCase. You cannot specify both Pitch and NoPitch.
Number of arguments do not match for PROPERTY GET and SET <property_name>
The number of parameters to Get and Set for a property are not the same.
Change the signature of the base class property or of the corresponding property in the derived class so that they match.
553
554
User-defined error
A user-defined error occurred. You used the Error statement to create an error and assigned it a number that is not a LotusScript error number. You did not specify an error message in the Error statement, so LotusScript displays the default error message User-defined error. To display a more meaningful error message, provide the message string as the second argument to the Error statement.
v You tried to activate a program using the ActivateApp statement, but the program was not found. v The string specified in the SendKeys statement contained an unmatched parenthesis, an illegal key name, or an illegal repeat count; or the string was too long to be processed.
555
Overflow
The result of a numeric operation, value conversion, or assignment is outside the range of allowable values for the result data type. Do one or both of the following: v Change the numeric data type of one or more values being used in the operation, conversion, or assignment. v Change the destination data type to accommodate the result. For example:
Dim N As Long I% = 30000 J% = 10000 Print (I% + J%) Print CInt(40000&) Invar% = 40000 N = 40000 MN = 40000 Declare I implicitly as an Integer. J is also an Integer. Overflow from numeric operation. The number 40000 cannot be represented as an Integer. Overflow from attempted conversion of a Long value to an Integer value. Overflow from attempted assignment of a large value to an Integer variable. No error. N was declared a Long. No error. MN is implicitly declared a Long by the assignment of a large value to it.
Out of memory
There is not enough system memory to perform an operation. To free memory on your computer, end one or more other programs that are currently in memory, other than the Lotus software running LotusScript.
556
Division by zero
In a mathematical operation, there was an attempt to divide by zero. It is impossible to divide by zero. Check the appropriate operand for a zero value before using it as a divisor.
Type mismatch
One of the following conditions could have caused this error: v You attempted an operation on operands with conflicting data types. v You assigned a value to a variable that has a different data type, and LotusScript cannot convert it automatically. v You are passing a value as an argument that has a different declared data type, and LotusScript cannot convert it automatically. v You used a string as the initial value, or as the To or Step value, in a For statement. Use the correct data type.
557
No RESUME
You are using an On Error statement in a procedure, but have not included a Resume statement. Insert one or more Resume statements at the appropriate points in the script.
558
Internal error
An internal error occurred. Record the error message and contact Lotus Software Support.
559
Make sure there is a diskette in the drive and that it has read-write access.
Disk full
You tried to save a file on a disk that did not have enough room for the file. Save the file on another disk.
560
Device unavailable
You specified an invalid drive. Specify a drive that exists on your system.
Permission denied
One of the following conditions could have caused this error: v You tried to access a file that is currently locked by another program. Close the file in the other program. v You tried to write to a file that has been write-protected. In DOS, this attribute can be changed with the Attrib command. In Windows, this attribute can be changed with the File Properties command. To correct this problem in Windows, open the File Manager (or Windows Explorer), choose File Properties to remove the read-only attribute from the file, then return to LotusScript and try again to write to the file.
561
v The object reference variable has been deleted. Remove the statement that refers to the deleted variable.
In a For statement, the step value must be numeric. LotusScript attempts to convert the value in S to a number when executing the Forstatement above. This is an invalid use of NULL. Use the IsNull function to determine if a value is NULL.
562
563
Bad attribute
You supplied an illegal file attribute number using the FileAttr function. Supply a legal attribute number (either 1 or 2) that specifies the type of information you want.
564
Compiler error
The function signature of an external C-callout function has been corrupted. Record the error message number and contact Lotus Software Support.
565
Module in use
You tried to unload the currently running module. Remove any attempt to unload the currently running module.
566
Reverse the order of the characters in the illegal range specification. v You specified an open square bracket without a close square bracket. For example:
"a" Like "[abc"
Supply the close square bracket. If you want to specify an open square bracket as a character to match, enclose it in square brackets:
"[" Like "[[]"
567
Change the suffix character to match the declared data type, or remove the suffix character.
Remove the reference or insert a statement before it that assigns an object reference to the Variant.
Remove the reference or insert a statement before it that assigns a list, fixed array, or reference to a collection to the Variant.
568
Class MyClass Function MyFunction(A As Integer) As Integer ... End Function End Class Dim varV As Variant Set varV = New MyClass Dim X As Integer X% = varV.MyFunction Illegal: too few arguments. X% = varV.MyFunction(5,10) Illegal: too many arguments.
Remove the reference or define the sub or function as a member of the class.
Remove the reference or redefine the sub as the appropriate type of class member.
569
Illegal DELETE
You tried to use the Delete statement to delete a member of an object rather than the object itself. The Delete statement requires a plain object name. For example:
Class MyClass Public X As Integer End Class Dim varV As Variant Set varV = New MyClass Delete varV.X Illegal. Delete varV Legal.
Remove the Delete statement or change its argument to an unqualified object name.
570
Remove the On Event statement or specify an event defined for the object.
Change the event handlers signature to make it have the required number of parameters.
571
End Sub Dim objRefVar As New Walden("ABC") On Event Moved From objRefVar Call GoodSub On Event Moved From objRefVar Call BadArgType
Change the event handlers signature so that its parameters are of the required data types.
Remove the reference or, if possible, change the definition of the class member from Private to Public.
Missing argument
You called a member sub or function of a product class and omitted one or more of the arguments that it expected. For example, assume a product class Walden that has a member sub Move that has two integer parameters:
Dim varV As Variant Set varV = New Walden("ABC") varV.Move 5 Illegal: Waldens Move method has two parameters, not one.
Supply the required number of arguments in the call, or remove the calling statement.
Use the ReDim statement to assign bounds to the array before assigning the array to the Variant. v You tried to pass an uninitialized dynamic array to the LBound or UBound function:
Dim anArray() As Integer LB% = LBound(anArray) Illegal.
Use the ReDim statement to assign bounds to the array before calling the LBound or UBound function.
572
Use one, and only one, subscript when referring to a collection member.
Remove the reference or replace its target with the name of a collection.
Add members to the collection before trying to refer to them; specify an index that identifies a member; or remove the reference.
Underflow
An internal error occurred. Record the error message and contact Lotus Software Support.
573
Class MyClass ... End Class Dim varV As Variant Dim otherVarv As Variant Dim X As New MyClass Set varV = X otherVarV = varV Illegal. otherVarV = New varV Illegal. Set otherVarV = varV Legal. Set otherVarV = New varV Legal.
Include the Set keyword in the assignment statement or remove the statement.
Automation-Object error
An error occurred when you tried to refer to an OLE Automation object. Check the syntax of the statement that caused the error, and check the documentation for the OLE Automation object to which you tried to refer.
574
Illegal REDIM
You used a ReDim statement in a context in which it is inappropriate: v In referring, with the Preserve keyword, to a variable of type variant that doesnt already contain an array. For example:
Dim varV As Variant varV = 5 ReDim Preserve varV(1 To 3)
Illegal
Remove the keyword Preserve if you want varV to hold an array, or remove the Redim statement. v You referred to a member variable of a class as though it were an array, though it isnt. For example:
Class AClass Public X As Integer End Class Dim varV As Variant Set varV = New AClass ReDim varV.X(1 To 3)
Declare X as a dynamic array or remove the ReDim statement. v You referred to a member variable or property of a class as though it held or returned a dynamic array rather than a fixed array. For example:
Class AClass Public X(1 To 2) As Integer End Class Dim varV As Variant Set varV = New AClass ReDim varV.X(1 To 3)
575
576
Variable is read-only
A set operation is attempted on a product variable that is read-only.
577
578
A
Abs function LotusScript 233 Absolute values LotusScript 233 Access keyword Lock and Unlock statements Access modes changing 111 Access types for files LotusScript 311 Acos function LotusScript 233 ActivateApp function LotusScript 182 ActivateApp statement LotusScript 234 Actual parameters LotusScript 93 Addition operator LotusScript 59 Addition operator (+) LotusScript 64 ADT errors 565 Agents, types of HTTP 171
384
B
Backslash LotusScript 59 Bars vertical (|) 8 Base classes 129 methods 130 properties 130 referring to a member 139 Base keyword Option Base statement 407 Base of numbers LotusScript 247, 340, 397 BAT files LotusScript 444, 445 Beep statement LotusScript 246 Bin function LotusScript 247 Binary files accessing 108
579
Binary files (continued) LotusScript 103, 108, 331, 353, 403, 416 opening 107 reading 107, 109 variable length record 107 writing 109 Binary keyword Lotusscript 407 LotusScript 403 Binary numbers LotusScript 7, 247 Binary operations LotusScript 18 Bind keyword LotusScript 440 Bitwise operators. See Operators 57 Blank spaces LotusScript 433, 448, 468, 472 LTrim function 387 statement construction rules 7 Block statements LotusScript 148, 150, 152 Boolean data type LotusScript 247 Boolean operators. See Operators 57 Boolean values LotusScript 51 Bounds for arrays LBound function 373 limiting 494 LotusScript 407, 477 Bounds lists LotusScript 36 Bracket notations LotusScript 177, 248 Branching statements LotusScript 153, 154, 155, 338, 339, 401, 427 Built-in constants EMPTY 25 FALSE 25 LotusScript 25, 180 NOTHING 25 NULL 25 PI 25 TRUE 25 Built-in functions ActivateApp 182 CDat 52 Command 177 CreateObject 184 DataType 43 Date 52 DateNumber 52 DateValue 52 Day 52 described 85 Environ 182 EOF 109 Erl 113 Err 113 Error 113 Error$ 113 FileDateTime 52 Format 52 FreeFile 109
Built-in functions (continued) GetObject 184 Hour 52 Input 109 InputBox 180 IsArray 43 IsDate 52 LBound 39 LOF 109 LotusScript 34 MessageBox 180 Minute 52 Month 52 Now 52 Second 52 Seek 109 Shell 182 Time 52 TimeNumber 52 Timer 52 TimeValue 52 Today 52 TypeName 43 WeekDay 52 Year 52 Yield 182 Byte data type LotusScript 249 Byte-oriented functions LenB function 377 LenBP function 379 LotusScript 354, 356, 359, 360, 392, 428 ByVal keyword 87 Declare statement 190 forward reference 285 LotusScript 282, 461
C
C functions 185 calling 185 calling convention 185 declaring 186 external 282 passing arguments to 187 return value 193, 282 C language 185 Call keyword LotusScript 250, 400 Call statement LotusScript 97, 250 Calling C functions 185 Sub Delete 139 Sub New 139 Case keyword LCase function 374 Lotusscript 407 LotusScript 436 Case sensitivity Lotusscript 407 LotusScript 357, 359, 360, 452 CBool function LotusScript 252 CByte function LotusScript 253
CCur function LotusScript 254 CDat function LotusScript 52, 255 CDbl function LotusScript 256 Character codes LotusScript 243, 258, 460, 478, 479, 482 Character extraction Left function 374 LeftBP function 375 LeftC function 376 LotusScript 391, 392, 393, 427, 428, 429 Character oriented functions InStrC function 361 LeftC function 376 LenC function 379 LotusScript 393, 429, 455, 456, 457 Characters case 407, 478 LCase function 374 Lotusscript 407 LotusScript 407 special 13 ChDir statement LotusScript 257 ChDrive statement LotusScript 258 Chr function LotusScript 258 CInt function LotusScript 259 Class constructor LotusScript 465 Class destructor LotusScript 463 Class members public and private 133 referring to 133 scope 133, 134 Class statement LotusScript 260 Classes array and list 143 base classes 129 benefits 129 bracket notation 177 class library 129 Collection classes 177 creating an object 177 creating object 144 declaring 144 defining a variable 130 deleting an object 136, 177 derived classes 129 dot (.) notation 133, 177 dotdot (..) notation 139 events 177 inheritance 129 instance 129 LotusScript 297 Me keyword 133 methods 129, 177 object member 133 object reference 17, 133, 144
580
Classes (continued) overriding a method 139 overriding a property 139 properties 177 scope 133, 134 user-defined 17 ClassName property JavaClass class 201 ClearJavaError method JavaSession class 223 CLng function LotusScript 263 Close statement LotusScript 264 CodeLock function LotusScript 264 CodeLockCheck function LotusScript 266 CodeUnlock function LotusScript 266 Collection classes LotusScript 177 Collections for an array 36 of lists 45 Columns printing output 468 COM files LotusScript 444, 445 Command function LotusScript 177, 267 Command line arguments LotusScript 267, 444, 445 Comments LotusScript 147, 421, 422 Compare keyword LotusScript 407 Comparing LotusScript 452 Comparison LotusScript 407, 452 Comparison operator. See Operators Compile times errors 3, 113 Compiled files LotusScript 129 Compiled modules loading 3 Compiled scripts 3 Compiler directives LotusScript 147, 344, 350, 422 placing 7 Compiler limits 495 Concatenation operator LotusScript 79 Concatenation operators. See Operators 57 Conditional statements LotusScript 341, 342, 343, 344 Const statement LotusScript 267 Constants built-in 25 data type suffix characters 26 defined 25 EMPTY 25 FALSE 25
59
Constants (continued) in LSCONST.LSS 26 in LSPRVAL.LSS 26 LotusScript 267 LSCONST.LSS file 25 naming rules 9 NOTHING 25 NULL 25 PI 25 platform identification 344 product-specific 26 scope 22 testing data type 26 TRUE 25 user-defined 26 Constructor (New sub) LotusScript 260 Constructor sub LotusScript 98, 465 Constructor sub. See Sub New 139 Container classes. See Collection classes 177 Container variable LotusScript 163 Context switch 171 Conversions changing case 478 lowercase 374 Converting data types LotusScript 252, 253, 254, 255, 256, 259, 263, 272, 273, 275 overview 18 Converting numbers LotusScript 247, 340, 397 Converting strings Case function 374 LotusScript 454, 482 Copying files LotusScript 312 Cos function LotusScript 269 Cosine LotusScript 269 Count property JavaMethodCollection class 210 JavaPropertyCollection class 220 CreateLock function LotusScript 270 CreateObject function LotusScript 184, 270 CreateObject method JavaClass class 201 CSng function LotusScript 272 CStr function LotusScript 273 CurDir function LotusScript 273 CurDrive function LotusScript 274 Curly braces ({ }) LotusScript 8 Currency LotusScript 274 Currency conversions LotusScript 254 Currency data types 17
Currency data types (continued) default value 29 LotusScript 274 Current errors LotusScript 113 Current property JavaMethodCollection class 211 JavaPropertyCollection class 220 CVar function LotusScript 275 CVDate alias LotusScript 507 CVDate function LotusScript 255
D
Data limiting 493 Data type suffix characters constants 26 LotusScript 26, 287, 290 omitting 26 Data types array 17, 39 constants 26 converting 18, 247, 254, 255 currency 17, 274 date/time 52 default 26 determining 26 Double data type 17 integer 17 list 17 long 17 LotusScript 17, 247, 249, 276, 277, 287, 297, 298, 362, 447, 460, 475, 483 numeric limits 493 object reference 17 scalar 17 single 17 string 17 user-defined 17, 126, 473 user-defined in C language function calls 192 variables 29 variant 144 variants 17 DataType function LotusScript 26, 43, 52, 276 Date and time handling converting 255, 279, 280, 470, 471, 485 measuring 471 reading 278, 281, 312, 340, 394, 395, 397, 433, 469, 472, 490 setting 279, 470 testing 363 Date function LotusScript 52, 278 Date statement LotusScript 52, 279 Date values valid range 52 DateNumber function LotusScript 52, 279
Index
581
DateSerial alias LotusScript 507 DateSerial function LotusScript 279 DateTime data type 52 DateValue function LotusScript 52, 280 Day function LotusScript 52, 281 Debugger. See Script Debugger 5 Debugging a script 5 Decimals LotusScript 7 Declarations LotusScript 147 scope 23 Declare keyword external C call 282 forward reference 285 LotusScript 409 Declare statement LotusScript 86, 186 Declaring a dynamic array 43 a list 45 a property 99 a sub 96 fixed array 39 object reference 144 user-defined 126 Declaring variables explicitly 29 implicitly 33 LotusScript 290, 409 Default data type LotusScript 26 Default values variables 29 DefByte statement LotusScript 287 DefCur statement LotusScript 287 Defining a function 86 a property 99 a sub 96 an error 113, 116 member variables 126, 130 Defining functions LotusScript 329 Definition statements LotusScript 148 DefInt statement LotusScript 287 DefLng statement LotusScript 287 DefSng statement LotusScript 287 Deftype statement LotusScript 33 DefVar statement LotusScript 287 Delete LotusScript 301
Delete statement LotusScript 136, 289 Delete sub 98 calling 139 Delimiters LotusScript 13 Derived classes 129, 137 defining a member 139 using Sub New 139 DestroyLock 175 DestroyLock function LotusScript 290 Destructor LotusScript 260, 289, 463 Destructor sub LotusScript 98 Destructor sub. See Sub Delete 139 Determining application use 177 Dialog boxes LotusScript 355, 388 Differences Macintosh platform 500 OS/2 platform 497 Dim statement 144 dynamic array 43 fixed array 39 for a list 45 LotusScript 29, 36, 290 Dimensions for an array 36 Dir function LotusScript 295 Directives LotusScript 147, 344, 350 Directories LotusScript 273, 295 Directories and files LotusScript 257, 258, 273, 274, 295, 312, 395, 396, 403, 430 Disjunction (Or) operator LotusScript 74 Disk drives LotusScript 258, 274, 295 Division operator floating-point division (/) 59 integer division 59 Division operator (/) LotusScript 63 Divisions remainder 59, 64 DLL files Declare statement 185 LotusScript 282, 480 using 185 Do keyword Do statement 296 Do loops LotusScript 157 Do statement LotusScript 157 DoEvents function and statement LotusScript 491 DominoAsynchronousAgents 175 Dot (.) notation LotusScript 133, 177, 224, 260, 297, 473
Dotdot (..) notation LotusScript 139 Double data types LotusScript 17, 298 Double precision numbers LotusScript 17 Drives LotusScript 258, 274, 295 Dynamic arrays DataType function 43 declaring 43 Dim statement 43 LotusScript 36, 290, 419 ReDim statement 43 TypeName function 43 Dynamic Link Libraries LotusScript 185
E
Early termination statements LotusScript 299, 309 Editor. See Script Editor 3 Elapsed time LotusScript 471 Elements array 39 array data type 43 Else keyword LotusScript 341, 342, 343, 436 ElseIf keyword LotusScript 343 Empty strings LotusScript 8 Empty values LotusScript 25, 290, 483 EMPTY values LotusScript 367 Encapsulation LotusScript 133 End of File LotusScript 300 End statement LotusScript 167, 299 Environ function LotusScript 182, 299 Environment variables LotusScript 182 EOF function LotusScript 109, 300 Equal sign 80 LotusScript 78 Equals operator LotusScript 59, 66, 78 Eqv operator LotusScript 59, 76 Erase statement LotusScript 43, 301 Erasing an object 177 Erl function LotusScript 113, 302 Err function LotusScript 113, 303 Err statement LotusScript 304
582
Error function LotusScript 113, 304 Error handling LotusScript 113, 116, 148, 302, 303, 304, 305, 398, 426 Error keyword LotusScript 398 Error line numbers returning 113 Error messages 148, 304, 528, 553, 555, 558, 573, 574, 575, 576, 577 compile-time 549 defining 116 file 116 LotusScript 511, 512, 513, 514, 515, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577 returning 113 run-time 576, 577 Error number LotusScript 303, 304 Error numbers defining 116 LotusScript 113 resetting 113 returning 113 Error statement LotusScript 305 Error statements LotusScript 113, 116 Error$ function LotusScript 113 ErrorMsg property JavaError class 205 Evaluate function and statement LotusScript 306 Event handling LotusScript 400 Event keyword LotusScript 400 Events defined 2 for Lotus product classes 177 Examples LotusScript 233, 251, 277, 299, 333, 342, 390, 411, 434, 468, 483 Exclusive Or (Xor) operator LotusScript 75 Exclusive Or operator LotusScript 59 EXE files LotusScript 444, 445 Execute function and statement LotusScript 307 Executing a script 5 a sub 97 a user-defined function 90 Exit statement flow 168 LotusScript 309
Exp function LotusScript 310 Explicit data type conversions LotusScript 19 Explicitly declaring variables LotusScript 29, 287, 290 Exponentiation operator (^) LotusScript 59, 61 Exporting library function 185, 282 Expression compiling as a temporary module 307 Expressions described 57 Expressions and operators LotusScript 57 Extended character sets LotusScript 347, 348 External declarations 185 library function 282 External functions library function 185 LotusScript 282
F
False values LotusScript 25, 51 File access Lock and Unlock statements 384 File attributes LotusScript 334, 442 File information LotusScript 311, 312, 313, 442 File number, unused LotusScript 327 File operations summary 103 FileAttr function LotusScript 311 FileCopy statement LotusScript 312 FileDateTime function LotusScript 52, 312 FileLen function LotusScript 313 Files binary 103, 107, 108, 331, 416 closing 111, 264, 425 compiling a script 3 fixed length 109 formatting data 486 limits on operations 494 Line Input # statement 381 LotusScript 264, 300, 331, 351, 353, 354, 356, 412, 416, 425, 434, 435, 448, 468, 486, 488 LotusScript constants 180 LSCONST.LSS 25 LSCONST.LSS file 180 LSO 3, 129 naming 3 opening 105, 109, 327 random 103, 105, 108, 331, 416 reading 103, 105, 107 reading from 109, 331, 351, 354, 356
Files (continued) sequential 103, 108, 351, 412, 488 using with data type 126 variable length 109 writing 103, 105, 107 writing to 109, 412, 416, 488 Files and directories, managing Kill statement 373 Files, deleting 373 Files, positioning 383 LotusScript 300, 434, 435 Fix function LotusScript 313 Fixed arrays bounds list 39 DataType function 43 declaring 39 Dim statement 39 dimension 39 LotusScript 290 lower bounds 39 reinitializing 43 size 39 TypeName function 43 upper bounds 39 Fixed length records LotusScript 109 Fixed length strings LotusScript 29 Floating-point numbers LotusScript 17, 298, 447 Flow control statements LotusScript 147 Flow of execution LotusScript 147 For keyword LotusScript 309, 314, 403 For loops LotusScript 159 For statement functioning 314 LotusScript 314 managing flow 159 nesting 159 ForAll keyword LotusScript 309 ForAll statement container variable 163, 316 functioning 316 LotusScript 316 managing flow 163 Formal parameters LotusScript 93 Format function LotusScript 52, 319 Forward references LotusScript 285 Fraction function LotusScript 327 FreeFile function LotusScript 109, 327 From keyword LotusScript 400 FullTrim function LotusScript 328 Function statement LotusScript 329 Index
583
Functions block terminator 85 calling C function 185 declaring C function 186 defining 86 described 85 executing 90 forward reference 285 in a class 130 in run-time errors 113 LotusScript 177, 250, 282 maximum argument 494 naming rules 9 overriding 139 passing arguments to C functions 187 predefined 34 recursive 90 return value 34, 89 signature 85 terminating 167 user-defined 90 with multiple arguments 90 with no arguments 90 with one argument 90
GoSub keyword LotusScript 338, 401 GoSub statement LotusScript 155 GoTo keyword LotusScript 339, 341, 398, 402 GoTo statement LotusScript 153, 339 Greater than operator LotusScript 59, 78 Greater than or equal to operator 80 LotusScript 59, 66, 78 greater than sign LotusScript 78 Greater than sign) LotusScript 59
H
Handling an error 113, 116 Hex function LotusScript 340 Hexadecimal numbers LotusScript 340 numeric construction 7 Hidden files LotusScript 295, 334, 442 Hiding data 133 Hiragana input mode LotusScript 347, 348 Host operating system differences 498, 500 Hour function LotusScript 52, 340 HTTP agents multi-threading 171 serial 171 threaded 171
G
Get keyword LotusScript 331, 403, 413 Get statement LotusScript 109, 331 GetAttr alias LotusScript 507 GetAttr function LotusScript 334 getClass method JavaSession class 224 getClassMethods method JavaClass class 202 getClassProperties method JavaClass class 203 GetFileAttr function LotusScript 334 getFirst method JavaMethodCollection class 212 JavaPropertyCollection class 221 getLastJavaError method JavaSession class 224 GetMethod method JavaClass class 203 getNext method JavaMethodCollection class 213 JavaPropertyCollection class 221 getNth method JavaMethodCollection class 213 JavaPropertyCollection class 222 GetObject function LotusScript 184, 335 GetProperty method JavaClass class 204 GetThreadInfo function LotusScript 337 Getting file information 385 getValue method JavaProperty class 217
497,
I
Identifiers construction rules 9 for variables 29 maximum length 494 reserved for LotusScript If (%If directive) LotusScript 344 If...GoTo statement LotusScript 341 If...GoTo...Else statement LotusScript 153 If...Then...Else statement LotusScript 148, 342 If...Then...Elseif statement LotusScript 150 If...Then...ElseIf statement LotusScript 343 IMESetMode function LotusScript 347 IMEStatus function LotusScript 348 Imp operator LotusScript 59, 77
10
Implicitly declaring variables LotusScript 33 Implode function LotusScript 349 Include (%Include directive) LotusScript 350 Inclusive Or (Or) operator LotusScript 74 Indexes for a list 45 for an array 36 Inheritance LotusScript 129, 130, 137 Initialize sub LotusScript 98, 464 Initializing values 473 Input # statement LotusScript 109, 351 Input function LotusScript 109, 353 Input keyword Input function 353 Line Input # statement 381 LotusScript 403 Input mode LotusScript 347, 348 InputB function LotusScript 354 InputBox function LotusScript 180, 355 InputBP function LotusScript 356 Instances of a class 260 Instances of a class. See Objects 144 InStr function LotusScript 357 InStrB function LotusScript 359 InStrBP function LotusScript 360 InStrC function LotusScript 361 Int function LotusScript 362 Integer data type LotusScript 17, 362 Integer division operator LotusScript 59 Integer division operator ( )\LotusScript 63 Interacting programs with applications 182 with the user 180 International functions LeftC function 376 LenC function 379 LotusScript 347, 348, 393, 429, 454, 455, 456, 457 Intrinsic functions. See Built-in functions 34 Invoke method JavaMethod class 209 Is keyword LotusScript 436
584
Is operator LotusScript 83, 135 IsA operator LotusScript 84 IsArray function LotusScript 43, 363 IsDate function LotusScript 52, 363 IsDefined function LotusScript 364 IsElement function LotusScript 365 IsEmpty function LotusScript 367 IsList function LotusScript 367 IsNull function LotusScript 368 IsNumeric function LotusScript 368 IsObject function LotusScript 370 IsScalar function LotusScript 370 IsUnknown function LotusScript 371 Iteration. See Loops 157 Iterative statements LotusScript 157, 159, 163, 167
JavaProperty class getValue method 217 JClass property 215 LS2J classes 215 Modifier property 216 PropertyName property 216 setValue method 218 Type property 217 JavaPropertyCollection class Count property 220 Current property 220 getFirst method 221 getNext method 221 getNth method 222 LS2J classes 219 JavaSession class ClearJavaError method 223 getClass method 224 getLastJavaError method 224 LS2J classes 223 JClass property JavaMethod class 207 JavaProperty class 215 Join function LotusScript 372 Jumps (branching) LotusScript 338, 339, 401, 427
K
Katakana input mode LotusScript 347, 348 Keystrokes sending 438 Keywords LotusScript 10 Me 133 new 144 Preserve 43 Kill statement 373
J
JavaClass class ClassName property 201 CreateObject method 201 getClassMethods method 202 getClassProperties method 203 GetMethod method 203 GetProperty method 204 LS2J classes 200 JavaConnect Arguments processing 225 Data type mappings 225 Java reference types 225 Java Virtual Machine (JVM) 223 limitations 225 JavaError class ErrorMsg property 205 LS2J classes 205 StackTrace property 205 JavaMethod class Invoke method 209 JClass property 207 LS2J classes 207 MethodName property 208 Modifier property 208, 216 Signature property 209 JavaMethodCollection class Count property 210 Current property 211 getFirst method 212 getNext method 213 getNth method 213 LS2J classes 210 JavaObject class LS2J classes 214
L
Labels for statements 148 placing 7 rules for construction 9 Language limits function and sub argument 494 source language statement 494 LBound function 373 LotusScript 39 LCase function 374 Left function 374 Left-align strings 387 LeftB function 375 LeftBP function 375 LeftC function 376 Len keyword Len function 376 LotusScript 403 LenB function 377 LenBP function 379 LenC function 379 Length of files LotusScript 313
Length of strings Len function 376 LenB function 377 LenBP function 379 LenC function 379 Lengths of a file 385 Less than operator LotusScript 66 Less than or equal to operator LotusScript 66 Less than sign) LotusScript 59 Let statement 380 Lib keyword LotusScript 282 Libraries script 3 Like operator LotusScript 81 Limits array size 494 array variable 494 compiled program structure 495 file operations 494 numeric data 493 string data 493 Line continuation character (_) LotusScript 7 Line Input # statement 381 LotusScript 109 Line numbers LotusScript 302 Line widths LotusScript 486 List data type LotusScript 17, 45 List element deleting 301 List keyword forward reference 285 LotusScript 290, 461 List tags case sensitivity 45 Lists declaring 45 deleting 301 list tag 45 ListTag function 382 LotusScript 290, 365, 367 ListTag function 382 Literal strings construction of 8 Lless than sign 80 LMBCS keyword Declare statement 190 LMBCS strings LotusScript 282 LOC function 383 Local variables LotusScript 93 Lock keyword Lock statement 384 LotusScript 403 LockID 175 Locking functions LotusScript 264, 266, 270, 290 Index
585
Locks creating and destroying 175 thread safe code 175 LOF function LotusScript 109 LOF Function 385 Log function 386 Logical operators And 73 Eqv 76 Imp 77 Not 73 Or 74 Xor 75 Logical operators. See Operators 57 Long data type 386 LotusScript 17 Loop control variables For statement 159 ForAll statement 163 Loop keyword LotusScript 157, 296 Loops Do loop 157 For loop 159 ForAll loop 163 LotusScript 296, 485 terminating 168 While loop 167 Lotus product classes bracket notation 177 Collection class 177 creating an object 177 deleting an object 177 dot (.) notation 177 events 177 methods 177 properties 177 Lotus products determining use 177 interacting 182 LotusScript data types 274 described 1 error messages file 116 keywords 10 REXX integration 505 LotusScript constants LotusScript 180 LotusScript constants. See Built-in constants 25 LotusScript data types 386 LotusScript 247, 249, 298, 362, 447, 460, 483 LotusScript statements Call 97 Date 52 Declare 86, 186 Deftype 33 Delete 136 Dim 29, 144 Do 157 End 167 Erase 43 Err 116 Error 116 Exit 168
LotusScript statements (continued) For 159 ForAll 163 Get/Set 413 getting 109 GoSub 155 GoTo 153 If...GoTo...Else 153 If...Then...Else 148 If...Then...Elseif 150 Input # 109 Line Input # 109 On...GoSub 155 On...GoTo 154 Open 109 Option Base 39 Print 180 Print # 109 Property Get 99 Property Set 99 Put 109 ReDim 43 Return 155 Seek 109 Select Case 152 SendKeys 182 Set 144 Time 52 using 3, 129 While 167 With 134 Write # 109 Yield 182 Lower bounds fixed array 39 LotusScript 36 LS2J ADT 197 classes 200 data type mappings 225 dot notation 197 error handling 198 example 227 installation 195 Java errors 198 Java precision 225 Java security 195 Java Virtual Machine (JVM) 195 limitations 200 method invoking 197 Notes agent 195 Script Libraries 196 string mapping 225 system requirements 195 Use statement 196 using 195 LS2J classes JavaClass class 200 JavaError class 205 JavaMethod class 207 JavaMethodCollection class 210 JavaObject class 214 JavaProperty class 215 JavaPropertyCollection class 219 JavaSession class 223 LSCONST.LSS file LotusScript 25, 26, 180
LSERR.LSS file LotusScript 116 LSet statement 387 LSO files 3 LotusScript 129 LSPRVAL.LSS file 26 LSS files LotusScript 350 LSX files LotusScript 195, 480 LTrim function 387
M
Macintosh limitations LotusScript 224 Macintosh platform differences 500 Margins script 7 Matching strings 81 Mathematical functions Log function 386 LotusScript 233, 244, 245, 269, 310, 313, 327, 362, 419, 430, 431, 443, 446, 451, 469 Me keyword LotusScript 133, 260 Member variables defining 126 referring to 126 Members of a class 260 of a type 473 Members of classes scope 134 MessageBox function LotusScript 180 MessageBox function and statement LotusScript 388 MethodName property JavaMethod class 208 Methods defining 130 for Lotus product classes 177 overriding 139 referring to 177 Mid function LotusScript 391 Mid statement LotusScript 391 MidB function LotusScript 392 MidB statement 392 MidBP function LotusScript 392 MidC function LotusScript 393 Minus sign (-) LotusScript 59, 65 Minute function LotusScript 52, 394 MkDir statement LotusScript 395 Mod operator LotusScript 59, 64
586
Modifier property JavaMethod class 208, 216 JavaProperty class 216 Module level variables LotusScript 93 Modules creating 3 limit on symbols 495 loading 3 LotusScript 464, 467, 480 using 3 Month function LotusScript 52, 395 Msgbox alias LotusScript 507 Multi-processing enabling 175 Multi-threading 171 Multiplication operator (*) LotusScript 59, 62
Numbers rounding 362 Numeric conversions implicit converting 18 LotusScript 247, 252, 253, 254, 255, 256, 259, 263, 272, 273, 275, 340, 397, 452, 482 Numeric operators. See Operators 59
O
Object arguments to C functions arrays 190 Object linking and embedding LotusScript 184 Object reference variables 125, 129 declaring 144 variant 144 Object references 133 as an argument 139 LotusScript 17 testing 135 Objects as an argument 139 bracket notation 177 creating 144, 177, 270, 465 declaring a variable 144 deleting 136, 177, 289, 463 Is operator 83 LotusScript 248, 260, 290, 297, 370, 371, 400, 440, 487 memory management 136 methods 129 object reference 144 opening 335 passing 190 referring to 177 referring to members 134 Oct function LotusScript 397 Octal numbers function 397 numeric construction 7 OLE automation LotusScript 184 OLE objects LotusScript language 270, 335, 370, 371 naming rules 9 On Error statement 113, 116, 120, 121 LotusScript 398 On Event statement LotusScript 400 On...GoSub statement LotusScript 155, 401 On...GoTo statement LotusScript 154, 402 Ones complement LotusScript 59 Open statement LotusScript 109, 403 MIME charset names 509 Opening files LotusScript 109 random 105 sequential 103
N
Name conflicts LotusScript 23 Name statement LotusScript 396 Named constants LotusScript 25 Names construction rules 9 of variables 29 Natural logarithm 386 Negation operator (-) LotusScript 62 Nested For loops LotusScript 159 New keyword 144 LotusScript 260, 290, 440 New sub 98, 130, 133 calling 139 LotusScript 465 Next keyword 398 Lotusscript 426 LotusScript 159 NoCase keyword LotusScript 407 NoPitch keyword LotusScript 407 Not equal operator 80 LotusScript 59 Not equal to operator LotusScript 66 Not operator LotusScript 59, 73 Nothing values LotusScript 260, 289, 290, 440 Now function LotusScript 52, 397 Null values LotusScript 25, 368, 483 Number handling Len function 376 limits 493 LotusScript 233, 313, 327, 362, 368, 431, 443 numeric construction 7
Operating system differences 497, 498, 500 Operators 59 addition 59 And 59 arithmetic 57 assignment 57 bitwise 57 Boolean 57 comparison 66 concatenation 57 described 57 division (/) 63 equal sign 59 Eqv 59 exponentiation (^) 59 floating-point division (/) 59 greater than 59 greater than or equal to 59 Imp 59 integer division 59 integer division (\) 63 Is 83, 135 IsA 84 less than 59 less than or equal to 59 Like operator 78 logical 57 LotusScript 57 Mod 59 multiplication (*) 59 negative (-) 62 Not 59 not equal to 59 Not equal to 78 numeric 59 Or 59 precedence 58 relational 57 string 78 string concatenation 79 subtraction 59 unary minus (-) 59 unary plus (+) 59 Xor 59 Option Base statement LotusScript 39, 407 Option Compare statement LotusScript 407 Option Compare Text alias LotusScript 507 Option Declare statement LotusScript 409 Option Explicit statement LotusScript 409 Option Public statement LotusScript 410 Or operator LotusScript 59, 74 OS information LotusScript 299 OS/2 platform differences 497 Output LotusScript 246, 388, 410 Output keyword LotusScript 403
Index
587
139
P
Parameters. See Arguments 93 Parentheses LotusScript 250 Passing arguments 93 C functions 187 LotusScript 87, 187 Passing arrays 190 Passing objects 190 Passing strings LotusScript 188 Passing types 190 Pattern matching LotusScript 81 Pausing in scripts LotusScript 447 PI values LotusScript 25 PIF files LotusScript 444, 445 Pitch keyword LotusScript 407 Pitch sensitivity LotusScript 407 Platform differences 497, 500 UNIX 498 Platforms identification 344, 364 Plus sign LotusScript 78 Plus sign (+) LotusScript 59 Positioning in a file 383, 434, 435 Pound sign LotusScript 78 Precedence of an operator 58 Predefined functions. See Built-in functions 34 Preserve keyword LotusScript 43, 419 Print # statement LotusScript 109, 412 Print keyword LotusScript 403 Print statement LotusScript 180, 410 Private class members LotusScript 133 Private keyword external C call 282 forward reference 285 LotusScript 260, 267, 290, 413, 461 Procedures 85 maximum argument 494 properties 99 sub 93 terminating 167 Process definition of 171 Processing an error 113
Product objects LotusScript 248, 289, 290, 297, 440 Product-specific constants LotusScript 26 Products determining use 177 interacting 182 Programs interacting with SendKeys statement 438 LotusScript 234, 444, 445 Properties declaring 99 defining 99, 130 for Lotus product classes 177 naming rules 9 overriding 139 overview 99 redefining 139 referring to 177 Property Get statement LotusScript 99 Property Get/Set statements LotusScript 413 Property keyword forward reference 285 Property Set statement LotusScript 99 PropertyName property JavaProperty class 216 Public class members LotusScript 133 Public keyword external C call 282 forward reference 285 LotusScript 260, 267, 290, 410, 413, 461 Put keyword LotusScript 403 Put statement 416 Put statement LotusScript 109, 416
Q
Quotation marks LotusScript 8
R
Random files accessing 108 defining a record type 105 LotusScript 103, 108, 331, 403, 416 opening 105 reading 105, 109 writing 105 Random keyword LotusScript 403 Random numbers LotusScript 430 Randomize statement LotusScript 419 Read keyword LotusScript 403
Read-only files LotusScript 334, 442 Reading from files binary 107 Line Input # statement 381 LotusScript 331, 351, 353, 354, 356 random 105 sequential 103 Records fixed length 109 variable length 109 Recovering storage in a dynamic array 43 Recursion limiting 495 Recursive functions LotusScript 90 Redefining a method 139 a property 139 ReDim statement LotusScript 43, 419 Reference external 188 Reference, argument passing by LotusScript 18 References, forward 285 Referring to a method 177 an object 177 bracket notation 177 class members 134 member variables 126 members of an object 134 objects 133 properties 177 Reinitializing a fixed array 43 Relational operators LotusScript 66 Relational operators. See Operators 57 Rem keyword LotusScript 422 Rem statement LotusScript 421 Remainder of division LotusScript 64 Remainders determining 59 Remarks. See Comments 147 Remove keyword LotusScript 400 Replace function LotusScript 423 Reserved words LotusScript 10 Reset statement LotusScript 425 Resizing arrays 43 Resume 0 keyword LotusScript 120 Resume keyword 120 Lotusscript 426 LotusScript 398 Resume Next keyword LotusScript 120
588
Resume statement LotusScript 113, 116, 426 Return statement LotusScript 155, 427 Return values for a function 89 LotusScript 193, 282, 285 of functions 34 REXX 505 Right function LotusScript 427 Right-aligning strings LotusScript 432 RightBP function LotusScript 428 RightC function LotusScript 429 RmDir statement LotusScript 430 Rnd function LotusScript 430 Round function LotusScript 431 RSet statement LotusScript 432 RTrim function LotusScript 433 Rules constructing a script 7 for scripts and statements 7 Run statement LotusScript 433 Run-time errors 3 LotusScript 113, 116
S
Scalar data types currency 17 double 17 integer 17 long 17 LotusScript 17 single 17 string 17 Scalar values LotusScript 370 Scope of class members 134 of constants 26 of declarations 23 Screen printing 410 Script Debugger 5 Script Editor 3 Script modules creating 3 using 3 Scripts comments 147 compiler directive 147 compiling 3 constructing rules 7 debugging 5 declaration 147 defined 2 definition statements 148
Scripts (continued) flow of execution 147 labels 148 limiting 495 pausing 447 viewing 3 writing 3 Searching in strings 357, 359, 360, 361 Second function LotusScript 52, 433 Seeding the random number generator 419 Seek function LotusScript 109, 434 Seek statement LotusScript 109, 435 Select Case statement LotusScript 152, 436 SendKeys statement LotusScript 182, 438 Separators LotusScript 13 Sequential files accessing 108 Line Input # statement 381 LotusScript 103, 108, 351, 353, 403, 412, 488 opening 103 reading 103, 109 writing 103, 109 Set keyword LotusScript 413, 440 Set statement LotusScript 144, 440 SetAttr alias LotusScript 507 SetAttr function LotusScript 442 SetFileAttr function LotusScript 442 setValue method JavaProperty class 218 Sgn function LotusScript 443 Shadowing LotusScript 23 variables 93 Shared keyword LotusScript 403 Shared libraries external C call 185, 282 Shell function LotusScript 182, 444, 445 Shellid function LotusScript 182, 444, 445 Signature property JavaMethod class 209 Sin function LotusScript 446 Single data type LotusScript 17, 447 Slash (/) LotusScript 59 Slash (/) notation LotusScript 224
Sleep statement LotusScript 447 Space function LotusScript 448 Spaces LotusScript 433, 448, 468, 472 Spc function LotusScript 448 Special characters LotusScript 13 Split function LotusScript 449 Sqr function LotusScript 451 Square roots LotusScript 451 StackTrace property JavaError class 205 Statement labels LotusScript 148 Statements comments 147 compiler directive 147 construction rules 7 continuation character (_) 7 declaration 147 defining 148 flow of execution 147 in run-time errors 116 separation character (:) 7 Statements, LotusScript. See LotusScript statements 180 Static keyword for data type 290 forward reference 285 LotusScript 413, 461 Stepping through applications 5 Stop statement 5 LotusScript 451 Str function LotusScript 452 StrCom function LotusScript 452 StrComp alias LotusScript 507 StrCompare function LotusScript 452 StrConv function LotusScript 454 String arguments to C functions 188 LotusScript 190 string concatenation operator LotusScript 79 String concatenation operator LotusScript 79 String conversions LotusScript 452, 454 String data type LotusScript 17, 460 String function LotusScript 460 String handling changing case 478 comparing 407, 452 concatenation operator 79 conversion 452, 454, 482 extracting 391, 392, 393, 427, 428, 429 Index
589
String handling (continued) LCase function 374 Left function 374 LeftBP function 375 LeftC function 376 Len function 376 LenB function 377 LenBP function 379 LenC function 379 limits 493 LotusScript 482 LSet statement 387 LTrim function 387 pattern matching 81 position in string 357, 359, 360, 361 replacing 391 searching 455, 456, 457 setting to string variable 432 spaces 448 string construction rules 8 String function 460 trimming 433, 472 String operators. See Operators 78 Strings fixed length 29 passing 188 variable length 29 StrLeft function LotusScript 455 StrLeftBack function LotusScript 456 StrRight function LotusScript 457 StrRightBack function LotusScript 457 StrToken function LotusScript 458 Sub Delete 98, 130, 136 calling 139 LotusScript 463 Sub Initialize LotusScript 98, 464 Sub keyword external C call 282 forward reference 285 LotusScript 461 Sub New 130, 133 calling 139 LotusScript 465 Sub Terminate 98 LotusScript 467 Subprograms. See Subs 85 Subs 93 declaring 96 defining 96 deleting 260, 289 described 96 executing 97 in a class 130 LotusScript 250, 338, 461 maximum argument 494 overriding 139 signature 96 terminating 167 Subscripts for a list 45 for an array 36
Subtraction operator (-) LotusScript 59, 65 Suffix characters constants 26 for data type 290 LotusScript 287 omitting 26 Symbolic constants LotusScript 267 Symbols limiting 495 Synchronization 171, 172 LotusScript 447 Synchronization functions 172 System date LotusScript 278, 279 System files LotusScript 295, 334, 442
T
Tab function LotusScript 468 Tabs in scripts 7 Tag names in a list 382 Tan function LotusScript 469 Temporary module LotusScript 307 Terminate sub LotusScript 98, 467 Terminating a loop 168 Terminating functions LotusScript 167 Terminating procedures LotusScript 167 Terminating subs LotusScript 167 Termination statements Exit 309 LotusScript 299 Testing for data type 26 Text keyword LotusScript 407 Then keyword LotusScript 342, 343 Thread safe code 175 Threading functions LotusScript 337 Threads common problems 175 definition of 171 Tilde escape character (~) LotusScript 9 Time function LotusScript 52, 469 Time slice giving up 447 multi-threading 171 Time statement LotusScript 52, 470 TimeDate values 52
TimeNumber function LotusScript 52, 470 Timer function LotusScript 52, 471 TimeSerial alias LotusScript 507 TimeSerial function LotusScript 470 TimeValue function LotusScript 52, 471 To keyword Lock and Unlock statements 384 LotusScript 290, 419, 436 Today function LotusScript 52, 472 Trigonometric functions LotusScript 233, 244, 245, 269, 446, 469 Trim function LotusScript 472 Trimming spaces LotusScript 433, 472 LTrim Function 387 Trimming spaces from strings LotusScript 328 True values LotusScript 25, 51 Type arguments to C functions 190 Type property JavaProperty class 217 Type statement LotusScript 473 TypeName function LotusScript 26, 43, 475 Types naming rules 9 passing 190
U
UBound function LotusScript 477 UCase function LotusScript 478 UChr function LotusScript 478 Unary minus operator (-) LotusScript 59 Unary plus operator (+) LotusScript 59 Uni function LotusScript 479 Unicode characters LotusScript 282, 478, 479, 482 Unicode keyword LotusScript 190 UNIX platform differences 498 Unknown values LotusScript 371 Unlock statement 384 LotusScript 479 Until keyword LotusScript 157, 296 Upper bounds fixed array 39 LotusScript 36 Use statement 3
590
Use statement (continued) LotusScript 129, 480 UseLSX statement LotusScript 480 User interactions LotusScript 180 User-defined classes described 125 LotusScript 17 User-defined constants LotusScript 26 User-defined data types 130, 192 declaring 126 defining 126 described 125 LotusScript 17, 473 naming rules 9 using 126 User-defined variables 192 UString function LotusScript 482
V
V_IUNKNOWN value LotusScript 371 Val function LotusScript 482 Values 188, 190 Boolean 51 Default data type 26 EMPTY 25 FALSE 25 for literal numbers 7 literal string 8 NOTHING 25 NULL 25 PI 25 TRUE 25 Variable length records LotusScript 109 Variable length strings LotusScript 29 Variables data type 29 declaring 130 declaring data type 126 declaring explicitly 29 declaring implicitly 33 declaring object reference
Variables (continued) declaring two or more at once 29 default value 29 defining 126 environment 182 for a list 45 for an array 36 in a loop control expression 159 initializing 133 Let statement 380 lifetime 22 local 93 LotusScript 290, 409, 432, 440 LSet statement 387 module level 93 naming 29 naming rules 9 object reference 129 scope 22 shadowing 93 string 29 user-defined in C language function calls 192 variants 49 Variant data type 144 data type converting 18 LotusScript 17, 49, 276, 483 Variants date and time value 52 referring to 54 valid date range 52 VarType alias LotusScript 507 VarType function LotusScript 276 Vertical bars (|) LotusScript 8 Volume labels LotusScript 295, 334, 442
WeekDay function LotusScript 52 Wend keyword LotusScript 167 While keyword LotusScript 296 While loops LotusScript 167 While statement LotusScript 167, 485 White space in LotusScript 328, 433 in scripts 7 Whitespace, removing LTrim function 387 Width # statement LotusScript 486 Wildcards file name 295 Like operator 81 Windows LotusScript 234, 438, 444, 445 With statement LotusScript 134, 487 Write # statement LotusScript 109, 488 Write keyword LotusScript 403 Writing to files binary 107 Lock and Unlock statements 384 LotusScript 412, 416, 488 random 105 sequential 103
X
Xor operator LotusScript 59, 75
W
Waiting LotusScript 447 Web agents multi-threads 171 serial 171 threaded 171 Weekday function LotusScript 485
Y
Year function LotusScript 52, 490 Yield function LotusScript 182, 491 Yield statement LotusScript 182, 491
144
Index
591
Notices
This information was developed for products and services offered in the USA. IBM may not offer the products, services, or features discussed in this document in all countries. Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service. IBM may have patents or pending patent applications covering subject matter described in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to: IBM Director of Licensing IBM Corporation North Castle Drive Armonk, NY 10504-1785 U.S.A. For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property Department in your country/region or send inquiries, in writing, to: IBM World Trade Asia Corporation Licensing 2-31 Roppongi 3-chome, Minato-ku Tokyo 106, Japan The following paragraph does not apply to the United Kingdom or any other country/region where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties in certain transactions; therefore, this statement may not apply to you. This information could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; these changes will be incorporated in new editions of the publication. IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this publication at any time without notice. Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the materials for this IBM product, and use of those Web sites is at your own risk. IBM may use or distribute any of the information you supply in any way it believes appropriate without incurring any obligation to you.
Licensees of this program who wish to have information about it for the purpose of enabling: (i) the exchange of information between independently created programs and other programs (including this one) and (ii) the mutual use of the information that has been exchanged, should contact: Lotus Software IBM Software Group One Rogers Street Cambridge, MA 02142 USA Such information may be available, subject to appropriate terms and conditions, including in some cases payment of a fee. The licensed program described in this document and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement, IBM International Program License Agreement, or by any equivalent agreement between us. Any performance data contained herein was determined in a controlled environment. Therefore, the results obtained in other operating environments may vary significantly. Some measurements may have been made on development-level systems, and there is no guarantee that these measurements will be the same on generally available systems. Furthermore, some measurements may have been estimated through extrapolation. Actual results may vary. Users of this document should verify the applicable data for their specific environment. Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements, or other publicly available sources. IBM has not tested those products and cannot confirm the accuracy of performance, compatibility, or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products. All statements regarding IBM's future direction or intent are subject to change or withdrawal without notice, and represent goals and objectives only. This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.
Trademarks
IBM, the IBM logo, AIX, DB2, Domino, Freelance, Freelance Graphics, iSeries, i5/OS, Lotus, Lotus Notes, LotusScript, Notes, 1-2-3, OS/400, Quickplace, S/390, Sametime, SmartSuite, WebSphere, z/OS, and zSeries are trademarks or registered trademarks of IBM Corporation in the United States, other countries, or both. Additional IBM copyright information can be found at: http://www.ibm.com/legal/copytrade.shtml Java and all Java-based trademarks and logos are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Microsoft, Windows, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. Intel and Pentium are trademarks of Intel Corporation in the United States, other countries, or both. The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated. UNIX is a registered trademark of The Open Group in the United States and other countries. Linux is a trademark of Linus Torvalds in the United States, other countries, or both. Other company, product and service names may be trademarks or service marks of others.