Smart Script User Manual
Smart Script User Manual
Part 3
Smart Script User Manual
Table of Content
Chapter1 Introduction
Features _______________________________________________________ 1-1
Chapter 2 Editor
User Interface __________________________________________________ 2-1
Chapter 3 Applications
Run a Script When Project Starts ___________________________________ 3-1
Chapter 4 Syntax
Overview ______________________________________________________ 4-1
CD ______________________________________________________________ 5-9
CRC32( ) ________________________________________________________5-15
CREATE _________________________________________________________5-16
DAY( ) __________________________________________________________5-16
DATETIME$() ____________________________________________________5-17
DEL ____________________________________________________________5-17
DIM ____________________________________________________________5-18
DIR$( ) __________________________________________________________5-18
END ____________________________________________________________5-19
ERRID( ) ________________________________________________________5-19
ERRORTAG( ) ____________________________________________________5-20
EXEC ___________________________________________________________5-21
EXIT ____________________________________________________________5-22
EXP( ) __________________________________________________________5-22
FAC( ) __________________________________________________________5-23
FCHECK( ) _______________________________________________________5-23
FILE$( ) _________________________________________________________5-24
FLEN( ) _________________________________________________________5-24
FMBCD ( ) ________________________________________________________5-25
FMDBL ( ) ________________________________________________________5-25
FMFLT ( )_________________________________________________________5-26
Format( ) ________________________________________________________5-29
FPOS( ) _________________________________________________________5-33
FPRINT _________________________________________________________5-33
GOSUB _________________________________________________________5-34
GOTO __________________________________________________________5-35
HOUR( ) ________________________________________________________5-35
SmartScript 使用手冊 目錄
MD _____________________________________________________________ 5-43
RD _____________________________________________________________5-53
READ ___________________________________________________________5-54
RETURN ________________________________________________________5-55
RIGHT$( ) _______________________________________________________5-55
RSTERR ________________________________________________________5-56
RTRIM$( ) _______________________________________________________5-56
SECOND( ) ______________________________________________________5-56
SEEK ___________________________________________________________5-57
SETDIR _________________________________________________________5-58
SHORTCUT ______________________________________________________5-59
SHUTDOWN _____________________________________________________5-60
SIN( ) ___________________________________________________________5-61
SINH( ) __________________________________________________________5-61
SLEEP __________________________________________________________5-62
SQRT( ) _________________________________________________________5-62
STOP ___________________________________________________________5-62
STR$( ) _________________________________________________________5-63
STRING$( ) ______________________________________________________5-63
SUM08( ) ________________________________________________________5-63
SYSINFO$( ) _____________________________________________________5-65
TAG( ) __________________________________________________________5-66
TAN( ) __________________________________________________________5-67
TANH( ) _________________________________________________________5-67
TICK( ) __________________________________________________________5-68
TIMER( ) ________________________________________________________5-68
TOKEN _________________________________________________________5-69
SmartScript 使用手冊 目錄
SmartScript is the built-in script language of Lab-Link for Windows. It is simple yet powerful and
is closely integrated with Lab-LINK to provide a quick solution when complex logics are involved.
With SmartScript, developers can write the control logic or math calculation they need without
using a programming language and any other programming tools.
SmartScript provide the basic functions of a script language including data type, variable, loop,
conditional branch, file access and IO communication. There are also abundant functions for
various needs. A simple editor is also provided to help users edit and debug their script.
This manual will describe the features of SmartScript and the usage of the SmartScript editor.
Detail explanation of the syntax, statements and function are also included for developers’
reference.
Features
File access
1-1
SmartScript User Manual Chapter 1
Mode
SmartScript module can be executed in two modes: Edit and Run. When executed in Edit mode,
the SmartScript editor will be activated to allow editing, compiling and debugging of script files. This
mode is usually used in develop stage to write script logics. When executed in Run mode,
SmartScript module will load the specified script file and executed the statements in the script.
The execution file of SmartScript module is CONTROL.EXE, Its command line parameters will
be discussed in the following section.
Command Line
None Activate SmartScript editor and open a new unnamed script file. Edit
ScriptFile Activate SmartScript editor and load the specified script file. Edit
ScriptFile /R Run SmartScript and load the specified script file for execution. Run
A script file has the extension name of .CSL and is stored in standard text file format.
1-2
Chapter 2 Editor
User Interface
When SmartScript is executed in Edit mode, the screen below will appear:
If a script file name is included in its command line parameter, the file name will be shown on
the title of SmartScript editor window. Below the title bar is the menu of the editor which providing
File, Edit, View, Run, Help functions. These functions are described as follows.
2-1
SmartScript User Manual Chapter 2
File Menu
New
Open
Save
Save the currently editing file. If an untitled file is being edited, the Save As dialog will appear
to request for a file name.
Save As
Print the currently editing file. A dialog will appear to allow the selection of printer, range and
copies.
Print Direct
Print the currently editing file directly without showing the Print dialog.
Print Preview
Print Setup
Exit
Edit Menu
2-2
SmartScript User Manual Chapter 2
Undo
Redo
Cut
Copy
Paste
Paste the cut or copied text to the current location of the cursor.
Delete
Select All
Find
Move the cursor to the target text. A Find dialog will appear. Enter the text to be found in the
Find what field and do either of the followings:
Move cursor to the next appearing of the target string and select the text.
Cancel 按鈕
2-3
SmartScript User Manual Chapter 2
Find Next
Find the next appearance of the target string specified in the previous Find action.
Replace
Replace the target text with the specified string. A Replace dialog will appear. enter target and
replace string in the Find what and Replace with respectively. Use the buttons to do the
operations below:
Replace button
Replace all target text in the file with the replace text.
Cancel button
View Menu
2-4
SmartScript User Manual Chapter 2
Run Menu
Compile ─ Check the syntax of the script. Since SmartScript is an interpreter, the compiling only
does syntax checking and will not generate any object or execution file. If there is any syntax
error, it will be shown in the window below. See Appendix D for error codes.
Execute─ Run the script. The execution will continue until the last statement is executed or the
execution is interrupted by the user. If any error occurs during the execution, an error message
will appear to show error code and message. Execution of script can be interrupted by Break or
Stop in the Run menu.
Step Into─ Execute the script one statement at a time. Each the menu item is selected, a
statement will be executed. After the execution of the statement, the script will stop to wait for
user operation. User can either select Stop Into again to execute the next statement or select
Step Over or Go to execute the remaining statements. Function key F8 can be used as a hot
key of Step Into. For statements in a subroutine, Step Into will also execute one statement at a
time.
Step Over─ Similar to Stop Into with the exception on the execution of statements in a
subroutine. When Step Over is used to execute a subroutine call, it will finish all statements in
the subroutine and return to the main program before stop for user operation.
Go─ Continue running all the remaining statements in the script until the end is reached or any
error occurs to interrupt its execution.
Break─ Halt the execution of the script. Step Into, Step Over or Go can be used to continue the
execution after Break.
Stop─ Stop the execution of the script. All opened files will be closed automatically when the
script is stopped.
2-5
Chapter 3 Applications
Although SmartScript can be run independently, it is usually integrated with a Lab-LINK project
to provide extra functions in real applications. Examples may include complex math computation or
control logic, file reading and writing or even IO communication. This chapter will illustrate some
possible applications using simple examples.
The simplest and also the most common way of running a script is to run it when a Lab -LINK
project starts. Add a Script module in the project and the script will be run when the project starts.
The script will be terminated when the project ends.
To add a Script into a project, right click on the Script node in the Project window of PAM and
select Add Script from the popup menu. An Add SmartScript dialog will appear to allow the
selection of Script File source. There are two selections available: Create a new script and
3-1
SmartScript User Manual Chapter 3
Create a new script : Create a new blank script file in the CSL
subfolder of the project and run SmrtScript Editor to load the
empty for user to edit
When a script is added and the project is regenerated, the script will be run when the projec t
starts. The example script below will write a line of message recording the time the system starts into
a text file. After the writing, the script will close the file and end.
3-2
SmartScript User Manual Chapter 3
Code
Line Code
1 FileName$="LABLINK.LOG"
3 IF (!FCHECK(1))
4 CREATE 1, FileName$
5 ENDIF
7 SEEK 1, 0, "E"
11 CLOSE 1
12 END
Note: The Line numbers are jest for reference and are not part of the script code
3-3
SmartScript User Manual Chapter 3
Script Description
Line 1: Specify the name of the recording file. The working directory of SmartScript is
the system folder of Lab-LINK (Installation default is C:\LABLINK\SYSTEM4).
Complete path should be included in the file name designation if the file does not
resides in this system folder. For example, FileName$="..\\CSL\LABLINK.LOG" specify
the file path at ..\CSL\LABLINK.LOG. (This is equivalent to the absolute path of
C:\LABLINK4\CSL\LABLINK.LOG) Note that “\\” is used to replace the “\” in path
definition since “\” is a keyword in SmartScript.
Line 2: Open the file in Write mode and assign the file number as 1. The file number will
be used in later file access statement until the file is closed.
Line 3-5: Check if the file is opened successfully. If not , create the specified file using
CREATE statement.
Line 6: Any texts after “//” will be treated as remark and will not be interpreted and
executed..
Line 7: Move the read-write pointer to the end of the file. The new text will be appended
to the end of the file.
Line 8-10: Write system date/time and the message “LABLINK STARTED” System date
and time are acquired using the time related functions YEAR()、MONTH()、DAY()、
HOUR()、MINUTE() and SECOND(). “\r” and “\n” represent the control characters
“Carriage Return” and “Line Feed” respectively and used to change line. The three
statement can be combine into one by joining the text strings using “+” operators.
Line 11: Close the file. After the file is closed, the file number 1 is also released for use
of other file access statements.
Line 12: End of the script. This SmartScript module will also end its execution.
3-4
SmartScript User Manual Chapter 3
SmartScript can be integrated with SmartPanel by running it with a Executer object. For
example, a script may be run when user presses a button. The following example shows a script
which is run when with a LOGIN button to record newly log-in user’s identity into a file.
Note: Pressing this button will set the value of the tag LOGIN to 1.
Set Push Button to reset the tag to 0 when the button is release.
Parameter: ..\PROJECT\PROJ1\CSL\LOGIN.CSL /R
Note: Script files are stored under the CSL subfolder of the project. The project name is PROj1 and
the script file name is “Login.csl “in this example.
3-5
SmartScript User Manual Chapter 3
Code
Line Code
1 FileName$="LABLINK.LOG"
3 IF (!FCHECK(1))
4 CREATE 1, FileName$
5 ENDIF
7 SEEK 1, 0, "E"
11
CLOSE 1
12
END
Note: The Line numbers are jest for reference and are not part of the script code
LOGIN TAG The tag used to trigger the execution of the script.
$USER System TAG The system Tag whose message field indicate the name of the
current logged-in user.
FileName$ String Variable The variable used to store the name of the file for log-in logging.
3-6
SmartScript User Manual Chapter 3
Script Description
Line 2: Open the file in Write mode and assign the file number as 1. The file number will
be used in later file access statement until the file is closed.
Line 3-5: Check if the file is opened successfully. If not , create the specified file using
CREATE statement.
Line 6: Any texts after “//” will be treated as remark and will not be interpreted and
executed..
Line 7: Move the read-write pointer to the end of the file. The new text will be appended
to the end of the file.
Line 8-10: Write system date/time and the user log-in message into the file. {$USER.$}
is the message field of the system tag $USER and its content is the name of the current
log-in user.
Line 11: Close the file. After the file is closed, the file number 1 is also released for use
of other file access statements.
Line 12: End of the script. This SmartScript module will also end its execution.
3-7
SmartScript User Manual Chapter 3
Using Loop
In the two previous examples, SmartScript end after all statements are executed. However,
some applications may need the script to keep running. In this example, the script will enter a loop to
do integration of Tag1 when user press Integrate button, The loop will continue until the user press
Stop button after which the integration loop stop and the script ends.
3-8
SmartScript User Manual Chapter 3
StaticText Caption: Real Time Value Show the text “Real time
Value”
Note: Script files are stored under the CSL subfolder of the project. The project name is PROj1 and
the script file name is “INTEGRAL.csl “in this example.
Code
Line Code
1 PrevTime%={$TIME}
2 PrevValue={Tag1}
3 {Int_Tag1}=0
4 WHILE({StartInt})
5 {Int_Tag1}={Int_Tag1}+({Tag1}+PrevValue)*({$TIME}-PrevTime%)/2
6 PrevTime%={$TIME}
7 PrevValue={Tag1}
8 LOOP
9 END
Note: The Line numbers are jest for reference and are not part of the script code
3-9
SmartScript User Manual Chapter 3
$TIME System TAG Its value will increase by 1 every second. It is used as a one
second clock to trigger periodic event.
Line 4: Use StartInt=1 as the entering condition of a While loop. The loop stops and the
script ends if StartInt=0. StartInt is also used as the tag to start running the script.
Line 5: Integrate Tag1. PrevValue is the value of Tag in previous integration calculation.
{$TIME}-PrevTime% is the time elapsed between the previous calculation and current
calculation.
Line9: End of the script. This SmartScript module will also end its execution.
When the user press Integrate button and set the value of StartInt to 1, the script is executed.
The script will first set the integration value to 0 and keep calculating the integration until the Stop
button is pressed and StartInt is set to 0. If the user press Integrate button again, the script will be
run again and reinitiate the integration calculation.
To keep the loop running when Lab-LINK is running, the condition of the WHILE loop can be set
to1 to start an infinite loop. A infinite loop will keep running until Lab-LINK runtime ends. However,
the infinite will consume system resource.
3-10
SmartScript User Manual Chapter 3
Tag Event
In some applications, it is more efficient to use Tag events instead of loops. The example in
previous section will calculate the integration value at every recurrence of the loop even though
the values of $TIME and Tag1 do not change. The integration script is rewritten in this example to
use tag event to calculate integration. The panel object, Tags and variables settings are the same
as the previous section , and only the script will be discuss here.
Code
Line Code
1 PrevTime%={$TIME}
2 PrevValue={Tag1}
3 {Int_Tag1}=0
3-11
SmartScript User Manual Chapter 3
Line Code
4 WHILE({StartInt})
5 LOOP
6 END
7 {$TIME}:
8 {Int_Tag1}={Int_Tag1}+({Tag1}+PrevValue)*({$TIME}-PrevTime%)/2
9 PrevTime%={$TIME}
10 PrevValue={Tag1}
11 RETURN
Note: The Line numbers are jest for reference and are not part of the script code
Script Description
Line 4: Use StartInt=1 as entering condition to start a While loop. If StartInt=0, the
loop will stop and the script ends. StartInt is also used in the Executer object in panel to
start the running of the script.
Line 7: Start of tag event of $TIME. By using the Tag as its label, the subroutine below
will be executed when the value of $TIME changes.
Line 8: Integrate Tag1. PrevValue is the value of Tag in previous integration calculation.
{$TIME}-PrevTime% is the time elapsed between the previous calculation and current
calculation.
3-12
SmartScript User Manual Chapter 3
Line 11: End of the subroutine. Return to when it was interrupted in the main program
and continue,
Similar to the example in the previous section, when the user press Integrate button and set the
value of StartInt to 1, the script is executed. However, the script will enter the empty loop after the
initial setting statement in the beginning. The loop itself contains no statement. When the value of
$TIME changes (once every second), the tag event subroutine with {$TIME}: will be run to
calculate the integration. Since the calculation statement will be executed only once per second, it
is more efficient. To keep the loop running when Lab-LINK is running, the condition of the WHILE
loop can be set to1 to start an infinite loop. A infinite loop will keep running until Lab-LINK runtime
ends. A more efficient alternative than the infinite loop is to use the IDLE statement which will no
consume system resource. See chapter 5 for syntax and usage of these statements.
Although Tag event is a very useful feature in SmartScript, programmers must be very careful to
control its behaviors due to its event-driven nature. In general, a Tag event subroutine is a series
of SmartScript statements that start with a line label which is a Tag name and end with the
RETURN statement. The code below is a typical example:
… // Other statements
{Tag1}: // This is the Tag name line label
… // Script code of Tag1 event subroutine
RETURN
As shown below, there can be more than one Tag line table for each event subroutine. Data
change of any of the Tags will trigger the execution of the event subroutine.
… // Other statements
{Tag1}: // This is the first Tag name line label
{Tag2}: // This is the second Tag name line label
{Tag3}: // This is the third Tag name line label
… // Script code of Tag1, Tag2 and Tag3 event subroutine
RETURN
When the data of any of the event subroutine label Tag change, SmartScript logic execution will
jump to the Tag label and execute the statements after the label until the RETURN statement is
reached. Script logic will then return to the last statement before the event occurs and continue
3-13
SmartScript User Manual Chapter 3
with the execution of the remaining statements. The data changes triggering a Tag event include
the changes of value, message, data, time and status field of the Tag data.
Since the change of Tag data will trigger a new event, if there is a new event triggered before the
finish of a previous even, unpredictable result may occurs if the script logic is not properly
controlled. There are two commands, namely TRAPOFF and TRAPON, designed to help
programmers event triggering. TRAPOFF is used to suspend event triggering by setting a
TRAPOFF flag while TRAPON is used to do the opposite by resetting TRAPOFF flag to allow
event triggering. When Tag event triggering is suspended, SmartScript will store all new Tag events
occur during the period in the Event Queue. These buffered events will be executed after the
event triggering is enabled again.
To help programmer understand how to use TRAPOFF and TRAPON in writing Tag event
subroutines, the process flow of SmartScript event subroutines execution is described as follows.
During the execution of SmartScript, if any Tag event is triggered and the
corresponding event subroutine is not in the Event Queue, the new Tag event
subroutine will be added into the Event Queue.
After the execution of any SmartScript statement, the following examination and
process will be done:
Check TRAPOFF flag. If the flag is not set, check if there is any Tag event
subroutine in the Event Queue waiting for execution. If there is any event in
the queue, retrieve the event subroutine from the queue and move the next
statement pointer of SmartScript to the event subroutine.
If the previous executed statement is TRAPON, reset the TRAPOFF flag.
Continue with next statement.
Based on description above, TRAPOFF and TRAPON can be used as shown in the
example below to guarantee that the execution of an event subroutine will not be
interrupted by any other new event.
… // Other statements
{Tag1}:
TRAPOFF // TRAPOFF flag is set.
// Event triggering is disabled
… // Script code of Tag1 event subroutine
TRAPON // TRAPOFF flag is reset.
RETURN // Event triggering is enabled
- When Tag1 event is triggered, the first statement executed is TRAPOFF (the line
label is not considered as a statement). TRAPOFF will set TRAPOFF flag
immediately and all new event will not be triggered but stored in the Event
3-14
SmartScript User Manual Chapter 3
Queue.
- When the execution reaches the TRAPON statement, since SmartScript will first
check the TRAPOFF flag (it is not reset yet at this moment) before resetting the
TRAPOFF flag, it will not execute any new event right away. Instead, SamrtScript
will wait after the execution of the next statement, RETURN in this case, to find
that TRAPOFF flag is reset and jump to the new event subroutine. By using
these two commands, possibilities of interruption by any new event during the
execution of the event subroutine can be excluded.
The following problems may occur if TRAPOFF and TRAPON statement are not used:
- During the execution of a Tag event subroutine, it is possible that script logic
execution can be switched to a new event. This may result in problems such as
the difficulties in determining which event will be handled first and variable values
may be changed by new events.
- If an event subroutine is not completely executed before switching to a new event,
the unfinished subroutine will be stored in a stack to wait for execution after the
returning from the new event. In the case of large number of events triggered in a
short period of time, many unfinished event subroutines will be accumulated in
the stack. This may cause the system error of “Stack overflow” eventually and
end the execution of the SmartScript module.
Besides the discussion above, there are some more issues need to be considered when
using Tag event subroutines:
- During the execution of a Tag event subroutine, it is always possible that Tag
data referenced in the subroutine can be modified by other Lab-LINK modules.
Programmer should make no assumption that Tag data will remain unchanged
during the execution of the subroutine. To lessen the effect of this characteristic,
it is recommended that Tag values can be stored in variables at the beginning of
the event subroutine. Reference of Tag data can then be replaced by the variable
values. However, please note that during the Tag data assignment to the
variables, Tag data can still change during this relative short period of time.
- For each Tag event subroutine, only one record is kept in the Event Queue.
Therefore, during the period that TRAPOFF flag is set.
If multiple Tag line labels share the same event subroutine, multiple
instances of data changes of these Tags will only add the event routine
once into the Event Queue. The position of the event subroutine in the
Event Queue is determined when it is first added into the queue.
If an event Tag changes data more than once, the event subroutine will only
3-15
SmartScript User Manual Chapter 3
be added once into the Event Queue. The position of the event subroutine
in the Event Queue is determined when it is first added into the queue.
- Due to the capacity of the Event Queue (512 events), the time required to run an
event subroutine should be kept as short as possible. Otherwise, if more than
512 events are triggered during the TRAPOFF period, the events occur after the
queue is full will be ignored.
Some applications may need a script to be run only when a panel is opened. This can be
achieved by using a similar loop as the previous example but with proper condition. This is useful
when the script is only necessary for this display of the panel and should be close to prevent waste
of system time when the panel is closed.
In the following example, when user press “Open Panel” button to open a panel file, a script is
run to accumulate the time the panel is opened.
3-16
SmartScript User Manual Chapter 3
Two panel files are used in this example: WKS1.PNL(The root panel) and SUBPANEL.PNL. Their
settings are as follows:
WKS1.PNL
Button Caption: Open Panel OpenPnl Pressing the button will set the
value of OpenPnl to 1.
SUBPANEL.PNL
Note: Script files are stored under the CSL subfolder of the project. The project name is PROj1 and
the script file name is “OPENTIME.csl “in this example.
3-17
SmartScript User Manual Chapter 3
$TIME System TAG The system tag whose value will increase by 1 per second. Used as
one second clock.
OpenTime% Integer Used to store the total accumulation open time in seconds.
Variable
Code
Line Code
1 OpenTime%={OpenHour}*3600+{OpenMin}*60+{OpenSec}
2 PrevTime%={$TIME}
3 WHILE({OpenPnl})
4 LOOP
5 END
6 {$TIME}:
7 OpenTime%=OpenTime%+{$TIME}-PrevTime%
8 {OpenHour}=OpenTime%/3600
9 {OpenMin}=(OpenTime%\3600)/60
10 {OpenSec}=(OpenTime%\3600)\60
11 PrevTime%={$TIME}
12 RETURN
3-18
SmartScript User Manual Chapter 3
Note: The Line numbers are jest for reference and are not part of the script code
Script Description
Line 6: Start of tag event of $TIME. By using the Tag as its label, the subroutine below
will be executed when the value of $TIME changes.
Line 7: Accumulate the open time of the panel SUBPANEL.PNL. PrevValue% is the
value of Tag1 at previous loop recurrence. {$TIME}-PrevTime% is the time elapsed
since last loop recurrence. The statement add the elapsed time to the accumulated
time.
Line 12: End of the event subroutine and return to the main program.
3-19
SmartScript User Manual Chapter 3
Communication Application
C$ String Variable Used to store the command string for reading data.
V$ String Variable Used to store the value parsed from the returned string.
TickBeg Variable Used to store the previous TICK value. TICK is a time function in
mini seconds.
Code
Line Code
1 C$ = "#S00\r"
3 IF (! FCHECK(1))
5 STOP
6 ENDIF
3-20
SmartScript User Manual Chapter 3
Line Code
7 CommLoop:
8 WRITE 1, C$
10 LOOP
11 READ 1, R$, 11
12 V$ = MID$(R$, 4, 5)
13 {Data-01} = VAL(V$)
14 TickBeg = TICK()
16 LOOP
17 GOTO CommLoop:
18 END
Note: The Line numbers are jest for reference and are not part of the script code
Script Description
Line 1: Store the data reading command string to the variable C$. “\r” is the Carriage
Return control character.
Line 2: Open communication port COM1 with the communication parameters: 9600, N,
8,1. Set the capacity of Interrupt-driven receive-queue to 1024 characters, and the
capacity of Interrupt-driven transmit-queue to 256 characters.
Line 3-6: Handle communication port open failure. Show a message on the screen and
end the script after user acknowledgement.
3-21
SmartScript User Manual Chapter 3
Line 9-10: Wait until ay least 11 characters of return data received in the Interrupt-driven
receive-queue.
Line 11: Take the first 11 characters in the Interrupt-driven receive-queue and store it to
R$.
Line 12: Take the fourth to the eighth characters from R$, the value part, and store it to
V$.
Line 13: Use VAL function to covert V$ from a string to a number and assign the
number to the value of tag Data-01.
Line 17: Go back to the beginning of the GOTO loop, the label CommLoop, to repeat
the operation.
3-22
Chapter 4 Syntax
Overview
The SmartScript Module provides users with a complete programming environment, allowing
communication with other modules of Lab-LINK for Windows, and acts as a built in program
development tool. SmartScript Module contains most of the commands and functions found in
traditional BASIC or C but also includes additional statements, which deal with specific features of
Lab-LINK.
Command Line
CONTROL.EXE, located in the system folder of Lab-LINK, is the execution file of SmartScript.
Its command line can include the parameters:
Option Description
source-file Name of the script file loaded when SmartScript starts.
source-file /R Causes SmartScript to load and run a program file.
Line Label
Every program line may begin with a line label. Line labels are used as references of branching.
The characters allowed in a line labels are alphanumerical characters and underscore. Line label must
be within the length between 1 to 16, and the first character must be a letter. Some special type
declaration characters are also allowed—see below.
4-1
SmartScript User Manual Chapter 4
A line label may be a reserved word or may contain an embedded reserved word, though this is
not recommend. Reserved words include all commands, statements, function names and operator
names.
When a line label enclosed in the curly brackets, it is a special kind of line label called TAG label.
In this case the label name within the curly brackets must be a TAG name. Whenever the value of the
corresponding TAG changed, the original program flow will be suspended, and the statement block
following the label will be executed. After execution of this statement block, the original program flow
will be resumed.
Character Set
SmartScript Module character set includes alphabetic characters (A-Z, a-z), numeric characters
(0-9 and A-F or a-f for hexadecimal numbers), and special characters. Some characters have special
meanings in SmartScript Module:
Data-Type Suffixes
% Integer
$ String
{} TAG
Mathematical Operators
. Decimal point
+ Plus sign
- Minus sign
* Multiplication symbol
/ Division symbol (slash)
\ Integer division symbol (backslash)
^ Exponentiation symbol (up arrow or caret)
Relational operators
4-2
SmartScript User Manual Chapter 4
!= Not Equal
Logical operators
! Logic NOT
& Logic AND
| Logic OR
Bitwise operators
~ Invert
<< Shift left
>> Shift right
^< Rotate left
>^ Rotate right
Special
= Assignment symbol
: Line label suffix
@ Break point mark
, Parameter delimiter
=> Then symbol
// Comment line
Constants
Constants are the actual values SmartScript Module users during execution. There are two
types of constants: string and numeric.
String Constant
A string constant is a sequence of characters enclosed in double quotation marks. Examples of
string constants:
“$25,000.00”
“This is a test.”
The characters enclosed in double quotation mark may be alphanumeric or special characters.
The escape sequences allow you to use a sequence of characters to represent special
characters. Escape sequences are listed below.
4-3
SmartScript User Manual Chapter 4
Sequence Name
\n New Line
\r Carriage Return
\t Horizontal Tab
\" Double Quotation Mark
\\ Backslash
\bnnnnnnnn
ASCII character in binary notation
\Bnnnnnnnn
\onnn
\Onnn ASCII character in octal notation
\0nnn
\dnnn
\Dnnn ASCII character in decimal notation
\nnn
\xnn
\Xnn
ASCII character in hexadecimal notation
\hnn
\Hnn
Numeric Constant
Numeric constants are positive or negative numbers. Numeric constants in SmartScript Module
cannot contain commas. There are seven types of numeric constants:
1. Integer Constants
Whole numbers between -2147483648 and +2147483647. Integer constants do not have
decimal points.
4-4
SmartScript User Manual Chapter 4
523E3 = 523000
A special keyword “PI” presents the floating-point constant π (3.141592653589793).
4. Decimal Constants
Decimal numbers with no prefix or the prefix 0d or 0D.
Examples:
1024
0d13
0D27
5. Hexadecimal Constants
Hexadecimal numbers with the prefix 0x, 0X, 0h or 0H.
Examples:
0x41FF
0X0D
0hE6
0H1A0
6. Octal Constants
Octal numbers with the prefix 0o or 0O.
Examples:
0o10
0O361
7. Binary Constants
Binary numbers with the prefix 0b or 0B.
Examples:
0b1010
0B11000011
Variables
Variables are names used to represent values that are used in a SmartScript Module Program.
The value of a variable may be assigned explicitly by the programmer, or it may be assigned as the
result of calculations in the program. Before a variable is assigned a value, its value is assumed to
be zero.
A variable name may not be a reserved word, but may contain an embedded reserved word.
Reserved words include all commands, statements, function names and operator names.
4-5
SmartScript User Manual Chapter 4
Variables may represent either a numeric value or a string. String variable names are written
with a dollar sign ($) as the last character. For example: A$ = “Hello the world”. The dollar sign
is a variable type declaration character; that is, it “declares” that the variable will represent a
string.
Numeric variable names may declare integer or real (double precision) values. The type
declaration characters for these variable names are as follows:
% Integer variable
Tag Variables
In SmartScript, a special kind of variables called TAG variables is used to access and
manipulate TAG data. TAG variables should be named as follows:
{tag-name} tag-name is the name of a TAG. If the TAG does not exist, it will be created.
{tag-name} can be used just like a regular numeric variable (double precision) ,
and it presents the value field of the TAG. Any modification made to the TAG
variable will modify the value field of tag-name as well.
{tag-name.$} tag-name is the name of a TAG. If the TAG does not exist, it will be created.
{tag-name.$} can be used just like a regular string variable, and it presents the
message field of the TAG. Any modification made to the TAG variable will modify
the message field of tag-name as well.
{tag-name.t} tag-name is the name of a TAG. The variable can also be denoted as
{tag-name.T}. If the TAG does not exist, it will be created. {tag-name.t} can be
used just like a regular numeric variable. Its integer part represents the date field
of the TAG, and its fraction part represents the time field of the TAG. Both integer
and fraction parts are of the same unit of days. Any modification made to the
TAG date/time variable will modify the date and time field of tag-name as well.
Note: When the value or message field of a TAG is modified, the system will
update the date and time fields of the TAG automatically to indicate the date and
time the TAG data is changed.
4-6
SmartScript User Manual Chapter 4
{tag-name.s} tag-name is the name of a TAG. The variable can also be denoted as
{tag-name.S}. If the TAG does not exist, it will be created. {tag-name.s} can be
used just like a regular numeric variable but its value represents the 16 bits
binary encoded status field of the tag. Definition of the status bits are shown in
the table below. Bit operators >> (Right shift) and AND can be used to acquire
the specific status bit(s) of the tag status variable.
Array Variables
An array is a group or table of values referenced by the same variable name. Each element in
an array is referenced by an array variable that is subscripted with an integer or an integer
expression. An array variable name has as many subscripts as there are dimensions in the
array. For example V(6) would reference a value in a one-dimension array, M(2, 7) would
reference a value in a two-dimension array, and so on. The maximum number of dimensions for
an array is 3. The maximum number of elements of all dimensions is 8,192.
Integer 4 Bytes Integer 4 Bytes per element 3 bytes overhead plus the present
Real 8 Bytes Real 8 Bytes per element contents of the string
4-7
SmartScript User Manual Chapter 4
Type Conversion
When necessary, SmartScript Module will convert a numeric constant from one type to another.
The following rules and examples should be kept in mind.
1. If a numeric constant of one type is set equal to a numeric variable of a different type, the
number will be stored as the type declared in the variable name. (If a string variable is set
equal to a numeric value or vice versa, a “Type mismatch” error occurs.)
Example:
N% = 32.64
After this statement was executed, the value of N% is 32.
2. During expression evaluation, all of the operands in an arithmetic or relational operation are
converted to the same degree of precision; i.e., that of the most precise operand. Also, the
result of an arithmetic operation is returned to this degree of precision.
Examples:
A = 15.0 / 2
The arithmetic equation is performed in double precision and the result was returned in A as a
double precision value. After this statement was executed, the value of A is 7.5.
A=9/5
The arithmetic was performed in integer precision and the result was returned in A as a
double precision value. After this statement was executed, the value of A is 1.0.
3. Logical operators convert their operands to integers and return an integer result.
Example:
N% = 2.5 XOR 1
After this statement was executed, the value of N% is 3.
When a floating-point value is converted to an integer, the fractional portion is rounded.
Example:
N% = 6.67
M% = -6.67
After this statement was executed, the value of N% is 6 and M% is -6.
An expression may be a string or numeric constant, or a variable, or it may combine constants and
variables with operators to produce a single value.
4-8
SmartScript User Manual Chapter 4
1. Arithmetic
2. Relational
3. Logical
4. Bitwise
Arithmetic Operators
The arithmetic operators, in order of precedence, are:
To change the order, in which the operations are performed, use parentheses. Operations within
parentheses are performed first. Inside parentheses, the usual order of operations is
maintained.
Here are some sample algebraic expressions and their SmartScript Module counterparts.
X + 2Y X+2*Y
Y
X− X–Y/Z
Z
X ⋅Y
X*Y/Z
Z
X +Y
(X + Y) / Z
Z
( X 2 )Y X^2^Y
Z
XY X ^ (Y ^ Z)
X ⋅ −Y X * -Y
4-9
SmartScript User Manual Chapter 4
Integer modulus arithmetic is denoted by the backslash (\). The operands are rounded to
integers before the modulus is performed, and it gives the integer value that is the remainder of
an integer division.
Example:
N% = 8.9 \ 3
Division by Zero
If, during the evaluation of an expression, a division by zero is encountered, the “Division by
Zero !!” error message is displayed, and execution stops.
Relational Operators
Relational operators are used to compare two values. The result of the comparison is either
“True” (one) or “False” (zero). This result may then be used to make a decision regarding
program flow. The relational operators, in order of precedence, are:
When arithmetic and relational operators are combined in one expression, the arithmetic is
always performed first. For example, the expression
X + Y < (Z + 5) / W
is true if the value of X plus Y is less than the value of Z+5 divided by W. More examples:
IF (N% \ 2 != 0) => L% = L% + 1
4-10
SmartScript User Manual Chapter 4
Logical Operators
Logical operators perform tests on multiple relations or Boolean operations. The logical
operator returns an result which is either “True” (one) or “False” (zero). The logical operators, in
order of precedence, are:
! (Logical NOT)
X !X
True (not zero) False (zero)
False (zero) True (one)
| (Logical OR)
X Y X|Y
True (not zero) True (not zero) True (one)
True (not zero) False (zero) True (one)
False (zero) True (not zero) True (one)
False (zero) False (zero) False (zero)
Just as the relational operators can be used to make decisions regarding program flow, logical
operators can connect two or more relations and return a true or false value to be used in a
decision (see IF statement).
4-11
SmartScript User Manual Chapter 4
Examples:
Bitwise Operators
Bitwise operators perform bit manipulation and return a bitwise result. The operands are
rounded to integers before the bit manipulation is performed, and it returns the integer value
that is the bitwise result of the operation. The bitwise operators, in order of precedence, are:
~ (Invert)
X ~X
1 0
0 1
AND
X Y X AND Y
1 1 1
1 0 0
0 1 0
0 0 0
4-12
SmartScript User Manual Chapter 4
XOR
X Y X XOR Y
1 1 0
1 0 1
0 1 1
0 1 1
OR
X Y X OR Y
1 1 1
1 0 1
0 1 1
0 0 0
15 0
<< (Shift left) 0
15 0
>> (Shift right)
0
15 0
^< (Rotate left)
15 0
>^ (Rotate right)
String Operations
Strings may be concatenated using “+”.
Example:
A$ = “ABC”
B$ = “DEF”
C$ = A$ + “ ” +B$
4-13
SmartScript User Manual Chapter 4
String comparisons are made by taking one character at a time from each string and
comparing the ASCII codes. If all the ASCII codes are the same, the strings are equal. If the
ASCII codes differ, the lower code number precedes the higher. If, during string comparison, the
end of one string is reached, the shorter string is said to be smaller. Leading and trailing blanks
are significant.
Examples:
“OK” != “ok”
4-14
Chapter 5 Statements and Functions
This chapter describes in detail the various statements and functions applicable to SmartScript
Module. Most descriptions consist of five parts, FUNCTION, VERSIONS, FORMAT, REMARKS and
EXAMPLE, which are listed below.
VERSIONS Indicates which versions of Control Script Module support the particular statement.
CAPS Keywords are indicated by capital letters and should be entered as shown.
Punctuation must be indicated where indicated except for square brackets and the
ellipsis.
EXAMPLE Illustrates various ways of using the statement and highlights, where applicable,
unusual modes of operation.
5-1
SmartScript User Manual Chapter 5
5-2
SmartScript User Manual Chapter 5
This section consists of an alphabetical listing of all statements and functions with a detailed
description of each.
ABS() Function
FORMAT Y = ABS(numeric-expression)
ACOS() Function
FORMAT Y = ACOS(numeric-expression)
5-3
SmartScript User Manual Chapter 5
ALARM() Function
FORMAT Y = ALARM(string-expression)
EXAMPLE N% = ALARM(“AI-0001”)
5-4
SmartScript User Manual Chapter 5
ALMGRP() Function
FORMAT N% = ALMGRP(string-expression)
ALMPRI() Function
FORMAT N% = ALMPRI(string-expression)
5-5
SmartScript User Manual Chapter 5
ALMTAG$() 函數
FUNCTION ALMTAG$ returns the tag name of the active alarm which has the highest priority.
FORMAT A$ = ALMTAG$()
REMARKS Return value of this function is a string. The string is the tag name of the alarm
which has the highest priority or is the newest among all active alarm. Which alarm
is the highest priority alarm is determined by the following logics:
(1) If there are more than one active alarms and some of the alarms are not
acknowledged, the unacknowledged alarm that has the highest alarm priority
setting is the highest priority alarm. In other word, unacknowledged alarm s have
(2) If all active alarms are acknowledged, the acknowledged alarm with the highest
(3) If multiple alarms have the same priority setting, the newest alarm among them
The highest priority alarm is also the alarm shown in AlarmBar object in
SmartPanel.
EXAMPLE A$ = ALMTAG$()
5-6
SmartScript User Manual Chapter 5
ASC() Function
FUNCTION ASC returns the value of the ASCII code of the first character in the specified string.
FORMAT N% = ASC(string-expression)
ASIN() Function
FORMAT Y = ASIN(numeric-expression)
5-7
SmartScript User Manual Chapter 5
ATAN() Function
FORMAT Y = ATAN(numeric-expression)
BEEP Statement
FORMAT BEEP
REMARKS This statement generates a beep sound from your computer's speaker.
EXAMPLE BEEP
5-8
SmartScript User Manual Chapter 5
CD Statement
FORMAT CD directory-name
CHOICE() Function
FUNCTION CHOICE returns the true expression or false expression depends on conditional
expression.
5-9
SmartScript User Manual Chapter 5
CHR$() Function
FORMAT M$ = CHR$(numeric-expression)
CLOSE Statement
REMARKS file-number is the number under which the file or device was opened.
CLOSE 1
5-10
SmartScript User Manual Chapter 5
COMMODE Statement
REMARKS file-number is an integer expression whose value should reference the file
number of an opened communication device.
5-11
SmartScript User Manual Chapter 5
COMOPEN Statement
5-12
SmartScript User Manual Chapter 5
CONTINUE Statement
FUNCTION CONTINUE passes control to the next iteration of the smallest enclosing FOR or
WHILE statement in which it appears.
FORMAT CONTINUE
REMARKS For more information, see FOR … LOOP, WHILE … LOOP and EXIT statements.
...
LOOP
COPY Statement
FUNCTION COPY copies the specified file or folder to the specified target path.
REMARKS source-path is a string expression used to specify the path of the source file
or folder.
target-path is a string expression used to specify the path of the target file or
folder.
The statement may fail if the source file does not exist, the target path does not exist,
or there is other reason prevents its proceeding. The failure will be counted as an
internal error but the script will continue its execution. ERRID() function can be used
to get the error code.
If the target file exists, COPY statement will overwrite the file with the source file.
5-13
SmartScript User Manual Chapter 5
COS() Function
FORMAT Y = COS(numeric-expression)
If the target file exists, COPY statement will overwrite the file with the source file.
COSH() Function
FORMAT Y = COSH(numeric-expression)
5-14
SmartScript User Manual Chapter 5
CRC16() Function
FUNCTION CRC16 returns the value of CRC-16 of the specified string. CRC-16 is an algorithm
commonly used in communication protocol for error checking.
FORMAT N% = CRC16(string-expression)
CRC32() Function
FUNCTION CRC32 returns the value of CRC-32 of the specified string. CRC-32 is an algorithm
commonly used in communication protocol for error checking.
FORMAT N% = CRC32(string-expression)
5-15
SmartScript User Manual Chapter 5
CREATE Statement
If the file does not exist, the statement creates a new file and opens it for writing. If the
file does exist, the statement truncates the file size to zero and opens it for reading
and writing. When the statement opens the file, the read-write pointer is set to the
beginning of the file.
CLOSE 1
DATETIME$() Function
5-16
SmartScript User Manual Chapter 5
DAY() Function
FORMAT N% = DAY()
EXAMPLE N% = DAY()
DEL Statement
DEL may fail If the specified file does not exist or there is other reason prevents its
deletion. The failure will be counted as an internal error but the script will continue its
execution. ERRID() function can be used to get the error code.
DEL can delete the specified file even it has read-only attribute set.
5-17
SmartScript User Manual Chapter 5
DIM Statement
FUNCTION DIM specifies the maximum values for array variable subscripts and allocates storage
accordingly.
numeric-const specifies the maximum values for array subscripts and must be
an integer constant.
The DIM statement sets all the elements of the specified array to an initial value of
zero. The maximum allowable number of dimensions for an array is 3. The maximum
allowable number of elements is 8,192. The minimum value for a subscript is always
1.
A(1) = 6.5
DIR$() Function
FUNCTION DIR$() can be used to query for current directory, Windows and system directory.
FORMAT M% = DIR$(“NOW”|”WIN”|”SYS”)
5-18
SmartScript User Manual Chapter 5
END Statement
FORMAT END
REMARKS END statements may be placed anywhere in the program to terminate execution. An
END statement at the end of a program is optional.
ERRID() Function
FUNCTION ERRID() returns the error code of the latest script internal error.
FORMAT N% = ERRID()
REMARKS Return value of ERRID() is the error code of the latest internal error. (See appendix
for a list of all error code.) A return value of 0 means there is no error.
Note that any successful execution of a statement or function will clear the error code
return by this function. Be sure to place this function right next to the statement or
function where error is expected to get its error code.
5-19
SmartScript User Manual Chapter 5
ERRORTAG Statement
FUNCTION ERRORTAG can specify a Tag name. When the SmartScript end abnormally, the
error code and error message will be set to the valu and message field of the Tag.
If the Tag specified by the tag name string-expression does not exist, it will be created
automatically at runtime. The tag name string-expression should comply with the
naming rule of Lab-LINK Tag.
When the script with ERRORTAG statement ends abnormally, the value of the error
tag will indicate the error code while its message will be the name of the script file, the
error line number and the error message.
If the statement has been used more than once in a SmartScript, only the last
executed one will tak effect.
Store the sript above is stored as a script file named “CSLPRG.csl”. After it is
executed and ended abnormally due to the error of divided by zero occurs, the value
of ETag will be set to 18 and its message will be “ERROR 18: Division by Zero!! @
CSLPRG1.csl Line: 2 “.
5-20
SmartScript User Manual Chapter 5
EXEC Statement
REMARKS file-name must be a string expression that specifies the file to open or the
folder to open or explore. The statement can open an
executable file or a document file.
2. To run DBSaver
3. To run Report
5-21
SmartScript User Manual Chapter 5
EXIT Statement
FUNCTION EXIT terminates the smallest enclosing FOR or WHILE statement in which it appears.
FORMAT EXIT
REMARKS For more information, see FOR … LOOP, WHILE … LOOP and CONTINUE
statements.
...
...
LOOP
EXP() Function
FORMAT Y = EXP(numeric-expression)
5-22
SmartScript User Manual Chapter 5
FAC() Function
FORMAT Y = FAC(numeric-expression)
FCHECK() Function
FUNCTION FCHECK determines whether or not the specified file number is valid.
FORMAT N% = FCHECK(file-number)
If the file associated with the specified file number was successful opened, it returns
true (one); otherwise it returns false (zero).
5-23
SmartScript User Manual Chapter 5
FILE$() Function
FORMAT M$ = FILE$(filename)
REMARKS Filename is a string expression representing the path of the file to be All
characters, including control character such as line-feed, will
be stored into a string.
If the file associated with the specified file number was successful opened, it returns
true (one); otherwise it returns false (zero).
EXAMPLE M$ = FILE$(“C:\\PROJ1\\Log.txt”)
FLEN() Function
FORMAT N% = FLEN(file-number)
If the file associated with the specified file number was successful opened, it returns
the length of the file. If the file is a communications file, this function returns the
number of characters in the receive-queue.
N% = FLEN(1)
CLOSE 1
5-24
SmartScript User Manual Chapter 5
FMBCD () Function
FUNCTION FMBCD decodes the argument as a BCD number and returns its value as an integer.
FORMAT N% = FMBCD(numeric-expression)
This function is used to decode a BCD number, such as a number read from a PLC
register, and convert it into an integer for SCADA usage.
FMDBL () Function
FUNCTION FMDBL combines four arguments as a 4 word data and convert it to a double precision
floating number.
This function is used to convert 4 word data into a double precision floating number.
5-25
SmartScript User Manual Chapter 5
FMFLT () Function
FUNCTION FMFLT combines its two arguments as two word data and return its value as a single
precision floating number.
This function is used to convert 2 word data into a single precision floating number.
5-26
SmartScript User Manual Chapter 5
LOOP
If the value of the counter is less than or equal to the value of final-expression then Control
Script Module continues with the statement following the FOR statement.
The program statements following the FOR are executed until the LOOP statement is
encountered. At this point the counter is incremented by the STEP value (inc-expression)
and Control Script Module branches back to the FOR statement where the process begins
again.
If the value of the counter is greater than the value of final-expression, then Control Script
Module branches to the statement following the LOOP statement.
If the value of inc-expression is negative, then the test is reversed. The counter is
decreased each time through the loop, and the loop is executed until the counter is less
than the final value.
Nested Loops
FOR … LOOP may be nested; that is, one FOR … LOOP may be placed inside another
FOR … LOOP. When loops are nested, each loop must have a unique variable name as its
counter. Each LOOP will match the most recent FOR.
DIM A(3, 4)
EXAMPLE
FOR I = 1 TO 3
FOR J = 1 TO 4
A(I, J) = (I – 1) * 4 + (J – 1)
5-27
SmartScript User Manual Chapter 5
LOOP
LOOP
Y = FMFLT(0x0000, 0x4124) // Y will be 10.25
5-28
SmartScript User Manual Chapter 5
Format$() Function
FUNCTION Format covert the integer argument into a string with the format specified by the format
string argument.
REMARKS string- expression is a string used to define the format needed. See description below
for details.
Format string consists of the following fields while fields in square brackets are optional and
can be omitted:
Each field in the format string is either a single character or a number and is used to specify
a format option. The simplest form of format string contains only a percent symbol % and a
type character for data type. Ex. %d. The optional fields before the type character are used
to control other format feature.
type
type character is the only mandatory field in format string. It must appear after any other
format character. type character specify the data type of the numeric argument. It can be
one of the following characters:
5-29
SmartScript User Manual Chapter 5
floating number)
f Double Signed floating number in the format of
(double precision [ – ]dddd.dddd where dddd is a single or multiple
floating number) digits decimal number. The number of digits before
the decimal point depends on the value of the
number and the number of digits after the decimal
point depends on the precision needed.
g Double Signed floating number using f or e format. The
(double precision format actually used depends on which format
floating number) produce a shorter string. Extra trailing 0 will be
trimmed. Decimal point appears only when
necessary.
G Double Same as format g except that capital letter E
(double precision replaces the lower case letter e for exponential
floating number) expression.
flags
flag character is the first optional field in format string. flag is a single character used to
specify alignment of sign, space, decimal point, and prefix of octal or hexadecimal number.
Format string can contain one or more flag characters.
5-30
SmartScript User Manual Chapter 5
width
width is the second optional field in format string. width is a non-negative decimal integer. It
is used to control the minimum number of characters in the output. If the output number
contain less characters than the specified width, space characters will be added before or
after the number based on the existence of – flag (which means aligning to left) to make up
the specified minimum width. If 0 flag is added before width, trailing 0 will be used to make
up the width. 0 flag is ignore if left alignment is set.
width setting will not remove any number characters. If the number of characters of the
output is greater than the specified width, the width setting will be ignored and all characters
will be output. (The actual number of output characters may still be controlled by the
precision setting)
precision
precision is the third optional field in the format string. It is a non-negative decimal integer
with a period symbol (.) as prefix. It is used to specify number of characters, number of
fraction digits and number of significant digits. (See table below). This setting differs from
the width setting because it will remove some of the output characters and will round up
some digits if the output is a floating point number. If precision is set to 0 and the output
number is also 0, no character will be output.
Type setting determines how precision will be interpreted and the default if precision is not
used. See the table below:
5-31
SmartScript User Manual Chapter 5
5-32
SmartScript User Manual Chapter 5
FPOS() Function
FUNCTION FPOS returns the current read-write pointer position of the specified file.
FORMAT N% = FPOS(file-number)
If the file associated with the specified file number was successful opened, it returns the
current read-write pointer position of the file. If the file is a communications file, this function
returns the number of characters in the transmit-queue.
OPEN 1, “TEST.TXT”
EXAMPLE
N% = FPOS(1) // N% will be 0
CLOSE 1
FPRINT Statement
expression may be any numeric or string expression that will be written to the
file.
All numeric value will be converted to ASCII string by free format then written to the file.
Expressions should be delimited by commas, and no extra blanks will be inserted between
expressions.
A = PI
EXAMPLE
CREATE 1, “TEST.TXT”
FPRINT 1, “A = “, A, “\r\n”
CLOSE 1
5-33
SmartScript User Manual Chapter 5
GOSUB Statement
A subroutine must be end with a RETURN statement, and cause Control Script Module to
branch back to the statement following the most recent GOSUB statement. A subroutine
may be called any number of times in a program, and a subroutine may be called from
within another subroutine. Such nesting of subroutines is limited only by available memory.
Subroutines may appear anywhere in the program, but it is recommended that the
subroutine be readily distinguishable from the main program. To prevent inadvertent entry
into the subroutine, it may be preceded by a STOP, END or GOTO statement that directs
program control around the subroutine.
GOSUB ShowMsg:
EXAMPLE
MESSAGE "Test Program", "In main program"
END
ShowMsg:
MESSAGE "Test Program", "In subroutine"
RETURN
5-34
SmartScript User Manual Chapter 5
GOTO Statement
FUNCTION GOTO branches unconditionally out of the normal program sequence to a specified line
label..
If line label is an executable statement, that statement and those following are executed. If it
is a non-executable statement, execution proceeds at the first executable statement
encountered after line label.
HOUR() Function
FORMAT N% = HOUR()
REMARKS This function returns the current hours after midnight (0 ~ 23).
EXAMPLE N% = HOUR()
5-35
SmartScript User Manual Chapter 5
IDLE Statement
FUNCTION IDLE suspend the execution of the script but can still handle event.
FORMAT IDLE
REMARKS IDLE statement is usually used to wait for events to occur. It is similar to running an empty
loop (Ex. WHILE(1)……..LOOP), but unlike a loop, it will not consume system resource
during the waiting.
EXAMPLE IDLE
{EVENT}:
{Value} = {Value} + 1 //{Value} will increase by 1 when {EVENT} changes
RETURN
5-36
SmartScript User Manual Chapter 5
FUNCTION IF makes a decision regarding program flow based on the result of an expression.
IF (cond-expression)
...
[ELSEIF (cond-expression)]
...
[ELSE]
...
ENDIF
If the result of the cond-expression is true (non-zero), the statement following the “then
symbol” or statements following the IF is executed. If the result is false (zero), the
statements following the IF are ignored and the statement ELSEIF, if present, is executed.
As the IF statement, If the result of the cond-expression is true, the statements following the
ELSEIF is executed. Otherwise, the next ELSEIF, if present, is executed, and so on. Finally,
if no one of the ELSEIF is true, the statements following the ELSE, if present, is executed. If
no ELSE present, the statement following the ENDIF is executed.
IF … ENDIF statements may be nested. Each ENDIF will match the most recent IF.
5-37
SmartScript User Manual Chapter 5
INT() Function
FUNCTION INT returns the truncated integer part of the specified value.
FORMAT N% = INT(numeric-expression)
N% = INT(99.9) // N% will be 99
EXAMPLE
N% = INT(-4.8) // N% will be -4
ISTR$() Function
This function converts the result of numeric_expression to an unsigned long integer, and
then converts it to a string by the specified notation.
5-38
SmartScript User Manual Chapter 5
IVAL() Function
This function converts the result of string_expression to an integer by the specified notation.
IVAL returns 0 if no conversion can be performed.
LEFT$() Function
FUNCTION LEFT$ returns a string comprised of the leftmost N characters of the specified string.
5-39
SmartScript User Manual Chapter 5
LEN() Function
FORMAT N% = LEN(string-expression)
LN() Function
FORMAT Y = LN(numeric-expression)
5-40
SmartScript User Manual Chapter 5
LOG() Function
FORMAT Y = LOG(numeric-expression)
This function is equivalent to the algebraic expression y log x log10 x . The logarithm
is the logarithm to the base 10.
LOWER$() Function
FUNCTION LOWER$ returns a string same as the specified string but all characters were converted to
lowercase.
FORMAT M$ = LOWER$(string-expression)
5-41
SmartScript User Manual Chapter 5
LTRIM$() Function
FUNCTION LTRIM$ returns a string same as the specified string but without the leading space.
FORMAT M$ = LTRIM$(string-expression)
MAX() Function
FUNCTION MAX compares two values and returns the larger one.
5-42
SmartScript User Manual Chapter 5
MD Statement
FORMAT MD directory-name
REMARKS directory-name is a string expression representing the path of the new folder to be
created.
MD may fail to create the specify folder due to file access privilege setting. Such failure will
be counted as an internal error but the script will continue its execution. ERRID() function
can be used to get the error code.
EXAMPLE MD “C:\\NewFolder”
MESSAGE Statement
The message box contains an application-defined title and message, plus an icon
consisting of a lowercase letter i in a circle-combination and one push buttons: OK.
Windows does not automatically break the lines to fit in the message box, however, so the
message string must contain carriage returns to break the lines at the appropriate places.
5-43
SmartScript User Manual Chapter 5
MID$() Function
MIN() Function
FUNCTION MIN compares two values and returns the smaller one.
5-44
SmartScript User Manual Chapter 5
MINUTE() Function
FORMAT N% = MINUTE()
REMARKS This function returns the current minutes after hour (0 ~ 59).
EXAMPLE N% = MINUTE()
MONTH() Function
FORMAT N% = MONTH()
EXAMPLE N% = MONTH()
5-45
SmartScript User Manual Chapter 5
MOVE Statement
REMARKS source-path is a string expression representing the path of the source file or
folder.
target-path is a string expression representing the path of the target file or folder.
When moving a file or a folder, MOVE may fail due to the source file or folder doesn’t
exist, the target path doesn’t exist or any other reason. Such failure will be counted as an
internal error but the script will continue its execution. ERRID() function can be used to get
the error code.
MOVE will fail if the target file exists. Note that this is different from the result of COPY
statement which will overwrite the existing target file automatically.
5-46
SmartScript User Manual Chapter 5
MSGBOARD Statement
FUNCTION MSGBOARD opens an “Important Message” window and displays a line of message.
Executing this statement will open an “Import Message” window to display the specified
message string. Date, time and a [CslMan32] label will be added to the message
automatically. After the message is shown, SmartScript will not wait for user to close the
window before executing the following statements in the script. If the “Important Message”
window is already opened when the statement is executed, the message will be added
below those messages already shown in the window.
There are two buttons at the bottom of the “Important Message” window. If “Save & Close”
button is pressed, the system save all the messages in the window to the text file
“MsgBoard.log” in the system folder (default path is c:\lablink\system4), clear the messages
and close the window; if “Close button” is pressed, the system will clear all messages and
close the window immediately.
Each execution of the statement will add one and only one line of message, <Carriage
Return> and <Line Feed> character in the message string will be trimmed.
5-47
SmartScript User Manual Chapter 5
NERR() Function
FORMAT N% = NERR()
REMARKS NERR() returns the accumulated error count. Whenever a statement or a function cause
an internal error, the error count will be incremented by 1. RSTERR statement can clear the
error count.
NOW() Function
FUNCTION NOW() returns the current system date/time represented as a real number.
FORMAT N% = NOW()
REMARKS NOW() return the current system date/time. The date/time will be represented as a real
number. Its integer part represents the date field of the TAG, and its fraction part represents
the time field of the TAG. Both integer and fraction parts are of the same unit of days. The
returned value of this function can be assign to a TAG variable to modify its date/time field.
EXAMPLE {Tag1.t} = NOW() // The date/time filed of Tag1 are modifie as current system
// date/time.
5-48
SmartScript User Manual Chapter 5
NOW$() Function
FORMAT M$ = NOW$()
REMARKS NOW$() return the current system date/time. The date/time will be represented as a string.
The output string has the format of ”yyyy/mm/dd hh:ii:ss.sss”, where yyyy is the four digits
year part, mm is the two digits month part, dd is the two digits day part, hh is the two digits
hour part, ii is the two digits minute part, integer part of ss.sss is the two digits second and
its fraction part is the three digits millisecond part of a complete date.time notation. The
length of the output string is fixed at 23 charcters.
5-49
SmartScript User Manual Chapter 5
OPEN Statement
REMARKS file-number is an integer expression, which evaluates to a valid file number. The
number is then associated with the file for as long as it is open and is
used by other file I/O statements to refer to the file. The valid file
numbers are 1 to 16.
access-type is a string expression that specifies the type of access to the file. This
parameter can be one of the following values:
When the statement opens the file, the read-write pointer is set to the beginning of the file.
5-50
SmartScript User Manual Chapter 5
PASS Statement
FUNCTION PASS is used to open an executable file or a document file. It is similar to EXEC, but will
wait for the application used to open the specified file terminates before continuing the
execution of the statements following this statement.
REMARKS file-name must be a string expression that specifies the file to open or the folder
to open or explore. The statement can open an executable file or a
document file.
5-51
SmartScript User Manual Chapter 5
PLAY Statement
REMARKS file-name is a string expression, which names the wave file to be played.
play-mode is a string expression that specifies the mode of play to the wave file.
This parameter can be one of the following values:
The sound is played asynchronously and PLAY returns immediately after beginning the
sound. To terminate an asynchronously played waveform sound, call PLAY with file-name
set to empty string.
The sound specified by file-name must fit into available physical memory and be playable
by an installed waveform-audio device driver.parameter must be a string expression
that specifies parameters to be passed to the application (if file-name specifies an
executable file). If file-name specifies a document file, parameter should be an empty string.
5-52
SmartScript User Manual Chapter 5
RAND() Function
FORMAT Y = RAND(numeric-expression)
REMARKS file-name is a string expression, which names the wave file to be played.
This function returns a random number between 0 and the result of numeric-expression.
The random number generator is auto re-seeded, so the different sequence of random
numbers is generated each time the program is run.
EXAMPLE Y = RAND(5.5)
RD Statement
FORMAT RD directory-name
RD statement may fail if the specified folder does not exits or is not empty. Such failure will
be counted as an internal error but the script will continue its execution. ERRID() function
can be used to get the error code.
EXAMPLE RD “C:\\EmptyFolder”
5-53
SmartScript User Manual Chapter 5
READ Statement
string-variable is a string variable that receives the data read from the file.
If the file associated with the specified file number was successful opened, this statement
reads data from the file. If the file is a communications file, this statement reads data from
the receive-queue.
5-54
SmartScript User Manual Chapter 5
RETURN Statement
FORMAT RETURN
REMARKS The RETURN statement(s) in a subroutine cause SmartScript Module to branch back to the
statement following the most recent GOSUB statement. A subroutine may contain more
thane one RETURN statement, should logic-dictate a return at different points in the
subroutine. Subroutines may appear anywhere in the program, but it is recommended that
the subroutine be readily distinguishable from the main program. To prevent inadvertent
entry into the subroutine, it may be preceded by a STOP, END or GOTO statement that
directs program control around the subroutine.
ShowMsg:
MESSAGE "Test Program", "In subroutine"
RETURN
RIGHT$() Function
FUNCTION RIGHT$ returns a string comprised of the rightmost N characters of the specified string.
5-55
SmartScript User Manual Chapter 5
RSTERR Statement
FUNCTION RSTERR is used to reset the internal error counter of SmartScript module.
FORMAT RSTERR
REMARKS SmartScript has a counter to count the number of internal error occurs. Whenever a
statement or a function cause an internal error, the counter will be incremented by 1 and
NERR() can be used to return the error count. Execution of the statement RSTERR will
reset the value of the counter to 0. After the execution of this statement, NERR() will
return 0.
RTRIM$() Function
FUNCTION RTRIM$ returns a string same as the specified string but without the trailing Space (ASCII
code=32) and control characters including Tab (ASCII code=9), Carriage Return(ASCII
code=13) and Line Feed (ASCII code=10).
FORMAT M$ = RTRIM$(string-expression)
SECOND() Function
FORMAT N% = SECOND()
REMARKS This function returns the current seconds after minute (0 ~ 59).
EXAMPLE N% = SECOND()
5-56
SmartScript User Manual Chapter 5
SEEK Statement
If the file associated with the specified file number was successful opened, it moves the
read-write pointer of the file to the specified position. If the file is a communications file, this
statement flushes all characters from the receive-queue (seek-mode = “C”), transmit-queue
(seek-mode = “B”) or both (seek-mode = “E”).
When a file is initially opened, the read-write pointer is set to the beginning of the file. SEEK
moves the pointer an arbitrary amount without reading data, which facilitates random
access to the file's contents.
5-57
SmartScript User Manual Chapter 5
SETDIR Statement
FUNCTION SETDIR can set the path of Reference Path (~0,…,~19) during Lab-LINK runtime
REMARKS numeric - expression is a numeric expression with value between 0 and 19. It is used
to specify which reference path will be defined.
Reference Path is a shorthand notation of file path used by Lab-LINK objects. Please see
Appendix of SmartPanel Manual for details.
SETDIR can define or redefine the actual path of the specified Reference Path at Lab-LINK
runtime. Note that the reference path used by some of the Lab-LINK modules are loaded
when Lab-LINK starts and modification of these reference paths at later time will have no
effect to these modules. For example, the Data module use reference path ~6 as its default
data path and will load the definition of ~6 when Lab-LINK starts. Any change on the
reference path ~6 after Lab-LINK starts will not change the path of data files.
SETDIR 8, "..\\PROJECT\\PROJ1\\DAT\\01”
5-58
SmartScript User Manual Chapter 5
SHORTCUT Statement
REMARKS link-file is a string expression representing the file name of the shortcut.
Shortcut statement may fail if it contains invalid path. Such failure will be counted as an
internal error but the script will continue its execution. ERRID() function can be used to get
the error code.
If the shortcut file specified by link-file already exists, SHORTCUT statement will create a
new shortcut to replace the old one.
5-59
SmartScript User Manual Chapter 5
SHUTDOWN Statement
FORMAT SHUTDOWN
REMARKS This command is used to end the execution of Lab-LINK system. Although there is a system
tag named $EXIT can end the execution by setting its value to 1, it is not recommended. It is
possible that some Lab-LINK modules may not be terminated when setting $EXIT to 1 in
Smart Script. Thereful, it is recommended to use this statement to end Lab-LINK in Smart
Script.
SHUTDOWN
5-60
SmartScript User Manual Chapter 5
SIN() Function
FORMAT Y = SIN(numeric-expression)
SINH() Function
FORMAT Y = SINH(numeric-expression)
5-61
SmartScript User Manual Chapter 5
SLEEP Statement
FUNCTION SLEEP is used to suspend the execution of the script for a specified period of time.
REMARKS numeric expression is a numeric expression. It must be greater than 0 and its unit is
second.
SQRT() Function
FORMAT Y = SQRT(numeric-expression)
REMARKS numeric-expression is a numeric expression and must be greater than or equal to zero.
STOP Statement
FORMAT STOP
REMARKS STOP statements may be placed anywhere in the program to terminate execution.
5-62
SmartScript User Manual Chapter 5
STR$() Function
FORMAT M$ = STR$(numeric-expression)
STRING$() Function
FUNCTION STRING$ returns a string formed by repeating the specified character a specified number of
times.
REMARKS string-expression may be any string expression. The first character in the string
expression will be repeated.
SUM08() Function
FUNCTION SUM08 returns the 8-bit checksum value of the specified string.
FORMAT N% = SUM08(string-expression)
5-63
SmartScript User Manual Chapter 5
FUNCTION SWITCH evaluates expression and executes any statement associated with
case-expression whose value matches the initial expression.
The SWITCH and CASE keywords evaluate switch-expression and execute any
statement associated with case-expression whose value matches the initial
switch-expression.
If there is no match with a case-expression, the statement associated with the DEFAULT
keyword is executed. If the DEFAULT keyword is not used, control passes to the
statement following the ENDSW.
5-64
SmartScript User Manual Chapter 5
SYSINFO$() Function
REMARKS info-name a string expression which must be one of the following keyword
used to specified the system information returned.
HOSTNAME return the computer name
HOSTADDR return the IP address. If there are more than
one IP addresses associated with the
computer, the retuened IP addresses will be
separated with SPACE character.
5-65
SmartScript User Manual Chapter 5
TAG() Function
REMARKS string- expression is a string expression which is a valid Tag name or Tag name with
postfix “.$”.
expression may be any numeric or string expression. Its data type should be
consistent with the tag field specified by the Tag name string-
expression.
If the Tag specified by tag name string-expression does not exist, it will be created
automatically at runtime. The tag name string-expression should comply with the naming
rule of Lab-LINK Tag. When the last two characters in string-expression are “.$”, it indicates
that the message field of the specified tag is used in this function. If the last two characters
in string-expression are “.t” or “.T”, it indicates that the date/time field of the specified tag is
used in this function.
If the result of expression is a string, note that there is a length limit of 80 characters for the
message field of a Tag.
When TAG function is placed on the right of the operator “=” in a statement, it will returns
the value or message of the specified tag. When TAG function is placed on the left of the
operator “=” in a statement, it will assign the result of the expression on the right to the value
or message field of the specified tag.
5-66
SmartScript User Manual Chapter 5
TAN() Function
FUNCTION TAN returns the tangent of the specified angle.
FORMAT Y = TAN(numeric-expression)
TANH() Function
FORMAT Y = TANH(numeric-expression)
5-67
SmartScript User Manual Chapter 5
TICK() Function
FUNCTION TICK returns the number of milliseconds that have elapsed since Windows was started.
FORMAT Y = TICK()
REMARKS The return value is the number of milliseconds that have elapsed since Windows was
started. The elapsed time is stored as a 32-bit value, which means Windows can record no
more than 2^32 millisecond intervals before the 32-bit value overflows to zero. This is
approximately 49.7 days. If you use the elapsed time, check for the overflow condition when
comparing times.
EXAMPLE Y = TICK()
TIMER() Function
FORMAT N% = TIMER()
REMARKS The return value is the number of seconds that have elapsed since midnight.
EXAMPLE N% = TIMER()
5-68
SmartScript User Manual Chapter 5
TOKEN Statement
FUNCTION TOKEN removes the first token that delimited by the delimiters from the specified string.
This statement searches for the occurrence of any delimiter (specified by delimiters) in the
source string, and breaks it to two separated strings. The first string assigns to the
token-variable, and the second assigns back to the source-variable.
5-69
SmartScript User Manual Chapter 5
TONE Statement
FUNCTION TONE generate a sound with specified frequency and length using the built-in buzzer of the
PC.
Script will wait for the end of the sound playing before executing statements following TONE
statement.
TRAPOFF Statement
FORMAT TRAPOFF
REMARKS This statement disables the TAG events trapping and all TAG events will be ignored.
After the execution of this statement, despite that all other new TAG event won’t be
executed, these new event will be stored in a TAG event queue and will be executed after
TRAPON statement is executed to restore TAG event handling. Since there is a limit on the
capacity of the TAG event queue, it is suggested to keep the duration of TRAPOFF as short
as possible. Otherwise, an out of stack error may occur if there are too many unexecuted
TAG events.
EXAMPLE TRAPOFF
5-70
SmartScript User Manual Chapter 5
TRAPON Statement
FORMAT TRAPON
REMARKS This statement enables the TAG events trapping and all TAG events will be processed.
Refer to “Line Label” in chapter 1.
EXAMPLE TRAPON
UPPER$() Function
FUNCTION UPPER$ returns a string same as the specified string but all characters were converted to
uppercase.
FORMAT M$ = UPPER$(string-expression)
VAL() Function
FORMAT Y = VAL(string-expression)
If the first characters of string-expression are not numeric, then VAL returns 0. VAL also
strips leading blanks, tabs, carriage-returns and line-feeds from the specified string.
5-71
SmartScript User Manual Chapter 5
WEEKDAY() Function
FORMAT N% = WEEKDAY()
REMARKS This function returns the current day of week (0 ~ 6, Sunday = 0).
EXAMPLE N% =WEEKDAY()
FUNCTION WHILE executes a series of statements in a loop as long as a given condition is true.
WHILE … LOOP may be nested to any level. Each LOOP will match the most recent
WHILE.
5-72
SmartScript User Manual Chapter 5
WRITE Statement
If the file associated with the specified file number was successful opened, this statement
writes data to the file. If the file is a communications file, this statement writes data to the
transmit-queue.
XOR08() Function
FUNCTION XOR08 returns the 8-bit exclusive OR checksum value of the specified string.
FORMAT N% = XOR08(string-expression)
5-73
SmartScript User Manual Chapter 5
YEAR() Function
FORMAT N% = YEAR()
EXAMPLE N% = YEAR()
5-74
Appendix A Environment Limits
Maximum Minimum
Variable-name length
16 characters 1 character
String length
32,767 characters 0 character
Integer
-2147483648 2147483647
Real:
Positive
1.79769313486231D+308 4.940656458412465D-324
Negative
-4.940656458412465D-324 -1.79769313486231D+308
Array Limits
Maximum Minimum
Maximum Minimum
^ Exponentiation →
* Multiplication
/ Division →
\ Integer Modulus
+ Addition
→
- Subtraction
<< Shift left
>> Shift right
→
^< Rotate left
>^ Rotate right
< Less than
> Greater than
→
<= Less than or equal to
>= Greater than or equal to
== Equality
→
!= Inequality
AND AND →
XOR Exclusive OR →
OR OR →
& Logic AND →
| Logic OR → Low
Appendix D Error Codes
Code Message
1 Out of Memory !!
2 Too many Variable !!
3 Too many Constant !!
4 Too many Label !!
5 Out of Operator Stack !!
6 Invalid Line Label !!
7 Invalid Command !!
8 Syntax Error !!
9 Invalid String Constant !!
10 Invalid Variable !!
11 Expression too Complex !!
12 Extra Argument !!
13 Type Mismatch !!
14 Array Error !!
15 Math Error !!
16 Expression Error !!
17 Undefined Label !!
18 Division by Zero !!
19 RETURN without GOSUB !!
20 ENDIF without IF !!
21 IF without ENDIF !!
22 ENDSW without SWITCH !!
23 SWITCH without ENDSW!!
24 LOOP without FOR or WHILE !!
25 FOR or WHILE without LOOP !!
26 Invalid Option !!
27 Program no Compiled !!
28 End of Program !!
29 Program Break !!
30 Out of Range !!
31 Out of String Length !!
32 Operation fail !!
33 Variable redefined !!
34 File in used !!
35 File not open !!
36 Invalid Tag !!
37 Inner Error !!