2.3.1.1 Data Types and Variables


LabTalk Data Types

LabTalk supports 9 data types:

Type Comment
Double Double-precision floating-point number
Integer Integers
Constant Numeric data type that value cannot be changed once declared
Dataset Array of numeric values
String Sequences of characters
StringArray Array of strings
Range Refers to a specific region of Origin object (workbook, worksheet, etc.)
Tree Emulates data with a set of branches and leaves
Graphic Object Objects like labels, arrows, lines, and other user-created graphic elements

Numeric

LabTalk supports three numeric data types: double, int, and const.

  1. Double: double-precision floating-point number; this is the default variable type in Origin.
  2. Integer: integers (int) are stored as double in LabTalk; truncation is performed during assignment.
  3. Constant: constants (const) are a third numeric data type in LabTalk. Once declared, the value of a constant cannot be changed. From Origin 2016, constant is auto-saved to orgvar.ogs once declared. It means that the constant will be saved as "System Variable" and available whenever a new Origin session is conducting.
// Declare a new variable of type double:
double dd = 4.5678;
// Declare a new integer variable:
int vv = 10;
// Declare a new constant:
const em = 0.5772157;

Note:

  • To use a constant after open a new Origin session, you will need to define the constant in the CONST.CNF file under User File Folder.
  • LabTalk does not have a complex datatype. A column can be set as Numeric Complex and basic operations (+,-,*,/) work between columns or using literal values. While functions are available for extracting real and imaginary parts of a complex column value or literal expression, you should use Origin C if you need complex variables.
// Direct, literal expression:
(3-13i) / (7+2i) =; 
// (3-13i) / (7+2i)=-0.094339622641509-1.8301886792453i
// Assign literal expression to complex column
col(A)[3] = (3-13i) * (7+2i);
// Get Real part of complex column or literal expression
dReal1 = imreal(col(A)[3]);
dReal2 = imreal((3-13i) + (7+2i));
// Get imaginary part of complex column or literal expression
dImag1 = imaginary(col(A)[3]);
dImag2 = imaginary((3-13i) - (7+2i));

Values such as 0.0, NANUM (missing value) and values between -1.0E-290 to 1.0E-290 will be evaluated to be False in logic statement. For instance, LabTalk command will return a value 0 (False) instead of 1 (True).

type $(-1e-290?1:0); // Returns 0 (False)
type $(1/0?1:0); // Returns 0 (False), where 1/0 == NANUM

Dataset

The Dataset data type is designed to hold an array of numeric values.

Temporary Loose Dataset

When you declare a dataset variable it is stored internally as a local, temporary loose dataset. Temporary means it will not be saved with the Origin project; loose means it is not affiliated with a particular worksheet. Temporary loose datasets are used for computation only, and cannot be used for plotting.

The following brief example demonstrates the use of this data type (Dataset type declaration and $() Substitution Notation are used in this example):

// Declare a dataset 'aa' with values from 1-10, 
// with an increment of 0.2: 
dataset aa={1:0.2:10}; 

// Declare integer 'nSize',
// and assign to it the length of the new array: 
int nSize = aa.GetSize();

// Output the number of values in 'aa' to the Script Window: 
type "aa has $(nSize) values";

Project Level Loose Dataset

When you create a dataset by vector assignment (without declaration) or by using the Create (Command) it becomes a project level loose dataset, which can be used for computation or plotting.

Create a project-level loose dataset by assignment,

bb = {10:2:100}

Or by using the Create command:

create %(strWks$) -wdn 10 aa bb;

For more on project-level and local-level variables see the section below on Scope of Variables.

For more on working with Datasets, see Datasets.

For more on working with %( ), see $( ) Substitution - Numeric to String Conversion.

String

LabTalk supports string handling in two ways: string variables and string registers.

String Variables

String variables may be created by declaration and assignment or by assignment alone (depending on the desired variable scope), and are denoted in LabTalk by a name comprised of continuous characters (see Naming Rules below) followed by a $-sign (i.e., stringName$):

// Create a string with local/session scope by declaration and assignment

// Creates a string named "greeting", 
// and assigns to it the value "Hello":  
string greeting$ = "Hello";

// $ termination is optional in declaration, mandatory for assignment
string FirstName, LastName; 
FirstName$ = Isaac;
LastName$ = Newton;

// Create a project string by assignment without declaration: 
greeting2$ = "World";//project scope and saved with OPJ

// string variable can make use of string class methods
string str$ = Johann Sebastian Bach;
str.Find('Sebastian')=;

// Define literal strings
// The syntax <[< indicates the start of literal strings
// The syntax >]> indicates the end of literal strings
// Can be used to include special symbols like double quotation marks in a string
string s1$ = <[<a"b'";"c">]>;
s1$=;
//Should return a"b'";"c"

//Use literal strings in X-Function arguments
// Fill in three rows in the current selected worksheet column
patternT text:=<[<"Sample A" "Sample B" "Sample C">]>;

For more information on working with string variables, see the String Processing section.

String Registers

Strings may be stored in String registers, denoted by a leading %-sign followed by a letter of the alphabet (i.e., %A-%Z). String Registers are always global in scope.

/* Assign to the string register %A the string "Hello World": */
%A = "Hello World";

For current versions of Origin, we encourage the use of string variables for working with strings, as they are supported by several useful built-in methods; for more, see String(Object). If, however, you are already using string registers, see String Registers for complete documentation on their use.


StringArray

The StringArray data type handles arrays of strings in the same way that the Datasets data type handles arrays of numbers. Like the String data type, StringArray is supported by several built-in methods; for more, see StringArray (Object).

The following example demonstrates the use of StringArray:

// Declare string array named "aa",
// and use built-in methods Add, and GetSize: 
StringArray aa;             // aa is an empty string array
aa.Add("Boston");           // aa now has one element: "Boston"
aa.Add("New York");         // aa has a second element: "New York"

/* Prints "aa has 2 strings in it:" then each string. */ 
type "aa has $(aa.GetSize()) strings in it:"; 
loop(ii,1,aa.GetSize())
{
	ty aa.GetAt(ii)$;
}


Range

The range data type allows functional access to many data-related Origin objects, referring to a specific region in a workbook, worksheet, graph, layer, or window.

The general syntax is:

range rangeName = [WindowName]LayerNameOrIndex!DataRange[subRange]

which can be made specific to data in a workbook, matrix, or graph:

range rangeName = [BookName]SheetNameOrIndex!ColumnNameOrIndex[RowBegin:RowEnd]

range rangeName = [MatrixBookName]MatrixSheetNameOrIndex!MatrixObjectNameOrIndex[CellBegin:CellEnd]

range rangeName =[GraphName]LayerNameOrIndex!DataPlotIndex[RowBegin:RowEnd]

The special syntax [??] is used to create a range variable to access a loose dataset.

For example:

// Access Column 3 on Book1, Sheet2:
range cc = [Book1]Sheet2!Col(3); 
// Access second curve on Graph1, layer1:  
range ll = [Graph1]Layer1!2; 
// Access second matrix object on MBook1, MSheet1:      
range mm = [MBook1]MSheet1!2;
// Access loose dataset tmpdata_a:      
range xx = [??]!tmpdata_a;

Notes:

  • CellRange can be a single cell, (part of) a row or column, a group of cells, or a non-contiguous selection of cells.
  • Worksheets, Matrixsheets, and Graph Layers can each be referenced by name or index.
  • You can define a range variable to represent an origin object, or use range directly as an X-Function argument.
  • Many more details on the range data type and uses of range variables can be found in the Range Notation.

Tree

LabTalk supports the standard tree data type, which emulates a tree structure with a set of branches and leaves. The branches contain leaves, and the leaves contain data. Both branches and leaves are called nodes.

Leaf: A node that has no children, so it can contain a value
Branch: A node that has child nodes and does not contain a value

A leaf node may contain a variable that is of numeric, string, or dataset (vector) type.

// Declare an empty tree
tree report;        
// Tree nodes are added automatically during assignment:
//report two has 2 branches, each branche has two leaves
report.user.name$="dog"; //string
report.user.age=22; // number
report.test.name$="sensor";
report.test.temp = 32.0;

report.=; //output the tree contents

// Save the tree contents to an XML string
string strXML;
report.ToString(strXML$);
strXML$=;

// Declare a new tree 'newReport' and assign to it data from tree 'report': 
tree newReport = report; 
newReport.user.name$=;
newReport.test.temp=;


Check if a tree, branch or leaf exists

//Run after above script. Return 24 if exists. Otherwise return 0
exist(report)=; //returns 24
exist(report.user.name)=; //returns 24
exist(report.test.temp)=; /returns 24
exist(report.test.x)=; //returns 0


Check if it's branch or leaf

//returns 2 for branch, 1 for leaf, 0 for invalid
report@= //returns 2 tree itself is a branch
report.user@=;   // returns 2, branch
report.user.name@=; // returns 1, leaf
report.test.temp@=; // returns 1, leaf
report.test.speed@=;/// return 0, invalid


Trees are commonly used in Origin to set and store a set related of parameters. The tree data type is often used in X-Function's tree type argument, no matter it's input or output.

For example: when using impasc X-Function to import data into Origin, a tree type argument options holds the parameters which determine how the import is performed. This is options tree is an input argument.

string str$ = system.path.program$ + "Samples\Graphing\Group.dat"; 
impasc fname:=str$
/* Start with new sheet */ 
options.ImpMode:=4 
/* Only import the first three columns */
options.Cols.NumCols:=3;


impinfo X-Function has a tree type output argument trInfo After importing data into a worksheet, the following script put the file info. into a tree variable 'fileInfo'.

impinfo trInfo:=fileInfo; 
fileInfo.= //output all contents of the tree


Tree nodes can be strings or numbers. The following example shows how to copy tree nodes with string data and numeric data to worksheet columns:

//Import the data file into worksheet
newbook;
string fn$=system.path.program$ + "\samples\statistics\automobile.dat"; 
impasc fname:=fn$;
tree tr;
//Perform discrte frequency counts on 2nd column, save results to tr
discfreqs irng:=2 rd:=tr;
newsheet name:=Result; //add a new worksheet with name 'Result'
col(1) = tr.freqcount1.data1; // put 'data1' leaf (all strings) to 1st column
col(2) = tr.freqcount1.count1; //put 'count1' leaf (numbers) to 2nd column

Tree nodes can also be vectors. Prior to Origin 8.1 SR1 the only way to access a vector in a Tree variable was to make a direct assignment, as shown in the example code below:

tree tr;
// If you assign a dataset to a tree node,
// it will be a vector node automatically:
tr.a=data(1,10); 
// A vector treenode can be assigned to a column:
col(1)=tr.a; 
// A vector treenode can be assigned to a loose dataset, which is
// convenient since a tree node cannot be used for direct calculations
dataset temp=tr.a;
// Perform calculation on the loose dataset:
col(2)=temp*2;


You can access elements of a vector tree node directly, with statements such as:

// Following the example immediately above,
col(3)[1] = tr.a[3];

that assigns the third element of vector tr.a to the first row of column 3 in the current worksheet.

You can also output analysis results to a tree variable, like the example below.

newbook;
//Import the data file into worksheet
string fn$=system.path.program$ + "\samples\Signal Processing\fftfilter1.dat"; 
impasc fname:=fn$;
tree mytr;
//Perform FFT and save results to a tree variable
fft1 ix:=col(2) rd:=mytr;
page.active=1;
col(3) = mytr.fft.real;
col(4) = mytr.fft.imag;

More information on trees can be found in the chapter on Origin Projects,Accessing Metadata section.

Graphic Objects

The new LabTalk variable type GObject allows the control of graphic objects in any book/layer.

The general syntax is:

GObject name = [GraphPageName]LayerIndex!ObjectName;

GObject name = [GraphPageName]LayerName!ObjectName;

GObject name = LayerName!ObjectName; // active graph

GObject name = LayerIndex!ObjectName; // active graph

GObject name = ObjectName; // active layer

You can declare GObject variables for both existing objects as well as for not-yet created objects.

For example:

GObject myLine = line1;
draw -n myLine -l {1,2,3,4};
win -t plot;
myLine.X+=2; 
/* Even though myLine is in a different graph 
that is not active, you can still control it! */

For a full description of Graphic Objects and their properties and methods, please see Graphic Objects.

Variables

A variable is simply an instance of a particular data type. Every variable has a name, or identifier, which is used to assign data to it, or access data from it. The assignment operator is the equal sign (=), and it is used to simultaneously create a variable (if it does not already exist) and assign a value to it.

Variable Naming Rules

Variable, dataset, command, and macro names are referred to generally as identifiers. When assigning identifiers in LabTalk:

  • Use any combination of letters and numbers, but note that:
    • the identifier cannot be more than 25 characters in length.
    • the first character cannot be a number.
    • the underscore character "_" has a special meaning in dataset names and should be avoided.
  • Use the Exist (Function) to check if an identifier is being used to name a window, macro, tool, dataset, or variable.
  • Note that several common identifiers are reserved for system use by Origin, please see System Variables for a complete list.
  • To avoid conflict with column short names in column value calculations, it is recommended that you use at least 4 characters when assigning variable names.

Handling Variable Name Conflicts

The @ppv system variable controls how Origin handles naming conflicts between project, session, and local variables. Like all system variables, @ppv can be changed from script anytime and takes immediate effect.

Variable Description
@ppv=0 This is the DEFAULT option and allows both session variables and local variables to use existing project variable names. In the event of a conflict, session or local variables are used.
@ppv=1 This option makes declaring a session variable with the same name as an existing project variable illegal. Upon loading a new project, session variables with a name conflict will be disabled until the project is closed or the project variable with the same name is deleted.
@ppv=2 This option makes declaring a local variable with the same name as an existing project variable illegal. Upon loading of new project, local variables with a name conflict will be disabled until the project is closed or the project variable with the same name is deleted.
@ppv=3 This is the combination of @ppv=1 and @ppv=2. In this case, all session and local variables will not be allowed to use project variable names. If a new project is loaded, existing session or local variables of the same name will be disabled.

Listing and Deleting Variables

Use the LabTalk commands list and del for listing variables and deleting variables, respectively.

/* Use the LabTalk command "list" with various options to list 
variables; the list will print in the Script Window by default: */

list a;       // List all the session variables
list v;       // List all project and session variables
list vs;      // List all project and session string variables
list vt;      // List all project and session tree variables

// Use the LabTalk command "del" to delete variables:

del -al <variableName>;  // Delete specific local or session variable
del -al *;               // Delete all the local and session variables

// There is also a viewer for LabTalk variables:
// "ed" command can also open the viewer
list;                     // Open the LabTalk Variables Viewer

Please see the List (Command), and Del (Command) (in Language Reference: Command Reference) for all listing and deleting options.

If no options are specified, running either the List or Edit command will open the LabTalk Variables and Functions dialog and list all variables and functions.

Scope of Variables

The way a variable is declared determines its scope. Variables created without declaration (only allowed for types double, string, and dataset) become Project variables and are saved with the Origin Project file. Declared variables become Session or Local variables. Scope in LabTalk consists of three (nested) levels of visibility:


In practical terms this means that (a) you can have multiple variables of the same name and (b) when that is the case, the value returned at any given time is dependent upon the current scope (see Session and Local variables, below).

Project Variables

  • Project variables are saved with the Origin Project (*.OPJ). Project variables are said to have Project scope.
  • Project variables are automatically created without declaration for variables of type double, string, and dataset as in:
// Define a project (project scope) variable of type double:
myvar = 3.5;
// Define a loose dataset (project scope):
temp = {1,2,3,4,5};
// Define a project (project scope) variable of type string:    
str$ = "Hello";
  • All other variable types must be declared, which makes their default scope either Session or Local. Note that you can make Local variables available as Session variables, using the @glob system variable, as described below.

Session Variables

  • Session variables are not saved with the Origin Project, and are available in the current Origin session across projects. Thus, once a Session variable has been defined, they exist until the Origin application is terminated or the variable is deleted. Session variables are defined with variable declarations:
// Defines a variable of type double:
double var1 = 4.5; 
// Define loose dataset:             
dataset mytemp = {1,2,3,4,5};

You can have a Project variable and a Session variable of the same name. In such cases, the Session variable takes precedence:

aa = 10;
type "First, aa is a project variable equal to $(aa)";
double aa = 20;
type "Then aa is a session variable equal to $(aa)";
del -al aa;
type "Now aa is project variable equal to $(aa)";

And the output is:

First, aa is a project variable equal to 10
Then aa is a session variable equal to 20
Now aa is project variable equal to 10

Local Variables

Local variables exist only within the current scope of a particular script.

Script-level scope exists for scripts:

  • enclosed in curly braces {},
  • in separate *.OGS files or individual sections of *.OGS files,
  • inside the Set Column/Matrix Values Dialog, or
  • behind a custom button (Button Script).

Local variables are declared and assigned values in the same way as Session variables:

loop(i,1,10){
     double a = 3.5;
     const e = 2.718;
     // some other lines of script...
}
// "a" and "e" exist only inside the code enclosed by {}

It is possible to have Local variables with the same name as Session variables or Project variables. In this case, the Local variable takes precedence over the Session or Project variable of the same name, within the scope of the script. For example, if you run the following script (Please refer to Run LabTalk Script From Files for details on how to run such script):

[Main]
double aa = 10;
type "In the main section, aa equals $(aa)";
run.section(, section1);
run.section(, section2);

[section1]
double aa = 20;
type "In section1, aa equals $(aa)";

[section2]
// This section does not declare a local variable named 'aa'.
// A variable named 'aa' will be searched for in the following order:
// If a Session variable named 'aa' exists then it will be used.
// Else if a Project variable named 'aa' exists then it will be used.
// Else if this section is called from another section and the caller
//     section declared a local variable named 'aa' then it will be used.
// Else 'aa' will be a missing value.
type "In section2, aa equals $(aa)";

Origin will output:

In the main section, aa equals 10
In section1, aa equals 20
In section2, aa equals 10

Making Local Variables and Functions Available in the Session

At times you may want to define variables or functions in a *.OGS file, but then be able to use them from the Script Window, in a text label, etc. (normally, the Local variable or function ceases to exist when the OGS runs to completion). To do so, set the value of the @glob system variable to 1 (default value is 0). This makes Local variables and functions in the OGS file available in the Session:

[Main]
@glob = 1;
// the following declarations become available in the session
range a = 1, b= 2;
if(a[2] > 0)
{ 
  // begin a local scope
  range c = 3; // this declaration is still available in the session
}

Upon exiting the *.OGS, the @glob variable is automatically restored to its default value, 0.

Note that one can also control a block of code by placing @glob at the beginning and end, as in:

@glob=1;
double alpha=1.2;
double beta=2.3;
Function double myPeak(double x, double x0)
{
   double y = 10*exp(-(x-x0)^2/4);
   return y;
}
@glob=0;
double gamma=3.45;

In the above script, variables alpha, beta, and the user-defined function myPeak will be available in the session. The variable gamma will not be available because it was declared after @glob was returned to its default value of 0.

Summary Table: Scope of Variables

Data Type Declared? Where Defined Example Lifetime
Constant constant Yes (const)
  • Script Window
  • Command Window
  • OGS File
  • Various GUI dialogs
const av = 6.022×1023; While Origin runs. All constants are saved in orgvar.ogs.
Project Variable double,
string,
dataset
No
  • Script Window
  • Command Window
  • OGS File
  • Various GUI dialogs
av = 6.022×1023; While the OPJ is open.
Saved with the OPJ.
Session Variable all types Yes
  • Script Window
  • Command Window
double av = 6.022×1023; While the session runs.
NOT saved with the OPJ.
Local Variable all types Yes
  • OGS file
  • Various GUI dialogs
double av = 6.022×1023; While the script runs.
Local Variable
as
Session Variable
all types Yes
  • OGS file
  • Various GUI dialogs
@glob=1;
double av = 6.022×1023;
While the session runs.
Can be saved with the OPJ (see ProjectEvents.OGS).